<commit_before>#pragma once

#ifndef MP1_USE_BOO
#define MP1_USE_BOO 0
#endif
#ifndef MP1_VARIABLE_DELTA_TIME
#define MP1_VARIABLE_DELTA_TIME 1
#endif

#include "IMain.hpp"
#include "CTweaks.hpp"
#include "CPlayMovie.hpp"
#include "IOStreams.hpp"
#include "CBasics.hpp"
#include "CMemoryCardSys.hpp"
#include "CResFactory.hpp"
#include "CSimplePool.hpp"
#include "Character/CAssetFactory.hpp"
#include "World/CAi.hpp"
#include "CGameState.hpp"
#include "CInGameTweakManager.hpp"
#include "Particle/CElementGen.hpp"
#include "Character/CAnimData.hpp"
#include "Particle/CDecalManager.hpp"
#include "Particle/CGenDescription.hpp"
#include "Graphics/CBooRenderer.hpp"
#include "Audio/CAudioSys.hpp"
#include "Input/CInputGenerator.hpp"
#include "GuiSys/CGuiSys.hpp"
#include "CIOWinManager.hpp"
#include "GuiSys/CSplashScreen.hpp"
#include "CMainFlow.hpp"
#include "GuiSys/CConsoleOutputWindow.hpp"
#include "GuiSys/CErrorOutputWindow.hpp"
#include "GuiSys/CTextParser.hpp"
#include "CAudioStateWin.hpp"
#include "GameGlobalObjects.hpp"
#include "CArchitectureQueue.hpp"
#include "CTimeProvider.hpp"
#include "GuiSys/CTextExecuteBuffer.hpp"
#include "DataSpec/DNAMP1/Tweaks/CTweakPlayer.hpp"
#include "DataSpec/DNAMP1/Tweaks/CTweakGame.hpp"
#include "World/CScriptMazeNode.hpp"
#include "hecl/Console.hpp"

struct DiscordUser;

namespace urde {
class IFactory;
class IObjectStore;

namespace MP1 {
class CMain;

class CGameGlobalObjects {
  friend class CMain;

  std::unique_ptr<CSimplePool> m_gameSimplePool;
  std::unique_ptr<CResFactory> m_gameResFactory;
  std::unique_ptr<CMemoryCardSys> x0_memoryCardSys;
  IFactory* x4_resFactory;
  CSimplePool* xcc_simplePool;
  CCharacterFactoryBuilder xec_charFactoryBuilder;
  CAiFuncMap x110_aiFuncMap;
  std::unique_ptr<CGameState> x134_gameState;
  TLockedToken<CStringTable> x13c_mainStringTable;
  CInGameTweakManager x150_tweakManager;
  std::unique_ptr<IRenderer> m_renderer;
  TLockedToken<CTextureCache> m_textureCache;

  void LoadStringTable() {
    x13c_mainStringTable = g_SimplePool->GetObj("STRG_Main");
    g_MainStringTable = x13c_mainStringTable.GetObj();
  }
  void LoadTextureCache() {
    m_textureCache = g_SimplePool->GetObj("TextureCache"sv);
    g_TextureCache = m_textureCache.GetObj();
  }
  void AddPaksAndFactories();
  static IRenderer* AllocateRenderer(IObjectStore& store, IFactory& resFactory) {
    g_Renderer = new CBooRenderer(store, resFactory);
    return g_Renderer;
  }

public:
  CGameGlobalObjects(IFactory* resFactory, CSimplePool* objStore)
  : x4_resFactory(resFactory), xcc_simplePool(objStore) {
    if (!x4_resFactory) {
      m_gameResFactory = std::make_unique<CResFactory>();
      x4_resFactory = m_gameResFactory.get();
    }
    if (!xcc_simplePool) {
      m_gameSimplePool = std::make_unique<CSimplePool>(*x4_resFactory);
      xcc_simplePool = m_gameSimplePool.get();
    }
    g_ResFactory = x4_resFactory;
    g_SimplePool = xcc_simplePool;
    g_CharFactoryBuilder = &xec_charFactoryBuilder;
    g_AiFuncMap = &x110_aiFuncMap;
    x134_gameState = std::make_unique<CGameState>();
    g_GameState = x134_gameState.get();
    g_TweakManager = &x150_tweakManager;
  }

  ~CGameGlobalObjects();

  void PostInitialize() {
    AddPaksAndFactories();
    LoadTextureCache();
    LoadStringTable();
    m_renderer.reset(AllocateRenderer(*xcc_simplePool, *x4_resFactory));
    CEnvFxManager::Initialize();
    CScriptMazeNode::LoadMazeSeeds();
  }

  void ResetGameState() {
    x134_gameState = std::make_unique<CGameState>();
    g_GameState = x134_gameState.get();
  }

  void StreamInGameState(CBitStreamReader& stream, u32 saveIdx) {
    x134_gameState = std::make_unique<CGameState>(stream, saveIdx);
    g_GameState = x134_gameState.get();
  }
};

#if MP1_USE_BOO
class CGameArchitectureSupport : public boo::IWindowCallback
#else
class CGameArchitectureSupport
#endif
{
  friend class CMain;
  CMain& m_parent;
  CArchitectureQueue x4_archQueue;
  CAudioSys x0_audioSys;
  CInputGenerator x30_inputGenerator;
  CGuiSys x44_guiSys;
  CIOWinManager x58_ioWinManager;
  s32 x78_gameFrameCount = 0;

  enum class EAudioLoadStatus { Loading, Loaded, Uninitialized };
  EAudioLoadStatus x88_audioLoadStatus = EAudioLoadStatus::Uninitialized;
  std::vector<TToken<CAudioGroupSet>> x8c_pendingAudioGroups;

  boo::SWindowRect m_windowRect;
  bool m_rectIsDirty;

  void destroyed() { x4_archQueue.Push(MakeMsg::CreateRemoveAllIOWins(EArchMsgTarget::IOWinManager)); }

  void resized(const boo::SWindowRect& rect) {
    m_windowRect = rect;
    m_rectIsDirty = true;
  }

public:
  CGameArchitectureSupport(CMain& parent, boo::IAudioVoiceEngine* voiceEngine, amuse::IBackendVoiceAllocator& backend);
  ~CGameArchitectureSupport();

  void mouseDown(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mods) {
    x30_inputGenerator.mouseDown(coord, button, mods);
  }
  void mouseUp(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mods) {
    x30_inputGenerator.mouseUp(coord, button, mods);
  }
  void mouseMove(const boo::SWindowCoord& coord) { x30_inputGenerator.mouseMove(coord); }
  void scroll(const boo::SWindowCoord& coord, const boo::SScrollDelta& scroll) {
    x30_inputGenerator.scroll(coord, scroll);
  }
  void charKeyDown(unsigned long charCode, boo::EModifierKey mods, bool isRepeat);
  void charKeyUp(unsigned long charCode, boo::EModifierKey mods) { x30_inputGenerator.charKeyUp(charCode, mods); }
  void specialKeyDown(boo::ESpecialKey key, boo::EModifierKey mods, bool isRepeat);

  void specialKeyUp(boo::ESpecialKey key, boo::EModifierKey mods);
  void modKeyDown(boo::EModifierKey mod, bool isRepeat) { x30_inputGenerator.modKeyDown(mod, isRepeat); }
  void modKeyUp(boo::EModifierKey mod) { x30_inputGenerator.modKeyUp(mod); }

  void PreloadAudio();
  bool LoadAudio();
  void UnloadAudio();
  void UpdateTicks(float dt);
  void Update(float dt);
  void Draw();

  bool isRectDirty() const { return m_rectIsDirty; }
  const boo::SWindowRect& getWindowRect() {
    m_rectIsDirty = false;
    return m_windowRect;
  }

  CIOWinManager& GetIOWinManager() { return x58_ioWinManager; }
};

#if MP1_USE_BOO
class CMain : public boo::IApplicationCallback,
              public IMain
#else
class CMain : public IMain
#endif
{
  friend class CGameArchitectureSupport;
#if MP1_USE_BOO
  boo::IWindow* mainWindow;
  int appMain(boo::IApplication* app);
  void appQuitting(boo::IApplication*) { xe8_b24_finished = true; }
  void appFilesOpen(boo::IApplication*, const std::vector<std::string>& paths) {
    fmt::print(stderr, fmt("OPENING: "));
    for (const std::string& path : paths)
      fprintf(stderr, "%s ", path.c_str());
    fprintf(stderr, "\n");
  }
#endif
private:
  struct BooSetter {
    BooSetter(boo::IGraphicsDataFactory* factory, boo::IGraphicsCommandQueue* cmdQ,
              const boo::ObjToken<boo::ITextureR>& spareTex);
  } m_booSetter;

  // CMemorySys x6c_memSys;
  CTweaks x70_tweaks;
  EGameplayResult xe4_gameplayResult;

  /* urde addition: these are simply initialized along with everything else */
  CGameGlobalObjects x128_globalObjects;

  EFlowState x12c_flowState = EFlowState::Default;

  u32 x130_[10] = {1000000};

  union {
    struct {
      bool x160_24_finished : 1;
      bool x160_25_mfGameBuilt : 1;
      bool x160_26_screenFading : 1;
      bool x160_27_ : 1;
      bool x160_28_manageCard : 1;
      bool x160_29_ : 1;
      bool x160_30_ : 1;
      bool x160_31_cardBusy : 1;
      bool x161_24_gameFrameDrawn : 1;
    };
    u16 _dummy = 0;
  };

  std::unique_ptr<CGameArchitectureSupport> x164_archSupport;

  boo::IWindow* m_mainWindow = nullptr;

  hecl::CVarManager* m_cvarMgr = nullptr;
  std::unique_ptr<hecl::Console> m_console;
  // Warmup state
  std::vector<SObjectTag> m_warmupTags;
  std::vector<SObjectTag>::iterator m_warmupIt;
  bool m_needsWarmupClear = false;
  bool m_loadedPersistentResources = false;
  bool m_doQuit = false;

#if MP1_VARIABLE_DELTA_TIME
  bool m_firstFrame = true;
  using delta_clock = std::chrono::high_resolution_clock;
  std::chrono::time_point<delta_clock> m_prevFrameTime;
#endif

  void InitializeSubsystems();
  static void InitializeDiscord();
  static void ShutdownDiscord();
  static void HandleDiscordReady(const DiscordUser* request);
  static void HandleDiscordDisconnected(int errorCode, const char* message);
  static void HandleDiscordErrored(int errorCode, const char* message);

public:
  CMain(IFactory* resFactory, CSimplePool* resStore, boo::IGraphicsDataFactory* gfxFactory,
        boo::IGraphicsCommandQueue* cmdQ, const boo::ObjToken<boo::ITextureR>& spareTex);
  void RegisterResourceTweaks();
  void AddWorldPaks();
  void AddOverridePaks();
  void ResetGameState();
  void StreamNewGameState(CBitStreamReader&, u32 idx);
  void RefreshGameState();
  void CheckTweakManagerDebugOptions() {}
  void SetMFGameBuilt(bool b) { x160_25_mfGameBuilt = b; }
  void SetScreenFading(bool b) { x160_26_screenFading = b; }
  bool GetScreenFading() const { return x160_26_screenFading; }

  static void UpdateDiscordPresence(CAssetId worldSTRG = {});

  // int RsMain(int argc, const boo::SystemChar* argv[]);
  void Init(const hecl::Runtime::FileStoreManager& storeMgr, hecl::CVarManager* cvarManager, boo::IWindow* window,
            boo::IAudioVoiceEngine* voiceEngine, amuse::IBackendVoiceAllocator& backend) override;
  void WarmupShaders() override;
  bool Proc() override;
  void Draw() override;
  void Shutdown() override;
  boo::IWindow* GetMainWindow() const override;

  void MemoryCardInitializePump();

  bool CheckReset() const { return m_doQuit; }
  bool CheckTerminate() const { return m_doQuit; }
  void DrawDebugMetrics(double, CStopwatch&) {}
  void DoPredrawMetrics() {}
  void FillInAssetIDs();
  bool LoadAudio();
  void ShutdownSubsystems();
  EGameplayResult GetGameplayResult() const { return xe4_gameplayResult; }
  void SetGameplayResult(EGameplayResult wl) { xe4_gameplayResult = wl; }
  void SetManageCard(bool v) { x160_28_manageCard = v; }
  bool GetCardBusy() const { return x160_31_cardBusy; }
  void SetCardBusy(bool v) { x160_31_cardBusy = v; }
  void SetGameFrameDrawn() { x161_24_gameFrameDrawn = true; }
  static void EnsureWorldPaksReady();
  static void EnsureWorldPakReady(CAssetId mlvl);

  EFlowState GetFlowState() const override { return x12c_flowState; }
  void SetFlowState(EFlowState s) override { x12c_flowState = s; }

  void SetX30(bool v) { x160_30_ = v; }

  CGameArchitectureSupport* GetArchSupport() const { return x164_archSupport.get(); }

  size_t GetExpectedIdSize() const override { return sizeof(u32); }
  void quit(hecl::Console*, const std::vector<std::string>&) { m_doQuit = true; }
  void Give(hecl::Console*, const std::vector<std::string>&);
  void Remove(hecl::Console*, const std::vector<std::string>&);
  void God(hecl::Console*, const std::vector<std::string>&);
  void Teleport(hecl::Console*, const std::vector<std::string>&);
  void ListWorlds(hecl::Console*, const std::vector<std::string>&);
  void Warp(hecl::Console*, const std::vector<std::string>&);
  hecl::Console* Console() const override { return m_console.get(); }

  int m_warpWorldIdx = -1;
  TAreaId m_warpAreaId = 0;
  u64 m_warpLayerBits = 0;
  std::vector<TEditorId> m_warpMemoryRelays;
};

} // namespace MP1
} // namespace urde
<commit_msg>Disable variable delta time<commit_after>#pragma once

