Example #1
0
/* plFileInfo */
plFileInfo::plFileInfo(const plFileName &filename)
    : fFileSize(-1), fCreateTime(), fModifyTime(), fFlags()
{
    if (!filename.IsValid())
        return;

#if HS_BUILD_FOR_WIN32
    struct __stat64 info;
    if (_wstat64(filename.AsString().ToWchar(), &info) != 0)
        return;
#else
    struct stat info;
    if (stat(filename.AsString().c_str(), &info) != 0)
        return;
#endif

    fFlags |= kEntryExists;
    fFileSize = info.st_size;
    fCreateTime = info.st_ctime;
    fModifyTime = info.st_mtime;
    if (info.st_mode & S_IFDIR)
        fFlags |= kIsDirectory;
    if (info.st_mode & S_IFREG)
        fFlags |= kIsNormalFile;
}
Example #2
0
bool plFileSystem::SetCWD(const plFileName &cwd)
{
#if HS_BUILD_FOR_WIN32
    return SetCurrentDirectoryW(cwd.AsString().ToWchar());
#else
    return (chdir(cwd.AsString().c_str()) == 0);
#endif
}
Example #3
0
bool plFileSystem::Move(const plFileName &from, const plFileName &to)
{
#if HS_BUILD_FOR_WIN32
    return MoveFileExW(from.AsString().ToWchar(), to.AsString().ToWchar(),
                       MOVEFILE_REPLACE_EXISTING);
#else
    if (!Copy(from, to))
        return false;
    return Unlink(from);
#endif
}
Example #4
0
bool plFileSystem::Unlink(const plFileName &filename)
{
#if HS_BUILD_FOR_WIN32
    plStringBuffer<wchar_t> wfilename = filename.AsString().ToWchar();
    _wchmod(wfilename, S_IWRITE);
    return _wunlink(wfilename) == 0;
#else
    chmod(filename.AsString().c_str(), S_IWRITE);
    return unlink(filename.AsString().c_str()) == 0;
#endif
}
Example #5
0
static bool AutoExportDir(const char* inputDir, const char* outputDir, const plFileName& groupFiles, std::vector<plFileName>& excludeFiles)
{
    bool exportedFile = false;

    char outputFileName[MAX_PATH];
    sprintf(outputFileName, "%s\\Export.prd", outputDir);

    char outputLog[MAX_PATH];
    sprintf(outputLog, "%s\\AutoExport.log", outputDir);
    
    char doneDir[MAX_PATH];
    sprintf(doneDir, "%s\\Done\\", inputDir);
    CreateDirectory(doneDir, NULL);

    // Don't give missing bitmap warnings
    TheManager->SetSilentMode(TRUE);

    std::vector<plFileName> sources = plFileSystem::ListDir(inputDir, "*.max");
    for (auto iter = sources.begin(); iter != sources.end(); ++iter)
    {
        if (IsExcluded(iter->GetFileName(), excludeFiles))
            continue;

        // If we're doing grouped files, and this isn't one, keep looking
        if (groupFiles.IsValid() && groupFiles != iter->GetFileName())
            continue;

        hsUNIXStream log;
        if (log.Open(outputLog, "ab"))
        {
            log.WriteFmt("%s\r\n", iter->GetFileName().c_str());
            log.Close();
        }

        if (GetCOREInterface()->LoadFromFile(iter->AsString().c_str()))
        {
            plFileSystem::Move(*iter, plFileName::Join(inputDir, "Done", iter->GetFileName()));

            GetCOREInterface()->ExportToFile(outputFileName, TRUE);
            exportedFile = true;

            // If we're not doing grouped files, this is it, we exported our one file
            if (!groupFiles.IsValid())
                break;
        }
    }

    return exportedFile;
}
Example #6
0
void pfPatcherWorker::WhitelistFile(const plFileName& file, bool justDownloaded, hsStream* stream)
{
    // if this is a newly downloaded file, fire off a completion callback
    if (justDownloaded && fFileDownloaded)
        fFileDownloaded(file);

    // we want to whitelist our game code, so here we go...
    if (fGameCodeDiscovered) {
        plString ext = file.GetFileExt();
        if (ext.CompareI("pak") == 0 || ext.CompareI("sdl") == 0) {
            if (!stream) {
                stream = new hsUNIXStream;
                stream->Open(file, "rb");
            }

            // if something terrible goes wrong (eg bad encryption), we can exit sanely
            // callback eats stream
            if (!fGameCodeDiscovered(file, stream))
                EndPatch(kNetErrInternalError, "SecurePreloader failed.");
        }
    } else if (stream) {
        // no dad gum memory leaks, m'kay?
        stream->Close();
        delete stream;
    }
}
Example #7
0
plStatusLog::plStatusLog( uint8_t numDisplayLines, const plFileName &filename, uint32_t flags )
{
    fFileHandle = nil;
    fSema = nil;
    fSize = 0;
    fForceLog = false;

    fMaxNumLines = numDisplayLines;
    if (filename.IsValid())
    {
        fFilename = filename;
        fSema = new hsGlobalSemaphore(1, fFilename.AsString().c_str());
    }
    else
    {
        fFilename = "";
        flags |= kDontWriteFile;

        fSema = new hsGlobalSemaphore(1);
    }

    fOrigFlags = fFlags = flags;

    IInit();
}
Example #8
0
static plFileName GetFullPath(const plFileName &filename)
{
    if (filename.StripFileName().IsValid())
        return filename;

    return plFileName::Join("sfx", filename);
}
Example #9
0
static bool InitPhysX()
{
#ifdef HS_BUILD_FOR_WIN32
    plSimulationMgr::Init();
    if (!plSimulationMgr::GetInstance()) {
        if (plFileInfo(s_physXSetupExe).Exists()) {
            // launch the PhysX installer
            SHELLEXECUTEINFOW info;
            memset(&info, 0, sizeof(info));
            info.cbSize = sizeof(info);
            info.lpFile = s_physXSetupExe.AsString().to_wchar();
            info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC;
            ShellExecuteExW(&info);

            // wait for completion
            WaitForSingleObject(info.hProcess, INFINITE);

            // cleanup
            CloseHandle(info.hProcess);
        } else {
            hsMessageBox("You must install PhysX before you can play URU.", "Error", hsMessageBoxNormal, hsMessageBoxIconError);
            return false;
        }
    }
    if (plSimulationMgr::GetInstance()) {
        plSimulationMgr::GetInstance()->Suspend();
        return true;
    } else {
        hsMessageBox("PhysX install failed. You will not be able to play URU.", "Error", hsMessageBoxNormal, hsMessageBoxIconError);
        return false;
    }
#else
    return false;
#endif // HS_BUILD_FOR_WIN32
}
Example #10
0
std::vector<plFileName> plStreamSource::GetListOfNames(const plFileName& dir, const plString& ext)
{
    plFileName sDir = dir.Normalize('/');
    hsAssert(ext.CharAt(0) != '.', "Don't add a dot");
    std::lock_guard<std::mutex> lock(fMutex);

    // loop through all the file data records, and create the list
    std::vector<plFileName> retVal;
    for (auto curData = fFileData.begin(); curData != fFileData.end(); curData++)
    {
        if ((curData->second.fDir.AsString().CompareI(sDir.AsString()) == 0) &&
            (curData->second.fExt.CompareI(ext) == 0))
            retVal.push_back(curData->second.fFilename);
    }

#ifndef PLASMA_EXTERNAL_RELEASE
    // in internal releases, we can use on-disk files if they exist
    // Build the search string as "dir/*.ext"
    std::vector<plFileName> files = plFileSystem::ListDir(sDir, ("*." + ext).c_str());
    for (auto iter = files.begin(); iter != files.end(); ++iter)
    {
        plFileName norm = iter->Normalize('/');
        if (fFileData.find(norm) == fFileData.end()) // we haven't added it yet
            retVal.push_back(norm);
    }
#endif // PLASMA_EXTERNAL_RELEASE

    return retVal;
}
Example #11
0
plFileName plBrowseFolder::GetFolder(const plFileName &startPath, const ST::string &title, HWND hwndOwner)
{
    BROWSEINFOW bi;
    memset(&bi, 0, sizeof(bi));
    ST::wchar_buffer titleW = title.to_wchar();
    ST::wchar_buffer startPathW = startPath.WideString();
    bi.hwndOwner    = hwndOwner;
    bi.lpszTitle    = titleW.data();
    bi.lpfn         = BrowseCallbackProc;
    bi.lParam       = (LPARAM) startPathW.data();

    LPITEMIDLIST iil = SHBrowseForFolderW(&bi);
    plFileName path;
    if (!iil) {
        // Browse failed, or cancel was selected
        path = ST::null;
    } else {
        // Browse succeded.  Get the path.
        wchar_t buffer[MAX_PATH];
        SHGetPathFromIDListW(iil, buffer);
        path = ST::string::from_wchar(buffer);
    }

    // Free the memory allocated by SHBrowseForFolder
    LPMALLOC pMalloc;
    SHGetMalloc(&pMalloc);
    pMalloc->Free(iil);
    pMalloc->Release();

    return path;
}
Example #12
0
static void IAuthThingDownloadCB(ENetError result, void* param, const plFileName& filename, hsStream* writer)
{
    pfPatcherWorker* patcher = static_cast<pfPatcherWorker*>(param);

    if (IS_NET_SUCCESS(result)) {
        PatcherLogGreen("\tDownloaded Legacy File '%s'", filename.AsString().c_str());
        patcher->IssueRequest();

        // Now, we pass our RAM-backed file to the game code handlers. In the main client,
        // this will trickle down and add a new friend to plStreamSource. This should never
        // happen in any other app...
        writer->Rewind();
        patcher->WhitelistFile(filename, true, writer);
    } else {
        PatcherLogRed("\tDownloaded Failed: File '%s'", filename.AsString().c_str());
        patcher->EndPatch(result, filename.AsString());
    }
}
Example #13
0
 pfPatcherStream(pfPatcherWorker* parent, const plFileName& filename, const NetCliFileManifestEntry& entry)
     : fParent(parent), fFlags(entry.flags), fBytesWritten(0)
 {
     // ugh. eap removed the compressed flag in his fail manifests
     if (filename.GetFileExt().CompareI("gz") == 0) {
         fFlags |= pfPatcherWorker::kFlagZipped;
         parent->fTotalBytes += entry.zipSize;
     } else
         parent->fTotalBytes += entry.fileSize;
 }
