Example #1
0
TEST(plCmdParser, wchar_argv_parsing)
{
    const plCmdArgDef cmds[] = {
        { kCmdArgRequired | kCmdTypeString, "path", 0}
    };

    plCmdParser parser(cmds, arrsize(cmds));

    const wchar_t* args[] = {L"plCmdParser", L"~/.plasma/config.dat"};
    int argc = 2;

    std::vector<ST::string> tokens(argc);
    for (int i = 0; i < argc; i++) {
        tokens.push_back(ST::string::from_wchar(args[i]));
    }

    bool success = parser.Parse(tokens);

    ST::string prog = parser.GetProgramName();
    ST::string path = parser.GetString(0);

    EXPECT_EQ(success, true);
    EXPECT_STREQ(prog.c_str(), "plCmdParser");
    EXPECT_STREQ(path.c_str(), "~/.plasma/config.dat");
    EXPECT_EQ(parser.GetError(), kCmdErrorSuccess);
}
Example #2
0
/*****************************************************************************
 ** pfMacPasswordStore                                                      **
 *****************************************************************************/
ST::string pfMacPasswordStore::GetPassword(const ST::string& username)
{
    ST::string service = GetServerDisplayName();

    void* passwd = nullptr;
    uint32_t passwd_len = 0;

    if (SecKeychainFindGenericPassword(nullptr,
                                       service.size(),
                                       service.c_str(),
                                       username.size(),
                                       username.c_str(),
                                       &passwd_len,
                                       &passwd,
                                       nullptr) != errSecSuccess)
    {
        return ST::null;
    }

    ST::string ret(reinterpret_cast<const char*>(passwd), size_t(passwd_len));

    SecKeychainItemFreeContent(nullptr, passwd);

    return ret;
}
Example #3
0
bool pfMacPasswordStore::SetPassword(const ST::string& username, const ST::string& password)
{
    ST::string service = GetServerDisplayName();

    return SecKeychainAddGenericPassword(nullptr,
                                         service.size(),
                                         service.c_str(),
                                         username.size(),
                                         username.c_str(),
                                         password.size(),
                                         password.c_str(),
                                         nullptr) == errSecSuccess;
}
Example #4
0
plLocation plPluginResManager::ICreateLocation(const ST::string& age, const ST::string& page, int32_t seqNum, bool itinerant)
{
    bool willBeReserved = age.compare_i("global") == 0;

    int32_t oldNum = seqNum;
    seqNum = VerifySeqNumber(seqNum, age, page);
    if (seqNum != oldNum)
    {
        hsAssert(false, "Conflicting page sequence number. Somebody called NameToLoc without verifying their seq# first!"); 
    }

    if (seqNum < 0)
    {
        willBeReserved = true;
        seqNum = -seqNum;
    }

    plLocation newLoc;
    if (willBeReserved)
        newLoc = plLocation::MakeReserved(seqNum);
    else
        newLoc = plLocation::MakeNormal(seqNum);

    // Flag common pages
    for (int i = 0; i < plAgeDescription::kNumCommonPages; i++)
    {
        if (page.compare(plAgeDescription::GetCommonPage(i)) == 0)
        {
            newLoc.SetFlags(plLocation::kBuiltIn);
            break;
        }
    }

    // If we have an age description file for the age we're creating a location
    // for, grab some extra flags from it
    plAgeDescription* ageDesc = plPageInfoUtils::GetAgeDesc(age.c_str());
    plAgePage* agePage = ageDesc ? ageDesc->FindPage(page.c_str()) : nil;
    if (agePage)
    {
        if (agePage->GetFlags() & plAgePage::kIsLocalOnly)
            newLoc.SetFlags(plLocation::kLocalOnly);

        if (agePage->GetFlags() & plAgePage::kIsVolatile)
            newLoc.SetFlags(plLocation::kVolatile);
    }
    if (itinerant)
        newLoc.SetFlags(plLocation::kItinerant);

    delete ageDesc;
    return newLoc;
}
Example #5
0
void plResponderModifier::ILog(uint32_t color, const char* format, ...)
{
#ifdef STATUS_LOG
    if (!gLog)
        gLog = plStatusLogMgr::GetInstance().CreateStatusLog(15, "Responder", plStatusLog::kFilledBackground | plStatusLog::kDeleteForMe | plStatusLog::kDontWriteFile | plStatusLog::kAlignToTop);

    if (!format || *format == '\0')
        return;

    ST::string keyName = GetKeyName();

    // Make sure this key isn't in our list of keys to deny
    for (const auto& it : gNoLogStrings) {
        if (keyName.starts_with(it))
            return;
    }

    // Format the log text
    char buf[256];
    va_list args;
    va_start(args, format);
    int numWritten = hsVsnprintf(buf, sizeof(buf), format, args);
    hsAssert(numWritten > 0, "Buffer too small");
    va_end(args);

    // Strip the redundant part off the key name
    ST_ssize_t modPos = keyName.find("_ResponderModifier");
    if (modPos != -1)
        keyName = keyName.left(modPos);

    ST::string logLine = ST::format("{}: {}", keyName, buf);
    gLog->AddLine(logLine.c_str(), color);
#endif // STATUS_LOG
}
Example #6
0
void plPythonMgr::LoadPythonFiles()
{
    plFileName clientPath = plMaxConfig::GetClientPath(false, true);
    if (clientPath.IsValid())
    {
        plFileName oldCwd = plFileSystem::GetCWD();
        plFileSystem::SetCWD(clientPath);

        // Get the path to the Python subdirectory of the client
        plFileName pythonPath = plFileName::Join(clientPath, "Python");

        PythonInterface::initPython();

        // Iterate through all the Python files in the folder
        std::vector<plFileName> pys = plFileSystem::ListDir(pythonPath, "*.py");
        for (auto iter = pys.begin(); iter != pys.end(); ++iter)
        {
            // Get the filename without the ".py" (module name)
            ST::string fileName = iter->GetFileNameNoExt();

            IQueryPythonFile(fileName.c_str());
        }

        PythonInterface::finiPython();

        plFileSystem::SetCWD(oldCwd);
    }
}
Example #7
0
void plAgeDescInterface::INewPage()
{
    ST::string name = ST_LITERAL("New Page Name");

    // Get the name of the new age from the user
    int ret = DialogBoxParam(hInstance,
                            MAKEINTRESOURCE(IDD_AGE_NAME),
                            GetCOREInterface()->GetMAXHWnd(),
                            NewAgeDlgProc,
                            (LPARAM)&name);
    if (ret != 1)
        return;

    HWND hPages = GetDlgItem(fhDlg, IDC_PAGE_LIST);

    // Make sure this page doesn't already exist
    int count = ListBox_GetCount(hPages);
    for (int i = 0; i < count; i++)
    {
        char pageName[256];
        ListBox_GetText(hPages, i, pageName);
        if (!name.compare_i(pageName))
            return;
    }

    // Add the new page and select it
    int idx = ListBox_AddString(hPages, name.c_str());

    // Choose a new sequence suffix for it
    plAgePage *newPage = new plAgePage( name, IGetFreePageSeqSuffix( hPages ), 0 );
    ListBox_SetItemData( hPages, idx, (LPARAM)newPage );
   
    fDirty = true;
}
Example #8
0
TEST(plCmdParser, basic_parsing)
{
    const plCmdArgDef cmds[] = {
        { kCmdArgRequired | kCmdTypeString, "path", 0}
    };

    plCmdParser parser(cmds, arrsize(cmds));
    bool success = parser.Parse("plCmdParser ~/.plasma/config.dat");

    ST::string prog = parser.GetProgramName();
    ST::string path = parser.GetString(0);

    EXPECT_EQ(success, true);
    EXPECT_STREQ(prog.c_str(), "plCmdParser");
    EXPECT_STREQ(path.c_str(), "~/.plasma/config.dat");
    EXPECT_EQ(parser.GetError(), kCmdErrorSuccess);
}
bool pfUnixPasswordStore::SetPassword(const ST::string& username,
                                      const ST::string& password)
{
    GError *error = nullptr;
    ST::string server = GetServerDisplayName();
    secret_password_store_sync(&pfPasswordStore_Schema, SECRET_COLLECTION_DEFAULT,
                               ST::format("Myst Online Password for {}", server).c_str(),
                               password.c_str(), nullptr, &error,
                               "username", username.c_str(),
                               "server", server.c_str(),
                               nullptr);
    if (error) {
        g_error_free(error);
        return false;
    } else {
        return true;
    }
}
Example #10
0
void plSDLParser::DebugMsg(const ST::string& msg) const
{
    return;
    plNetApp* netApp = plSDLMgr::GetInstance()->GetNetApp();

    if (netApp)
        hsLogEntry(netApp->DebugMsg(msg));
    else
        hsStatusMessage(msg.c_str());
}
Example #11
0
ST::string CleanFileName(const ST::string& fname) {
    ST::char_buffer result;
    char* buf = result.create_writable_buffer(fname.size());
    memcpy(buf, fname.c_str(), fname.size() + 1);
    for (char* bp = buf; *bp; bp++) {
        if (*bp == '?' || *bp == '*' || *bp == '<' || *bp == '>' ||
            *bp == '"' || *bp == '|' || *bp < (char)0x20)
            *bp = '_';
        if (*bp == '/' || *bp == '\\' || *bp == ':')
            *bp = '_';
    }
    return result;
}
Example #12
0
TEST(plCmdParser, flagged_string_bystring)
{
    const plCmdArgDef cmds[] = {
        { kCmdTypeString, "path", 0}
    };

    plCmdParser parser(cmds, arrsize(cmds));
    parser.Parse("plCmdParser --path foo");

    ST::string path = parser.GetString("path");

    EXPECT_STREQ(path.c_str(), "foo");
}
Example #13
0
ST::string FixSlashes(const ST::string& src) {
    if (src.is_empty())
        return src;

    ST::char_buffer dest;
    char* pbuf = dest.create_writable_buffer(src.size());
    memcpy(pbuf, src.c_str(), src.size() + 1);
    for (char* pc = pbuf; *pc != 0; pc++) {
        if (*pc == '/' || *pc == '\\')
            *pc = PATHSEP;
    }
    return dest;
}
Example #14
0
void plMtlEventProc::ILoadUser(HWND hWnd, IParamBlock2* pb)
{
    HWND hList = GetDlgItem(hWnd, IDC_EVENT_LIST);
    ListBox_ResetContent(hList);

    //
    // If we don't have a valid material, we should be disabled
    //
    Mtl* mtl = pb->GetMtl(kMtlMtl);
    if (!mtl)
    {
        EnableWindow(hList, FALSE);
        return;
    }
    else
        EnableWindow(hList, TRUE);

    //
    // Load the events
    //
    int idx;

    idx = ListBox_AddStringData(hList, "(Begin)", kAnimEventBegin);
    if (pb->GetInt(kMtlBegin))
        ListBox_SetSel(hList, TRUE, idx);

    idx = ListBox_AddStringData(hList, "(End)", kAnimEventEnd);
    if (pb->GetInt(kMtlEnd))
        ListBox_SetSel(hList, TRUE, idx);

    if (mtl)
    {
        ST::string mtlAnim = ST::string::from_utf8(pb->GetStr(kMtlAnim));

        // Get the shared animations for all the nodes this component is applied to
        plNotetrackAnim anim(mtl, nil);
        plAnimInfo info = anim.GetAnimInfo(mtlAnim);

        RemoveDeadMarkers(pb, kMtlMarkers, info);

        // Get all the markers in this animation
        ST::string marker;
        while (!(marker = info.GetNextMarkerName()).is_empty())
        {
            idx = ListBox_AddStringData(hList, marker.c_str(), kAnimEventMarker);

            if (IsMarkerSelected(pb, kMtlMarkers, marker))
                ListBox_SetSel(hList, TRUE, idx);
        }
    }
}
Example #15
0
void plAnimEventProc::ILoadUser(HWND hWnd, IParamBlock2* pb)
{
    HWND hList = GetDlgItem(hWnd, IDC_EVENT_LIST);
    ListBox_ResetContent(hList);

    plAnimComponentBase* comp;
    plMaxNode* node;

    //
    // If we don't have a valid comp and node, we should be disabled
    //
    if (!GetCompAndNode(pb, (plComponentBase*&)comp, node))
    {
        EnableWindow(hList, FALSE);
        return;
    }
    else
        EnableWindow(hList, TRUE);

    //
    // Load the events
    //
    int idx;

    idx = ListBox_AddStringData(hList, "(Begin)", kAnimEventBegin);
    if (pb->GetInt(kAnimBegin))
        ListBox_SetSel(hList, TRUE, idx);

    idx = ListBox_AddStringData(hList, "(End)", kAnimEventEnd);
    if (pb->GetInt(kAnimEnd))
        ListBox_SetSel(hList, TRUE, idx);

    if (comp)
    {
        // Get the shared animations for all the nodes this component is applied to
        plNotetrackAnim anim(comp, nil);
        plAnimInfo info = anim.GetAnimInfo(comp->GetAnimName());

        RemoveDeadMarkers(pb, kAnimMarkers, info);

        // Get all the markers in this animation
        ST::string marker;
        while (!(marker = info.GetNextMarkerName()).is_empty())
        {
            idx = ListBox_AddStringData(hList, marker.c_str(), kAnimEventMarker);

            if (IsMarkerSelected(pb, kAnimMarkers, marker))
                ListBox_SetSel(hList, TRUE, idx);
        }
    }
}
Example #16
0
TEST(plCmdParser, argv_preserving_spaces)
{
    const plCmdArgDef cmds[] = {
        { kCmdArgRequired | kCmdTypeString, "path", 0}
    };

    plCmdParser parser(cmds, arrsize(cmds));

    const char* args[] = {"plCmdParser", "~/.plasma/Uru Live/config.dat"};
    int argc = 2;

    std::vector<ST::string> tokens(args, args+argc);

    bool success = parser.Parse(tokens);

    ST::string prog = parser.GetProgramName();
    ST::string path = parser.GetString(0);

    EXPECT_EQ(success, true);
    EXPECT_STREQ(prog.c_str(), "plCmdParser");
    EXPECT_STREQ(path.c_str(), "~/.plasma/Uru Live/config.dat");
    EXPECT_EQ(parser.GetError(), kCmdErrorSuccess);
}
Example #17
0
static void SendBasic(unsigned char*& buf, const msgparm_t& data,
                      unsigned int size, unsigned int count)
{
    // Also works for floats and doubles
    if (count == 0) {
        if (size == 1) {
            *(uint8_t*)buf = (uint8_t)data.fUint;
            buf += sizeof(uint8_t);
        } else if (size == 2) {
            *(uint16_t*)buf = (uint16_t)data.fUint;
            buf += sizeof(uint16_t);
        } else if (size == 4) {
            *(uint32_t*)buf = data.fUint;
            buf += sizeof(uint32_t);
        }

#ifdef COMMDEBUG
        plDebug::Debug("     -> Int{}: {}", size * 8, data.fUint);
#endif
    } else {
        if (size == 1) {
            memcpy(buf, data.fData, count * sizeof(uint8_t));
            buf += count * sizeof(uint8_t);
        } else if (size == 2) {
            memcpy(buf, data.fData, count * sizeof(uint16_t));
            buf += count * sizeof(uint16_t);
        } else if (size == 4) {
            memcpy(buf, data.fData, count * sizeof(uint32_t));
            buf += count * sizeof(uint32_t);
        }

#ifdef COMMDEBUG
        ST::string ln = ST::format("     -> Int{}[{}]: ", size * 8, count);
        size_t lnbufSize = count * ((size * 2) + 1);
        char* lnbuf = new char[lnbufSize + 1];
        for (size_t i=0; i<count; i++) {
            if (size == 1)
                sprintf(lnbuf + (i * 3), "%02X ", ((uint8_t*)data.fData)[i]);
            else if (size == 2)
                sprintf(lnbuf + (i * 5), "%04X ", ((uint16_t*)data.fData)[i]);
            else if (size == 4)
                sprintf(lnbuf + (i * 9), "%08X ", ((uint32_t*)data.fData)[i]);
        }
        lnbuf[lnbufSize] = 0;
        ln += lnbuf;
        delete[] lnbuf;
        plDebug::Debug(ln.c_str());
#endif
    }
}
Example #18
0
static void RecvBasic(pnSocket* sock, msgparm_t& data,
                      unsigned int size, unsigned int count)
{
    // Also works for floats
    if (count == 0) {
        if (size == 1) {
            uint8_t v;
            sock->recv(&v, sizeof(uint8_t));
            data.fUint = v;
        } else if (size == 2) {
            uint16_t v;
            sock->recv(&v, sizeof(uint16_t));
            data.fUint = v;
        } else if (size == 4) {
            uint32_t v;
            sock->recv(&v, sizeof(uint32_t));
            data.fUint = v;
        }

#ifdef COMMDEBUG
        plDebug::Debug("     <- Int{}: {}", size * 8, data.fUint);
#endif
    } else {
        if (size == 1)
            sock->recv(data.fData, count * sizeof(uint8_t));
        else if (size == 2)
            sock->recv(data.fData, count * sizeof(uint16_t));
        else if (size == 4)
            sock->recv(data.fData, count * sizeof(uint32_t));

#ifdef COMMDEBUG
        ST::string ln = ST::format("     <- Int{}[{}]: ", size * 8, count);
        size_t lnbufSize = count * ((size * 2) + 1);
        char* lnbuf = new char[lnbufSize + 1];
        for (size_t i=0; i<count; i++) {
            if (size == 1)
                sprintf(lnbuf + (i * 3), "%02X ", ((uint8_t*)data.fData)[i]);
            else if (size == 2)
                sprintf(lnbuf + (i * 5), "%04X ", ((uint16_t*)data.fData)[i]);
            else if (size == 4)
                sprintf(lnbuf + (i * 9), "%08X ", ((uint32_t*)data.fData)[i]);
        }
        lnbuf[lnbufSize] = 0;
        ln += lnbuf;
        delete[] lnbuf;
        plDebug::Debug(ln.c_str());
#endif
    }
}
Example #19
0
/*****************************************************************************
 ** pfUnixPasswordStore                                                     **
 *****************************************************************************/