#ifndef MP1_USE_BOO
#define MP1_USE_BOO 0
#endif
#ifndef MP1_VARIABLE_DELTA_TIME
#define MP1_VARIABLE_DELTA_TIME 0
#endif

#include "IMain.hpp"
#include "CTweaks.hpp"
#include "CPlayMovie.hpp"
#include "IOStreams.hpp"
#include "CBasics.hpp"
#include "CMemoryCardSys.hpp"
#include "CResFactory.hpp"
#include "CSimplePool.hpp"
#include "Character/CAssetFactory.hpp"
#include "World/CAi.hpp"
#include "CGameState.hpp"
#include "CInGameTweakManager.hpp"
#include "Particle/CElementGen.hpp"
#include "Character/CAnimData.hpp"
#include "Particle/CDecalManager.hpp"
#include "Particle/CGenDescription.hpp"
#include "Graphics/CBooRenderer.hpp"
#include "Audio/CAudioSys.hpp"
#include "Input/CInputGenerator.hpp"
#include "GuiSys/CGuiSys.hpp"
#include "CIOWinManager.hpp"
#include "GuiSys/CSplashScreen.hpp"
#include "CMainFlow.hpp"
#include "GuiSys/CConsoleOutputWindow.hpp"
#include "GuiSys/CErrorOutputWindow.hpp"
#include "GuiSys/CTextParser.hpp"
#include "CAudioStateWin.hpp"
#include "GameGlobalObjects.hpp"
#include "CArchitectureQueue.hpp"
#include "CTimeProvider.hpp"
#include "GuiSys/CTextExecuteBuffer.hpp"
#include "DataSpec/DNAMP1/Tweaks/CTweakPlayer.hpp"
#include "DataSpec/DNAMP1/Tweaks/CTweakGame.hpp"
#include "World/CScriptMazeNode.hpp"
#include "hecl/Console.hpp"

struct DiscordUser;

namespace urde {
class IFactory;
class IObjectStore;

namespace MP1 {
class CMain;

class CGameGlobalObjects {
  friend class CMain;

  std::unique_ptr<CSimplePool> m_gameSimplePool;
  std::unique_ptr<CResFactory> m_gameResFactory;
  std::unique_ptr<CMemoryCardSys> x0_memoryCardSys;
  IFactory* x4_resFactory;
  CSimplePool* xcc_simplePool;
  CCharacterFactoryBuilder xec_charFactoryBuilder;
  CAiFuncMap x110_aiFuncMap;
  std::unique_ptr<CGameState> x134_gameState;
  TLockedToken<CStringTable> x13c_mainStringTable;
  CInGameTweakManager x150_tweakManager;
  std::unique_ptr<IRenderer> m_renderer;
  TLockedToken<CTextureCache> m_textureCache;

  void LoadStringTable() {
    x13c_mainStringTable = g_SimplePool->GetObj("STRG_Main");
    g_MainStringTable = x13c_mainStringTable.GetObj();
  }
  void LoadTextureCache() {
    m_textureCache = g_SimplePool->GetObj("TextureCache"sv);
    g_TextureCache = m_textureCache.GetObj();
  }
  void AddPaksAndFactories();
  static IRenderer* AllocateRenderer(IObjectStore& store, IFactory& resFactory) {
    g_Renderer = new CBooRenderer(store, resFactory);
    return g_Renderer;
  }

public:
  CGameGlobalObjects(IFactory* resFactory, CSimplePool* objStore)
  : x4_resFactory(resFactory), xcc_simplePool(objStore) {
    if (!x4_resFactory) {
      m_gameResFactory = std::make_unique<CResFactory>();
      x4_resFactory = m_gameResFactory.get();
    }
    if (!xcc_simplePool) {
      m_gameSimplePool = std::make_unique<CSimplePool>(*x4_resFactory);
      xcc_simplePool = m_gameSimplePool.get();
    }
    g_ResFactory = x4_resFactory;
    g_SimplePool = xcc_simplePool;
    g_CharFactoryBuilder = &xec_charFactoryBuilder;
    g_AiFuncMap = &x110_aiFuncMap;
    x134_gameState = std::make_unique<CGameState>();
    g_GameState = x134_gameState.get();
    g_TweakManager = &x150_tweakManager;
  }

  ~CGameGlobalObjects();

  void PostInitialize() {
    AddPaksAndFactories();
    LoadTextureCache();
    LoadStringTable();
    m_renderer.reset(AllocateRenderer(*xcc_simplePool, *x4_resFactory));
    CEnvFxManager::Initialize();
    CScriptMazeNode::LoadMazeSeeds();
  }

  void ResetGameState() {
    x134_gameState = std::make_unique<CGameState>();
    g_GameState = x134_gameState.get();
  }

  void StreamInGameState(CBitStreamReader& stream, u32 saveIdx) {
    x134_gameState = std::make_unique<CGameState>(stream, saveIdx);
    g_GameState = x134_gameState.get();
  }
};

#if MP1_USE_BOO
class CGameArchitectureSupport : public boo::IWindowCallback
#else
class CGameArchitectureSupport
#endif
{
  friend class CMain;
  CMain& m_parent;
  CArchitectureQueue x4_archQueue;
  CAudioSys x0_audioSys;
  CInputGenerator x30_inputGenerator;
  CGuiSys x44_guiSys;
  CIOWinManager x58_ioWinManager;
  s32 x78_gameFrameCount = 0;

  enum class EAudioLoadStatus { Loading, Loaded, Uninitialized };
  EAudioLoadStatus x88_audioLoadStatus = EAudioLoadStatus::Uninitialized;
  std::vector<TToken<CAudioGroupSet>> x8c_pendingAudioGroups;

  boo::SWindowRect m_windowRect;
  bool m_rectIsDirty;

  void destroyed() { x4_archQueue.Push(MakeMsg::CreateRemoveAllIOWins(EArchMsgTarget::IOWinManager)); }

  void resized(const boo::SWindowRect& rect) {
    m_windowRect = rect;
    m_rectIsDirty = true;
  }

public:
  CGameArchitectureSupport(CMain& parent, boo::IAudioVoiceEngine* voiceEngine, amuse::IBackendVoiceAllocator& backend);
  ~CGameArchitectureSupport();

  void mouseDown(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mods) {
    x30_inputGenerator.mouseDown(coord, button, mods);
  }
  void mouseUp(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mods) {
    x30_inputGenerator.mouseUp(coord, button, mods);
  }
  void mouseMove(const boo::SWindowCoord& coord) { x30_inputGenerator.mouseMove(coord); }
  void scroll(const boo::SWindowCoord& coord, const boo::SScrollDelta& scroll) {
    x30_inputGenerator.scroll(coord, scroll);
  }
  void charKeyDown(unsigned long charCode, boo::EModifierKey mods, bool isRepeat);
  void charKeyUp(unsigned long charCode, boo::EModifierKey mods) { x30_inputGenerator.charKeyUp(charCode, mods); }
  void specialKeyDown(boo::ESpecialKey key, boo::EModifierKey mods, bool isRepeat);

  void specialKeyUp(boo::ESpecialKey key, boo::EModifierKey mods);
  void modKeyDown(boo::EModifierKey mod, bool isRepeat) { x30_inputGenerator.modKeyDown(mod, isRepeat); }
  void modKeyUp(boo::EModifierKey mod) { x30_inputGenerator.modKeyUp(mod); }

  void PreloadAudio();
  bool LoadAudio();
  void UnloadAudio();
  void UpdateTicks(float dt);
  void Update(float dt);
  void Draw();

  bool isRectDirty() const { return m_rectIsDirty; }
  const boo::SWindowRect& getWindowRect() {
    m_rectIsDirty = false;
    return m_windowRect;
  }

  CIOWinManager& GetIOWinManager() { return x58_ioWinManager; }
};

#if MP1_USE_BOO
class CMain : public boo::IApplicationCallback,
              public IMain
#else
class CMain : public IMain
#endif
{
  friend class CGameArchitectureSupport;
#if MP1_USE_BOO
  boo::IWindow* mainWindow;
  int appMain(boo::IApplication* app);
  void appQuitting(boo::IApplication*) { xe8_b24_finished = true; }
  void appFilesOpen(boo::IApplication*, const std::vector<std::string>& paths) {
    fmt::print(stderr, fmt("OPENING: "));
    for (const std::string& path : paths)
      fprintf(stderr, "%s ", path.c_str());
    fprintf(stderr, "\n");
  }
#endif
private:
  struct BooSetter {
    BooSetter(boo::IGraphicsDataFactory* factory, boo::IGraphicsCommandQueue* cmdQ,
              const boo::ObjToken<boo::ITextureR>& spareTex);
  } m_booSetter;

  // CMemorySys x6c_memSys;
  CTweaks x70_tweaks;
  EGameplayResult xe4_gameplayResult;

  /* urde addition: these are simply initialized along with everything else */
  CGameGlobalObjects x128_globalObjects;

  EFlowState x12c_flowState = EFlowState::Default;

  u32 x130_[10] = {1000000};

  union {
    struct {
      bool x160_24_finished : 1;
      bool x160_25_mfGameBuilt : 1;
      bool x160_26_screenFading : 1;
      bool x160_27_ : 1;
      bool x160_28_manageCard : 1;
      bool x160_29_ : 1;
      bool x160_30_ : 1;
      bool x160_31_cardBusy : 1;
      bool x161_24_gameFrameDrawn : 1;
    };
    u16 _dummy = 0;
  };

  std::unique_ptr<CGameArchitectureSupport> x164_archSupport;

  boo::IWindow* m_mainWindow = nullptr;

  hecl::CVarManager* m_cvarMgr = nullptr;
  std::unique_ptr<hecl::Console> m_console;
  // Warmup state
  std::vector<SObjectTag> m_warmupTags;
  std::vector<SObjectTag>::iterator m_warmupIt;
  bool m_needsWarmupClear = false;
  bool m_loadedPersistentResources = false;
  bool m_doQuit = false;

#if MP1_VARIABLE_DELTA_TIME
  bool m_firstFrame = true;
  using delta_clock = std::chrono::high_resolution_clock;
  std::chrono::time_point<delta_clock> m_prevFrameTime;
#endif

  void InitializeSubsystems();
  static void InitializeDiscord();
  static void ShutdownDiscord();
  static void HandleDiscordReady(const DiscordUser* request);
  static void HandleDiscordDisconnected(int errorCode, const char* message);
  static void HandleDiscordErrored(int errorCode, const char* message);

public:
  CMain(IFactory* resFactory, CSimplePool* resStore, boo::IGraphicsDataFactory* gfxFactory,
        boo::IGraphicsCommandQueue* cmdQ, const boo::ObjToken<boo::ITextureR>& spareTex);
  void RegisterResourceTweaks();
  void AddWorldPaks();
  void AddOverridePaks();
  void ResetGameState();
  void StreamNewGameState(CBitStreamReader&, u32 idx);
  void RefreshGameState();
  void CheckTweakManagerDebugOptions() {}
  void SetMFGameBuilt(bool b) { x160_25_mfGameBuilt = b; }
  void SetScreenFading(bool b) { x160_26_screenFading = b; }
  bool GetScreenFading() const { return x160_26_screenFading; }

  static void UpdateDiscordPresence(CAssetId worldSTRG = {});

  // int RsMain(int argc, const boo::SystemChar* argv[]);
  void Init(const hecl::Runtime::FileStoreManager& storeMgr, hecl::CVarManager* cvarManager, boo::IWindow* window,
            boo::IAudioVoiceEngine* voiceEngine, amuse::IBackendVoiceAllocator& backend) override;
  void WarmupShaders() override;
  bool Proc() override;
  void Draw() override;
  void Shutdown() override;
  boo::IWindow* GetMainWindow() const override;

  void MemoryCardInitializePump();

  bool CheckReset() const { return m_doQuit; }
  bool CheckTerminate() const { return m_doQuit; }
  void DrawDebugMetrics(double, CStopwatch&) {}
  void DoPredrawMetrics() {}
  void FillInAssetIDs();
  bool LoadAudio();
  void ShutdownSubsystems();
  EGameplayResult GetGameplayResult() const { return xe4_gameplayResult; }
  void SetGameplayResult(EGameplayResult wl) { xe4_gameplayResult = wl; }
  void SetManageCard(bool v) { x160_28_manageCard = v; }
  bool GetCardBusy() const { return x160_31_cardBusy; }
  void SetCardBusy(bool v) { x160_31_cardBusy = v; }
  void SetGameFrameDrawn() { x161_24_gameFrameDrawn = true; }
  static void EnsureWorldPaksReady();
  static void EnsureWorldPakReady(CAssetId mlvl);

  EFlowState GetFlowState() const override { return x12c_flowState; }
  void SetFlowState(EFlowState s) override { x12c_flowState = s; }

  void SetX30(bool v) { x160_30_ = v; }

  CGameArchitectureSupport* GetArchSupport() const { return x164_archSupport.get(); }

  size_t GetExpectedIdSize() const override { return sizeof(u32); }
  void quit(hecl::Console*, const std::vector<std::string>&) { m_doQuit = true; }
  void Give(hecl::Console*, const std::vector<std::string>&);
  void Remove(hecl::Console*, const std::vector<std::string>&);
  void God(hecl::Console*, const std::vector<std::string>&);
  void Teleport(hecl::Console*, const std::vector<std::string>&);
  void ListWorlds(hecl::Console*, const std::vector<std::string>&);
  void Warp(hecl::Console*, const std::vector<std::string>&);
  hecl::Console* Console() const override { return m_console.get(); }

  int m_warpWorldIdx = -1;
  TAreaId m_warpAreaId = 0;
  u64 m_warpLayerBits = 0;
  std::vector<TEditorId> m_warpMemoryRelays;
};

} // namespace MP1
} // namespace urde
<|endoftext|>