Example #14
0
plFileName plFileSystem::GetUserDataPath()
{
    static plFileName _userData;

    if (!_userData.IsValid()) {
#if HS_BUILD_FOR_WIN32
        wchar_t path[MAX_PATH];
        if (!SHGetSpecialFolderPathW(NULL, path, CSIDL_LOCAL_APPDATA, TRUE))
            return "";

        _userData = plFileName::Join(plString::FromWchar(path), plProduct::LongName());
#else
        _userData = plFileName::Join(getenv("HOME"), "." + plProduct::LongName());
#endif
        plFileSystem::CreateDir(_userData);
    }

    return _userData;
}
Example #15
0
plKey plAvatarMgr::LoadAvatar(plString name, plString accountName, bool isPlayer, plKey spawnPoint, plAvTask *initialTask,
                              const plString &userStr, const plFileName &clothingFile)
{
    // *** account is currently unused. the idea is that eventually an NPC will
    // *** be able to use a customization account
    plKey result = nullptr;
    plKey requestor = GetKey(); // avatar manager is always the requestor for avatar loads
    plNetClientMgr *netMgr = plNetClientMgr::GetInstance();

    if(netMgr)      // can't clone without the net manager
    {
        hsAssert(!name.IsEmpty(), "name required by LoadPlayer fxn");
        netMgr->DebugMsg("Local: Loading player %s", name.c_str());

        // look up player by key name provided by user.
        // this string search should be replaced with some other method of 
        // avatar selection and key lookup.

        // Get the location for the player first
        plKey playerKey = nullptr;
        const plLocation& globalLoc = plKeyFinder::Instance().FindLocation("GlobalAvatars", name);
        const plLocation& maleLoc = plKeyFinder::Instance().FindLocation("GlobalAvatars", "Male");
        const plLocation& custLoc = plKeyFinder::Instance().FindLocation("CustomAvatars", name);

#ifdef PLASMA_EXTERNAL_RELEASE
        // Try global. If that doesn't work, players default to male.
        // If not a player, try custLoc. If that doesn't work, fall back to male
        const plLocation& loc = (globalLoc.IsValid() ? globalLoc : isPlayer ? maleLoc : custLoc.IsValid() ? custLoc : maleLoc);
#else
        // Try global. If that doesn't work try custom. Otherwise fall back to male
        const plLocation& loc = (globalLoc.IsValid() ? globalLoc : custLoc.IsValid() ? custLoc : maleLoc);
#endif

        if (loc == maleLoc)
            name = "Male";

        if (loc.IsValid())
        {
            plUoid uID(loc, plSceneObject::Index(), name);
            plLoadAvatarMsg *cloneMsg = new plLoadAvatarMsg(uID, requestor, 0, isPlayer, spawnPoint, initialTask, userStr);
            if (clothingFile.IsValid())
            {
                plLoadClothingMsg *clothingMsg = new plLoadClothingMsg(clothingFile);
                cloneMsg->SetTriggerMsg(clothingMsg);
            }
            result =  cloneMsg->GetCloneKey();
            
            // the clone message is automatically addressed to the net client manager
            // we'll receive the message back (or a similar message) when the clone is loaded
            cloneMsg->Send();
        }
    }
    return result;
}
Example #16
0
plFileName plFileName::Join(const plFileName &base, const plFileName &path)
{
    if (!base.IsValid())
        return path;
    if (!path.IsValid())
        return base;

    char last = base.fName.CharAt(base.GetSize() - 1);
    char first = path.fName.CharAt(0);
    if (last != '/' && last != '\\') {
        if (first != '/' && first != '\\') {
            return plString::Format("%s" PATH_SEPARATOR_STR "%s",
                                    base.fName.c_str(), path.fName.c_str());
        }
        return base.fName + path.fName;
    } else if (first != '/' && first != '\\') {
        return base.fName + path.fName;
    }
    // Both have a slash, but we only need one
    return base.fName + path.fName.Substr(1);
}
Example #17
0
void plExportDlgImp::IInitDlg(HWND hDlg)
{
    // Set the client path
    plFileName path = plMaxConfig::GetClientPath(false, true);
    SetDlgItemText(hDlg, IDC_CLIENT_PATH, path.AsString().c_str());

    // Set the preshade button
    CheckDlgButton(hDlg, IDC_PRESHADE_CHECK, fPreshade ? BST_CHECKED : BST_UNCHECKED);
    CheckDlgButton(hDlg, IDC_PHYSICAL_CHECK, fPhysicalsOnly ? BST_CHECKED : BST_UNCHECKED);
    CheckDlgButton(hDlg, IDC_LIGHTMAP_CHECK, fLightMap ? BST_CHECKED : BST_UNCHECKED);

    char buf[256];
    sprintf(buf, "Last export took %d:%02d", fLastExportTime/60, fLastExportTime%60);
    SetDlgItemText(hDlg, IDC_LAST_EXPORT, buf);

    SetWindowPos(hDlg, NULL, fXPos, fYPos, 0, 0, SWP_NOSIZE | SWP_NOZORDER);

    //
    // Get the names of all the pages in this scene and put them in the combo
    //
    HWND hPages = GetDlgItem(hDlg, IDC_PAGE_COMBO);
    ComboBox_AddString(hPages, kAllPages);

    bool foundPage = false;

    CompSet comps;
    GetPagesRecur((plMaxNode*)GetCOREInterface()->GetRootNode(), comps);
    for (CompSet::iterator it = comps.begin(); it != comps.end(); it++)
    {
        const char* page = LocCompGetPage(*it);
        if (page)
        {
            int idx = ComboBox_AddString(hPages, page);
            if (!strcmp(page, fExportPage))
            {
                foundPage = true;
                ComboBox_SetCurSel(hPages, idx);
            }
        }
    }

    if (!foundPage)
    {
        fExportPage[0] = '\0';
        ComboBox_SetCurSel(hPages, 0);
    }

    CheckRadioButton(hDlg, IDC_RADIO_FILE, IDC_RADIO_DIR, IDC_RADIO_FILE);
    IGetRadio(hDlg);

    SetDlgItemTextW(hDlg, IDC_EXPORT_PATH, fExportSourceDir.AsString().ToWchar());
}
Example #18
0
bool plFileSystem::Copy(const plFileName &from, const plFileName &to)
{
#if HS_BUILD_FOR_WIN32
    return CopyFileW(from.AsString().ToWchar(), to.AsString().ToWchar(), FALSE);
#else
    typedef std::unique_ptr<FILE, std::function<int (FILE *)>> _FileRef;

    _FileRef ffrom(Open(from, "rb"), fclose);
    _FileRef fto(Open(to, "wb"), fclose);
    if (!ffrom.get() || !fto.get())
        return false;

    size_t count;
    uint8_t buffer[4096];
    while (!feof(ffrom.get())) {
        count = fread(buffer, sizeof(uint8_t), arrsize(buffer), ffrom.get());
        if (ferror(ffrom.get()))
            return false;
        fwrite(buffer, sizeof(uint8_t), count, fto.get());
    }

    return true;
#endif
}
Example #19
0
std::vector<plFileName> plFileSystem::ListDir(const plFileName &path, const char *pattern)
{
    std::vector<plFileName> contents;

#if HS_BUILD_FOR_WIN32
    if (!pattern || !pattern[0])
        pattern = "*";
    plFileName searchPattern = plFileName::Join(path, pattern);

    WIN32_FIND_DATAW findData;
    HANDLE hFind = FindFirstFileW(searchPattern.AsString().ToWchar(), &findData);
    if (hFind == INVALID_HANDLE_VALUE)
        return contents;

    do {
        if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
            // Should also handle . and ..
            continue;
        }

        contents.push_back(plFileName::Join(path, plString::FromWchar(findData.cFileName)));
    } while (FindNextFileW(hFind, &findData));

    FindClose(hFind);