ST::string pfUnixPasswordStore::GetPassword(const ST::string& username)
{
    GError *error = nullptr;
    gchar *password = secret_password_lookup_sync(&pfPasswordStore_Schema,
                            nullptr, &error,
                            "username", username.c_str(),
                            "server", GetServerDisplayName().c_str(),
                            nullptr);

    ST::string result;
    if (error) {
        // Throw away the error and treat it as if no password was found...
        g_error_free(error);
    } else if (password) {
        result = ST::string::from_utf8(password);
        secret_password_free(password);
    }

    return result;
}
Example #20
0
msgparm_t* pnSocket::recvMsg(const pnNetMsg* msg)
{
    if (msg == NULL)
        return NULL;

#ifdef COMMDEBUG
    plDebug::Debug("<RECV> {}", msg->fMsgName);
#endif
    msgparm_t* data = NCAllocMessage(msg);

    unsigned int size = 0;
    unsigned int count = 0;
    for (size_t i=0; i<msg->fFieldCount; i++) {
        const pnNetMsgField* field = &msg->fFields[i];
        switch (field->fType) {
        case kFieldInteger:
        case kFieldFloat:
            RecvBasic(this, data[i], field->fSize, field->fCount);
            break;
        case kFieldString:
            {
                uint16_t len;
                recv(&len, sizeof(uint16_t));
                char16_t* str = new char16_t[len + 1];
                recv(str, len * sizeof(char16_t));
                str[len] = 0;
                data[i].fString = str;
#ifdef COMMDEBUG
                plDebug::Debug("     <- Str: {}", ST::string::from_utf16(data[i].fString, len));
#endif
            }
            break;
        case kFieldVarCount:
            size = field->fSize;
            recv(&count, sizeof(uint32_t));
            data[i].fUint = count;
#ifdef COMMDEBUG
            plDebug::Debug("     <- Count: {}", count);
#endif
            break;
        case kFieldVarPtr:
        case kFieldRawVarPtr:
            delete[] data[i].fData;
            data[i].fData = new uint8_t[size * count];
            recv(data[i].fData, size * count);
#ifdef COMMDEBUG
            {
                ST::string ln = "     <- VarData: ";
                char* sBuf = new char[(3 * (size * count)) + 1];
                for (size_t j=0; j<(size * count); j++)
                    sprintf(sBuf + (3*j), "%02X ", data[i].fData[j]);
                sBuf[3 * (size * count)] = 0;
                ln += sBuf;
                delete[] sBuf;
                plDebug::Debug(ln.c_str());
            }
#endif
            size = 0;
            count = 0;
            break;
        case kFieldData:
        case kFieldPtr:
        case kFieldRawData:
        case kFieldRawPtr:
            recv(data[i].fData, field->fSize * field->fCount);
#ifdef COMMDEBUG
            {
                ST::string ln = "     <- Data: ";
                char* sBuf = new char[(3 * (field->fSize * field->fCount)) + 1];
                for (size_t j=0; j<(field->fSize * field->fCount); j++)
                    sprintf(sBuf + (3*j), "%02X ", data[i].fData[j]);
                sBuf[3 * (field->fSize * field->fCount)] = 0;
                ln += sBuf;
                delete[] sBuf;
                plDebug::Debug(ln.c_str());
            }
#endif
            break;
        }
    }
    return data;
}
Example #21
0
void plSimulationMgr::ISendUpdates()
{
    for (CollisionVec::iterator it = fCollideMsgs.begin(); it != fCollideMsgs.end(); ++it)
    {
        plCollideMsg* pMsg = *it;
        DetectorLogYellow("Collision: %s was triggered by %s. Sending an %s msg", pMsg->GetReceiver(0)->GetName().c_str(),
                          pMsg->fOtherKey ? pMsg->fOtherKey->GetName().c_str() : "(nil)" , pMsg->fEntering ? "'enter'" : "'exit'");
        plgDispatch::Dispatch()->MsgSend(pMsg);
    }
    fCollideMsgs.clear();

    SceneMap::iterator it = fScenes.begin();
    for (; it != fScenes.end(); it++)
    {
        NxScene* scene = it->second;
        uint32_t numActors = scene->getNbActors();
        NxActor** actors = scene->getActors();

        for (int i = 0; i < numActors; i++)
        {
            plPXPhysical* physical = (plPXPhysical*)actors[i]->userData;
            if (physical)
            {
                if (physical->GetSceneNode())
                {
                    physical->SendNewLocation();
                }
                else
                {
                    // if there's no scene node, it's not active (probably about to be collected)
                    const plKey physKey = physical->GetKey();
                    if (physKey)
                    {
                        ST::string physName = physical->GetKeyName();
                        if (!physName.is_empty())
                        {
                            plSimulationMgr::Log("Removing physical <%s> because of missing scene node.\n", physName.c_str());
                        }
                    }
//                  Remove(physical);
                }
            }
        }

//      // iterate through the db types, which are powers-of-two enums.
//      for( plLOSDB db = static_cast<plLOSDB>(1) ;
//          db < plSimDefs::kLOSDBMax;
//          db = static_cast<plLOSDB>(db << 1) )
//      {
//          fLOSSolvers[db]->Resolve(fSubspace);
//      }
//      if(fNeedLOSCullPhase)
//      {
//          for( plLOSDB db = static_cast<plLOSDB>(1) ;
//              db < plSimDefs::kLOSDBMax;
//              db = static_cast<plLOSDB>(db << 1) )
//          {
//              fLOSSolvers[db]->Resolve(fSubspace);
//          }
//          fNeedLOSCullPhase = false;
//      }
    }
}
Example #22
0
bool plListener::IEval(double secs, float del, uint32_t dirty)
{
//  if (!plgAudioSys::Active())
//      return true;
    plSceneObject *pRefObject = nil;

    int y = 16 + 12, x = 400;
    if( fPrintDbgInfo ) 
        plDebugText::Instance().DrawString( x, 16, "Listener:", (uint32_t)0xffffffff, plDebugText::kStyleBold );

    // Get the avatar's SceneObject
    plKey key = plNetClientMgr::GetInstance()->GetLocalPlayerKey();
    if(key)
        pRefObject = plSceneObject::ConvertNoRef(key->ObjectIsLoaded());

    if( pRefObject == nil && fVCam == nil )
    {
        // We don't have a position to init by, so do NOT eval yet!!!
        if( fPrintDbgInfo ) 
            plDebugText::Instance().DrawString( x, y, "Not eval-ing yet", (uint32_t)0xffffffff );
        return true;
    }

    // Changed 2.19.02 mcn - Basing it off the head bone isn't what we really want, esp. since
    // it isn't what the camera uses. What we *really* want is a head-ish-positioned non-bobbing node
    // that we base both off of. Until then, we're just going to have to use the avatar's root (i.e. his
    // feet) and add in an appropriate height. See plAvBrain.cpp::BindAudioListener() for the other half
    // of the hack.
    // Note the 2nd: since GetAxis() is buggy, we'll just add in a constant vector. Of course, this implies
    // that the avatar is always oriented up, but then it also implies he's always of constant height, so
    // there.
    const hsVector3 kAvatarHeightVector = hsVector3( 0, 0, 6.33f ); // isn't *everyone* 6'4"?

    /// Collect the current values for our parameters
    hsPoint3    position;
    hsVector3   velocity, dir, up;

    enum 
    {
        kInvalid = 0,
        kVCam,
        kObject
    } facingType = kInvalid, posType = kInvalid, velType = kInvalid;

    // Facing
    if( fFacingRatio == 1.f )
    {
        if( pRefObject != nil && pRefObject->GetCoordinateInterface() )
        {
            hsMatrix44 facingL2W = pRefObject->GetCoordinateInterface()->GetLocalToWorld();
            dir = facingL2W.GetAxis( hsMatrix44::kView );
            up = facingL2W.GetAxis( hsMatrix44::kUp );

            facingType = kObject;
        }
    }
    else if( fVCam != nil )
    {
        dir = hsVector3( fVCam->GetCameraPOA() - fVCam->GetCameraPos() );
        up = fVCam->GetCameraUp();
        facingType = kVCam;
    }

    // Position
    if( fPosRatio == 1.f )
    {
        if( pRefObject != nil && pRefObject->GetCoordinateInterface() )
        {
            position = pRefObject->GetCoordinateInterface()->GetLocalToWorld().GetTranslate();
            position += kAvatarHeightVector;
            posType = kObject;
        }
    }
    else if( fVCam != nil )
    {
        position = fVCam->GetCameraPos();
        posType = kVCam;
    }

    // Velocity
    if( fVelRatio == 1.f )
    {
        if( pRefObject != nil )
        {
            plArmatureMod* arm = plAvatarMgr::GetInstance()->GetLocalAvatar();
            if (arm)
            {
                plPhysicalControllerCore* controller = arm->GetController();
                if (controller)
                {
                    velocity = controller->GetLinearVelocity();
                    velType = kObject;
                }
            }
        }
    }
    else if( fVCam != nil )
    {
        // Darn, can't do it
    }

    if( facingType == kInvalid || posType == kInvalid || velType == kInvalid )
    {
        if( fPrintDbgInfo ) 
            plDebugText::Instance().DrawString( x, y, "Not eval-ing: missing one or more parameter bases", (uint32_t)0xff0000ff );
        return true;
    }

    // Got the params, now construct and send out the message, as well as update the audio system
    plListenerMsg* msg = new plListenerMsg;
    msg->SetDirection( dir );
    msg->SetUp( up );
    msg->SetPosition( position );
    msg->SetVelocity( velocity );

    plgAudioSys::SetListenerOrientation( dir, up );
    plgAudioSys::SetListenerPos( position );
    plgAudioSys::SetListenerVelocity( velocity );

    if( fPrintDbgInfo ) 
    {
        ST::string str;
        str = ST::format("Direction: ({3.2f},{3.2f},{3.2f}) from {}", dir.fX, dir.fY, dir.fZ,
                         (facingType == kObject) ? pRefObject->GetKeyName() : "VCam");
        plDebugText::Instance().DrawString( x, y, str.c_str(), (uint32_t)0xffffffff );
        y += 12;

        str = ST::format("Up: ({3.2f},{3.2f},{3.2f}) from {}", up.fX, up.fY, up.fZ,
                         (facingType == kObject) ? pRefObject->GetKeyName() : "VCam");
        plDebugText::Instance().DrawString( x, y, str.c_str(), (uint32_t)0xffffffff );
        y += 12;

        str = ST::format("Position: ({3.2f},{3.2f},{3.2f}) from {}", position.fX, position.fY, position.fZ,
                         (posType == kObject) ? pRefObject->GetKeyName() : "VCam");
        plDebugText::Instance().DrawString( x, y, str.c_str(), (uint32_t)0xffffffff );
        y += 12;

        str = ST::format("Velocity: ({3.2f},{3.2f},{3.2f}) from {}", velocity.fX, velocity.fY, velocity.fZ,
                         (velType == kObject) ? pRefObject->GetKeyName() : "VCam");
        plDebugText::Instance().DrawString( x, y, str.c_str(), (uint32_t)0xffffffff );
        y += 12;
    }
    plgDispatch::MsgSend( msg );

    return true;
}
Example #23
0
int main(int argc, char* argv[]) {
    if (argc < 2 || argc > 3) {
        doHelp();
        return 0;
    }

    eDirection direction = kRepack;
    ST::string filename = argv[1];
    ST_ssize_t dotLoc = filename.find_last('.');
    if (argc == 3) {
        if (strcmp(argv[1], "-c") == 0)
            direction = kCreate;
        else if (strcmp(argv[1], "-x") == 0)
            direction = kExtract;
        else if (strcmp(argv[1], "-r") == 0)
            direction = kRepack;
        else {
            doHelp();
            return 1;
        }
        filename = argv[2];
    } else if (dotLoc >= 0 && filename.substr(dotLoc) == ".prd") {
        direction = kCreate;
    }

    plResManager rm;
    hsFileStream S, OS;
    if (!S.open(filename, fmRead)) {
        ST::printf(stderr, "Error opening {} for reading!", filename);
        return 1;
    }
    plPageInfo* page = new plPageInfo();

    //int len;
    short maj = 63, min = 11;
    unsigned int i, j;
    if (direction == kExtract || direction == kRepack) {
        S.close();
        delete page;
        page = rm.ReadPage(filename, true);
        OS.open(filenameConvert(filename, kExtract), fmCreate);
        OS.write(4, "PRD");
        OS.writeShort(page->getAge().size());
        OS.writeStr(page->getAge());
        OS.writeShort(page->getPage().size());
        OS.writeStr(page->getPage());
        if (rm.getVer().isUniversal()) {
            maj = 0x7FFF;
            min = 0x7FFF;
        } else  if (rm.getVer().isEoa()) {
            maj = -1;
            min = 1;
        } else if (rm.getVer().isHexIsle()) {
            maj = -1;
            min = 2;
        } else {
            maj = rm.getVer().revMajor();
            min = rm.getVer().revMinor();
        }
        OS.writeShort(maj);
        OS.writeShort(min);
        plLocation loc = page->getLocation();
        loc.write(&OS);
        OS.close();

        std::vector<short> types = rm.getTypes(loc);
      #ifdef _WIN32
        CreateDirectoryW(getOutputDir(filename, page).to_wchar().data(), NULL);
      #else
        mkdir(getOutputDir(filename, page).c_str(), S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
      #endif
        for (i=0; i<types.size(); i++) {
            std::vector<plKey> objs = rm.getKeys(loc, types[i]);
            for (j=0; j<objs.size(); j++) {
                ST::string po_file = ST::format("{}[{04X}]{}.po", getOutputDir(filename, page),
                                                types[i], CleanFileName(objs[j]->getName()));
                OS.open(po_file, fmCreate);
                OS.setVer(rm.getVer());
                rm.WriteCreatable(&OS, objs[j]->getObj());
                OS.close();
            }
        }
    }
    if (direction == kRepack) {
        filename = filenameConvert(filename, kExtract);
        S.open(filename, fmRead);
    }
    if (direction == kCreate || direction == kRepack) {
        OS.open(filenameConvert(filename, kCreate), fmCreate);
        char sig[4];
        S.read(4, sig);
        if (strncmp(sig, "PRD", sizeof(sig)) != 0) {
            fputs("Error: Invalid input file!\n", stderr);
            OS.close();
            S.close();
            return 1;
        }
        ST::string ageName = S.readStr(S.readShort());
        ST::string pageName = S.readStr(S.readShort());
        page->setAge(ageName);
        page->setPage(pageName);
        maj = S.readShort();
        min = S.readShort();
        if (maj == 0x7FFF) {
            OS.setVer(PlasmaVer::pvUniversal);
        } else if (maj == -1) {
            if (min == 1)
                OS.setVer(PlasmaVer::pvEoa);
            else if (min == 2)
                OS.setVer(PlasmaVer::pvHex);
        } else if (maj == 70) {
            OS.setVer(PlasmaVer::pvMoul);
        } else if (maj == 63) {
            if (min == 11)
                OS.setVer(PlasmaVer::pvPrime);
            if (min == 12)
                OS.setVer(PlasmaVer::pvPots);
        } else {
            ST::printf(stderr, "Error: Invalid Plasma version: {}.{}\n", maj, min);
            OS.close();
            S.close();
            return 1;
        }
        S.setVer(OS.getVer());
        plLocation loc;
        loc.read(&S);
        page->setLocation(loc);
        page->setReleaseVersion(0);
        page->setFlags(plPageInfo::kBasicChecksum);
        S.close();

        std::vector<ST::string> inFiles;
        std::vector<short> inClasses;
        hsFileStream PS;
        PS.setVer(OS.getVer());
      #ifdef _WIN32
        ST::string pattern = ST::format("{}*.po", getOutputDir(filename, page));
        WIN32_FIND_DATAW fd;
        HANDLE fr = FindFirstFileW(pattern.to_wchar().data(), &fd);
        if (fr != NULL) {
            do {
                ST::string po_file = getOutputDir(filename, page) + fd.cFileName;
                inFiles.push_back(po_file);
                PS.open(po_file, fmRead);
                short classType = PS.readShort();
                PS.close();
                bool haveClass = false;
                for (j=0; j<inClasses.size(); j++)
                    if (inClasses[j] == classType) {
                        haveClass = true;
                }
                if (!haveClass)
                    inClasses.push_back(classType);
            } while (FindNextFileW(fr, &fd));
            FindClose(fr);
        }
      #else
        dirent** des;
        unsigned int nEntries = scandir(getOutputDir(filename, page).c_str(), &des, &selPO, &alphasort);
        for (i=0; i<nEntries; i++) {
            ST::string po_file = getOutputDir(filename, page) + des[i]->d_name;
            inFiles.push_back(po_file);
            PS.open(po_file, fmRead);
            short classType = PS.readShort();
            PS.close();
            bool haveClass = false;
            for (j=0; j<inClasses.size(); j++)
                if (inClasses[j] == classType) {
                    haveClass = true;
            }
            if (!haveClass)
                inClasses.push_back(classType);
        }
      #endif
        page->setClassList(inClasses);
        page->write(&OS);
        page->setDataStart(OS.pos());
        plKeyCollector keys;

        for (i=0; i<inFiles.size(); i++) {
            plKey key = new plKeyData();
            PS.open(inFiles[i], fmRead);
            PS.setVer(S.getVer());
            unsigned int poLen = PS.size();
            uint8_t* objBuf = new uint8_t[poLen];
            key->setFileOff(OS.pos());
            key->setObjSize(poLen);
            PS.read(poLen, objBuf);
            OS.write(poLen, objBuf);
            delete[] objBuf;
            PS.seek(2);
            key->readUoid(&PS);
            PS.close();
            keys.add(key);
        }

        page->setIndexStart(OS.pos());
        keys.sortKeys(page->getLocation());
        std::vector<short> types = keys.getTypes(page->getLocation());
        //if (types != inClasses)
        //    throw "Wtf, mate?";
        OS.writeInt(types.size());
        for (i=0; i<types.size(); i++) {
            std::vector<plKey> kList = keys.getKeys(page->getLocation(), types[i]);
            OS.writeShort(pdUnifiedTypeMap::MappedToPlasma(types[i], OS.getVer()));
            unsigned int lenPos = OS.pos();
            if (!OS.getVer().isUruSP() && !OS.getVer().isUniversal()) {
                OS.writeInt(0);
                OS.writeByte(0);
            }
            OS.writeInt(kList.size());
            for (j=0; j<kList.size(); j++)
                kList[j]->write(&OS);
            if (!OS.getVer().isUruSP() && !OS.getVer().isUniversal()) {
                unsigned int nextPos = OS.pos();
                OS.seek(lenPos);
                OS.writeInt(nextPos - lenPos - 4);
                OS.seek(nextPos);
            }
        }
        if (OS.getVer().isNewPlasma())
            page->setChecksum(OS.pos());
        else
            page->setChecksum(OS.pos() - page->getDataStart());
        page->writeSums(&OS);
        OS.close();
    }

    // Delete temp files with the repack option
    if (direction == kRepack) {
      #ifdef _WIN32
        ST::string pattern = ST::format("{}*.po", getOutputDir(filename, page));
        WIN32_FIND_DATAW rfd;
        HANDLE rfr = FindFirstFileW(pattern.to_wchar().data(), &rfd);
        if (rfr != NULL) {
            do {
                ST::string po_file = getOutputDir(filename, page) + rfd.cFileName;
                DeleteFileW(po_file.to_wchar().data());
            } while (FindNextFileW(rfr, &rfd));
            FindClose(rfr);
        }
        RemoveDirectoryW(getOutputDir(filename, page).to_wchar().data());
        DeleteFileW(filename.to_wchar().data());
      #else
        dirent** rdes;
        unsigned int nEntries = scandir(getOutputDir(filename, page).c_str(), &rdes, &selAll, &alphasort);
        for (i=0; i<nEntries; i++) {
            ST::string po_file = getOutputDir(filename, page) + rdes[i]->d_name;
            unlink(po_file.c_str());
        }
        rmdir(getOutputDir(filename, page).c_str());
        unlink(filename.c_str());
      #endif
    }

    return 0;
}
Example #24
0
void plAgeDescInterface::ILoadAge( const plFileName &path, bool checkSeqNum )
{
    ISetControlDefaults();
    
    fDirty = false;

    // create and read the age desc
    plAgeDescription aged( path );

    // Get the name of the age
    ST::string ageName = path.GetFileNameNoExt();

    // Check the sequence prefix #
    if( checkSeqNum )
        ICheckSequenceNumber( aged );

    char str[ _MAX_FNAME + 30 ];
    sprintf( str, "Description for %s", ageName.c_str() );
    SetDlgItemText( fhDlg, IDC_AGEDESC, str );

    // Set up the Dlgs
    SYSTEMTIME st;

    HWND hTime = GetDlgItem(fhDlg, IDC_TIME);
    memset(&st,0, sizeof(st));
    st.wYear = 2000;
    st.wMonth = 1;
    st.wDay = 1;
    st.wHour = aged.GetStartHour();
    st.wMinute = aged.GetStartMinute();
    st.wSecond = aged.GetStartSecond();
    DateTime_SetSystemtime(hTime, GDT_VALID, &st);

    
    HWND hDate = GetDlgItem(fhDlg, IDC_DATE);
    memset(&st,0, sizeof(st));
    st.wMonth = aged.GetStartMonth();
    st.wDay = aged.GetStartDay();
    st.wYear = aged.GetStartYear();
    DateTime_SetSystemtime(hDate, GDT_VALID, &st);

    
    fSpin->SetValue(aged.GetDayLength(), FALSE);

    int maxCap = aged.GetMaxCapacity();
    if (maxCap == -1)
    {
        maxCap = kDefaultCapacity;
        fDirty = true;
    }
    fCapSpin->SetValue(maxCap, FALSE);

    int32_t seqPrefix = aged.GetSequencePrefix();
    if( seqPrefix < 0 )
    {
        // Reserved prefix
        fSeqPrefixSpin->SetValue( (int)( -seqPrefix ), FALSE );
        CheckDlgButton( fhDlg, IDC_RSVDCHECK, BST_CHECKED );
    }
    else
    {
        fSeqPrefixSpin->SetValue( (int)seqPrefix, FALSE );
        CheckDlgButton( fhDlg, IDC_RSVDCHECK, BST_UNCHECKED );
    }

    // Disable the registry controls for now
    EnableWindow( GetDlgItem( fhDlg, IDC_RSVDCHECK ), false );
    EnableWindow( GetDlgItem( fhDlg, IDC_SEQPREFIX_EDIT ), false );
    EnableWindow( GetDlgItem( fhDlg, IDC_SEQPREFIX_SPIN ), false );

    aged.SeekFirstPage();
    plAgePage *page;

    HWND hPage = GetDlgItem(fhDlg, IDC_PAGE_LIST);
    while( ( page = aged.GetNextPage() ) != nil )
    {
        int idx = ListBox_AddString( hPage, page->GetName().c_str() );
        ListBox_SetItemData( hPage, idx, (LPARAM)new plAgePage( *page ) );
    }
}
Example #25
0
//
// parsing stateDesc
// read name, version
// return true to skip the next token read
//
bool plSDLParser::IParseStateDesc(const plFileName& fileName, hsStream* stream, char token[],
                                  plStateDescriptor*& curDesc) const
{   
    plSDL::DescriptorList* descList = &plSDLMgr::GetInstance()->fDescriptors;

    bool ok = true;

    //
    // NAME
    //
//  curDesc=plSDLMgr::GetInstance()->FindDescriptor(token, plSDL::kLatestVersion);
//  if (!curDesc)
    {
        curDesc = new plStateDescriptor;
        curDesc->SetName(token);

        DebugMsg("SDL: DESC name={}", token);
    }
    
    //
    // {
    //
    stream->GetToken(token, kTokenLen); // skip '{'
    
    //
    // VERSION
    //
    if (stream->GetToken(token, kTokenLen)) 
    {
        if (!strcmp(token, "VERSION"))
        {
            // read desc version
            hsAssert(curDesc, ST::format("Syntax problem with .sdl file, fileName={}", fileName).c_str());
            if (stream->GetToken(token, kTokenLen))
            {
                int v=atoi(token);
                curDesc->SetVersion(v);
                DebugMsg("\tVersion={}", v);
            }               
        }
        else
        {
            hsAssert(false, ST::format("Error parsing state desc, missing VERSION, fileName={}", fileName).c_str());
            ok = false;
        }
    }
    else
    {
        hsAssert(false, ST::format("Error parsing state desc, fileName={}", fileName).c_str());
        ok = false;
    }

    if ( ok )
    {
        ok = ( plSDLMgr::GetInstance()->FindDescriptor(curDesc->GetName(), curDesc->GetVersion())==nil );
        if ( !ok )
        {
            ST::string err = ST::format("Found duplicate SDL descriptor for {} version {}.\nFailed to parse file: {}",
                                        curDesc->GetName(), curDesc->GetVersion(), fileName);
            plNetApp::StaticErrorMsg(err);
            hsAssert( false, err.c_str() );
        }
    }

    if ( ok )
    {
        descList->push_back(curDesc);
    }
    else
    {
        delete curDesc;
        curDesc = nil;
    }

    return false;
}
Example #26
0
bool pnSocket::sendMsg(const msgparm_t* data, const pnNetMsg* msg)
{
    if (msg == NULL)
        return false;

#ifdef COMMDEBUG
    plDebug::Debug("<SEND> {}", msg->fMsgName);
#endif

    size_t bufSize = sizeof(uint16_t) + NCMessageSize(data, msg);
    unsigned char* buffer = new unsigned char[bufSize];
    unsigned char* bp = buffer;
    *(uint16_t*)bp = msg->fMsgId;
    bp += sizeof(uint16_t);

    unsigned int size = 0;
    unsigned int count = 0;
    for (size_t i=0; i<msg->fFieldCount; i++) {
        const pnNetMsgField* field = &msg->fFields[i];
        switch (field->fType) {
        case kFieldInteger:
        case kFieldFloat:
            SendBasic(bp, data[i], field->fSize, field->fCount);
            break;
        case kFieldString:
            {
                uint16_t len = ST::utf16_buffer::strlen(data[i].fString);
                *(uint16_t*)bp = len;
                bp += sizeof(uint16_t);
                memcpy(bp, data[i].fString, len * sizeof(char16_t));
                bp += len * sizeof(char16_t);
#ifdef COMMDEBUG
                plDebug::Debug("     -> Str: {}",
                               ST::string::from_utf16(data[i].fString, len));
#endif
            }
            break;
        case kFieldVarCount:
            size = field->fSize;
            count = data[i].fUint;
            *(uint32_t*)bp = count;
            bp += sizeof(uint32_t);
#ifdef COMMDEBUG
            plDebug::Debug("     -> Count: {}", count);
#endif
            break;
        case kFieldVarPtr:
        case kFieldRawVarPtr:
            memcpy(bp, data[i].fData, size * count);
            bp += size * count;
#ifdef COMMDEBUG
            {
                ST::string ln = "     -> VarData: ";
                char* sBuf = new char[(3 * (size * count)) + 1];
                for (size_t j=0; j<(size * count); j++)
                    sprintf(sBuf + (3*j), "%02X ", data[i].fData[j]);
                sBuf[3 * (size * count)] = 0;
                ln += sBuf;
                delete[] sBuf;
                plDebug::Debug(ln.c_str());
            }
#endif
            size = 0;
            count = 0;
            break;
        case kFieldData:
        case kFieldPtr:
        case kFieldRawData:
        case kFieldRawPtr:
            memcpy(bp, data[i].fData, field->fSize * field->fCount);
            bp += field->fSize * field->fCount;
#ifdef COMMDEBUG
            {
                ST::string ln = "     -> Data: ";
                char* sBuf = new char[(3 * (field->fSize * field->fCount)) + 1];
                for (size_t j=0; j<(field->fSize * field->fCount); j++)
                    sprintf(sBuf + (3*j), "%02X ", data[i].fData[j]);
                sBuf[3 * (field->fSize * field->fCount)] = 0;
                ln += sBuf;
                delete[] sBuf;
                plDebug::Debug(ln.c_str());
            }
#endif
            break;
        }
    }
    bool result = (send(buffer, bufSize) > 0);
    delete[] buffer;
    return result;
}