<commit_before>//圆柱体表面积

#include <stdio.h>
#include <math.h>
int main(){
	const double pi = acos(-1.0);
	double r,h,s1,s2,s;
	scanf("%lf%lf",&r,&h);
	s1 = pi*r*r;
	s2 = 2*pi*r*h;
	s=s1*2.0+s2;
	printf("Area = %.3f\n",s);
	return 0;
}

//三位数反转

#include <stdio.h>
int main(){
	int n;
	scanf("%d",&n);
	printf("%d%d%d",n%10,n/10%10,n/100);
	return 0;
}

//三位数反转（避开25写成025的情况）

#include <stdio.h>
int main(){
	int n;
	scanf("%d",&n);
	printf("%d%d%d",n%10,n/10%10,n/100);
	return 0;
}

//两数交换（三变量法）

#include <stdio.h>
int main(){
	int a,b,t;
	scanf("%d%d",&a,&b);
	t=a;
	a=b;
	b=t;
	printf("%d %d\n",a,b);
	return 0;
}

//两数交换（手工理解）

#include <stdio.h>
int main(){
	int a,b;
	scanf("%d%d",&a,&b);
	a=a+b;
	b=a-b;
	a=a-b;
	printf("%d %d\n",a,b);
	return 0;
}
//分析：少一个变量，需手工分析,不推荐使用

//两数交换（黑盒思想）

#include <stdio.h>
int main(){
	int a,b;
	scanf("%d%d",&a,&b);
	printf("%d %d\n",b,a);
	return 0;
}
//分析：我们的目标是
//解决问题
//Keep It Simple and Stupid,KISS

//鸡兔同笼

//鸡兔总数n,总腿数m,鸡数a,兔数b
//输入n,m
//输出a,b
#include <stdio.h>
int main(){
	int a,b,n,m;
	scanf("%d%d",&n,&m);
	a = (4*n - m)/2;
	b=n-a;
	if(m%2==1 || a<0 || b<0)
		printf("No Answer\n");
	else
		printf("%d %d\n",a,b);
	return 0;
}
//a+b=n		2a+4b=m

//三数平均值（保留三位小数）

#include <stdio.h>
#include <math.h>
int main(){
	double a,b,c;
	scanf("%lf%lf%lf",&a,&b,&c);
	printf("The average number = %.3f\n",(a+b+c)/3);
	return 0;
}

//正弦余弦

#include <stdio.h>
#include <math.h>
int main(){
	int x;
	double a;
	const double pi = acos(-1.0);
	scanf("%d",&x);
	if(x<0 || x>360)
		printf("No answer");
	else{
		a=(double)(x*2*pi/360);
		printf("%.3f\n",sin(a));
		printf("%.3f\n",cos(a));
	}
	return 0;
}

//判断三角形

#include <stdio.h>
#include <math.h>
int main(){
	unsigned int a,b,c;
	scanf("%d%d%d",&a,&b,&c);
	if(a*a == ( b*b + c*c ) ||
	   b*b == ( a*a + c*c ) ||
	   c*c == ( a*a + b*b ) )
		printf("yes");
	else if(a + b < c ||
			b + c < a ||
			a + c < b)
		printf("Not a triangle");
	else{
		printf("No");
	}
	return 0;
}

//测试double能表示的范围

#include <stdio.h>
int main(){
	printf("%.50f",1.0/3.0);
	return 0;
}

//7744完全平方数

#include <stdio.h>
#include <math.h>
int main(){
	for(int a = 1;a <= 9; a++)
		for(int b = 0 ;b <=9 ;b++)
		{
			int n = a*1100 + b*11;
			int m = floor(sqrt(n) + 0.5);
			if(m*m == n)
				printf("%d\n",n);
		}
	return 0;
}
//floor:不超过一个数的最大值
//避免误差：单位区间左移0.5

//7744完全平方数（枚举平方根，避开开方）

#include <stdio.h>
int main(){
	for(int x = 1; ; x++)
	{
		int n = x*x;
		if(n<1000)	continue;
		if(n>9999)	break;
		int hi = n/100;
		int lo = n%100;
		if(hi/10 == hi%10 && lo/10 ==lo%10)	printf("%d\n",n);
	}
	return 0;
}
//continue:进行下次循环
//break:结束总循环
//for循环可残缺	for（ ； ； ）是一个死循环

//3n+1问题（乘法溢出）

#include <stdio.h>
int main(){
	int n2,count=0;
	scanf("%d",&n2);
	long long n = n2;
	while(n >1){
		if(n%2 == 1)	n=n*3+1;
		else n/=2;
		count++;
	}
	printf("%d\n",count);
	return 0;
}
//本题中n的范围在10的9次方，只比int的32位范围大了一些
//乘法溢出
//用long long 解决问题

//近似计算

#include <stdio.h>
int main(){
	double sum = 0;
	for(int i = 0; ;i++){
		double term = 1.0/(2*i+1);
		if(i%2 == 0)
			sum += term;
		else sum-= term;
		if(term < 1e-6)
			break;
	}
	printf("%f\n",sum);
	return 0;
}
//do-while循环

//阶乘之和

#include <stdio.h>
int main() {
	int n, S = 0;
	scanf_s("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		int factorial = 1;
		for (int j = 1; j <= i; j++)
			factorial *= j;
		printf("%d\n", factorial);
		S += factorial;
	}
	printf("%d\n", S % 1000000);
	while (1);
	return 0;
}
//10行printf"输出中间变量"法验证乘法出现溢出

//阶乘之和（取模在10的6次方内）

#include <stdio.h>
int main() {
	const int Mode = 1000000;
	int n, S = 0;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		int factorial = 1;
		for (int j = 1; j <= i; j++)
			factorial = (factorial * j % Mode);
		S = (S + factorial)% Mode;
	}
	printf("%d\n",S);
	printf("Time used = %.2f\n", (double)clock()/CLOCKS_PER_SEC);//实用：计时函数clock()      echo n|a
	return 0;
}

//数据统计

//输出最小值，最大值，平均值
#include <stdio.h>
int main() {
	int x,n = 0,min ,max,s = 0;
	scanf("%d",&x);
	min = max = x;
	while(scanf("%d",&x) == 1)
	{
		s+=x;
		if(x < min)	min = x;
		if(x > max)	max = x;
		//printf("%d\n",max);
		n++;
	}
	printf("%d %d %.3f\n",min,max,(double)s/n);
	return 0;
}
//windows下，输入完毕后先按Enter键，再按Ctrl+Z,再按Enter即可结束

//输入输出重定向

//输出最小值，最大值，平均值
#define LOCAL

#include <stdio.h>
#define INF 1000000000
int main() {

	#ifdef LOCAL
	freopen("data.in","r",stdin);
	freopen("data.out","w",stdout);
	#endif

	int x,n = 0,min = INF ,max = -INF,s = 0;
	while(scanf("%d",&x) == 1)
	{
		s+=x;
		if(x < min)	min = x;
		if(x > max)	max = x;
		//printf("x= %d,min= %d,max =%d\n",x,min,max);
		n++;
	}
	printf("%d %d %.3f\n",min,max,(double)s/n);
	return 0;
}
//重定向的部分写在了#ifdef和#endif中：只有定义了符号LOCAL才编译freopen语句
//输出中间结果的printf语句写在了注释中，在最终版本本不应该出现，又舍不得删除它
//万一有了新的bug需要用它输出新的中间信息

//数据统计（多组数据）

//输出最小值，最大值，平均值
#define LOCAL
#include <stdio.h>
#define INF 1000000000
int main() {

	#ifdef LOCAL
	freopen("data.in","r",stdin);
	freopen("data.out","w",stdout);
	#endif

	int x,n = 0,s = 0,kase = 0;
	while(scanf("%d",&n) == 1 && n)		//n是输入的数据的个数，当n=0时就退出了
	{
		int s = 0;
		int min = INF ,max = -INF;		//把min和max定义在循环体内部，避免上一组数据计算完后没有重置影响下一组数据的求解
		for(int i = 0; i < n; i++){
			scanf("%d",&x);
			s += x;
			if(x < min)	min = x;
			if(x > max)	max = x;
		}
		if(kase) printf("\n");
		printf("Case %d: %d %d %.3f\n",++kase,min,max,(double)s/n);
	}
	return 0;
}
//判断scanf的返回值是为了鲁棒性
//当嵌套的两个代码块中有同名变量时，内层屏蔽外层，有可能造成隐蔽的错误
//用gcc -Wall 可以给出很多警告错误，但不能解决所有的问题

//水仙花数

#include <stdio.h>
int main() {
	for(int i = 100; i < 1000; i++)
	{
		int a = i / 100;
		int b = i % 100 / 10;
		int c = i - a*100 - b*10;
		if(i == a*a*a + b*b*b +c*c*c)		//= =
			printf("%d\n",i);
	}
	return 0;
}

//倒三角形

#include <stdio.h>
int main() {

	int n;
	scanf("%d",&n);

	for(int i = 1;i <= n; i++)
	{
		for(int j = 1 ;j < i; j++)
		{
			printf(" ");
		}
		for(int k = n-i; k > 0; k--)
		{
			printf("*");
		}
		printf("*");
		for(int k = n-i; k > 0; k--)
		{
			printf("*");
		}
		for(int j = 1 ;j < i; j++)
		{
			printf(" ");
		}
		printf("\n");
	}

	return 0;
}
//双for循环？控制行列
//先打印*还是 ？每行打印几个？
//对称的怎么放在for循环里实现？

//子序列的和

#define LOCAL
#include <stdio.h>
int main(){

	#ifdef LOCAL
	freopen("data.in","r",stdin);
	freopen("data.out","w",stdout);
	#endif

	int n,m,kase=1;
	while(scanf("%d%d",&n,&m) == 2)		//scanf("%d%d", &a, &b) == 2
	{
		if(!n && !m)
			break;
		double sum = 0;		//循环中的变量需要每次刷新防止残留影响
		for(int i = n; i <= m; i++)
			sum += 1.0/i/i;			//有一个浮点数就可以转换为浮点数
		printf("Case %d: %.5f\n\n",kase++,sum);
	}

	return 0;
}
/*
scanf("%d%d", &a, &b);
如果a和b都被成功读入，那么scanf的返回值就是2
如果只有a被成功读入，返回值为1
如果a和b都未被成功读入，返回值为0
如果遇到错误或遇到end of file，返回值为EOF。
*/

//分数化小数

#define LOCAL
#include <stdio.h>
int main(){

	#ifdef LOCAL
	freopen("data.in","r",stdin);
	freopen("data.out","w",stdout);
	#endif

	int a,b,c,kase = 1;
	while(~scanf("%d%d%d",&a,&b,&c)){		//~scanf
		if(!a && !b && !c)
			break;
		double avr = a/(b*1.0);		//乘1.0转换为浮点数
		printf("Case %d: %.*f",kase++,c,avr);		//输出小数点位数为变量
		}
	return 0;
}
/*
printf("%*.*f", 10, 4, 123.3);
表示输出的总宽度是10，小数位数是4
*/s

//排列

#include <stdio.h>
int main(){
	int a[10];
	for(int x = 123;x < 329; x++)		//z最大987，除以3就是329
	{
		int y = 2*x;
		int z = 3*x;
		a[x/100] = a[x/10%10] = a[x%10] = 1;		//所有x,y,z的9个数都以1/0作为是否出现的判断依据
		a[y/100] = a[y/10%10] = a[y%10] = 1;
		a[z/100] = a[z/10%10] = a[z%10] = 1;

		int sum = 0;
		for(int i = 1; i < 10; i++){
			sum += a[i];
			a[i] = 0;			//若不清零，则1传递到下一循环中去造成影响
		}

		if(sum == 9 )			//若都不重复，则打印
			printf("%d %d %d\n",x,y,z);
	}
	return 0;
}
<commit_msg>Delete 1-2.cpp<commit_after><|endoftext|>


<commit_before>//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "vtlib/vtlib.h"
#include "vtdata/vtString.h"
#include <osgDB/ReadFile>

//
// Set any of these definitions to use OSG's own support for the various
// image file formats instead of our own.
//
#define USE_OSG_FOR_PNG		1
#define USE_OSG_FOR_BMP		1
#define USE_OSG_FOR_JPG		1

vtImage::vtImage(const char *fname, int internalformat) : vtImageBase(fname)
{
	m_pPngData = NULL;
	m_pOsgImage = NULL;
	m_internalformat = internalformat;
	m_strFilename = fname;

	vtDIB pDIB;

#if !USE_OSG_FOR_BMP
	if (!stricmp(fname + strlen(fname) - 3, "bmp"))
	{
		if (pDIB.ReadBMP(fname))
		{
			_CreateFromDIB(&pDIB);
			m_bLoaded = true;
		}
	}
	else
#endif

#if !USE_OSG_FOR_JPG
	if (!stricmp(fname + strlen(fname) - 3, "jpg"))
	{
		if (pDIB.ReadJPEG(fname))
		{
			_CreateFromDIB(&pDIB);
			m_bLoaded = true;
		}
	}
	else
#endif

#if !USE_OSG_FOR_PNG
	if (!stricmp(fname + strlen(fname) - 3, "png"))
	{
		_ReadPNG(fname);
	}
	else
#endif

	// try to load with OSG (osgPlugins libraries)
	{
		m_pOsgImage = osgDB::readImageFile(fname);
		if (m_pOsgImage)
			m_bLoaded = true;
	}
}

vtImage::vtImage(vtDIB *pDIB, int internalformat)
{
	m_pPngData = NULL;
	m_internalformat = internalformat;

	_CreateFromDIB(pDIB);
}

vtImage::~vtImage()
{
	if (m_pPngData) free(m_pPngData);
}