#else
    DIR *dir = opendir(path.AsString().c_str());
    if (!dir)
        return contents;

    struct dirent *de;
    while (de = readdir(dir)) {
        plFileName dir_name = plFileName::Join(path, de->d_name);
        if (plFileInfo(dir_name).IsDirectory()) {
            // Should also handle . and ..
            continue;
        }

        if (pattern && pattern[0] && fnmatch(pattern, de->d_name, 0))
            contents.push_back(dir_name);
        else if (!pattern || !pattern[0])
            contents.push_back(dir_name);
    }

    closedir(dir);
#endif

    return contents;
}
Example #20
0
bool plStreamSource::InsertFile(const plFileName& filename, hsStream* stream)
{
    plFileName sFilename = filename.Normalize('/');

    std::lock_guard<std::mutex> lock(fMutex);
    if (fFileData.find(sFilename) != fFileData.end())
        return false; // duplicate entry, return failure

    // copy the data over (takes ownership of the stream!)
    fFileData[sFilename].fFilename = sFilename;
    fFileData[sFilename].fDir = sFilename.StripFileName();
    fFileData[sFilename].fExt = sFilename.GetFileExt();
    fFileData[sFilename].fStream = stream;

    return true;
}
Example #21
0
plBufferedFileReader::plBufferedFileReader( const plFileName &path, plAudioCore::ChannelSelect whichChan )
{
    // Init some stuff
    fBufferSize = 0;
    fBuffer = nil;
    fCursor = 0;

    hsAssert( path.IsValid(), "Invalid path specified in plBufferedFileReader" );

    // Ask plAudioFileReader for another reader to get this file
    // Note: have this reader do the chanSelect for us
    plAudioFileReader *reader = plAudioFileReader::CreateReader( path, whichChan );
    if( reader == nil || !reader->IsValid() )
    {
        delete reader;
        IError( "Unable to open file to read in to RAM buffer" );
        return;
    }

    fHeader = reader->GetHeader();

    fBufferSize = reader->GetDataSize();
    fBuffer = new uint8_t[ fBufferSize ];
    //plProfile_NewMem( SndBufferedMem, fBufferSize );
    if( fBuffer == nil )
    {
        delete reader;
        IError( "Unable to allocate RAM buffer" );
        return;
    }

    if( !reader->Read( fBufferSize, fBuffer ) )
    {
        delete reader;
        IError( "Unable to read file into RAM buffer" );
        return;
    }

    // All done!
    delete reader;
}
Example #22
0
std::vector<plFileName> plFileSystem::ListSubdirs(const plFileName &path)
{
    std::vector<plFileName> contents;

#if HS_BUILD_FOR_WIN32
    plFileName searchPattern = plFileName::Join(path, "*");

    WIN32_FIND_DATAW findData;
    HANDLE hFind = FindFirstFileW(searchPattern.AsString().ToWchar(), &findData);
    if (hFind == INVALID_HANDLE_VALUE)
        return contents;

    do {
        if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
            plFileName name = plString::FromWchar(findData.cFileName);
            if (name != "." && name != "..")
                contents.push_back(plFileName::Join(path, name));
        }
    } while (FindNextFileW(hFind, &findData));

    FindClose(hFind);