void vtImage::_CreateFromDIB(vtDIB *pDIB)
{
	m_pOsgImage = new osg::Image();

	int i, w, h, bpp;
	char *data;

	w   = pDIB->GetWidth();
	h   = pDIB->GetHeight();
	bpp = pDIB->GetDepth();
	data = (char *) pDIB->GetDIBData();

	int SizeImage = w * h * (bpp / 8);
	int SizeRow = w * (bpp / 8);

	GLubyte *image = new GLubyte[SizeImage];

#if 1
	memcpy(image, data, SizeImage);
#else
	// Flip the orientation of the image: a DIB is stored bottom-up, but
	// OSG and OpenGL expect the bitmap to be top-down.
	// (Why is this not required?? It should be, but it works correctly
	//  if we don't do the flip.)
	for (i = 0; i < h; i++)
		memcpy(image + i * SizeRow, data + (h-1-i) * SizeRow, SizeRow);
#endif

	int z;
	int pixelFormat = GL_RGB;
	GLubyte tmp;
	if ( bpp == 24 )
	{
		z = 3;

		/* BGR --> RGB */
		for (i = 0; i < w * h; i++)
		{
			tmp = image [ 3 * i ];
			image [ 3 * i ] = image [ 3 * i + 2 ];
			image [ 3 * i + 2 ] = tmp;
		}
		pixelFormat = GL_RGB;
	}
	else if ( bpp == 32 )
	{
		z = 4;

		/* BGRA --> RGBA */
		for (i = 0; i < w * h; i++ )
		{
			tmp = image [ 4 * i ];
			image [ 4 * i ] = image [ 4 * i + 2 ];
			image [ 4 * i + 2 ] = tmp;
		}
		pixelFormat = GL_RGBA;
	}
	else if ( bpp == 8 )
	{
		pixelFormat = GL_LUMINANCE;
	}
	int internalFormat;

	if (m_internalformat == -1)
		internalFormat = pixelFormat;	// use default
	else
		internalFormat = m_internalformat;	// use specific

	m_pOsgImage->setImage(w, h, 1,	// s, t, r
	   internalFormat,		// int internalFormat,
	   pixelFormat,			// unsigned int pixelFormat,
	   GL_UNSIGNED_BYTE, 	// unsigned int dataType,
	   image,
	   osg::Image::USE_NEW_DELETE);
}

//////////////////////////

#if USE_OSG_FOR_PNG

bool vtImage::_ReadPNG(const char *filename)
{
	return false;
}

#else

#include "png.h"

/* Transparency parameters */
#define PNG_ALPHA		-2 /* Use alpha channel in PNG file, if there is one */
#define PNG_SOLID		-1 /* No transparency								*/
#define PNG_STENCIL		 0 /* Sets alpha to 0 for r=g=b=0, 1 otherwise	   */

typedef struct {
	unsigned int Width;
	unsigned int Height;
	unsigned int Depth;
	unsigned int Alpha;
} pngInfo;

bool vtImage::_ReadPNG(const char *filename)
{
	m_pOsgImage = new osg::Image();

	int trans = PNG_ALPHA;
	FILE *fp = NULL;
	pngInfo pInfo;
	pngInfo *pinfo = &pInfo;

	unsigned char header[8];
	png_structp png;
	png_infop   info;
	png_infop   endinfo;
	png_bytep  *row_p;

	png_uint_32 width, height;
	int depth, color;

	png_uint_32 i;
	png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (!png)
	{
		// We compiled against the headers of one version of libpng, but
		// linked against the libraries from another version.  If you get
		// this, fix the paths in your development environment.
		return false;
	}
	info = png_create_info_struct(png);
	endinfo = png_create_info_struct(png);

	fp = fopen(filename, "rb");
	if (fp && fread(header, 1, 8, fp) && png_check_sig(header, 8))
		png_init_io(png, fp);
	else
	{
		png_destroy_read_struct(&png, &info, &endinfo);
		return false;
	}
	png_set_sig_bytes(png, 8);

	png_read_info(png, info);
	png_get_IHDR(png, info, &width, &height, &depth, &color, NULL, NULL, NULL);

	if (pinfo != NULL) {
		pinfo->Width  = width;
		pinfo->Height = height;
		pinfo->Depth  = depth;
	}

	if (color == PNG_COLOR_TYPE_GRAY || color == PNG_COLOR_TYPE_GRAY_ALPHA)
		png_set_gray_to_rgb(png);

	if (color&PNG_COLOR_MASK_ALPHA && trans != PNG_ALPHA)
	{
		png_set_strip_alpha(png);
		color &= ~PNG_COLOR_MASK_ALPHA;
	}

//	if (!(PalettedTextures && mipmap >= 0 && trans == PNG_SOLID))
		if (color == PNG_COLOR_TYPE_PALETTE)
			png_set_expand(png);

	/*--GAMMA--*/
//	checkForGammaEnv();
	double screenGamma = 2.2 / 1.0;
#if 0
		// Getting the gamma from the PNG file is disabled here, since
		// PhotoShop writes bizarre gamma values like .227 (PhotoShop 5.0)
		// or .45 (newer versions)
	double	fileGamma;
	if (png_get_gAMA(png, info, &fileGamma))
		png_set_gamma(png, screenGamma, fileGamma);
	else
#endif
		png_set_gamma(png, screenGamma, 1.0/2.2);

	png_read_update_info(png, info);

	m_pPngData = (png_bytep) malloc(png_get_rowbytes(png, info)*height);
	row_p = (png_bytep *) malloc(sizeof(png_bytep)*height);

	bool StandardOrientation = true;
	for (i = 0; i < height; i++) {
		if (StandardOrientation)
			row_p[height - 1 - i] = &m_pPngData[png_get_rowbytes(png, info)*i];
		else
			row_p[i] = &m_pPngData[png_get_rowbytes(png, info)*i];
	}

	png_read_image(png, row_p);
	free(row_p);

	int iBitCount;

	if (trans == PNG_SOLID || trans == PNG_ALPHA || color == PNG_COLOR_TYPE_RGB_ALPHA || color == PNG_COLOR_TYPE_GRAY_ALPHA)
	{
		switch (color)
		{
			case PNG_COLOR_TYPE_GRAY:
			case PNG_COLOR_TYPE_RGB:
			case PNG_COLOR_TYPE_PALETTE:
				iBitCount = 24;
				if (pinfo != NULL) pinfo->Alpha = 0;
				break;

			case PNG_COLOR_TYPE_GRAY_ALPHA:
			case PNG_COLOR_TYPE_RGB_ALPHA:
				iBitCount = 32;
				if (pinfo != NULL) pinfo->Alpha = 8;
				break;

			default:
				return false;
		}
	}

	png_read_end(png, endinfo);
	png_destroy_read_struct(&png, &info, &endinfo);

//	free(m_pPngData);

	if (fp)
		fclose(fp);

	int pixelFormat;
	unsigned int internalFormat;

	if (iBitCount == 24)
		pixelFormat = GL_RGB;
	else if (iBitCount == 32)
		pixelFormat = GL_RGBA;

	if (m_internalformat == -1)
		internalFormat = pixelFormat;	// use default
	else
		internalFormat = m_internalformat;	// use specific

	m_pOsgImage->setImage(width, height, 1,
	   internalFormat,		// int internalFormat,
	   pixelFormat,			// unsigned int pixelFormat
	   GL_UNSIGNED_BYTE,	// unsigned int dataType
	   m_pPngData,
	   osg::Image::USE_MALLOC_FREE);

	m_bLoaded = true;

	return true;
}

#endif	// USE_OSG_FOR_PNG

<commit_msg>removed unused stuff, improved comments<commit_after>//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "vtlib/vtlib.h"
#include "vtdata/vtString.h"
#include <osgDB/ReadFile>

//
// Set any of these definitions to use OSG's own support for the various
// image file formats instead of our own.
//
#define USE_OSG_FOR_PNG		1
#define USE_OSG_FOR_BMP		1
#define USE_OSG_FOR_JPG		1

vtImage::vtImage(const char *fname, int internalformat) : vtImageBase(fname)
{
	m_pPngData = NULL;
	m_pOsgImage = NULL;
	m_internalformat = internalformat;
	m_strFilename = fname;

	vtDIB pDIB;

#if !USE_OSG_FOR_BMP
	if (!stricmp(fname + strlen(fname) - 3, "bmp"))
	{
		if (pDIB.ReadBMP(fname))
		{
			_CreateFromDIB(&pDIB);
			m_bLoaded = true;
		}
	}
	else
#endif

#if !USE_OSG_FOR_JPG
	if (!stricmp(fname + strlen(fname) - 3, "jpg"))
	{
		if (pDIB.ReadJPEG(fname))
		{
			_CreateFromDIB(&pDIB);
			m_bLoaded = true;
		}
	}
	else
#endif

#if !USE_OSG_FOR_PNG
	if (!stricmp(fname + strlen(fname) - 3, "png"))
	{
		_ReadPNG(fname);
	}
	else
#endif

	// try to load with OSG (osgPlugins libraries)
	{
		m_pOsgImage = osgDB::readImageFile(fname);
		if (m_pOsgImage)
			m_bLoaded = true;
	}
}

vtImage::vtImage(vtDIB *pDIB, int internalformat)
{
	m_pPngData = NULL;
	m_internalformat = internalformat;

	_CreateFromDIB(pDIB);
}

vtImage::~vtImage()
{
	if (m_pPngData) free(m_pPngData);
}

void vtImage::_CreateFromDIB(vtDIB *pDIB)
{
	m_pOsgImage = new osg::Image();

	int i, w, h, bpp;
	char *data;

	w   = pDIB->GetWidth();
	h   = pDIB->GetHeight();
	bpp = pDIB->GetDepth();
	data = (char *) pDIB->GetDIBData();

	int SizeImage = w * h * (bpp / 8);
	int SizeRow = w * (bpp / 8);

	GLubyte *image = new GLubyte[SizeImage];

#if 1
	memcpy(image, data, SizeImage);
#else
	// Flip the orientation of the image: a DIB is stored bottom-up, but
	// OSG and OpenGL expect the bitmap to be top-down.
	// (Why is this not required?? It should be, but it works correctly
	//  if we don't do the flip.)
	for (i = 0; i < h; i++)
		memcpy(image + i * SizeRow, data + (h-1-i) * SizeRow, SizeRow);
#endif

	int z;
	int pixelFormat = GL_RGB;
	GLubyte tmp;
	if ( bpp == 24 )
	{
		z = 3;

		/* BGR --> RGB */
		for (i = 0; i < w * h; i++)
		{
			tmp = image [ 3 * i ];
			image [ 3 * i ] = image [ 3 * i + 2 ];
			image [ 3 * i + 2 ] = tmp;
		}
		pixelFormat = GL_RGB;
	}
	else if ( bpp == 32 )
	{
		z = 4;

		/* BGRA --> RGBA */
		for (i = 0; i < w * h; i++ )
		{
			tmp = image [ 4 * i ];
			image [ 4 * i ] = image [ 4 * i + 2 ];
			image [ 4 * i + 2 ] = tmp;
		}
		pixelFormat = GL_RGBA;
	}
	else if ( bpp == 8 )
	{
		pixelFormat = GL_LUMINANCE;
	}
	int internalFormat;

	if (m_internalformat == -1)
		internalFormat = pixelFormat;	// use default
	else
		internalFormat = m_internalformat;	// use specific

	m_pOsgImage->setImage(w, h, 1,	// s, t, r
	   internalFormat,		// int internalFormat,
	   pixelFormat,			// unsigned int pixelFormat,
	   GL_UNSIGNED_BYTE, 	// unsigned int dataType,
	   image,
	   osg::Image::USE_NEW_DELETE);
}

//////////////////////////

#if USE_OSG_FOR_PNG

bool vtImage::_ReadPNG(const char *filename)
{
	return false;
}

#else

#include "png.h"

bool vtImage::_ReadPNG(const char *filename)
{
	m_pOsgImage = new osg::Image();

	FILE *fp = NULL;

	unsigned char header[8];
	png_structp png;
	png_infop   info;
	png_infop   endinfo;
	png_bytep  *row_p;

	png_uint_32 width, height;
	int depth, color;

	png_uint_32 i;
	png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (!png)
	{
		// We compiled against the headers of one version of libpng, but
		// linked against the libraries from another version.  If you get
		// this, fix the paths in your development environment.
		return false;
	}
	info = png_create_info_struct(png);
	endinfo = png_create_info_struct(png);

	fp = fopen(filename, "rb");
	if (fp && fread(header, 1, 8, fp) && png_check_sig(header, 8))
		png_init_io(png, fp);
	else
	{
		png_destroy_read_struct(&png, &info, &endinfo);
		return false;
	}
	png_set_sig_bytes(png, 8);

	png_read_info(png, info);
	png_get_IHDR(png, info, &width, &height, &depth, &color, NULL, NULL, NULL);

	if (color == PNG_COLOR_TYPE_GRAY || color == PNG_COLOR_TYPE_GRAY_ALPHA)
		png_set_gray_to_rgb(png);

	// never strip alpha
//	{
//		png_set_strip_alpha(png);
//		color &= ~PNG_COLOR_MASK_ALPHA;
//	}

	// Always expand paletted images
	if (color == PNG_COLOR_TYPE_PALETTE)
		png_set_expand(png);

	/*--GAMMA--*/
//	checkForGammaEnv();
	double screenGamma = 2.2 / 1.0;
#if 0
	// Getting the gamma from the PNG file is disabled here, since
	// PhotoShop writes bizarre gamma values like .227 (PhotoShop 5.0)
	// or .45 (newer versions)
	double	fileGamma;
	if (png_get_gAMA(png, info, &fileGamma))
		png_set_gamma(png, screenGamma, fileGamma);
	else
#endif
		png_set_gamma(png, screenGamma, 1.0/2.2);

	png_read_update_info(png, info);

	m_pPngData = (png_bytep) malloc(png_get_rowbytes(png, info)*height);
	row_p = (png_bytep *) malloc(sizeof(png_bytep)*height);

	bool StandardOrientation = true;
	for (i = 0; i < height; i++) {
		if (StandardOrientation)
			row_p[height - 1 - i] = &m_pPngData[png_get_rowbytes(png, info)*i];
		else
			row_p[i] = &m_pPngData[png_get_rowbytes(png, info)*i];
	}

	png_read_image(png, row_p);
	free(row_p);

	int iBitCount;

	switch (color)
	{
		case PNG_COLOR_TYPE_GRAY:
		case PNG_COLOR_TYPE_RGB:
		case PNG_COLOR_TYPE_PALETTE:
			iBitCount = 24;
			break;

		case PNG_COLOR_TYPE_GRAY_ALPHA:
		case PNG_COLOR_TYPE_RGB_ALPHA:
			iBitCount = 32;
			break;

		default:
			return false;
	}

	png_read_end(png, endinfo);
	png_destroy_read_struct(&png, &info, &endinfo);

	// Don't free the data, we're going to pass it to OSG
//	free(m_pPngData);

	if (fp)
		fclose(fp);

	int pixelFormat;
	unsigned int internalFormat;

	if (iBitCount == 24)
		pixelFormat = GL_RGB;
	else if (iBitCount == 32)
		pixelFormat = GL_RGBA;

	if (m_internalformat == -1)
		internalFormat = pixelFormat;	// use default
	else
		internalFormat = m_internalformat;	// use specific

	m_pOsgImage->setImage(width, height, 1,
	   internalFormat,		// int internalFormat,
	   pixelFormat,			// unsigned int pixelFormat
	   GL_UNSIGNED_BYTE,	// unsigned int dataType
	   m_pPngData,
	   osg::Image::USE_MALLOC_FREE);

	m_bLoaded = true;

	return true;
}