#else
    DIR *dir = opendir(path.AsString().c_str());
    if (!dir)
        return contents;

    struct dirent *de;
    while (de = readdir(dir)) {
        if (plFileInfo(de->d_name).IsDirectory()) {
            plFileName name = de->d_name;
            if (name != "." && name != "..")
                contents.push_back(plFileName::Join(path, name));
        }
    }

    closedir(dir);
#endif

    return contents;
}
Example #23
0
static void IFileThingDownloadCB(ENetError result, void* param, const plFileName& filename, hsStream* writer)
{
    pfPatcherWorker* patcher = static_cast<pfPatcherWorker*>(param);
    pfPatcherStream* stream = static_cast<pfPatcherStream*>(writer);
    stream->Close();

    if (IS_NET_SUCCESS(result)) {
        PatcherLogGreen("\tDownloaded File '%s'", stream->GetFileName().AsString().c_str());
        patcher->WhitelistFile(stream->GetFileName(), true);
        if (patcher->fSelfPatch && stream->IsSelfPatch())
            patcher->fSelfPatch(stream->GetFileName());
        if (patcher->fRedistUpdateDownloaded && stream->IsRedistUpdate())
            patcher->fRedistUpdateDownloaded(stream->GetFileName());
        patcher->IssueRequest();
    } else {
        PatcherLogRed("\tDownloaded Failed: File '%s'", stream->GetFileName().AsString().c_str());
        stream->Unlink();
        patcher->EndPatch(result, filename.AsString());
    }

    delete stream;
}
Example #24
0
bool pfConsoleEngine::ExecuteFile(const plFileName &fileName)
{
    char    string[ 512 ];
    int     line;

    hsStream* stream = plEncryptedStream::OpenEncryptedFile(fileName);

    if( !stream )
    {
        ISetErrorMsg( "Cannot open given file" );
//      return false;
        /// THIS IS BAD: because of the asserts we throw after this if we return false, a missing
        /// file will throw an assert. This is all well and good except for the age-specific .fni files,
        /// which aren't required to be there and rely on this functionality to test whether the file is
        /// present. Once age-specific .fni's are gone, reinstate the return false here. -mcn
        return true;
    }

    for( line = 1; stream->ReadLn( string, arrsize( string ) ); line++ )
    {
        strncpy( fLastErrorLine, string, arrsize( fLastErrorLine ) );

        if( !RunCommand( string, DummyPrintFn ) )
        {
            snprintf(string, arrsize(string), "Error in console file %s, command line %d: %s",
                     fileName.AsString().c_str(), line, fErrorMsg);
            ISetErrorMsg( string );
            stream->Close();
            delete stream;
            return false;
        }
    }
    stream->Close();
    delete stream;
    fLastErrorLine[ 0 ] = 0;

    return true;
}
Example #25
0
 plResDownloadStream(plOperationProgress* prog, const plFileName& reqFile)
     : fProgress(prog)
 { 
     fIsZipped = reqFile.GetFileExt().CompareI("gz") == 0;
 }