#endif	// USE_OSG_FOR_PNG

<|endoftext|>


<commit_before>//===-- lldb-log.cpp --------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/lldb-private-log.h"

// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Interpreter/Args.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/StreamFile.h"
#include <string.h>

using namespace lldb;
using namespace lldb_private;

// We want to avoid global constructors where code needs to be run so here we
// control access to our static g_log_sp by hiding it in a singleton function
// that will construct the static g_lob_sp the first time this function is
// called.
static LogSP &
GetLog ()
{
    static LogSP g_log_sp;
    return g_log_sp;
}

uint32_t
lldb_private::GetLogMask ()
{
    LogSP log(GetLog ());
    if (log)
        return log->GetMask().Get();
    return 0;
}

bool
lldb_private::IsLogVerbose ()
{
    uint32_t mask = GetLogMask();
    return (mask & LIBLLDB_LOG_VERBOSE);
}

LogSP
lldb_private::GetLogIfAllCategoriesSet (uint32_t mask)
{
    LogSP log(GetLog ());
    if (log && mask)
    {
        uint32_t log_mask = log->GetMask().Get();
        if ((log_mask & mask) != mask)
            return LogSP();
    }
    return log;
}

void
lldb_private::LogIfAllCategoriesSet (uint32_t mask, const char *format, ...)
{
    LogSP log(GetLogIfAllCategoriesSet (mask));
    if (log)
    {
        va_list args;
        va_start (args, format);
        log->VAPrintf (format, args);
        va_end (args);
    }
}

void
lldb_private::LogIfAnyCategoriesSet (uint32_t mask, const char *format, ...)
{
    LogSP log(GetLogIfAnyCategoriesSet (mask));
    if (log)
    {
        va_list args;
        va_start (args, format);
        log->VAPrintf (format, args);
        va_end (args);
    }
}

LogSP
lldb_private::GetLogIfAnyCategoriesSet (uint32_t mask)
{
    LogSP log(GetLog ());
    if (log && mask && (mask & log->GetMask().Get()))
        return log;
    return LogSP();
}

void
lldb_private::DisableLog (Args &args, Stream *feedback_strm)
{
    LogSP log(GetLog ());

    if (log)
    {
        uint32_t flag_bits = 0;
        const size_t argc = args.GetArgumentCount ();
        if (argc > 0)
        {
            flag_bits = log->GetMask().Get();
            for (size_t i = 0; i < argc; ++i)
            {
                const char *arg = args.GetArgumentAtIndex (i);

                if      (0 == ::strcasecmp(arg, "all"))         flag_bits &= ~LIBLLDB_LOG_ALL;
                else if (0 == ::strcasecmp(arg, "api"))         flag_bits &= ~LIBLLDB_LOG_API;
                else if (0 == ::strncasecmp(arg, "break", 5))   flag_bits &= ~LIBLLDB_LOG_BREAKPOINTS;
                else if (0 == ::strcasecmp(arg, "commands"))    flag_bits &= ~LIBLLDB_LOG_COMMANDS;
                else if (0 == ::strcasecmp(arg, "default"))     flag_bits &= ~LIBLLDB_LOG_DEFAULT;
                else if (0 == ::strcasecmp(arg, "dyld"))        flag_bits &= ~LIBLLDB_LOG_DYNAMIC_LOADER;
                else if (0 == ::strncasecmp(arg, "event", 5))   flag_bits &= ~LIBLLDB_LOG_EVENTS;
                else if (0 == ::strncasecmp(arg, "expr", 4))    flag_bits &= ~LIBLLDB_LOG_EXPRESSIONS;
                else if (0 == ::strncasecmp(arg, "object", 6))  flag_bits &= ~LIBLLDB_LOG_OBJECT;
                else if (0 == ::strcasecmp(arg, "process"))     flag_bits &= ~LIBLLDB_LOG_PROCESS;
                else if (0 == ::strcasecmp(arg, "script"))      flag_bits &= ~LIBLLDB_LOG_SCRIPT;
                else if (0 == ::strcasecmp(arg, "state"))       flag_bits &= ~LIBLLDB_LOG_STATE;
                else if (0 == ::strcasecmp(arg, "step"))        flag_bits &= ~LIBLLDB_LOG_STEP;
                else if (0 == ::strcasecmp(arg, "thread"))      flag_bits &= ~LIBLLDB_LOG_THREAD;
                else if (0 == ::strcasecmp(arg, "verbose"))     flag_bits &= ~LIBLLDB_LOG_VERBOSE;
                else if (0 == ::strncasecmp(arg, "watch", 5))   flag_bits &= ~LIBLLDB_LOG_WATCHPOINTS;
                else if (0 == ::strncasecmp(arg, "temp", 4))    flag_bits &= ~LIBLLDB_LOG_TEMPORARY;
                else if (0 == ::strncasecmp(arg, "comm", 4))    flag_bits &= ~LIBLLDB_LOG_COMMUNICATION;
                else if (0 == ::strncasecmp(arg, "conn", 4))    flag_bits &= ~LIBLLDB_LOG_CONNECTION;
                else if (0 == ::strncasecmp(arg, "host", 4))    flag_bits &= ~LIBLLDB_LOG_HOST;
                else if (0 == ::strncasecmp(arg, "unwind", 6))  flag_bits &= ~LIBLLDB_LOG_UNWIND;
                else
                {
                    feedback_strm->Printf ("error:  unrecognized log category '%s'\n", arg);
                    ListLogCategories (feedback_strm);
                    return;
                }

            }
        }
        if (flag_bits == 0)
            GetLog ().reset();
        else
            log->GetMask().Reset (flag_bits);
    }

    return;
}

LogSP
lldb_private::EnableLog (StreamSP &log_stream_sp, uint32_t log_options, Args &args, Stream *feedback_strm)
{
    // Try see if there already is a log - that way we can reuse its settings.
    // We could reuse the log in toto, but we don't know that the stream is the same.
    uint32_t flag_bits;
    LogSP log(GetLog ());
    if (log)
        flag_bits = log->GetMask().Get();
    else
        flag_bits = 0;

    // Now make a new log with this stream if one was provided
    if (log_stream_sp)
    {
        log = make_shared<Log>(log_stream_sp);
        GetLog () = log;
    }

    if (log)
    {
        bool got_unknown_category = false;
        const size_t argc = args.GetArgumentCount();
        for (size_t i=0; i<argc; ++i)
        {
            const char *arg = args.GetArgumentAtIndex(i);

            if      (0 == ::strcasecmp(arg, "all"))         flag_bits |= LIBLLDB_LOG_ALL;
            else if (0 == ::strcasecmp(arg, "api"))         flag_bits |= LIBLLDB_LOG_API;
            else if (0 == ::strncasecmp(arg, "break", 5))   flag_bits |= LIBLLDB_LOG_BREAKPOINTS;
            else if (0 == ::strcasecmp(arg, "commands"))    flag_bits |= LIBLLDB_LOG_COMMANDS;
            else if (0 == ::strcasecmp(arg, "default"))     flag_bits |= LIBLLDB_LOG_DEFAULT;
            else if (0 == ::strcasecmp(arg, "dyld"))        flag_bits |= LIBLLDB_LOG_DYNAMIC_LOADER;
            else if (0 == ::strncasecmp(arg, "event", 5))   flag_bits |= LIBLLDB_LOG_EVENTS;
            else if (0 == ::strncasecmp(arg, "expr", 4))    flag_bits |= LIBLLDB_LOG_EXPRESSIONS;
            else if (0 == ::strncasecmp(arg, "object", 6))  flag_bits |= LIBLLDB_LOG_OBJECT;
            else if (0 == ::strcasecmp(arg, "process"))     flag_bits |= LIBLLDB_LOG_PROCESS;
            else if (0 == ::strcasecmp(arg, "script"))      flag_bits |= LIBLLDB_LOG_SCRIPT;
            else if (0 == ::strcasecmp(arg, "state"))       flag_bits |= LIBLLDB_LOG_STATE;
            else if (0 == ::strcasecmp(arg, "step"))        flag_bits |= LIBLLDB_LOG_STEP;
            else if (0 == ::strcasecmp(arg, "thread"))      flag_bits |= LIBLLDB_LOG_THREAD;
            else if (0 == ::strcasecmp(arg, "verbose"))     flag_bits |= LIBLLDB_LOG_VERBOSE;
            else if (0 == ::strncasecmp(arg, "watch", 5))   flag_bits |= LIBLLDB_LOG_WATCHPOINTS;
            else if (0 == ::strncasecmp(arg, "temp", 4))    flag_bits |= LIBLLDB_LOG_TEMPORARY;
            else if (0 == ::strncasecmp(arg, "comm", 4))    flag_bits |= LIBLLDB_LOG_COMMUNICATION;
            else if (0 == ::strncasecmp(arg, "conn", 4))    flag_bits |= LIBLLDB_LOG_CONNECTION;
            else if (0 == ::strncasecmp(arg, "host", 4))    flag_bits |= LIBLLDB_LOG_HOST;
            else if (0 == ::strncasecmp(arg, "unwind", 6))  flag_bits |= LIBLLDB_LOG_UNWIND;
            else
            {
                feedback_strm->Printf("error: unrecognized log category '%s'\n", arg);
                if (got_unknown_category == false)
                {
                    got_unknown_category = true;
                    ListLogCategories (feedback_strm);
                    return log;
                }
            }
        }

        log->GetMask().Reset(flag_bits);
        log->GetOptions().Reset(log_options);
    }
    return log;
}

void
lldb_private::ListLogCategories (Stream *strm)
{
    strm->Printf("Logging categories for 'lldb':\n"
        "\tall - turn on all available logging categories\n"
        "\tapi - enable logging of API calls and return values\n"
        "\tdefault - enable the default set of logging categories for liblldb\n"
        "\tbreak - log breakpoints\n"
        "\tevents - log broadcaster, listener and event queue activities\n"
        "\texpr - log expressions\n"
        "\tobject - log object construction/destruction for important objects\n"
        "\tprocess - log process events and activities\n"
        "\tthread - log thread events and activities\n"
        "\tscript - log events about the script interpreter\n"
        "\tshlib - log shared library related activities\n"
        "\tstate - log private and public process state changes\n"
        "\tstep - log step related activities\n"
        "\tunwind - log stack unwind activities\n"
        "\tverbose - enable verbose logging\n"
        "\twatch - log watchpoint related activities\n");
}
<commit_msg>Make the log message & setter match for "dyld/shlib".  The "ListLogCategories" output should really be auto-generated from the settings so you can't make this sort of mistake...<commit_after>//===-- lldb-log.cpp --------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/lldb-private-log.h"

// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Interpreter/Args.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/StreamFile.h"
#include <string.h>

using namespace lldb;
using namespace lldb_private;

// We want to avoid global constructors where code needs to be run so here we
// control access to our static g_log_sp by hiding it in a singleton function
// that will construct the static g_lob_sp the first time this function is
// called.
static LogSP &
GetLog ()
{
    static LogSP g_log_sp;
    return g_log_sp;
}

uint32_t
lldb_private::GetLogMask ()
{
    LogSP log(GetLog ());
    if (log)
        return log->GetMask().Get();
    return 0;
}

bool
lldb_private::IsLogVerbose ()
{
    uint32_t mask = GetLogMask();
    return (mask & LIBLLDB_LOG_VERBOSE);
}

LogSP
lldb_private::GetLogIfAllCategoriesSet (uint32_t mask)
{
    LogSP log(GetLog ());
    if (log && mask)
    {
        uint32_t log_mask = log->GetMask().Get();
        if ((log_mask & mask) != mask)
            return LogSP();
    }
    return log;
}

void
lldb_private::LogIfAllCategoriesSet (uint32_t mask, const char *format, ...)
{
    LogSP log(GetLogIfAllCategoriesSet (mask));
    if (log)
    {
        va_list args;
        va_start (args, format);
        log->VAPrintf (format, args);
        va_end (args);
    }
}

void
lldb_private::LogIfAnyCategoriesSet (uint32_t mask, const char *format, ...)
{
    LogSP log(GetLogIfAnyCategoriesSet (mask));
    if (log)
    {
        va_list args;
        va_start (args, format);
        log->VAPrintf (format, args);
        va_end (args);
    }
}

LogSP
lldb_private::GetLogIfAnyCategoriesSet (uint32_t mask)
{
    LogSP log(GetLog ());
    if (log && mask && (mask & log->GetMask().Get()))
        return log;
    return LogSP();
}

void
lldb_private::DisableLog (Args &args, Stream *feedback_strm)
{
    LogSP log(GetLog ());

    if (log)
    {
        uint32_t flag_bits = 0;
        const size_t argc = args.GetArgumentCount ();
        if (argc > 0)
        {
            flag_bits = log->GetMask().Get();
            for (size_t i = 0; i < argc; ++i)
            {
                const char *arg = args.GetArgumentAtIndex (i);

                if      (0 == ::strcasecmp(arg, "all"))         flag_bits &= ~LIBLLDB_LOG_ALL;
                else if (0 == ::strcasecmp(arg, "api"))         flag_bits &= ~LIBLLDB_LOG_API;
                else if (0 == ::strncasecmp(arg, "break", 5))   flag_bits &= ~LIBLLDB_LOG_BREAKPOINTS;
                else if (0 == ::strcasecmp(arg, "commands"))    flag_bits &= ~LIBLLDB_LOG_COMMANDS;
                else if (0 == ::strcasecmp(arg, "default"))     flag_bits &= ~LIBLLDB_LOG_DEFAULT;
                else if (0 == ::strcasecmp(arg, "dyld"))        flag_bits &= ~LIBLLDB_LOG_DYNAMIC_LOADER;
                else if (0 == ::strncasecmp(arg, "event", 5))   flag_bits &= ~LIBLLDB_LOG_EVENTS;
                else if (0 == ::strncasecmp(arg, "expr", 4))    flag_bits &= ~LIBLLDB_LOG_EXPRESSIONS;
                else if (0 == ::strncasecmp(arg, "object", 6))  flag_bits &= ~LIBLLDB_LOG_OBJECT;
                else if (0 == ::strcasecmp(arg, "process"))     flag_bits &= ~LIBLLDB_LOG_PROCESS;
                else if (0 == ::strcasecmp(arg, "script"))      flag_bits &= ~LIBLLDB_LOG_SCRIPT;
                else if (0 == ::strcasecmp(arg, "state"))       flag_bits &= ~LIBLLDB_LOG_STATE;
                else if (0 == ::strcasecmp(arg, "step"))        flag_bits &= ~LIBLLDB_LOG_STEP;
                else if (0 == ::strcasecmp(arg, "thread"))      flag_bits &= ~LIBLLDB_LOG_THREAD;
                else if (0 == ::strcasecmp(arg, "verbose"))     flag_bits &= ~LIBLLDB_LOG_VERBOSE;
                else if (0 == ::strncasecmp(arg, "watch", 5))   flag_bits &= ~LIBLLDB_LOG_WATCHPOINTS;
                else if (0 == ::strncasecmp(arg, "temp", 4))    flag_bits &= ~LIBLLDB_LOG_TEMPORARY;
                else if (0 == ::strncasecmp(arg, "comm", 4))    flag_bits &= ~LIBLLDB_LOG_COMMUNICATION;
                else if (0 == ::strncasecmp(arg, "conn", 4))    flag_bits &= ~LIBLLDB_LOG_CONNECTION;
                else if (0 == ::strncasecmp(arg, "host", 4))    flag_bits &= ~LIBLLDB_LOG_HOST;
                else if (0 == ::strncasecmp(arg, "unwind", 6))  flag_bits &= ~LIBLLDB_LOG_UNWIND;
                else
                {
                    feedback_strm->Printf ("error:  unrecognized log category '%s'\n", arg);
                    ListLogCategories (feedback_strm);
                    return;
                }

            }
        }
        if (flag_bits == 0)
            GetLog ().reset();
        else
            log->GetMask().Reset (flag_bits);
    }

    return;
}

LogSP
lldb_private::EnableLog (StreamSP &log_stream_sp, uint32_t log_options, Args &args, Stream *feedback_strm)
{
    // Try see if there already is a log - that way we can reuse its settings.
    // We could reuse the log in toto, but we don't know that the stream is the same.
    uint32_t flag_bits;
    LogSP log(GetLog ());
    if (log)
        flag_bits = log->GetMask().Get();
    else
        flag_bits = 0;

    // Now make a new log with this stream if one was provided
    if (log_stream_sp)
    {
        log = make_shared<Log>(log_stream_sp);
        GetLog () = log;
    }

    if (log)
    {
        bool got_unknown_category = false;
        const size_t argc = args.GetArgumentCount();
        for (size_t i=0; i<argc; ++i)
        {
            const char *arg = args.GetArgumentAtIndex(i);

            if      (0 == ::strcasecmp(arg, "all"))         flag_bits |= LIBLLDB_LOG_ALL;
            else if (0 == ::strcasecmp(arg, "api"))         flag_bits |= LIBLLDB_LOG_API;
            else if (0 == ::strncasecmp(arg, "break", 5))   flag_bits |= LIBLLDB_LOG_BREAKPOINTS;
            else if (0 == ::strcasecmp(arg, "commands"))    flag_bits |= LIBLLDB_LOG_COMMANDS;
            else if (0 == ::strcasecmp(arg, "default"))     flag_bits |= LIBLLDB_LOG_DEFAULT;
            else if (0 == ::strcasecmp(arg, "dyld"))        flag_bits |= LIBLLDB_LOG_DYNAMIC_LOADER;
            else if (0 == ::strncasecmp(arg, "event", 5))   flag_bits |= LIBLLDB_LOG_EVENTS;
            else if (0 == ::strncasecmp(arg, "expr", 4))    flag_bits |= LIBLLDB_LOG_EXPRESSIONS;
            else if (0 == ::strncasecmp(arg, "object", 6))  flag_bits |= LIBLLDB_LOG_OBJECT;
            else if (0 == ::strcasecmp(arg, "process"))     flag_bits |= LIBLLDB_LOG_PROCESS;
            else if (0 == ::strcasecmp(arg, "script"))      flag_bits |= LIBLLDB_LOG_SCRIPT;
            else if (0 == ::strcasecmp(arg, "state"))       flag_bits |= LIBLLDB_LOG_STATE;
            else if (0 == ::strcasecmp(arg, "step"))        flag_bits |= LIBLLDB_LOG_STEP;
            else if (0 == ::strcasecmp(arg, "thread"))      flag_bits |= LIBLLDB_LOG_THREAD;
            else if (0 == ::strcasecmp(arg, "verbose"))     flag_bits |= LIBLLDB_LOG_VERBOSE;
            else if (0 == ::strncasecmp(arg, "watch", 5))   flag_bits |= LIBLLDB_LOG_WATCHPOINTS;
            else if (0 == ::strncasecmp(arg, "temp", 4))    flag_bits |= LIBLLDB_LOG_TEMPORARY;
            else if (0 == ::strncasecmp(arg, "comm", 4))    flag_bits |= LIBLLDB_LOG_COMMUNICATION;
            else if (0 == ::strncasecmp(arg, "conn", 4))    flag_bits |= LIBLLDB_LOG_CONNECTION;
            else if (0 == ::strncasecmp(arg, "host", 4))    flag_bits |= LIBLLDB_LOG_HOST;
            else if (0 == ::strncasecmp(arg, "unwind", 6))  flag_bits |= LIBLLDB_LOG_UNWIND;
            else
            {
                feedback_strm->Printf("error: unrecognized log category '%s'\n", arg);
                if (got_unknown_category == false)
                {
                    got_unknown_category = true;
                    ListLogCategories (feedback_strm);
                    return log;
                }
            }
        }

        log->GetMask().Reset(flag_bits);
        log->GetOptions().Reset(log_options);
    }
    return log;
}

void
lldb_private::ListLogCategories (Stream *strm)
{
    strm->Printf("Logging categories for 'lldb':\n"
        "\tall - turn on all available logging categories\n"
        "\tapi - enable logging of API calls and return values\n"
        "\tdefault - enable the default set of logging categories for liblldb\n"
        "\tbreak - log breakpoints\n"
        "\tevents - log broadcaster, listener and event queue activities\n"
        "\texpr - log expressions\n"
        "\tobject - log object construction/destruction for important objects\n"
        "\tprocess - log process events and activities\n"
        "\tthread - log thread events and activities\n"
        "\tscript - log events about the script interpreter\n"
        "\dyld - log shared library related activities\n"
        "\tstate - log private and public process state changes\n"
        "\tstep - log step related activities\n"
        "\tunwind - log stack unwind activities\n"
        "\tverbose - enable verbose logging\n"
        "\twatch - log watchpoint related activities\n");
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include"Bdados.h"
#include "Gestao.h"
#include <string>
#include <conio.h>

using namespace std;

/*******************************************************************************************/
Gestao _gestao;
BDados *ligacao;
Pessoa* ut;

void janelaUC();
void janelaLogin();
void janelaBV_Regente();
void janelaMensagens();
void janelaGerirConteudo();
void janelaDisciplina();
void janelaCaixaEntrada();
void janelaEnviarMensagem();
void janelaVisualizacao();
void janelaGerirEventos();
void janelaGerirAlunos();
void janelaAdicionarUC();
void janelaRemoverUC();
void janelaGerirDocente();
/*******************************************************************************************/

int main(void)
{
	system("color 79");
	system("cls");
	janelaLogin();
	return 0;
}

void janelaLogin()
{
	cout << "############################" << endl;
	cout << "######## UC Manager ########" << endl;
	cout << "############################" << endl << endl;
	cout << "Digite nome de utilizador: ";
	string _user;
	string _pw;
	char c = ' ';
	cin >> _user;
	cout << endl << "Password: ";
	int StarNum = 0;
	cin >> _pw;
	string utilizador = "B6_5";
	string palavra = "xico";
	string bd = "193.136.62.27:1521/pdborcl"; //ou em vez de ip, gandalf
	try {

		// cout << "Exemplo de ligacao: a ligar ..." << endl;
		ligacao = new BDados(utilizador, palavra, bd);
		//cout << "ligacao estabelecida" << endl;
		// cout << endl << endl << "Prima enter para continuar";
		//system("PAUSE");
		cin.get();

		ut = ligacao->login(_user, _pw);
		//cout << *ut;
		string null = "";

		if (ut->getTipo() == 'D')
		{
			cout << endl << "Bem-vindo " << ut->getNome() << endl;
			cout << "Tipo de acesso: Docente" << endl << endl;
			system("Pause");
			janelaUC();
		}
		if (ut->getTipo() == 'R'){
			cout << endl << "Bem-vindo " << ut->getNome() << endl;
			cout << "Tipo de acesso: Regente" << endl << endl;
			system("Pause");
			janelaBV_Regente();
		}

		cout << "Login incorreto" << endl;
		system("Pause");
		system("cls");
		janelaLogin();
		delete ligacao;

	}
	catch (SQLException erro) {
		cerr << "Erro: " << erro.getMessage() << endl;
	}

}

void janelaBV_Regente() //janela boas vindas
{
	system("cls");
	cout << "-----Bem-vindo-----" << endl << endl << "0-Sair" << endl <<
		"1-Entrar UC" << endl << "2-Adicionar UC" << endl << "3-Remover UC" << endl << "----------"
		<< endl << "m-Mensagens" << endl << endl << "A sua opcao: ";
	char opc;
	cin >> opc;
	switch (opc)
	{
	case '0':exit(0);
	case '1':janelaGerirConteudo();
	case '2':janelaAdicionarUC();
	case '3':janelaRemoverUC();
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaBV_Regente();
	}
}

void janelaAdicionarUC() //janela adiciona UC
{
	system("cls");
	cout << "-----Adicionar UC-----" << endl << endl << "0-Voltar" << endl
		<< endl << "m-Mensagens" << endl;
	_gestao->
	}
}
void janelaRemoverUC() //janela adiciona UC
{
	system("cls");
	cout << "-----Remover UC-----" << endl << endl << "0-Voltar" << endl
		<< endl << "m-Mensagens" << endl;
	char opc;
	cin >> opc;
	switch (opc)
	{
	case '0':janelaBV_Regente();
	case '1':;
	case '2':;
	case '3':;
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaRemoverUC();;
	}
}

void janelaGerirConteudo() //s acessivel pelo regente
{
	char opc;
	system("cls");
	cout << "-----Gerir Conteudos-----" << endl << endl << "0-Voltar" << endl <<
		"1-Gerir Eventos" << endl << "2-Gerir Docentes" << endl << "3-Gerir UC" << endl
		<< "4-Gerir Alunos" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaBV_Regente();
	case '1':janelaGerirEventos();
	case '2':janelaGerirDocente();
	case '3':janelaGerirConteudo(); // confirmar que  esta janela no tenho certeza
	case '4':janelaGerirAlunos();
	case 'm':janelaMensagens();
	default: cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaGerirConteudo();
	}
}
void janelaGerirDocente() //s acessivel pelo regente
{
	char opc;
	system("cls");
	cout << "-----Gerir Docente-----" << endl << endl << "0-Voltar" << endl <<
		"1-Adicionar Docente" << endl << "2-Remover Docente" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaGerirConteudo();
	case '1':_gestao.criarDocente();
	case '2':;
	case 'm':janelaMensagens();
	default: cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaGerirDocente();
	}
}

void janelaGerirAlunos() //s acessivel pelo regente
{
	char opc;
	system("cls");
	cout << "-----Gerir Alunos-----" << endl << endl << "0-Voltar" << endl <<
		"1-Adicionar aluno" << endl << "2-Remover aluno" << endl << "3-Adicionar alunos" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaBV_Regente();
	case '1':_gestao.criarAluno();
	case '2':;
	case '3':;
	case 'm':janelaMensagens();
	default: cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaGerirAlunos();
	}
}