Example #26
0
BOOL plExportDlgImp::DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_INITDIALOG:
        IInitDlg(hDlg);
        return TRUE;

    case WM_COMMAND:
        {
            int cmd = HIWORD(wParam);
            int resID = LOWORD(wParam);

            if (cmd == BN_CLICKED)
            {
                if (resID == IDCANCEL)
                {
                    IDestroy();
                    return TRUE;
                }
                else if (resID == IDC_EXPORT)
                {
                    IDoExport();
                    return TRUE;
                }
                else if (resID == IDC_PRESHADE_CHECK)
                {
                    fPreshade = (IsDlgButtonChecked(hDlg, IDC_PRESHADE_CHECK) == BST_CHECKED);
                    return TRUE;
                }
                else if (resID == IDC_PHYSICAL_CHECK)
                {
                    fPhysicalsOnly = (IsDlgButtonChecked(hDlg, IDC_PHYSICAL_CHECK) == BST_CHECKED);
                    return TRUE;
                }
                else if (resID == IDC_LIGHTMAP_CHECK)
                {
                    fLightMap = (IsDlgButtonChecked(hDlg, IDC_LIGHTMAP_CHECK) == BST_CHECKED);
                    return TRUE;
                }
                else if (resID == IDC_DIR)
                {
                    // Get a new client path
                    plFileName path = plMaxConfig::GetClientPath(true);
                    if (path.IsValid())
                        SetDlgItemText(hDlg, IDC_CLIENT_PATH, path.AsString().c_str());
                    return TRUE;
                }
                else if (resID == IDC_RADIO_FILE || resID == IDC_RADIO_DIR)
                {
                    IGetRadio(hDlg);
                    return TRUE;
                }
                else if (resID == IDC_BROWSE_EXPORT)
                {
                    fExportSourceDir = plBrowseFolder::GetFolder(fExportSourceDir,
                                              "Choose the source directory",
                                              hDlg);
                    SetDlgItemTextW(hDlg, IDC_EXPORT_PATH, fExportSourceDir.AsString().ToWchar());
                    return TRUE;
                }
            }
            else if (cmd == CBN_SELCHANGE && resID == IDC_PAGE_COMBO)
            {
                int sel = ComboBox_GetCurSel((HWND)lParam);
                // If the user selected a page, save it
                if (sel != 0 && sel != CB_ERR)
                    ComboBox_GetText((HWND)lParam, fExportPage, sizeof(fExportPage));
                // Else, clear it (export all pages)
                else
                    fExportPage[0] = '\0';
                return TRUE;
            }
        }
        break;
    }

    return FALSE;
}
Example #27
0
 void IGetAgeName(const plFileName& path)
 {
     fAgeName = path.GetFileNameNoExt();
 }