void janelaGerirEventos()
{
	char opc;
	system("cls");
	cout << "-----Gerir Eventos-----" << endl << endl << "0-Voltar" << endl <<
		"1-Alterar Eventos" << endl << "2-Remover Eventos" << endl << "3-Adicionar Eventos" << endl <<
		"----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";

	cin >> opc;
	switch (opc)
	{
	case '0':janelaGerirConteudo();
	case '1':;
	case '2':;
	case '3':;
	case '4':;
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaGerirEventos();
	}
}

void janelaUC()
{
	char opc;
	system("cls");
	cout << "-----Janela UC-----" << endl << endl << "0-Sair" << endl <<
		"1-Leccionadas" << endl << "2-Permissoes/Historico" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':exit(0);
	case '1':janelaDisciplina();
	case '2':janelaVisualizacao();
	case '3':;
	case '4':;
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!");
		system("pause");
		system("cls");
		janelaUC();
	}
}
void janelaMensagens()
{
	char opc;
	system("cls");
	cout << "-----Mensagens-----" << endl << endl << "0-Voltar" << endl <<
		"1-Caixa de entrada" << endl << "2-Escrever mensagem" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaUC();
	case '1':janelaCaixaEntrada();
	case '2':janelaEnviarMensagem();
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaMensagens();
	}
}

void janelaDisciplina()
{
	char opc;
	system("cls");
	cout << "-----Gestao Disciplina-----" << endl << endl << "0-Voltar" << endl <<
		"1-Marcar Avaliacao" << endl << "2-Publicar notas" << endl << "3-Visualizar notas" <<
		endl << "4-Escrever sumarios" << endl << "5-Visualizar Sumarios"
		<< endl << "6-Marcar aula extra" << endl << "7-Historico" << endl << "----------" << endl <<
		"m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaUC();
	case '1':;
	case '2':;
	case '3':;
	case '4':;
	case '5':;
	case '6':;
	case '7':;
	case 'm':; janelaMensagens();
	default: cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaDisciplina();
	}
}

void janelaVisualizacao()

{
	char opc;
	system("cls");
	cout << "-----Visualizacao-----" << endl << endl << "0-Voltar" << endl <<
		"1-Visualizar notas" << endl << "2-Visualizar sumarios" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaUC();
	case '1':;
	case '2':;
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaVisualizacao();
	}
}

void janelaCaixaEntrada() // caixa de entrada de mensagens

{
	int opc;
	system("cls");
	cout << "-----Caixa de entrada-----" << endl;
	_gestao.ListarMensagem(ut->getMsg());
	cout << endl << "Qual deseja ler ? (0 para voltar): ";
	cin >> opc;
	switch (opc)
	{
	case 0:janelaUC();
	case 'm':janelaMensagens();
	default:
		system("cls"); //metodo nao seguro, corrigir se possivel, pois caso o user utilize uma tecla que nao um numero ou "m" o programa no sabe o que fazer
		cout << ut->getMsg()[opc - 1] << endl;
	}

	system("PAUSE");
	janelaMensagens();
}

void janelaEnviarMensagem() // enviar mensagem (completo)
{
	string para;
	string mensagem;
	string assunto;
	string anexo;
	system("cls");
	cout << "-----Enviar mensagem-----" << endl;
	cout << "Para? ";
	cin >> para;
	cout << endl << "Assunto ";
	cin >> assunto;
	cout << endl << "Mensagem: ";
	cin >> mensagem;
	anexo = "l";
	while (anexo.compare("n") != 0 && anexo.compare("s") != 0)
	{
		cout << endl << "Deseja anexo? (s/n)";
		cin >> anexo;
	}
	bool an = false;
	if (anexo.compare("s") == 0)
	{
		an = true;
		cout << endl << "Nome anexo: ";
		cin >> anexo;
	}
	if (an) /// cria mensagem com anexo
	{
		try{
			ligacao->enviaMsgBD(ut->getCod_utilizador(), para, assunto, mensagem, anexo);
		}
		catch (int excp)
		{
			cout << "Mensagem no enviada, tente de novo" << endl;
			system("PAUSE");
			janelaCaixaEntrada();
		}
	}
	if (an == false) /// cria mensagem sem anexo
	{
		try{
			anexo = "Sem anexo";
			ligacao->enviaMsgBD(ut->getCod_utilizador(), para, assunto, mensagem, anexo);
		}
		catch (int excp)
		{
			cout << "Mensagem no enviada, tente de novo" << endl;
			system("PAUSE");
			janelaCaixaEntrada();
		}
	}
}

<commit_msg>1111315 correção de erros class main.cpp<commit_after>#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include"Bdados.h"
#include "Gestao.h"
#include <string>
#include <conio.h>

using namespace std;

/*******************************************************************************************/
Gestao _gestao;
BDados *ligacao;
Pessoa* ut;

void janelaUC();
void janelaLogin();
void janelaBV_Regente();
void janelaMensagens();
void janelaGerirConteudo();
void janelaDisciplina();
void janelaCaixaEntrada();
void janelaEnviarMensagem();
void janelaVisualizacao();
void janelaGerirEventos();
void janelaGerirAlunos();
void janelaAdicionarUC();
void janelaRemoverUC();
void janelaGerirDocente();
/*******************************************************************************************/

int main(void)
{
	system("color 79");
	system("cls");
	janelaLogin();
	return 0;
}

void janelaLogin()
{
	cout << "############################" << endl;
	cout << "######## UC Manager ########" << endl;
	cout << "############################" << endl << endl;
	cout << "Digite nome de utilizador: ";
	string _user;
	string _pw;
	char c = ' ';
	cin >> _user;
	cout << endl << "Password: ";
	int StarNum = 0;
	cin >> _pw;
	string utilizador = "B6_5";
	string palavra = "xico";
	string bd = "193.136.62.27:1521/pdborcl"; //ou em vez de ip, gandalf
	try {

		// cout << "Exemplo de ligacao: a ligar ..." << endl;
		ligacao = new BDados(utilizador, palavra, bd);
		//cout << "ligacao estabelecida" << endl;
		// cout << endl << endl << "Prima enter para continuar";
		//system("PAUSE");
		cin.get();

		ut = ligacao->login(_user, _pw);
		//cout << *ut;
		string null = "";

		if (ut->getTipo() == 'D')
		{
			cout << endl << "Bem-vindo " << ut->getNome() << endl;
			cout << "Tipo de acesso: Docente" << endl << endl;
			system("Pause");
			janelaUC();
		}
		if (ut->getTipo() == 'R'){
			cout << endl << "Bem-vindo " << ut->getNome() << endl;
			cout << "Tipo de acesso: Regente" << endl << endl;
			system("Pause");
			janelaBV_Regente();
		}

		cout << "Login incorreto" << endl;
		system("Pause");
		system("cls");
		janelaLogin();
		delete ligacao;

	}
	catch (SQLException erro) {
		cerr << "Erro: " << erro.getMessage() << endl;
	}

}

void janelaBV_Regente() //janela boas vindas
{
	system("cls");
	cout << "-----Bem-vindo-----" << endl << endl << "0-Sair" << endl <<
		"1-Entrar UC" << endl << "2-Adicionar UC" << endl << "3-Remover UC" << endl << "----------"
		<< endl << "m-Mensagens" << endl << endl << "A sua opcao: ";
	char opc;
	cin >> opc;
	switch (opc)
	{
	case '0':exit(0);
	case '1':janelaGerirConteudo();
	case '2':janelaAdicionarUC();
	case '3':janelaRemoverUC();
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaBV_Regente();
	}
}

void janelaAdicionarUC() //janela adiciona UC
{
	system("cls");
	cout << "-----Adicionar UC-----" << endl << endl << "0-Voltar" << endl
		<< endl << "m-Mensagens" << endl;
}
void janelaRemoverUC() //janela adiciona UC
{
	system("cls");
	cout << "-----Remover UC-----" << endl << endl << "0-Voltar" << endl
		<< endl << "m-Mensagens" << endl;
	char opc;
	cin >> opc;
	switch (opc)
	{
	case '0':janelaBV_Regente();
	case '1':;
	case '2':;
	case '3':;
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaRemoverUC();;
	}
}

void janelaGerirConteudo() //s acessivel pelo regente
{
	char opc;
	system("cls");
	cout << "-----Gerir Conteudos-----" << endl << endl << "0-Voltar" << endl <<
		"1-Gerir Eventos" << endl << "2-Gerir Docentes" << endl << "3-Gerir UC" << endl
		<< "4-Gerir Alunos" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaBV_Regente();
	case '1':janelaGerirEventos();
	case '2':janelaGerirDocente();
	case '3':janelaGerirConteudo(); // confirmar que  esta janela no tenho certeza
	case '4':janelaGerirAlunos();
	case 'm':janelaMensagens();
	default: cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaGerirConteudo();
	}
}
void janelaGerirDocente() //s acessivel pelo regente
{
	char opc;
	system("cls");
	cout << "-----Gerir Docente-----" << endl << endl << "0-Voltar" << endl <<
		"1-Adicionar Docente" << endl << "2-Remover Docente" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaGerirConteudo();
	case '1':_gestao.criarDocente();
	case '2':;
	case 'm':janelaMensagens();
	default: cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaGerirDocente();
	}
}

void janelaGerirAlunos() //s acessivel pelo regente
{
	char opc;
	system("cls");
	cout << "-----Gerir Alunos-----" << endl << endl << "0-Voltar" << endl <<
		"1-Adicionar aluno" << endl << "2-Remover aluno" << endl << "3-Adicionar alunos" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaBV_Regente();
	case '1':_gestao.criarAluno();
	case '2':;
	case '3':;
	case 'm':janelaMensagens();
	default: cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaGerirAlunos();
	}
}

void janelaGerirEventos()
{
	char opc;
	system("cls");
	cout << "-----Gerir Eventos-----" << endl << endl << "0-Voltar" << endl <<
		"1-Alterar Eventos" << endl << "2-Remover Eventos" << endl << "3-Adicionar Eventos" << endl <<
		"----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";

	cin >> opc;
	switch (opc)
	{
	case '0':janelaGerirConteudo();
	case '1':;
	case '2':;
	case '3':;
	case '4':;
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaGerirEventos();
	}
}

void janelaUC()
{
	char opc;
	system("cls");
	cout << "-----Janela UC-----" << endl << endl << "0-Sair" << endl <<
		"1-Leccionadas" << endl << "2-Permissoes/Historico" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':exit(0);
	case '1':janelaDisciplina();
	case '2':janelaVisualizacao();
	case '3':;
	case '4':;
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!");
		system("pause");
		system("cls");
		janelaUC();
	}
}
void janelaMensagens()
{
	char opc;
	system("cls");
	cout << "-----Mensagens-----" << endl << endl << "0-Voltar" << endl <<
		"1-Caixa de entrada" << endl << "2-Escrever mensagem" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaUC();
	case '1':janelaCaixaEntrada();
	case '2':janelaEnviarMensagem();
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaMensagens();
	}
}

void janelaDisciplina()
{
	char opc;
	system("cls");
	cout << "-----Gestao Disciplina-----" << endl << endl << "0-Voltar" << endl <<
		"1-Marcar Avaliacao" << endl << "2-Publicar notas" << endl << "3-Visualizar notas" <<
		endl << "4-Escrever sumarios" << endl << "5-Visualizar Sumarios"
		<< endl << "6-Marcar aula extra" << endl << "7-Historico" << endl << "----------" << endl <<
		"m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaUC();
	case '1':;
	case '2':;
	case '3':;
	case '4':;
	case '5':;
	case '6':;
	case '7':;
	case 'm':; janelaMensagens();
	default: cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaDisciplina();
	}
}

void janelaVisualizacao()

{
	char opc;
	system("cls");
	cout << "-----Visualizacao-----" << endl << endl << "0-Voltar" << endl <<
		"1-Visualizar notas" << endl << "2-Visualizar sumarios" << endl << "----------" << endl << "m-Mensagens" << endl << "A sua opcao: ";
	cin >> opc;
	switch (opc)
	{
	case '0':janelaUC();
	case '1':;
	case '2':;
	case 'm':janelaMensagens();
	default:cout << endl << ("Opcao incorreta!!!   ");
		system("pause");
		system("cls");
		janelaVisualizacao();
	}
}

void janelaCaixaEntrada() // caixa de entrada de mensagens

{
	int opc;
	system("cls");
	cout << "-----Caixa de entrada-----" << endl;
	_gestao.ListarMensagem(ut->getMsg());
	cout << endl << "Qual deseja ler ? (0 para voltar): ";
	cin >> opc;
	switch (opc)
	{
	case 0:janelaUC();
	case 'm':janelaMensagens();
	default:
		system("cls"); //metodo nao seguro, corrigir se possivel, pois caso o user utilize uma tecla que nao um numero ou "m" o programa no sabe o que fazer
		cout << ut->getMsg()[opc - 1] << endl;
	}

	system("PAUSE");
	janelaMensagens();
}

void janelaEnviarMensagem() // enviar mensagem (completo)
{
	string para;
	string mensagem;
	string assunto;
	string anexo;
	system("cls");
	cout << "-----Enviar mensagem-----" << endl;
	cout << "Para? ";
	cin >> para;
	cout << endl << "Assunto ";
	cin >> assunto;
	cout << endl << "Mensagem: ";
	cin >> mensagem;
	anexo = "l";
	while (anexo.compare("n") != 0 && anexo.compare("s") != 0)
	{
		cout << endl << "Deseja anexo? (s/n)";
		cin >> anexo;
	}
	bool an = false;
	if (anexo.compare("s") == 0)
	{
		an = true;
		cout << endl << "Nome anexo: ";
		cin >> anexo;
	}
	if (an) /// cria mensagem com anexo
	{
		try{
			ligacao->enviaMsgBD(ut->getCod_utilizador(), para, assunto, mensagem, anexo);
		}
		catch (int excp)
		{
			cout << "Mensagem no enviada, tente de novo" << endl;
			system("PAUSE");
			janelaCaixaEntrada();
		}
	}
	if (an == false) /// cria mensagem sem anexo
	{
		try{
			anexo = "Sem anexo";
			ligacao->enviaMsgBD(ut->getCod_utilizador(), para, assunto, mensagem, anexo);
		}
		catch (int excp)
		{
			cout << "Mensagem no enviada, tente de novo" << endl;
			system("PAUSE");
			janelaCaixaEntrada();
		}
	}
}

<|endoftext|>


<commit_before>/*
    The overall strategy is to consider all possible vertices of triangles,
    and to search through a relevant adjacency list how many triangles there
    are.

    First, we split the lines into three grids, and then color these grids:

    Blue:   Lines parallel or perpendicular to the line joining the center of
            the triangle to the top vertex.
    Red:    Lines parallel or perpendicular to the line joining the center of
            the triangle to the bottom left vertex.
    Green:  Lines parallel or perpendicular to the line joining the center of
            the triangle to the bottom right vertex.

    Notice that for every possible point that can become the vertex of some
    triangle, the adjacent points can be partitioned into adjacent points in
    each of the three grids. Hence we can consider the three grids separately
    when generating the adjaceny list for possible vertices of triangles.

    Note that we can form an orthogonal basis using each of this grid. For each
    grid, we set the center of the triangle as the origin. For each color, we
    have as basis:

    Blue:   (0, 1) is the height of one size 1 triangle along the direction of
            the top of the triangle from the origin.
            (1, 0) is the same distance to the right of the origin.
    Green:  (0, 1) is the height of one size 1 triangle along the direction of
            the bottom left vertex of the triangle from the origin.
            (1, 0) is the same distance in the perpendicular direction towards
            the left edge of the triangle.
    Red:    (0, 1) is the height of one size 1 triangle along the direction of
            the bottom right vertex of the triangle from the origin.
            (1, 0) is the same distance in the perpendicular direction towards
            the right edge of the triangle.

    Denote B, R, G as the bases for the blue, red, and green grids respectively.
    Let a point P = X^Y denote having coordinates X in basis Y.

    Let T_{RB} be the transition matrix from B to R. Note that

        [2; 0]^B = [-1; -1]^R
        [0; 2/3]^B = [1; -1/3]^R

    where we exploit the fact that the inradius of an equilateral triangle is
    1/3 that of its altitude. This gives us

        T_{RB} = [-1 1;-1 -1/3] * [1/2 0;0 1/c]
               = [-1 3;-1 -1] / 2

    Note also that T_{RB} = T_{GR} = T_{BG}. This gives us a very clean way
    to transform coordinates between the different bases.

    The generation of the adjacency list is relatively trivial afterwards. I
    used the first method I could think of. You only need to consider one of the
    three grids, because if M^Y and N^Y are adjacent, then so is M^Z and N^Z for
    the other Z's.

    For the search, I went through each point A, and for each point A, I went
    through distinct pairs of adjacent points (B, C) such that A, B, C are
    not collinear. This is to exclude straight lines. If B and C are adjacent,
    then we have a hit.

    As an optimization, note that all coordinates have fractional part dividing
    6, so we can scale everything by 6 and use integers instead of having to
    deal with fractions.
*/

#include <iostream>
#include <unordered_set>
#include <unordered_map>

int make_point(int x, int y) { return (x << 16) | (y & 0xFFFF); }
int get_x(int point) { return ((point >> 31) & 1) ? (0xFFFF0000 | (point >> 16)) : (point >> 16); }
int get_y(int point) { return ((point >> 15) & 1) ? (0xFFFF0000 | (point & 0xFFFF)) : (point & 0xFFFF); }

int transform(int point, int basis_changes)
{
    for (int i = 0; i < basis_changes; i++)
        point = make_point((-get_x(point) + 3 * get_y(point)) / 2, (-get_x(point) - get_y(point)) / 2);
    return point;
}

int main()
{
    int n = 36;

    std::unordered_map<int, std::unordered_set<int>> adjacency;
    for (int c = 0; c < n; c++)
    {
        for (int r1 = 2 * c; r1 < 2 * n; r1++)
        {
            for (int r2 = r1 + 1; r2 < 2 * n + 1; r2++)
            {
                int offset1 = make_point(6 * c, r1 % 2 == 0 ? 3 * r1 : r1 % 4 == (c % 2 == 0 ? 1 : 3) ? 3 * (r1 - 1) + 4 : 3 * (r1 - 1) + 2);
                int offset2 = make_point(6 * c, r2 % 2 == 0 ? 3 * r2 : r2 % 4 == (c % 2 == 0 ? 1 : 3) ? 3 * (r2 - 1) + 4 : 3 * (r2 - 1) + 2);
                int endpoint1 = make_point(get_x(offset1), 4 * n - get_y(offset1));
                int endpoint2 = make_point(get_x(offset2), 4 * n - get_y(offset2));

                for (int basis = 0; basis < 3; basis++)
                {
                    adjacency[transform(endpoint1, basis)].emplace(transform(endpoint2, basis));
                    adjacency[transform(endpoint2, basis)].emplace(transform(endpoint1, basis));
                    if (c > 0)
                    {
                        adjacency[transform(make_point(-get_x(endpoint1), get_y(endpoint1)), basis)].emplace(transform(make_point(-get_x(endpoint2), get_y(endpoint2)), basis));
                        adjacency[transform(make_point(-get_x(endpoint2), get_y(endpoint2)), basis)].emplace(transform(make_point(-get_x(endpoint1), get_y(endpoint1)), basis));
                    }
                }
            }
        }
    }
    for (int i = 1; i < n + 1; i++)
    {
        for (int c1 = -i; c1 < i; c1++)
        {
            for (int c2 = c1 + 1; c2 < i + 1; c2++)
            {
                int offset1 = make_point(6 * c1, 6 * i), offset2 = make_point(6 * c2, 6 * i);
                int endpoint1 = make_point(get_x(offset1), 4 * n - get_y(offset1));
                int endpoint2 = make_point(get_x(offset2), 4 * n - get_y(offset2));

                for (int basis = 0; basis < 3; basis++)
                {
                    adjacency[transform(endpoint1, basis)].emplace(transform(endpoint2, basis));
                    adjacency[transform(endpoint2, basis)].emplace(transform(endpoint1, basis));
                }
            }
        }
    }

    int count = 0;
    for (auto const &pair : adjacency)
    {
        int point = pair.first;
        std::unordered_set<int> const &adjacent_points = pair.second;

        for (auto it1 = adjacent_points.begin(), it2 = it1; it1 != adjacent_points.end(); it2 = ++it1)
            for (; it2 != adjacent_points.end(); ++it2)
                if (adjacency[*it1].find(*it2) != adjacency[*it1].end() && adjacency[*it2].find(*it1) != adjacency[*it2].end())
                    if ((get_y(point) - get_y(*it1)) * (get_x(point) - get_x(*it2)) != (get_y(point) - get_y(*it2)) * (get_x(point) - get_x(*it1)))
                        count++;
    }

    std::cout << count / 3;
}<commit_msg>Removed unnecerepeated searches.<commit_after>/*
    The overall strategy is to consider all possible vertices of triangles,
    and to search through a relevant adjacency list how many triangles there
    are.

    First, we split the lines into three grids, and then color these grids:

    Blue:   Lines parallel or perpendicular to the line joining the center of
            the triangle to the top vertex.
    Red:    Lines parallel or perpendicular to the line joining the center of
            the triangle to the bottom left vertex.
    Green:  Lines parallel or perpendicular to the line joining the center of
            the triangle to the bottom right vertex.

    Notice that for every possible point that can become the vertex of some
    triangle, the adjacent points can be partitioned into adjacent points in
    each of the three grids. Hence we can consider the three grids separately
    when generating the adjaceny list for possible vertices of triangles.

    Note that we can form an orthogonal basis using each of this grid. For each
    grid, we set the center of the triangle as the origin. For each color, we
    have as basis:

    Blue:   (0, 1) is the height of one size 1 triangle along the direction of
            the top of the triangle from the origin.
            (1, 0) is the same distance to the right of the origin.
    Green:  (0, 1) is the height of one size 1 triangle along the direction of
            the bottom left vertex of the triangle from the origin.
            (1, 0) is the same distance in the perpendicular direction towards
            the left edge of the triangle.
    Red:    (0, 1) is the height of one size 1 triangle along the direction of
            the bottom right vertex of the triangle from the origin.
            (1, 0) is the same distance in the perpendicular direction towards
            the right edge of the triangle.

    Denote B, R, G as the bases for the blue, red, and green grids respectively.
    Let a point P = X^Y denote having coordinates X in basis Y.

    Let T_{RB} be the transition matrix from B to R. Note that

        [2; 0]^B = [-1; -1]^R
        [0; 2/3]^B = [1; -1/3]^R

    where we exploit the fact that the inradius of an equilateral triangle is
    1/3 that of its altitude. This gives us

        T_{RB} = [-1 1;-1 -1/3] * [1/2 0;0 1/c]
               = [-1 3;-1 -1] / 2

    Note also that T_{RB} = T_{GR} = T_{BG}. This gives us a very clean way
    to transform coordinates between the different bases.

    The generation of the adjacency list is relatively trivial afterwards. I
    used the first method I could think of. You only need to consider one of the
    three grids, because if M^Y and N^Y are adjacent, then so is M^Z and N^Z for
    the other Z's.

    For the search, I went through each point A, and for each point A, I went
    through distinct pairs of adjacent points (B, C) such that A, B, C are
    not collinear. This is to exclude straight lines. If B and C are adjacent,
    then we have a hit.

    As an optimization, note that all coordinates have fractional part dividing
    6, so we can scale everything by 6 and use integers instead of having to
    deal with fractions.
*/

#include <iostream>
#include <unordered_set>
#include <unordered_map>

int make_point(int x, int y) { return (x << 16) | (y & 0xFFFF); }
int get_x(int point) { return ((point >> 31) & 1) ? (0xFFFF0000 | (point >> 16)) : (point >> 16); }
int get_y(int point) { return ((point >> 15) & 1) ? (0xFFFF0000 | (point & 0xFFFF)) : (point & 0xFFFF); }

int transform(int point, int basis_changes)
{
    for (int i = 0; i < basis_changes; i++)
        point = make_point((-get_x(point) + 3 * get_y(point)) / 2, (-get_x(point) - get_y(point)) / 2);
    return point;
}

int main()
{
    int n = 36;

    std::unordered_map<int, std::unordered_set<int>> adjacency;
    for (int c = 0; c < n; c++)
    {
        for (int r1 = 2 * c; r1 < 2 * n; r1++)
        {
            for (int r2 = r1 + 1; r2 < 2 * n + 1; r2++)
            {
                int offset1 = make_point(6 * c, r1 % 2 == 0 ? 3 * r1 : r1 % 4 == (c % 2 == 0 ? 1 : 3) ? 3 * (r1 - 1) + 4 : 3 * (r1 - 1) + 2);
                int offset2 = make_point(6 * c, r2 % 2 == 0 ? 3 * r2 : r2 % 4 == (c % 2 == 0 ? 1 : 3) ? 3 * (r2 - 1) + 4 : 3 * (r2 - 1) + 2);
                int endpoint1 = make_point(get_x(offset1), 4 * n - get_y(offset1));
                int endpoint2 = make_point(get_x(offset2), 4 * n - get_y(offset2));

                for (int basis = 0; basis < 3; basis++)
                {
                    adjacency[transform(endpoint1, basis)].emplace(transform(endpoint2, basis));
                    adjacency[transform(endpoint2, basis)].emplace(transform(endpoint1, basis));
                    if (c > 0)
                    {
                        adjacency[transform(make_point(-get_x(endpoint1), get_y(endpoint1)), basis)].emplace(transform(make_point(-get_x(endpoint2), get_y(endpoint2)), basis));
                        adjacency[transform(make_point(-get_x(endpoint2), get_y(endpoint2)), basis)].emplace(transform(make_point(-get_x(endpoint1), get_y(endpoint1)), basis));
                    }
                }
            }
        }
    }
    for (int i = 1; i < n + 1; i++)
    {
        for (int c1 = -i; c1 < i; c1++)
        {
            for (int c2 = c1 + 1; c2 < i + 1; c2++)
            {
                int offset1 = make_point(6 * c1, 6 * i), offset2 = make_point(6 * c2, 6 * i);
                int endpoint1 = make_point(get_x(offset1), 4 * n - get_y(offset1));
                int endpoint2 = make_point(get_x(offset2), 4 * n - get_y(offset2));

                for (int basis = 0; basis < 3; basis++)
                {
                    adjacency[transform(endpoint1, basis)].emplace(transform(endpoint2, basis));
                    adjacency[transform(endpoint2, basis)].emplace(transform(endpoint1, basis));
                }
            }
        }
    }

    int count = 0;
    for (auto const &pair : adjacency)
    {
        int point = pair.first;
        std::unordered_set<int> const &adjacent_points = pair.second;

        for (auto it1 = adjacent_points.begin(); it1 != adjacent_points.end(); ++it1)
        {
            auto it2 = it1;
            ++it2;
            for (; it2 != adjacent_points.end(); adjacency[*(it2++)].erase(point))
                if ((get_y(point) - get_y(*it1)) * (get_x(point) - get_x(*it2)) != (get_y(point) - get_y(*it2)) * (get_x(point) - get_x(*it1)))
                    if (adjacency[*it1].find(*it2) != adjacency[*it1].end() && adjacency[*it2].find(*it1) != adjacency[*it2].end())
                        count++;
            adjacency[*it1].erase(point);
        }
    }

    std::cout << count;
}<|endoftext|>