Example #28
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 #29
0
void WritePythonFile(const plFileName &fileName, const plFileName &path, hsStream *s)
{
    hsUNIXStream pyStream, glueStream;
    plFileName filePath;
    ST_ssize_t filestart = fileName.AsString().find_last('.');
    if (filestart >= 0)
        filePath = fileName.AsString().substr(filestart+1);
    else
        filePath = fileName;
    filePath = plFileName::Join(path, filePath + ".py");

    if (!pyStream.Open(filePath) || !glueStream.Open(glueFile))
    {
        ST::printf("Unable to open path {}, ", filePath);
        return;
    }

    ST::printf("==Packing {}, ", fileName);

    pyStream.FastFwd();
    uint32_t pyFileSize = pyStream.GetPosition();
    pyStream.Rewind();

    glueStream.FastFwd();
    uint32_t glueFileSize = glueStream.GetPosition();
    glueStream.Rewind();

    uint32_t totalSize = pyFileSize + glueFileSize + 2;

    char *code = new char[totalSize];

    uint32_t amountRead = pyStream.Read(pyFileSize, code);
    hsAssert(amountRead == pyFileSize, "Bad read");

    code[pyFileSize] = '\n';

    amountRead = glueStream.Read(glueFileSize, code+pyFileSize+1);
    hsAssert(amountRead == glueFileSize, "Bad read");

    code[totalSize-1] = '\0';

    // remove the CRs, they seem to give Python heartburn
    int k = 0;
    for (int i = 0; i < totalSize; i++)
    {
        if (code[i] != '\r')    // is it not a CR?
            code[k++] = code[i];
        // else
        //   skip the CRs
    }

    // import the module first, to make packages work correctly
    PyImport_ImportModule(fileName.AsString().c_str());
    PyObject* pythonCode = PythonInterface::CompileString(code, fileName);
    if (pythonCode)
    {
        // we need to find out if this is PythonFile module
        // create a module name... with the '.' as an X
        // and create a python file name that is without the ".py"
        PyObject* fModule = PythonInterface::CreateModule(fileName.AsString().c_str());
        // run the code
        if (PythonInterface::RunPYC(pythonCode, fModule) )
        {
    // set the name of the file (in the global dictionary of the module)
            PyObject* dict = PyModule_GetDict(fModule);
            PyObject* pfilename = PyString_FromString(fileName.AsString().c_str());
            PyDict_SetItemString(dict, "glue_name", pfilename);
    // next we need to:
    //  - create instance of class
            PyObject* getID = PythonInterface::GetModuleItem("glue_getBlockID",fModule);
            bool foundID = false;
            if ( getID!=nil && PyCallable_Check(getID) )
            {
                PyObject* id = PyObject_CallFunction(getID,nil);
                if ( id && PyInt_Check(id) )
                    foundID = true;
            }
            if ( foundID == false )     // then there was an error or no ID or somethin'
            {
                // oops, this is not a PythonFile modifier
                // re-read the source and compile it without the glue code this time
                pyStream.Rewind();
                amountRead = pyStream.Read(pyFileSize, code);
                hsAssert(amountRead == pyFileSize, "Bad read");
                code[amountRead] = '\n';
                code[amountRead+1] = '\0';
                k = 0;
                int len = strlen(code)+1;
                for (int i = 0; i < len; i++)
                {
                    if (code[i] != '\r')    // is it not a CR?
                        code[k++] = code[i];
                    // else
                    //   skip the CRs
                }
                pythonCode = PythonInterface::CompileString(code, fileName);
                hsAssert(pythonCode,"Not sure why this didn't compile the second time???");
                fputs("an import file ", stdout);
            }
            else
                fputs("a PythonFile modifier(tm) ", stdout);
        }
        else
        {
            fputs("......blast! Error during run-code!\n", stdout);

            char* errmsg;
            int chars_read = PythonInterface::getOutputAndReset(&errmsg);
            if (chars_read > 0)
            {
                puts(errmsg);
            }
        }
    }

    // make sure that we have code to save
    if (pythonCode)
    {
        int32_t size;
        char* pycode;
        PythonInterface::DumpObject(pythonCode,&pycode,&size);

        fputc('\n', stdout);
        // print any message after each module
        char* errmsg;
        int chars_read = PythonInterface::getOutputAndReset(&errmsg);
        if (chars_read > 0)
        {
            puts(errmsg);
        }
        s->WriteLE32(size);
        s->Write(size, pycode);
    }
    else
    {
        fputs("......blast! Compile error!\n", stdout);
        s->WriteLE32(0);

        PyErr_Print();
        PyErr_Clear();

        char* errmsg;
        int chars_read = PythonInterface::getOutputAndReset(&errmsg);
        if (chars_read > 0)
        {
            puts(errmsg);
        }
    }

    delete [] code;

    pyStream.Close();
    glueStream.Close();
}