hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
47de0bae8799ee97f013e5856084fc22d7601d31
2,113
cc
C++
src/crypt/aes_serpent_twofish_algorithm.cc
slwilliams/stegasis
8f7c466231588d51f0af01b46092218324f5e6b1
[ "MIT", "Unlicense" ]
2
2015-12-18T01:14:53.000Z
2016-01-26T15:33:03.000Z
src/crypt/aes_serpent_twofish_algorithm.cc
slwilliams/stegasis
8f7c466231588d51f0af01b46092218324f5e6b1
[ "MIT", "Unlicense" ]
null
null
null
src/crypt/aes_serpent_twofish_algorithm.cc
slwilliams/stegasis
8f7c466231588d51f0af01b46092218324f5e6b1
[ "MIT", "Unlicense" ]
null
null
null
#include <stdio.h> #include <string> #include <crypto/aes.h> #include <crypto/serpent.h> #include <crypto/twofish.h> #include <crypto/modes.h> #include "crypt/cryptographic_algorithm.h" using namespace std; class AESSerpentTwofishAlgorithm : public CryptographicAlgorithm { public: AESSerpentTwofishAlgorithm(string password, VideoDecoder *dec): CryptographicAlgorithm(password, dec) {}; virtual void encrypt(char *data, int dataBytes) { CryptoPP::CTR_Mode<CryptoPP::AES>::Encryption aesEncryption((unsigned char *)key, CryptoPP::AES::DEFAULT_KEYLENGTH, (unsigned char *)(key+64)); aesEncryption.ProcessData((unsigned char *)data, (unsigned char *)data, dataBytes); CryptoPP::CTR_Mode<CryptoPP::Serpent>::Encryption serpentEncryption((unsigned char *)key, CryptoPP::Serpent::DEFAULT_KEYLENGTH, (unsigned char *)(key+64+16)); serpentEncryption.ProcessData((unsigned char *)data, (unsigned char *)data, dataBytes); CryptoPP::CTR_Mode<CryptoPP::Twofish>::Encryption twofishEncryption((unsigned char *)key, CryptoPP::Twofish::DEFAULT_KEYLENGTH, (unsigned char *)(key+64+16+16)); twofishEncryption.ProcessData((unsigned char *)data, (unsigned char *)data, dataBytes); }; virtual void decrypt(char *data, int dataBytes) { CryptoPP::CTR_Mode<CryptoPP::AES>::Decryption aesDecryption((unsigned char *)key, CryptoPP::AES::DEFAULT_KEYLENGTH, (unsigned char *)(key+64)); aesDecryption.ProcessData((unsigned char *)data, (unsigned char *)data, dataBytes); CryptoPP::CTR_Mode<CryptoPP::Serpent>::Decryption serpentDecryption((unsigned char *)key, CryptoPP::Serpent::DEFAULT_KEYLENGTH, (unsigned char *)(key+64+16)); serpentDecryption.ProcessData((unsigned char *)data, (unsigned char *)data, dataBytes); CryptoPP::CTR_Mode<CryptoPP::Twofish>::Decryption twofishDecryption((unsigned char *)key, CryptoPP::Twofish::DEFAULT_KEYLENGTH, (unsigned char *)(key+64+16+16)); twofishDecryption.ProcessData((unsigned char *)data, (unsigned char *)data, dataBytes); }; };
48.022727
109
0.71557
slwilliams
47df1e0b20cc1229167be32aa783555c8fbb9aea
8,583
cpp
C++
grim-code/Engine/main.cpp
ariabonczek/GrimoireEngine
94952b98232b4baac8caa1189dac7c38672c6ae0
[ "MIT" ]
null
null
null
grim-code/Engine/main.cpp
ariabonczek/GrimoireEngine
94952b98232b4baac8caa1189dac7c38672c6ae0
[ "MIT" ]
null
null
null
grim-code/Engine/main.cpp
ariabonczek/GrimoireEngine
94952b98232b4baac8caa1189dac7c38672c6ae0
[ "MIT" ]
null
null
null
#include "Precompiled.h" #include <string.h> #include <stdio.h> #include <Engine/CommandContext.h> #include <Engine/EngineGlobals.h> #include <Engine/Filesystem.h> #include <Engine/Gfx.h> #include <Engine/GfxDebug.h> #include <Engine/GrimInput.h> #include <Engine/Memory.h> #include <Engine/View.h> #include <Shared/Core/grimJson.h> #include <Shared/Core/Timer.h> // TEMP AHH #include <Engine/d3dx12.h> #include <Engine/DXGfx.h> #include <Engine/Surface.h> #include <Engine/GraphicsState.h> #include <Engine/DrawElement.h> #include <Engine/Buffer.h> #include <Engine/ForwardLighting.h> #include <Engine/RenderGraph.h> static ID3D12PipelineState* m_pipelineState; static gfx::Shader shader; static gfx::Buffer vertexBuffer; static gfx::Buffer indexBuffer; static gfx::Buffer s_viewBuffer; static gfx::Buffer s_lightBuffer; static gfx::GraphicsState m_graphicsState; static gfx::ResourceState m_resourceState; gfx::View s_view; static gfx::RenderView s_renderView; gfx::DrawElement* s_drawElements; static gfx::RenderPass s_passDef; #include <d3dcompiler.h> // END TEMP static bool HasArg(const char* buffer, const char* arg) { return strstr(buffer, arg) != nullptr; } static void CheckForArgs(char* args) { if (HasArg(args, "-coolSkateboard")) g_engineGlobals.hasCoolSkateboard = true; if (HasArg(args, "-bootingFromEditor")) g_engineGlobals.bootingFromEditor = true; } static void HandleArgs(const int argc, char** argv) { char buffer[1024]; buffer[0] = '\0'; if (argc > 1) { for (int i = 1; i < argc; ++i) { strcat(buffer, " "); strcat(buffer, argv[i]); } } else { char path[256]; snprintf(path, 256, "%s\\argv.txt", CODE_PATH); grimFile::LoadTextFile(path, buffer, 1024); } printf("Starting game with command line arguments:%s\n", buffer); CheckForArgs(buffer); } static void LoadEngineConfig() { char path[256]; snprintf(path, 256, "%s\\config.txt", CODE_PATH); char* config = grimFile::LoadTextFile(path); grimJson::JsonDocument doc; grimJson::ParseDocument(doc, config); g_engineGlobals.windowWidth = doc["windowWidth"].GetUint(); g_engineGlobals.windowHeight = doc["windowHeight"].GetUint(); g_engineGlobals.frameBufferWidth = doc["displayBufferResolutionX"].GetUint(); g_engineGlobals.frameBufferHeight = doc["displayBufferResolutionY"].GetUint(); g_engineGlobals.aspectRatio = (float)g_engineGlobals.frameBufferWidth / g_engineGlobals.frameBufferHeight; g_engineGlobals.numDisplayBuffers = doc["numDisplayBuffers"].GetUint(); if(g_engineGlobals.hasCoolSkateboard) strcpy(g_engineGlobals.windowTitle, "How bout that skateboard though?"); else strcpy(g_engineGlobals.windowTitle, doc["windowTitle"].GetString()); delete config; } // <<<<<<< TEMP struct Vertex { float position[3]; float normals[3]; float uv[2]; }; // >>>>>>>> TEMP static void Init() { Clock::Initialize(); mem::Init(); grimFile::Init(); // Loads engine settings from config.txt LoadEngineConfig(); gfx::Init(); grimInput::InitAndSetupMap(g_engineGlobals.windowWidth, g_engineGlobals.windowHeight); // Load the scene file, create all of the resources, initialize state of systems // <<<<<<<<< TEMP HRESULT hr; shader.shaderStages = gfx::kVertex | gfx::kPixel; // TODO: Reflect shader stage information gfx::LoadShader(shader, "shaders.hlsl"); // Create the vertex buffer. { // pos, normal, uv Vertex triangleVertices[] = { { { -0.5f, 0.5f, -0.5f }, { -0.577f, 0.577f, -0.577f }, { 0.0f, 0.0f } }, { { 0.5f, 0.5f, -0.5f }, { 0.577f, 0.577f, -0.577f }, { 1.0f, 0.0f } }, // 4--------5 { { -0.5f, -0.5f, -0.5f }, { -0.577f, -0.577f, -0.577f }, { 0.0f, 1.0f } }, // /| /| { { 0.5f, -0.5f, -0.5f }, { 0.577f, -0.577f, -0.577f }, { 1.0f, 1.0f } }, // / | / | // 0--------1 | // | 6-----|--7 { { -0.5f, 0.5f, 0.5f }, { -0.577f, 0.577f, 0.577f }, { 0.0f, 1.0f } }, // | / | / { { 0.5f, 0.5f, 0.5f }, { 0.577f, 0.577f, 0.577f }, { 0.0f, 0.0f } }, // |/ |/ { { -0.5f, -0.5f, 0.5f }, { -0.577f, -0.577f, 0.577f }, { 1.0f, 1.0f } }, // 2--------3 { { 0.5f, -0.5f, 0.5f }, { 0.577f, -0.577f, 0.577f }, { 0.0f, 1.0f } } }; const uint32_t vertexBufferSize = sizeof(triangleVertices); gfx::BufferDefinition vertexBufferDefinition = {"Cube Vertex Buffer", triangleVertices, { vertexBufferSize, 0 }, gfx::kVertexBuffer, sizeof(Vertex) }; gfx::CreateBuffer(vertexBufferDefinition, vertexBuffer); } // index buffer uint16_t indices[] = { 0, 1, 2, 1, 3, 2, 1, 5, 3, 5, 7, 3, 5, 4, 7, 4, 6, 7, 4, 0, 6, 0, 2, 6, 4, 5, 0, 5, 1, 0, 2, 3, 6, 3, 7, 6 }; gfx::BufferDefinition indexBufferDefinition = { "Cube Index Buffer", indices,{ sizeof(indices), 0 }, gfx::kIndexBuffer, sizeof(uint16_t) }; gfx::CreateBuffer(indexBufferDefinition, indexBuffer); // view constant buffer Matrix viewLW = Matrix::CreateLookAt(Vector3(0.0f, 0.0f, -3.0f), Vector3::kZero, Vector3::kUp); s_view = gfx::MakeView(0.25f * 3.141592f, (float)g_engineGlobals.frameBufferWidth, (float)g_engineGlobals.frameBufferHeight, 0.01f, 100.0f, viewLW); s_renderView = gfx::RenderViewFromView(s_view); gfx::BufferDefinition viewBufferDef{ "View Buffer", &s_renderView, { sizeof(gfx::RenderView), 0 }, gfx::kConstantBuffer, sizeof(gfx::RenderView) }; gfx::CreateBuffer(viewBufferDef, s_viewBuffer); gfx::RasterizerState rs = { gfx::kSolid, gfx::kBack, false }; gfx::BlendState bs = { false, gfx::kOne, gfx::kZero, gfx::kAdd, gfx::kOne, gfx::kZero, gfx::kAdd }; gfx::MultisampleState ms = { 1, 0 }; gfx::DepthStencilState dss = { false, false, gfx::kLessEqual }; m_graphicsState = { rs, dss, ms,{ bs, bs, bs, bs, bs, bs, bs, bs }, gfx::kTriangleList }; m_resourceState = { &shader, &vertexBuffer, &indexBuffer, &s_viewBuffer }; const gfx::Surface* renderTarget[8] = { g_renderGraph.GetSurface(gfx::RenderGraph::kFramebufferIndex) }; const gfx::Surface* depthRenderTarget = g_renderGraph.GetSurface(0); // fix me D3D12_GRAPHICS_PIPELINE_STATE_DESC pipelineDesc = plat::StateToPipelineDesc(m_graphicsState, m_resourceState, renderTarget, depthRenderTarget); hr = plat::GetDevice()->CreateGraphicsPipelineState(&pipelineDesc, IID_PPV_ARGS(&m_pipelineState)); GRIM_ASSERT(!hr, "Failed to create graphics pipeline state"); s_drawElements = new gfx::DrawElement[1]; s_drawElements[0].resourceState = m_resourceState; s_drawElements[0].indexCount = 36; s_passDef.renderTarget[0] = -1; s_passDef.depthTarget = 0; s_passDef.view = s_view; s_passDef.state = m_graphicsState; // >>>>>>>>>>>> END TEMP } static void GameLoop() { debug::DebugCameraMovement(s_view, Clock::GetFrameTime()); } static void RunRenderGraph() { s_renderView = RenderViewFromView(s_view); gfx::UploadBufferData(s_viewBuffer); const int contextIndex = gfx::GetCurrentCommandContextIndex(); gfx::CommandContext* ctx = gfx::GetCommandContext(contextIndex); gfx::ForwardLighting_Data data; data.drawElements = s_drawElements; data.numElements = 1; ctx->Reset(); ctx->HACK_SetPipelineState(m_pipelineState); //ForwardLighting_Execute(ctx, s_passDef, (size_t)&data); g_renderGraph.Execute(ctx); ctx->Close(); } static void Shutdown() { gfx::SyncForShutdown(); // TEMP delete[] s_drawElements; m_pipelineState->Release(); DestroyShader(shader); DestroyBuffer(vertexBuffer); DestroyBuffer(indexBuffer); DestroyBuffer(s_viewBuffer); DestroyBuffer(s_lightBuffer); // TEMP gfx::Shutdown(); mem::Shutdown(); } static void Debug_UpdateWindowTitle() { float mouseX = grimInput::GetFloat(grimInput::kMouseReticleX); float mouseY = grimInput::GetFloat(grimInput::kMouseReticleY); char newTitle[EngineGlobals::kMaxWindowTitleLength]; float timeSeconds = Clock::GetFrameTime(); Vector4 eyePosition = s_renderView.eyePosition; snprintf(newTitle, EngineGlobals::kMaxWindowTitleLength, "Grimoire Engine - Process Time: %.3f, Frame Time: %.1fms (%.2f fps) Mouse X: %.3f, Mouse Y: %.3f, Cam X: %.3f, Cam Y: %.3f, Cam Z: %.3f", Clock::GetTimeSinceProcessStart(), timeSeconds * 1000.0f, 1.0f / timeSeconds, mouseX, mouseY, eyePosition.x, eyePosition.y, eyePosition.z ); EngineGlobals::SetWindowTitle(newTitle); } int EngineMain(int argc, char** argv) { HandleArgs(argc, argv); Init(); while (true) { Clock::FrameTick(); plat::ProcessGfx(); if (gfx::ShouldClose()) break; grimInput::Update(); GameLoop(); RunRenderGraph(); gfx::SubmitAllContexts(); gfx::FlipAndAdvanceFrame(); Debug_UpdateWindowTitle(); } Shutdown(); return 0; }
27.866883
197
0.685774
ariabonczek
47e52b32af0a9f7d0b4688374f9ba705d857f6e6
726
cpp
C++
cpp/1001-10000/1751-1760/Minimum Limit of Balls in a Bag.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/1001-10000/1751-1760/Minimum Limit of Balls in a Bag.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/1001-10000/1751-1760/Minimum Limit of Balls in a Bag.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
class Solution { bool check(const vector<int>& nums, int maxOperations, int penalty) { int ops = 0; for (int num : nums) { ops += (num-1) / penalty; } return ops <= maxOperations; } public: int minimumSize(vector<int>& nums, int maxOperations) { int left = 1, right = *max_element(nums.begin(), nums.end()); while (left < right) { int mid = (left + right) / 2; bool can_do_it = check(nums, maxOperations, mid); if (can_do_it) { right = mid; } else { left = mid + 1; } } return left; } };
24.2
73
0.440771
KaiyuWei
47eb3359d208291d1f453ee04de4d6def4ef9554
1,537
cc
C++
src/HesaiLidar_General_SDK/test/test.cc
sustech-isus/HesaiLidar_General_ROS
f604478e3bd316a20eb886850bef16a9903a8bc6
[ "Apache-2.0" ]
null
null
null
src/HesaiLidar_General_SDK/test/test.cc
sustech-isus/HesaiLidar_General_ROS
f604478e3bd316a20eb886850bef16a9903a8bc6
[ "Apache-2.0" ]
null
null
null
src/HesaiLidar_General_SDK/test/test.cc
sustech-isus/HesaiLidar_General_ROS
f604478e3bd316a20eb886850bef16a9903a8bc6
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright 2019 The Hesai Technology Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "pandarGeneral_sdk/pandarGeneral_sdk.h" void gpsCallback(int timestamp) { printf("gps: %d", timestamp); } void lidarCallback(boost::shared_ptr<PPointCloud> cld, double timestamp) { printf("Frame timestamp: %lf,", timestamp); printf("point_size: %ld,",cld->points.size()); } int main(int argc, char** argv) { // PandarGeneralSDK pandarGeneral(std::string("192.168.1.201"), 2368, 10110, \ // lidarCallback, gpsCallback, 0, 0, 1, std::string("Pandar40P")); PandarGeneralSDK pandarGeneral(std::string("/home/fanglinwen/my_project/Pandar128SDK/Crowded_Crossing_Pandar40P.pcap"), \ lidarCallback, 0, 0, 1, std::string("Pandar40P")); pandarGeneral.Start(); while (true) { sleep(100); } return 0; }
34.155556
127
0.641509
sustech-isus
47eb39ecd4a3a462dc39981462c3466ec76d5a18
3,106
hpp
C++
libvfs/include/vfs_bundle.hpp
mbenniston/vfs
24aa9fa15ff8aab9a4235dd16a7a889aa1868b7c
[ "MIT" ]
1
2021-09-18T06:59:29.000Z
2021-09-18T06:59:29.000Z
libvfs/include/vfs_bundle.hpp
mbenniston/vfs
24aa9fa15ff8aab9a4235dd16a7a889aa1868b7c
[ "MIT" ]
null
null
null
libvfs/include/vfs_bundle.hpp
mbenniston/vfs
24aa9fa15ff8aab9a4235dd16a7a889aa1868b7c
[ "MIT" ]
null
null
null
/** * @file vfs_bundle.hpp * @brief Contains the manager class responsible for handling the mounting and access of bundles */ #pragma once #include "vfs_bundle_def.hpp" #include "vfs_file.hpp" namespace vfs { // responsible for handling the mounting and access of bundles /** * @brief Handles mounting and access of bundles * Allows for the user to store global and named bundles (mounted bundles) * Also allows the user to access files within bundles. */ class BundleManager final { private: std::vector<Bundle> m_globalBundles; std::unordered_map<std::string_view, Bundle> m_mountedBundles; std::unordered_map<std::string, std::pair<const Bundle*, std::weak_ptr<Resource>>> m_globalBundleResources; std::unordered_map<std::string, std::unordered_map<std::string, std::weak_ptr<Resource>>> m_mountedBundleResources; void disownMountedBundle(const std::string& bundleName); public: /** * @brief Adds a new bundle to the list of global bundles * * @param bundle The bundle to be added to the global list */ void addGlobalBundle(const Bundle& bundle); /** * @brief Removes a given bundle from the list of global bundles * * @param bundle The bundle to be removed */ void removeGlobalBundle(const Bundle& bundle); /** * @brief Mounts a new bundle at the given bundle name * * @param bundleName The identifier to access the bundle * @param bundle The bundle to be attached */ void addBundle(const std::string& bundleName, const Bundle& bundle); /** * @brief Removes a bundle from a given mount point * * @param bundleName The bundle to be unmounted */ void removeBundle(const std::string& bundleName); /** * @brief Retrieve a resource from the list of global bundles * * @param fileName The name of the file to be retrieved * @return std::shared_ptr<Resource> A pointer to a shared resource representing the bundle data */ std::shared_ptr<Resource> getResourceFromGlobalBundle(const std::string& fileName); /** * @brief Retrieve a resource from a specified mounted bundle * * @param bundleName The name of the bundle to be accessed * @param fileName The name of the file to be retrieved * @return std::shared_ptr<Resource> A pointer to a shared resource representing the bundle data */ std::shared_ptr<Resource> getResourceFromMountedBundle(const std::string& bundleName, const std::string& fileName); // explicitly disable copying and moving BundleManager& operator=(BundleManager&&) = delete; BundleManager& operator=(const BundleManager&) = delete; BundleManager(BundleManager&&) = delete; BundleManager(const BundleManager&) = delete; BundleManager(); ~BundleManager(); }; }
36.116279
123
0.63812
mbenniston
47ee55cbc8b51b3ed413ad61ecf68166bae30b5b
2,035
cpp
C++
aff3ct-server/src/aff3ct-errc.cpp
simonrus/aff3ct-bfe
c84ddc11ec75140632471e13f3f55dae3ce7950e
[ "MIT" ]
null
null
null
aff3ct-server/src/aff3ct-errc.cpp
simonrus/aff3ct-bfe
c84ddc11ec75140632471e13f3f55dae3ce7950e
[ "MIT" ]
null
null
null
aff3ct-server/src/aff3ct-errc.cpp
simonrus/aff3ct-bfe
c84ddc11ec75140632471e13f3f55dae3ce7950e
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2017 aff3ct * Copyright (c) 2019 Sergei Semenov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ # include <aff3ct-errc.h> std::ostringstream g_err_stream; char g_log_buffer[LOG_BUF_SIZE]; char* getLastLogEntry() { return g_log_buffer; } namespace { // anonymous namespace struct Aff3ctErrCategory : std::error_category { const char* name() const noexcept override; std::string message(int ev) const override; }; const char* Aff3ctErrCategory::name() const noexcept { return "aff3ct-server errors"; } std::string Aff3ctErrCategory::message(int ev) const { switch (static_cast<Aff3ctErrc> (ev)) { case Aff3ctErrc::ParsingError: return "General parsing error"; default: return "(Uknown error)"; } } const Aff3ctErrCategory theAff3ctErrCategory {}; } // anonymous namespace std::error_code make_error_code(Aff3ctErrc e) { return {static_cast<int>(e), theAff3ctErrCategory}; }
31.307692
81
0.728747
simonrus
47f56a64d5b4b5c3c124a4300f8e82ef90a9d947
1,854
cpp
C++
src/CommonControls/GenericStaticBitmap/GenericStaticBitmap.cpp
ericfont/Examples_wxWidgets
5cd123eff9a5f9971413ec2f8effc15b76622987
[ "MIT" ]
70
2019-11-18T15:04:23.000Z
2022-03-28T22:42:16.000Z
src/CommonControls/GenericStaticBitmap/GenericStaticBitmap.cpp
gammasoft71/Examples.wxWidgets
c710f31c29d502fee699f044014a5eae4ce6ef22
[ "MIT" ]
10
2020-11-18T02:37:11.000Z
2021-09-16T17:05:29.000Z
src/CommonControls/GenericStaticBitmap/GenericStaticBitmap.cpp
gammasoft71/Examples.wxWidgets
c710f31c29d502fee699f044014a5eae4ce6ef22
[ "MIT" ]
10
2021-05-14T11:41:42.000Z
2022-03-20T00:38:17.000Z
#include <wx/app.h> #include <wx/combobox.h> #include <wx/frame.h> #include <wx/generic/statbmpg.h> #include <wx/panel.h> #include <wx/sizer.h> #include "Logo.xpm" namespace Examples { class Frame : public wxFrame { public: Frame() : wxFrame(nullptr, wxID_ANY, "GenericStaticBitmap example") { SetClientSize(300, 340); choice1->Append("Scale_None", reinterpret_cast<void*>(wxStaticBitmap::Scale_None)); choice1->Append("Scale_Fill", reinterpret_cast<void*>(wxStaticBitmap::Scale_Fill)); choice1->Append("Scale_AspectFit", reinterpret_cast<void*>(wxStaticBitmap::Scale_AspectFit)); choice1->Append("Scale_AspectFill", reinterpret_cast<void*>(wxStaticBitmap::Scale_AspectFill)); choice1->SetSelection(0); choice1->Bind(wxEVT_CHOICE, [&](wxCommandEvent& e) { staticBitmap1->SetScaleMode(static_cast<wxStaticBitmap::ScaleMode>(reinterpret_cast<long long>(choice1->GetClientData(choice1->GetSelection())))); }); boxSizer->Add(choice1, 0, wxALIGN_CENTER|wxTOP|wxLEFT|wxRIGHT, 20); boxSizer->Add(staticBitmap1, 1, wxGROW|wxALL, 20); staticBitmap1->SetScaleMode(static_cast<wxStaticBitmap::ScaleMode>(reinterpret_cast<long long>(choice1->GetClientData(choice1->GetSelection())))); staticBitmap1->SetWindowStyle(wxBORDER_SIMPLE); staticBitmap1->SetBitmap({Logo_xpm}); panel->SetSizerAndFit(boxSizer); } private: wxPanel* panel = new wxPanel(this); wxBoxSizer* boxSizer = new wxBoxSizer(wxVERTICAL); wxGenericStaticBitmap* staticBitmap1 = new wxGenericStaticBitmap(panel, wxID_ANY, wxNullBitmap); wxChoice* choice1 = new wxChoice(panel, wxID_ANY); }; class Application : public wxApp { bool OnInit() override { (new Frame())->Show(); return true; } }; } wxIMPLEMENT_APP(Examples::Application);
38.625
154
0.707659
ericfont
47f5777fbf743a2b1f16159e5715786f538c8f52
1,579
cc
C++
tests/decode_matrix_den_delay_individualg_dense/test.cc
9inpachi/genn-opencl
33231225a72611c7b629ef1d13f325f35d4ae2f7
[ "MIT" ]
1
2020-06-28T19:48:48.000Z
2020-06-28T19:48:48.000Z
tests/decode_matrix_den_delay_individualg_dense/test.cc
9inpachi/genn-opencl
33231225a72611c7b629ef1d13f325f35d4ae2f7
[ "MIT" ]
1
2020-02-10T15:26:29.000Z
2020-02-10T15:26:29.000Z
tests/decode_matrix_den_delay_individualg_dense/test.cc
9inpachi/genn-opencl
33231225a72611c7b629ef1d13f325f35d4ae2f7
[ "MIT" ]
1
2020-02-10T10:47:12.000Z
2020-02-10T10:47:12.000Z
//-------------------------------------------------------------------------- /*! \file decode_matrix_den_delay_individualg_dense/test.cc \brief Main test code that is part of the feature testing suite of minimal models with known analytic outcomes that are used for continuous integration testing. */ //-------------------------------------------------------------------------- // Google test includes #include "gtest/gtest.h" // Auto-generated simulation code includess #include "decode_matrix_den_delay_individualg_dense_CODE/definitions.h" // **NOTE** base-class for simulation tests must be // included after auto-generated globals are includes #include "../../utils/simulation_test_den_delay_decoder_matrix.h" //---------------------------------------------------------------------------- // SimTest //---------------------------------------------------------------------------- class SimTest : public SimulationTestDecoderDenDelayMatrix { public: //---------------------------------------------------------------------------- // SimulationTest virtuals //---------------------------------------------------------------------------- virtual void Init() { // Loop through presynaptic neurons for(unsigned int i = 0; i < 10; i++) { // Connect row to output neuron with weight of one and dendritic delay of (9 - i) dSyn[i] = (uint8_t)(9 - i); } } }; TEST_F(SimTest, DecodeMatrixDenDelayIndividualgDense) { // Check total error is less than some tolerance EXPECT_TRUE(Simulate()); }
35.088889
102
0.498417
9inpachi
47f5d0768a7860af7e6d61effb807078e526a19e
1,057
cpp
C++
src/GFX_Base/GFX_BaseController.cpp
ldornbusch/All2D_Base
c790293b3030de97f65d62f6617222c42d18fa6a
[ "Apache-2.0" ]
null
null
null
src/GFX_Base/GFX_BaseController.cpp
ldornbusch/All2D_Base
c790293b3030de97f65d62f6617222c42d18fa6a
[ "Apache-2.0" ]
null
null
null
src/GFX_Base/GFX_BaseController.cpp
ldornbusch/All2D_Base
c790293b3030de97f65d62f6617222c42d18fa6a
[ "Apache-2.0" ]
null
null
null
// GFX_BaseController.cpp: Implementierung der Klasse GFX_BaseController. // ////////////////////////////////////////////////////////////////////// #include "GFX_BaseController.hpp" #include "../All2DEngine/All2D/All2D_System.h" ////////////////////////////////////////////////////////////////////// // Konstruktion/Destruktion ////////////////////////////////////////////////////////////////////// GFX_BaseController::GFX_BaseController(): All2D_Controller("GFX_Base") { } bool GFX_BaseController::paint(Image& backBuffer) { int x_max=All2D_System::fixedX-1, y_max=All2D_System::fixedY-1; static int t = 0; t++; int x = t*6 % x_max; int y = (int)(((float)x / x_max) * y_max); backBuffer.clear(); backBuffer.getBitMap()->Line(x,0,x_max/2,y_max/2,0x000000,0xffffff); backBuffer.getBitMap()->Line(0,y_max-y,x_max/2,y_max/2,0x000000,0xffffff); backBuffer.getBitMap()->Line(x_max,y,x_max/2,y_max/2,0x000000,0xffffff); backBuffer.getBitMap()->Line(x_max-x,y_max,x_max/2,y_max/2,0x000000,0xffffff); return (!isExit); }
36.448276
82
0.573321
ldornbusch
47fc5c9b28e5ff4511ebb4a9dd2f2d2eabf1eee1
151
cpp
C++
somaate10.cpp
gilsonaureliano/Introducao_a_programacao_estrutura_em_c
d186d72de6fd6002cad511d6d7d8545d61090a9f
[ "MIT" ]
null
null
null
somaate10.cpp
gilsonaureliano/Introducao_a_programacao_estrutura_em_c
d186d72de6fd6002cad511d6d7d8545d61090a9f
[ "MIT" ]
null
null
null
somaate10.cpp
gilsonaureliano/Introducao_a_programacao_estrutura_em_c
d186d72de6fd6002cad511d6d7d8545d61090a9f
[ "MIT" ]
null
null
null
#include <stdio.h> int main(){ int soma = 0; for(int cont=1;cont<=10;cont=cont+1){ soma +=cont; printf(" %d", cont); } printf(" = %d\n", soma); }
12.583333
37
0.562914
gilsonaureliano
47fe1c112dae37ec3e655236bbda825d5964b8ff
7,356
cpp
C++
Insipid3D/EntityPhysicsProp.cpp
thehugh100/Insipid3D
429a9e6022c1a0bca842209310f949647f4c441e
[ "MIT" ]
90
2017-04-10T20:08:53.000Z
2022-03-28T19:16:04.000Z
Insipid3D/EntityPhysicsProp.cpp
CristianRodrigoGuarachiIbanez/Insipid3D
429a9e6022c1a0bca842209310f949647f4c441e
[ "MIT" ]
2
2019-11-29T04:00:26.000Z
2021-05-29T10:39:24.000Z
Insipid3D/EntityPhysicsProp.cpp
CristianRodrigoGuarachiIbanez/Insipid3D
429a9e6022c1a0bca842209310f949647f4c441e
[ "MIT" ]
15
2017-10-02T03:15:03.000Z
2022-03-28T20:46:34.000Z
#include "EntityPhysicsProp.h" #include "engine.h" #include "EntityManager.h" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <algorithm> #include "Raytrace.h" #include "BulletCollision/CollisionShapes/btShapeHull.h" #include "Util.h" #include "EntityLight.h" #include <glm/gtc/quaternion.hpp> #include <glm/common.hpp> #include "Base64.h" #include "MeshManager.h" EntityPhysicsProp::EntityPhysicsProp(std::string modelName, glm::vec3 origin, float mass) :origin(origin), modelName(modelName), mass(mass) { entityType = "EntityPhysicsProp"; entityTraits.setTrait("EntityPhysicsProp"); entityTraits.setTrait("PhysicsEntity"); active = 1; backfaceCull = 1; transform = glm::mat4(0.f); velocity = glm::vec3(0, 0, 0); angularVelocity = glm::vec3(0, 0, 0); physicsState = ""; vars.registerVal("origin", Serializer(&origin)); vars.registerVal("modelName", Serializer(&modelName)); vars.registerVal("transform", Serializer(&transform)); vars.registerVal("mass", Serializer(&mass)); vars.registerVal("velocity", Serializer(&velocity)); vars.registerVal("angularVelocity", Serializer(&angularVelocity)); //vars.registerVal("physicsState", Serializer(&physicsState)); } EntityPhysicsProp::EntityPhysicsProp() { entityType = "EntityPhysicsProp"; entityTraits.setTrait("EntityPhysicsProp"); entityTraits.setTrait("PhysicsEntity"); mass = 1; body = nullptr; origin = glm::vec3(0.); modelName = ""; model = nullptr; active = 1; backfaceCull = 1; transform = glm::mat4(0.f); velocity = glm::vec3(0, 0, 0); angularVelocity = glm::vec3(0, 0, 0); physicsState = ""; vars.registerVal("origin", Serializer(&origin)); vars.registerVal("modelName", Serializer(&modelName)); vars.registerVal("transform", Serializer(&transform)); vars.registerVal("mass", Serializer(&mass)); vars.registerVal("velocity", Serializer(&velocity)); vars.registerVal("angularVelocity", Serializer(&angularVelocity)); //vars.registerVal("physicsState", Serializer(&physicsState)); } EntityPhysicsProp::~EntityPhysicsProp() { std::cout << "removed EntityPhysicsProp" << std::endl; remove(); } void EntityPhysicsProp::tick() { } void EntityPhysicsProp::init() { model = engine->meshManager->getMesh(modelName); btConvexHullShape* pConvexHullShape; Mesh* eHull = engine->meshManager->getMesh(modelName + ".hull.glb"); if (eHull != nullptr && eHull->meshEntries.size() != 0) { btConvexHullShape convexHullShape((btScalar*)eHull->meshEntries[0]->meshRef->mVertices, eHull->meshEntries[0]->meshRef->mNumVertices, 3 * sizeof(float)); convexHullShape.setMargin(0); btShapeHull* hull = new btShapeHull(&convexHullShape); hull->buildHull(0, 1); pConvexHullShape = new btConvexHullShape((const btScalar*)hull->getVertexPointer(), hull->numVertices(), sizeof(btVector3)); delete hull; } else { btConvexHullShape convexHullShape((btScalar*)model->meshEntries[0]->meshRef->mVertices, model->meshEntries[0]->meshRef->mNumVertices, 3 * sizeof(float)); convexHullShape.setMargin(0); btShapeHull* hull = new btShapeHull(&convexHullShape); hull->buildHull(0); pConvexHullShape = new btConvexHullShape((const btScalar*)hull->getVertexPointer(), hull->numVertices(), sizeof(btVector3)); delete hull; } btTransform t; t.setIdentity(); t.setOrigin(btVector3(origin.x, origin.y, origin.z)); btVector3 inertia; pConvexHullShape->calculateLocalInertia(mass, inertia); btMotionState* motion = new btDefaultMotionState(t); btRigidBody::btRigidBodyConstructionInfo info(mass, motion, pConvexHullShape, inertia); body = new btRigidBody(info); body->setUserPointer(this); engine->getMap()->collisionState->world->addRigidBody(body); initialised = 1; } void EntityPhysicsProp::destroy() { remove(); } void EntityPhysicsProp::remove() { engine->getMap()->collisionState->world->removeRigidBody(body); active = 0; } void EntityPhysicsProp::applyForce(glm::vec3 force) { body->activate(); body->applyCentralImpulse(Util::vec3Conv(force)); } void EntityPhysicsProp::applyImpulse(glm::vec3 impulse) { body->activate(); body->applyCentralImpulse(Util::vec3Conv(impulse)); } void EntityPhysicsProp::update() { float m[16]; body->getWorldTransform().getOpenGLMatrix(m); transform = glm::make_mat4(m); } void EntityPhysicsProp::setTransform(glm::mat4 transform) { body->getWorldTransform().setFromOpenGLMatrix(glm::value_ptr(transform)); } nlohmann::json EntityPhysicsProp::serialize() { /*btDefaultSerializer* serializer = new btDefaultSerializer(); size_t sBufSize = body->calculateSerializeBufferSize(); char* sBuf = new char[sBufSize]; body->serialize(sBuf, serializer); physicsState = macaron::Base64::Encode(std::string((const char*)sBuf, sBufSize)); delete serializer; delete sBuf;*/ velocity = Util::vec3Conv(body->getLinearVelocity()); angularVelocity = Util::vec3Conv(body->getAngularVelocity()); return nlohmann::json::parse(vars.serialize()); } glm::vec3 EntityPhysicsProp::getPosition() { return Util::vec3Conv(body->getWorldTransform().getOrigin()); } void EntityPhysicsProp::render() { if (active) { update(); if (!backfaceCull) glDisable(GL_CULL_FACE); GLuint shader = engine->shaderManager->getShader("shaders/default"); btTransform t; body->getMotionState()->getWorldTransform(t); float mat[16]; t.getOpenGLMatrix(mat); float brightnessMultiplier = !RayTrace::rayTrace(glm::vec3(mat[12], mat[13], mat[14]), -engine->getMap()->sunVec, engine->getMap()->getMesh()).hit; glUseProgram(shader); glActiveTexture(GL_TEXTURE0); glUniformMatrix4fv(glGetUniformLocation(shader, "model"), 1, GL_FALSE, mat); glUniformMatrix4fv(glGetUniformLocation(shader, "view"), 1, GL_FALSE, glm::value_ptr(engine->camera->getViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(shader, "proj"), 1, GL_FALSE, glm::value_ptr(engine->camera->getProjectionMatrix())); glUniform3fv(glGetUniformLocation(shader, "cameraPos"), 1, glm::value_ptr(engine->camera->pos)); glUniform4fv(glGetUniformLocation(shader, "sunVec"), 1, glm::value_ptr(glm::vec4(engine->getMap()->sunVec, brightnessMultiplier))); engine->getMap()->getLightsShaderUniforms(shader, getPosition()); model->render(); if (!backfaceCull) glEnable(GL_CULL_FACE); //GLuint flatShader = engine->shaderManager->getShader("shaders/flat"); //glUseProgram(flatShader); //glActiveTexture(GL_TEXTURE0); //glUniformMatrix4fv(glGetUniformLocation(flatShader, "model"), 1, GL_FALSE, glm::value_ptr(glm::mat4(1.))); //glUniformMatrix4fv(glGetUniformLocation(flatShader, "view"), 1, GL_FALSE, glm::value_ptr(engine->camera->getViewMatrix())); //glUniformMatrix4fv(glGetUniformLocation(flatShader, "proj"), 1, GL_FALSE, glm::value_ptr(engine->camera->getProjectionMatrix())); //glUniform3f(glGetUniformLocation(flatShader, "col"), 1., 1., 1.); //glDepthMask(GL_FALSE); //glPointSize(4); //glLineWidth(4); //auto rot = body->getWorldTransform().getRotation(); //glm::quat gQuat = glm::quat(rot.getW(), rot.getX(), rot.getY(), rot.getZ()); //glBegin(GL_LINES); //glVertex3fv(glm::value_ptr( getPosition() )); //glVertex3fv(glm::value_ptr( getPosition() + gQuat * glm::vec3(0, 1, 0) )); //glEnd(); // //glDepthMask(GL_TRUE); } }
30.02449
155
0.733279
thehugh100
9a069fd3ed57fe5b68398f8b7acc176c222ab318
988
cpp
C++
Input/MouseKeyboardInput.cpp
cryptobuks1/Stratum
3ecf56c0ce9010e6e95248c0d63edc41eeb13910
[ "MIT" ]
2
2019-10-01T22:55:47.000Z
2019-10-04T20:25:29.000Z
Input/MouseKeyboardInput.cpp
cryptobuks1/Stratum
3ecf56c0ce9010e6e95248c0d63edc41eeb13910
[ "MIT" ]
null
null
null
Input/MouseKeyboardInput.cpp
cryptobuks1/Stratum
3ecf56c0ce9010e6e95248c0d63edc41eeb13910
[ "MIT" ]
null
null
null
#include <Input/MouseKeyboardInput.hpp> #include <Core/Window.hpp> MouseKeyboardInput::MouseKeyboardInput(){ mMousePointer.mDevice = this; mMousePointer.mAxis.emplace(0, 0.f); mMousePointer.mAxis.emplace(1, 0.f); mMousePointer.mAxis.emplace(2, 0.f); mLockMouse = false; mCurrent.mCursorPos = mLast.mCursorPos = 0; mCurrent.mCursorDelta = mLast.mCursorDelta = 0; mCurrent.mCursorDelta = mLast.mScrollDelta = 0; mCurrent.mKeys = {}; mLast.mKeys = {}; } void MouseKeyboardInput::LockMouse(bool l) { #ifdef WINDOWS if (mLockMouse && !l) ShowCursor(TRUE); else if (!mLockMouse && l) ShowCursor(FALSE); #else // TODO: hide cursor on linux #endif mLockMouse = l; } void MouseKeyboardInput::NextFrame() { mMousePointer.mLastWorldRay = mMousePointer.mWorldRay; mMousePointer.mLastAxis = mMousePointer.mAxis; mMousePointer.mLastGuiHitT = mMousePointer.mGuiHitT; mLast = mCurrent; mCurrent.mScrollDelta = 0; mCurrent.mCursorDelta = 0; mMousePointer.mGuiHitT = -1.f; }
26
55
0.744939
cryptobuks1
9a090e2466b778645520f27a7e7642900a8148de
7,016
cpp
C++
src/server/Network/ServerBase.cpp
NoUITeam/TinyAndPretty-plus
37f5b7367d7f41d1142ebc357223f0cccbb66d27
[ "Apache-2.0" ]
null
null
null
src/server/Network/ServerBase.cpp
NoUITeam/TinyAndPretty-plus
37f5b7367d7f41d1142ebc357223f0cccbb66d27
[ "Apache-2.0" ]
null
null
null
src/server/Network/ServerBase.cpp
NoUITeam/TinyAndPretty-plus
37f5b7367d7f41d1142ebc357223f0cccbb66d27
[ "Apache-2.0" ]
null
null
null
#include <connect/Network/ServerBase.h> #include <sys/sendfile.h> #include <netinet/tcp.h> #include <sys/signal.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> Socket::Socket() { // Initialize socket port sockfd = socket(PROTO_FAMILT, SOCK_TYPE, 0); NETERROR(sockfd < 0, "init socket error "); // Set up host address #ifdef IPV_4 address = sockaddr_in { sin_family : PROTO_FAMILT, sin_port : htons(PORT), sin_addr : {s_addr : htonl(HOST_ADDR)}, }; #elif IPV_6 // near future #endif // Permit to reuse address #ifdef ADDR_REUSE int addr_reuse = ADDR_REUSE; NETERROR( setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &addr_reuse, sizeof(int)) < 0 , "set address reuse"); #endif //Set up timeout limit for receive and send struct timeval recv_timeout = (timeval)RECV_TIMEOUT; NETERROR( setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,&recv_timeout,sizeof(timeval)) < 0 , "set timeVal error"); struct timeval send_timeout = (timeval)SEND_TIMEOUT; NETERROR( setsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,&send_timeout,sizeof(timeval)) < 0 , "set timeVal error"); // Bind port to socket file NETERROR( bind(sockfd, (sockaddr *)(&address), sizeof(address)) < 0 , "bind error"); // Set up max capacity of listening queue NETERROR( listen(sockfd, LISTEN_Q_MAX) < 0 , "listen error"); ::printf("Successfully Listen on %d\n" , PORT); } /* get one valid connection */ Connection *Socket::onConnect() { struct sockaddr_in _addr {0}; socklen_t _len = sizeof(_addr); int _connfd = accept(sockfd, (sockaddr *)&_addr, &_len); if(_connfd == -1) {errno = 0; return nullptr;} else return new Connection{_connfd, _len, _addr}; } /* block recv with time out*/ size_t Socket::recvData ( int _connfd, uint8_t **data, int flags, size_t buff_size ) { //initial temporary length var size_t cur = 0; ssize_t buff_len = 0; *data = static_cast<uint8_t *>( calloc(1 , buff_size) ); //loop recv and adjust buff size dynamically while ( (buff_len = recv(_connfd, *data + cur, buff_size - cur, flags)) ) { IFDEBUG ( std::cerr << "Recv Buff Info : FROM - " << _connfd << " " << cur << " " << buff_len << "\n" << "\terrno : " << errno << " ## " << std::endl; ) // handle errno occurs if (buff_len == -1) { if (errno == EAGAIN && !flags) {errno = 0; break;} else if (errno == EINTR) {errno = 0; continue;} else {errno = 0; break;} } cur += buff_len; // handle PEEK read if (flags & MSG_PEEK) break; // adjust buff size to 2x if (cur == buff_size && !flags) { buff_size <<= 1; if (buff_size > BUFF_MAX_SIZE || buff_size < cur) { cur = -1ULL; // ulld max break; } else { *data = static_cast<uint8_t *>( realloc(*data, buff_size) ); // 2^N memset(*data + cur, 0, buff_size >> 1); } } } return cur; } /* block recv but don't flush buffer */ size_t Socket::recvPeekData(int _connfd , uint8_t **data) { return recvData(_connfd , data , MSG_PEEK | MSG_DONTWAIT); } /* non-block recv */ size_t Socket::recvNonBlockData(int _connfd , uint8_t **data) { return recvData(_connfd , data , MSG_DONTWAIT); } /* non-block recv with absolutely length */ size_t Socket::recvCertainData(int _connfd , uint8_t **data , size_t _len) { //initial temporary length var size_t cur = 0; ssize_t buff_len = 0; *data = static_cast<uint8_t *>( calloc(1 , _len + 1) ); while ((buff_len = recv(_connfd , *data + cur , _len - cur , MSG_DONTWAIT | MSG_WAITALL))) { IFDEBUG ( std::cerr << "Cer Recv Buff Info : " << _len << " " << cur << " " << buff_len << "\n" << "\terrno : " << errno << " ## " << std::endl; ) if (buff_len == -1) { if (cur == _len) { errno = 0; break; } // successfully recv if (errno == EAGAIN) { errno = 0; continue; } else { errno = 0; break; } } cur += buff_len; } return (cur == _len) ? cur : -1ULL; } /* block send with time out */ size_t Socket::sendData(int _connfd , uint8_t* buff , size_t _len) // stupid version { //initial temporary length var ssize_t buff_len = 0; size_t cur = 0; //loop send while( ( buff_len = send(_connfd , buff + cur, _len - cur, MSG_NOSIGNAL ) ) ) { if(buff_len == -1) {errno = 0; break;} cur += buff_len; IFDEBUG ( std::cerr << "Send Buff Info : " << _len << " " << cur << " " << buff_len <<"\n" << "\terrno : " << errno << " ## " << std::endl ); } return ( cur == _len ) ? cur : -1ULL; } static void handlePipe(int id) { ::printf("# Broken pipe, Peer Socket Close\n"); } /* specially send file base on unix/sendfile() */ size_t Socket::sendFile(int _connfd , const char* _fpath) { struct stat target {0}; //check whether file exists and get it size if( stat(_fpath , &target) < 0 ) {errno = 0; return 0;} //initial temporary length var and open valid file int fd = open(_fpath , O_RDONLY); ssize_t cur = 0; ssize_t buff_len = 0; signal(SIGPIPE , handlePipe); //loop send while( ( buff_len = sendfile(_connfd , fd , (off_t *)&cur , target.st_size - cur) ) ) { if(buff_len == -1) {errno = 0; break;} IFDEBUG ( std::cerr << "Send FILE Info : " << target.st_size << " " << cur << " " << buff_len <<"\n" << "\terrno : " << errno << " ## " << std::endl ); } close(fd); return ( cur == target.st_size ) ? cur : -1ULL; } /* same as sendFile() just with a header */ size_t Socket::sendFileWithHeader(int _connfd , const char* _fpath , uint8_t *header , size_t header_len) { //int opt = 1; // use TCP_CORK , but segmentation fault *** // NETERROR( // setsockopt(sockfd, SOL_TCP, TCP_CORK, &opt, sizeof (opt)) < 0 // , "cork error"); if( sendData(_connfd , header , header_len) < 0 || sendFile(_connfd , _fpath) < 0 ) return -1ULL; //opt = 0; // NETERROR( // setsockopt(sockfd, SOL_TCP, TCP_CORK, &opt, sizeof (opt)) < 0 // , "cork error"); return 1ULL; } Socket::~Socket() { close(sockfd); } EventPool::EventPool() { epfd = epoll_create(0x1ADC); NETERROR(epfd < 0, "create epoll error"); } bool EventPool::mountFD(int _fd, uint32_t _type) { epoll_event ev = { events : _type, data : {fd : _fd} }; NETERROR( epoll_ctl(epfd, EPOLL_CTL_ADD, _fd, &ev) < 0 , "add epoll error"); return true; } bool EventPool::mountPtr(void *_ptr, int _fd, uint32_t _type) { epoll_event ev = { events : _type, data : {ptr : _ptr} }; NETERROR( epoll_ctl(epfd, EPOLL_CTL_ADD, _fd, &ev) < 0 , "add epoll error"); return true; } bool EventPool::modifyPtr(void *_ptr, int _fd, uint32_t _type) { epoll_event ev = { events : _type, data : {ptr : _ptr} }; NETERROR( epoll_ctl(epfd, EPOLL_CTL_MOD, _fd, &ev) < 0 , "mod epoll error"); return true; } void EventPool::Poll(EpollFunc &func) { size_t epfd_n = epoll_wait(epfd, events, MAX_EVENTS, -1); NETERROR(epfd_n < 0, "poll error"); for (size_t i = 0; i < epfd_n; i++) { func(events[i].data, events[i].events); } } void EventPool::Loop(EpollFunc func) { while (true) { Poll(func); } }
23.783051
106
0.624002
NoUITeam
9a0a78315a407228e6eb7321c80ece4359fcd841
558
cpp
C++
src/GameObjects/HealthPickup.cpp
marcogillies/ShooterInheritanceExample
7ee315a98e8e96d3086a354f585fa205c0608e9e
[ "MIT" ]
null
null
null
src/GameObjects/HealthPickup.cpp
marcogillies/ShooterInheritanceExample
7ee315a98e8e96d3086a354f585fa205c0608e9e
[ "MIT" ]
null
null
null
src/GameObjects/HealthPickup.cpp
marcogillies/ShooterInheritanceExample
7ee315a98e8e96d3086a354f585fa205c0608e9e
[ "MIT" ]
null
null
null
// // HealthPickup.cpp // ShooterInhertiance // // Created by Marco Gillies on 05/03/2016. // // #include "HealthPickup.hpp" #include "Player.hpp" HealthPickup::HealthPickup(float x, float y, float _health) :Pickup(x,y), health(_health) { } HealthPickup::~HealthPickup() { } // adds health to the player void HealthPickup::apply(Player *player) { if(player) player->addHealth(health); } // draw the pickup void HealthPickup::subclassDraw() { ofSetColor(200, 255, 200); ofFill(); ofDrawCircle(0, 0, getWidth()); }
15.5
59
0.655914
marcogillies
9a14a0435af65ba7d19f75c3073e987c7c1b28d3
1,753
cpp
C++
Mathematics/NumberTheory/extended_euclidean_algorithm.cpp
Electron1997/Algorithms
6bdbb518833db36f6ba38966ab0a063edec040ab
[ "MIT" ]
1
2021-06-11T15:28:09.000Z
2021-06-11T15:28:09.000Z
Mathematics/NumberTheory/extended_euclidean_algorithm.cpp
Electron1997/Algorithms
6bdbb518833db36f6ba38966ab0a063edec040ab
[ "MIT" ]
null
null
null
Mathematics/NumberTheory/extended_euclidean_algorithm.cpp
Electron1997/Algorithms
6bdbb518833db36f6ba38966ab0a063edec040ab
[ "MIT" ]
null
null
null
// Solution to https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=364 #include <bits/stdc++.h> #define f first #define s second #define loop(i, n) for (int i = 0; i < n; ++i) #define read(a, n) loop($, n) cin >> a[$]; #define show(a, n) \ loop($, n) cout << a[$] << " "; \ cout << endl; using namespace std; typedef long long ll; typedef unsigned long long ull; /* // RANDOM NUMBER GENERATOR // rng() generates u.a.r. from [0, 2^32 - 1] mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); */ // Time: O(log(ab)) tuple<ll, ll, ll> extended_euclidean_algorithm(ll r_0, ll r_1){ ll s_0 = 1, s_1 = 0, t_0 = 0, t_1 = 1, q, u; /* if(r_0 < r_1){ swap(r_0, r_1); // r_0 must be >= r_1 !!! } */ while(r_1){ q = r_0 / r_1; u = r_0 - q * r_1; r_0 = r_1; r_1 = u; u = s_0 - q * s_1; s_0 = s_1; s_1 = u; u = t_0 - q * t_1; t_0 = t_1; t_1 = u; } return {r_0, s_0, t_0}; } int main(){ /* auto start = chrono::high_resolution_clock::now(); */ ios_base::sync_with_stdio(false); // unsync C- and C++-streams (stdio, iostream) cin.tie(NULL); // untie cin from cout (no automatic flush before read) int T; cin >> T; loop(t, T){ ll n, m; cin >> n >> m; tuple<ll, ll, ll> r = extended_euclidean_algorithm(n, m); cout << get<0>(r) << " " << get<1>(r) << " " << get<2>(r) << endl; } /* auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop - start); cout << duration.count() << endl; */ return 0; }
25.042857
110
0.527667
Electron1997
9a15df3bacffefc4acdc57a85b516dfd4a90b427
420
cpp
C++
src/server/implementation/generated-cpp/SerializerExpanderSampleplugin_js_mv.cpp
mvolosin/kurento-module-sampleplugin-js-MV
5caf3931e1c0d11676ec580e3db374185444aff7
[ "MIT" ]
null
null
null
src/server/implementation/generated-cpp/SerializerExpanderSampleplugin_js_mv.cpp
mvolosin/kurento-module-sampleplugin-js-MV
5caf3931e1c0d11676ec580e3db374185444aff7
[ "MIT" ]
null
null
null
src/server/implementation/generated-cpp/SerializerExpanderSampleplugin_js_mv.cpp
mvolosin/kurento-module-sampleplugin-js-MV
5caf3931e1c0d11676ec580e3db374185444aff7
[ "MIT" ]
null
null
null
/* Autogenerated with kurento-module-creator */ #include "SamplePluginFilter_js_mvImpl.hpp" #include <jsonrpc/JsonSerializer.hpp> namespace kurento { namespace module { namespace sampleplugin_js_mv { void dummySampleplugin_js_mv () { { JsonSerializer s (true); std::shared_ptr<SamplePluginFilter_js_mv> object; s.SerializeNVP (object); } } } /* sampleplugin_js_mv */ } /* module */ } /* kurento */
15.555556
53
0.721429
mvolosin
9a20f59053841f7be21d1abe46fe2bcd0e3ddeea
791
cpp
C++
testingIMUthread.cpp
dungletran/research-vibrotactitle
bebf8fb97532b37c2c89ba63e3f30a3e46393ec6
[ "MIT" ]
null
null
null
testingIMUthread.cpp
dungletran/research-vibrotactitle
bebf8fb97532b37c2c89ba63e3f30a3e46393ec6
[ "MIT" ]
null
null
null
testingIMUthread.cpp
dungletran/research-vibrotactitle
bebf8fb97532b37c2c89ba63e3f30a3e46393ec6
[ "MIT" ]
null
null
null
#include "testingIMUthread.h" #include "USBConnector.h" #include "QDebug" //test #include "pthread.h" //test testingIMUthread::testingIMUthread() : QThread() { } void testingIMUthread::terminate() { chkTerminate = true; } void testingIMUthread::run() { chkTerminate = false; //open USB connection USBConnector usbconnector; if (usbconnector.ConnectToServer()== false) { qDebug("Cannot connect to server!"); return; } while (chkTerminate == false) { mutex.lock(); data = usbconnector.GetDataFromServer(); mutex.unlock(); emit dataTestingReady(); } //close IMU usbconnector.DisconnectToServer(); qDebug("Terminating Testing IMU Thread!"); }
18.395349
49
0.604298
dungletran
9a2396b5ed3f08c009f40fbb8a4875141fa6605f
28,870
cpp
C++
cmdline.cpp
jiangyuhang17/memcached_slo_benchmark
53f791e0dddfec167218f27df3361411f1b13ea4
[ "BSD-3-Clause" ]
null
null
null
cmdline.cpp
jiangyuhang17/memcached_slo_benchmark
53f791e0dddfec167218f27df3361411f1b13ea4
[ "BSD-3-Clause" ]
null
null
null
cmdline.cpp
jiangyuhang17/memcached_slo_benchmark
53f791e0dddfec167218f27df3361411f1b13ea4
[ "BSD-3-Clause" ]
null
null
null
/* File autogenerated by gengetopt version 2.22.6 generated with the following command: gengetopt -c cpp --show-required --default-optional -l The developers of gengetopt consider the fixed text that goes in all gengetopt output files to be in the public domain: we make no copyright claims on it. */ /* If we use autoconf. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef FIX_UNUSED #define FIX_UNUSED(X) (void) (X) /* avoid warnings for unused params */ #endif #include <getopt.h> #include "cmdline.h" const char *gengetopt_args_info_purpose = ""; const char *gengetopt_args_info_usage = "Usage: slo_measure -s server[:port] [options]"; const char *gengetopt_args_info_versiontext = ""; const char *gengetopt_args_info_description = "memcached measureing tool for latency measure"; const char *gengetopt_args_info_help[] = { " -h, --help Print help and exit", " --version Print version and exit", " -s, --server=STRING Memcached server hostname[:port]. Repeat to specify\n multiple servers.", " -t, --time=INT Maximum time to run (seconds). (default=`5')", " -K, --keysize=INT Length of memcached keys. (default=`30')", " -V, --valuesize=INT Length of memcached values. (default=`200')", " -r, --records=INT Number of memcached records to use. If multiple\n memcached servers are given, this number is divided\n by the number of servers. (default=`10000')", " -R, --ratio=FLOAT Ratio of set/get commands. (default=`0.0')", " -c, --connections=INT Connections to establish per server. (default=`1')", " -d, --depth=INT Maximum depth to pipeline requests. (default=`1')", 0 }; typedef enum {ARG_NO , ARG_STRING , ARG_INT , ARG_FLOAT } cmdline_parser_arg_type; static void clear_given (struct gengetopt_args_info *args_info); static void clear_args (struct gengetopt_args_info *args_info); static int cmdline_parser_internal (int argc, char **argv, struct gengetopt_args_info *args_info, struct cmdline_parser_params *params, const char *additional_error); static int cmdline_parser_required2 (struct gengetopt_args_info *args_info, const char *prog_name, const char *additional_error); static char * gengetopt_strdup (const char *s); static void clear_given (struct gengetopt_args_info *args_info) { args_info->help_given = 0 ; args_info->version_given = 0 ; args_info->server_given = 0 ; args_info->time_given = 0 ; args_info->keysize_given = 0 ; args_info->valuesize_given = 0 ; args_info->records_given = 0 ; args_info->ratio_given = 0 ; args_info->connections_given = 0 ; args_info->depth_given = 0 ; } static void clear_args (struct gengetopt_args_info *args_info) { FIX_UNUSED (args_info); args_info->server_arg = NULL; args_info->server_orig = NULL; args_info->time_arg = 5; args_info->time_orig = NULL; args_info->keysize_arg = 30; args_info->keysize_orig = NULL; args_info->valuesize_arg = 200; args_info->valuesize_orig = NULL; args_info->records_arg = 10000; args_info->records_orig = NULL; args_info->ratio_arg = 0.0; args_info->ratio_orig = NULL; args_info->connections_arg = 1; args_info->connections_orig = NULL; args_info->depth_arg = 1; args_info->depth_orig = NULL; } static void init_args_info(struct gengetopt_args_info *args_info) { args_info->help_help = gengetopt_args_info_help[0] ; args_info->version_help = gengetopt_args_info_help[1] ; args_info->server_help = gengetopt_args_info_help[2] ; args_info->server_min = 0; args_info->server_max = 0; args_info->time_help = gengetopt_args_info_help[3] ; args_info->keysize_help = gengetopt_args_info_help[4] ; args_info->valuesize_help = gengetopt_args_info_help[5] ; args_info->records_help = gengetopt_args_info_help[6] ; args_info->ratio_help = gengetopt_args_info_help[7] ; args_info->connections_help = gengetopt_args_info_help[8] ; args_info->depth_help = gengetopt_args_info_help[9] ; } void cmdline_parser_print_version (void) { printf ("%s %s\n", (strlen(CMDLINE_PARSER_PACKAGE_NAME) ? CMDLINE_PARSER_PACKAGE_NAME : CMDLINE_PARSER_PACKAGE), CMDLINE_PARSER_VERSION); if (strlen(gengetopt_args_info_versiontext) > 0) printf("\n%s\n", gengetopt_args_info_versiontext); } static void print_help_common(void) { cmdline_parser_print_version (); if (strlen(gengetopt_args_info_purpose) > 0) printf("\n%s\n", gengetopt_args_info_purpose); if (strlen(gengetopt_args_info_usage) > 0) printf("\n%s\n", gengetopt_args_info_usage); printf("\n"); if (strlen(gengetopt_args_info_description) > 0) printf("%s\n\n", gengetopt_args_info_description); } void cmdline_parser_print_help (void) { int i = 0; print_help_common(); while (gengetopt_args_info_help[i]) printf("%s\n", gengetopt_args_info_help[i++]); } void cmdline_parser_init (struct gengetopt_args_info *args_info) { clear_given (args_info); clear_args (args_info); init_args_info (args_info); } void cmdline_parser_params_init(struct cmdline_parser_params *params) { if (params) { params->override = 0; params->initialize = 1; params->check_required = 1; params->check_ambiguity = 0; params->print_errors = 1; } } struct cmdline_parser_params * cmdline_parser_params_create(void) { struct cmdline_parser_params *params = (struct cmdline_parser_params *)malloc(sizeof(struct cmdline_parser_params)); cmdline_parser_params_init(params); return params; } static void free_string_field (char **s) { if (*s) { free (*s); *s = 0; } } /** @brief generic value variable */ union generic_value { int int_arg; float float_arg; char *string_arg; const char *default_string_arg; }; /** @brief holds temporary values for multiple options */ struct generic_list { union generic_value arg; char *orig; struct generic_list *next; }; /** * @brief add a node at the head of the list */ static void add_node(struct generic_list **list) { struct generic_list *new_node = (struct generic_list *) malloc (sizeof (struct generic_list)); new_node->next = *list; *list = new_node; new_node->arg.string_arg = 0; new_node->orig = 0; } static void free_multiple_string_field(unsigned int len, char ***arg, char ***orig) { unsigned int i; if (*arg) { for (i = 0; i < len; ++i) { free_string_field(&((*arg)[i])); free_string_field(&((*orig)[i])); } free_string_field(&((*arg)[0])); /* free default string */ free (*arg); *arg = 0; free (*orig); *orig = 0; } } static void cmdline_parser_release (struct gengetopt_args_info *args_info) { free_multiple_string_field (args_info->server_given, &(args_info->server_arg), &(args_info->server_orig)); free_string_field (&(args_info->time_orig)); free_string_field (&(args_info->keysize_orig)); free_string_field (&(args_info->valuesize_orig)); free_string_field (&(args_info->records_orig)); free_string_field (&(args_info->ratio_orig)); free_string_field (&(args_info->connections_orig)); free_string_field (&(args_info->depth_orig)); clear_given (args_info); } static void write_into_file(FILE *outfile, const char *opt, const char *arg, const char *values[]) { FIX_UNUSED (values); if (arg) { fprintf(outfile, "%s=\"%s\"\n", opt, arg); } else { fprintf(outfile, "%s\n", opt); } } static void write_multiple_into_file(FILE *outfile, int len, const char *opt, char **arg, const char *values[]) { int i; for (i = 0; i < len; ++i) write_into_file(outfile, opt, (arg ? arg[i] : 0), values); } int cmdline_parser_dump(FILE *outfile, struct gengetopt_args_info *args_info) { int i = 0; if (!outfile) { fprintf (stderr, "%s: cannot dump options to stream\n", CMDLINE_PARSER_PACKAGE); return EXIT_FAILURE; } if (args_info->help_given) write_into_file(outfile, "help", 0, 0 ); if (args_info->version_given) write_into_file(outfile, "version", 0, 0 ); write_multiple_into_file(outfile, args_info->server_given, "server", args_info->server_orig, 0); if (args_info->time_given) write_into_file(outfile, "time", args_info->time_orig, 0); if (args_info->keysize_given) write_into_file(outfile, "keysize", args_info->keysize_orig, 0); if (args_info->valuesize_given) write_into_file(outfile, "valuesize", args_info->valuesize_orig, 0); if (args_info->records_given) write_into_file(outfile, "records", args_info->records_orig, 0); if (args_info->ratio_given) write_into_file(outfile, "ratio", args_info->ratio_orig, 0); if (args_info->connections_given) write_into_file(outfile, "connections", args_info->connections_orig, 0); if (args_info->depth_given) write_into_file(outfile, "depth", args_info->depth_orig, 0); i = EXIT_SUCCESS; return i; } int cmdline_parser_file_save(const char *filename, struct gengetopt_args_info *args_info) { FILE *outfile; int i = 0; outfile = fopen(filename, "w"); if (!outfile) { fprintf (stderr, "%s: cannot open file for writing: %s\n", CMDLINE_PARSER_PACKAGE, filename); return EXIT_FAILURE; } i = cmdline_parser_dump(outfile, args_info); fclose (outfile); return i; } void cmdline_parser_free (struct gengetopt_args_info *args_info) { cmdline_parser_release (args_info); } /** @brief replacement of strdup, which is not standard */ char * gengetopt_strdup (const char *s) { char *result = 0; if (!s) return result; result = (char*)malloc(strlen(s) + 1); if (result == (char*)0) return (char*)0; strcpy(result, s); return result; } static char * get_multiple_arg_token(const char *arg) { const char *tok; char *ret; size_t len, num_of_escape, i, j; if (!arg) return 0; tok = strchr (arg, ','); num_of_escape = 0; /* make sure it is not escaped */ while (tok) { if (*(tok-1) == '\\') { /* find the next one */ tok = strchr (tok+1, ','); ++num_of_escape; } else break; } if (tok) len = (size_t)(tok - arg + 1); else len = strlen (arg) + 1; len -= num_of_escape; ret = (char *) malloc (len); i = 0; j = 0; while (arg[i] && (j < len-1)) { if (arg[i] == '\\' && arg[ i + 1 ] && arg[ i + 1 ] == ',') ++i; ret[j++] = arg[i++]; } ret[len-1] = '\0'; return ret; } static const char * get_multiple_arg_token_next(const char *arg) { const char *tok; if (!arg) return 0; tok = strchr (arg, ','); /* make sure it is not escaped */ while (tok) { if (*(tok-1) == '\\') { /* find the next one */ tok = strchr (tok+1, ','); } else break; } if (! tok || strlen(tok) == 1) return 0; return tok+1; } static int check_multiple_option_occurrences(const char *prog_name, unsigned int option_given, unsigned int min, unsigned int max, const char *option_desc); int check_multiple_option_occurrences(const char *prog_name, unsigned int option_given, unsigned int min, unsigned int max, const char *option_desc) { int error_occurred = 0; if (option_given && (min > 0 || max > 0)) { if (min > 0 && max > 0) { if (min == max) { /* specific occurrences */ if (option_given != (unsigned int) min) { fprintf (stderr, "%s: %s option occurrences must be %d\n", prog_name, option_desc, min); error_occurred = 1; } } else if (option_given < (unsigned int) min || option_given > (unsigned int) max) { /* range occurrences */ fprintf (stderr, "%s: %s option occurrences must be between %d and %d\n", prog_name, option_desc, min, max); error_occurred = 1; } } else if (min > 0) { /* at least check */ if (option_given < min) { fprintf (stderr, "%s: %s option occurrences must be at least %d\n", prog_name, option_desc, min); error_occurred = 1; } } else if (max > 0) { /* at most check */ if (option_given > max) { fprintf (stderr, "%s: %s option occurrences must be at most %d\n", prog_name, option_desc, max); error_occurred = 1; } } } return error_occurred; } int cmdline_parser (int argc, char **argv, struct gengetopt_args_info *args_info) { return cmdline_parser2 (argc, argv, args_info, 0, 1, 1); } int cmdline_parser_ext (int argc, char **argv, struct gengetopt_args_info *args_info, struct cmdline_parser_params *params) { int result; result = cmdline_parser_internal (argc, argv, args_info, params, 0); if (result == EXIT_FAILURE) { cmdline_parser_free (args_info); exit (EXIT_FAILURE); } return result; } int cmdline_parser2 (int argc, char **argv, struct gengetopt_args_info *args_info, int override, int initialize, int check_required) { int result; struct cmdline_parser_params params; params.override = override; params.initialize = initialize; params.check_required = check_required; params.check_ambiguity = 0; params.print_errors = 1; result = cmdline_parser_internal (argc, argv, args_info, &params, 0); if (result == EXIT_FAILURE) { cmdline_parser_free (args_info); exit (EXIT_FAILURE); } return result; } int cmdline_parser_required (struct gengetopt_args_info *args_info, const char *prog_name) { int result = EXIT_SUCCESS; if (cmdline_parser_required2(args_info, prog_name, 0) > 0) result = EXIT_FAILURE; if (result == EXIT_FAILURE) { cmdline_parser_free (args_info); exit (EXIT_FAILURE); } return result; } int cmdline_parser_required2 (struct gengetopt_args_info *args_info, const char *prog_name, const char *additional_error) { int error_occurred = 0; FIX_UNUSED (additional_error); /* checks for required options */ if (check_multiple_option_occurrences(prog_name, args_info->server_given, args_info->server_min, args_info->server_max, "'--server' ('-s')")) error_occurred = 1; /* checks for dependences among options */ return error_occurred; } static char *package_name = 0; /** * @brief updates an option * @param field the generic pointer to the field to update * @param orig_field the pointer to the orig field * @param field_given the pointer to the number of occurrence of this option * @param prev_given the pointer to the number of occurrence already seen * @param value the argument for this option (if null no arg was specified) * @param possible_values the possible values for this option (if specified) * @param default_value the default value (in case the option only accepts fixed values) * @param arg_type the type of this option * @param check_ambiguity @see cmdline_parser_params.check_ambiguity * @param override @see cmdline_parser_params.override * @param no_free whether to free a possible previous value * @param multiple_option whether this is a multiple option * @param long_opt the corresponding long option * @param short_opt the corresponding short option (or '-' if none) * @param additional_error possible further error specification */ static int update_arg(void *field, char **orig_field, unsigned int *field_given, unsigned int *prev_given, char *value, const char *possible_values[], const char *default_value, cmdline_parser_arg_type arg_type, int check_ambiguity, int override, int no_free, int multiple_option, const char *long_opt, char short_opt, const char *additional_error) { char *stop_char = 0; const char *val = value; int found; char **string_field; FIX_UNUSED (field); stop_char = 0; found = 0; if (!multiple_option && prev_given && (*prev_given || (check_ambiguity && *field_given))) { if (short_opt != '-') fprintf (stderr, "%s: `--%s' (`-%c') option given more than once%s\n", package_name, long_opt, short_opt, (additional_error ? additional_error : "")); else fprintf (stderr, "%s: `--%s' option given more than once%s\n", package_name, long_opt, (additional_error ? additional_error : "")); return 1; /* failure */ } FIX_UNUSED (default_value); if (field_given && *field_given && ! override) return 0; if (prev_given) (*prev_given)++; if (field_given) (*field_given)++; if (possible_values) val = possible_values[found]; switch(arg_type) { case ARG_INT: if (val) *((int *)field) = strtol (val, &stop_char, 0); break; case ARG_FLOAT: if (val) *((float *)field) = (float)strtod (val, &stop_char); break; case ARG_STRING: if (val) { string_field = (char **)field; if (!no_free && *string_field) free (*string_field); /* free previous string */ *string_field = gengetopt_strdup (val); } break; default: break; }; /* check numeric conversion */ switch(arg_type) { case ARG_INT: case ARG_FLOAT: if (val && !(stop_char && *stop_char == '\0')) { fprintf(stderr, "%s: invalid numeric value: %s\n", package_name, val); return 1; /* failure */ } break; default: ; }; /* store the original value */ switch(arg_type) { case ARG_NO: break; default: if (value && orig_field) { if (no_free) { *orig_field = value; } else { if (*orig_field) free (*orig_field); /* free previous string */ *orig_field = gengetopt_strdup (value); } } }; return 0; /* OK */ } /** * @brief store information about a multiple option in a temporary list * @param list where to (temporarily) store multiple options */ static int update_multiple_arg_temp(struct generic_list **list, unsigned int *prev_given, const char *val, const char *possible_values[], const char *default_value, cmdline_parser_arg_type arg_type, const char *long_opt, char short_opt, const char *additional_error) { /* store single arguments */ char *multi_token; const char *multi_next; if (arg_type == ARG_NO) { (*prev_given)++; return 0; /* OK */ } multi_token = get_multiple_arg_token(val); multi_next = get_multiple_arg_token_next (val); while (1) { add_node (list); if (update_arg((void *)&((*list)->arg), &((*list)->orig), 0, prev_given, multi_token, possible_values, default_value, arg_type, 0, 1, 1, 1, long_opt, short_opt, additional_error)) { if (multi_token) free(multi_token); return 1; /* failure */ } if (multi_next) { multi_token = get_multiple_arg_token(multi_next); multi_next = get_multiple_arg_token_next (multi_next); } else break; } return 0; /* OK */ } /** * @brief free the passed list (including possible string argument) */ static void free_list(struct generic_list *list, short string_arg) { if (list) { struct generic_list *tmp; while (list) { tmp = list; if (string_arg && list->arg.string_arg) free (list->arg.string_arg); if (list->orig) free (list->orig); list = list->next; free (tmp); } } } /** * @brief updates a multiple option starting from the passed list */ static void update_multiple_arg(void *field, char ***orig_field, unsigned int field_given, unsigned int prev_given, union generic_value *default_value, cmdline_parser_arg_type arg_type, struct generic_list *list) { int i; struct generic_list *tmp; if (prev_given && list) { *orig_field = (char **) realloc (*orig_field, (field_given + prev_given) * sizeof (char *)); switch(arg_type) { case ARG_INT: *((int **)field) = (int *)realloc (*((int **)field), (field_given + prev_given) * sizeof (int)); break; case ARG_FLOAT: *((float **)field) = (float *)realloc (*((float **)field), (field_given + prev_given) * sizeof (float)); break; case ARG_STRING: *((char ***)field) = (char **)realloc (*((char ***)field), (field_given + prev_given) * sizeof (char *)); break; default: break; }; for (i = (prev_given - 1); i >= 0; --i) { tmp = list; switch(arg_type) { case ARG_INT: (*((int **)field))[i + field_given] = tmp->arg.int_arg; break; case ARG_FLOAT: (*((float **)field))[i + field_given] = tmp->arg.float_arg; break; case ARG_STRING: (*((char ***)field))[i + field_given] = tmp->arg.string_arg; break; default: break; } (*orig_field) [i + field_given] = list->orig; list = list->next; free (tmp); } } else { /* set the default value */ if (default_value && ! field_given) { switch(arg_type) { case ARG_INT: if (! *((int **)field)) { *((int **)field) = (int *)malloc (sizeof (int)); (*((int **)field))[0] = default_value->int_arg; } break; case ARG_FLOAT: if (! *((float **)field)) { *((float **)field) = (float *)malloc (sizeof (float)); (*((float **)field))[0] = default_value->float_arg; } break; case ARG_STRING: if (! *((char ***)field)) { *((char ***)field) = (char **)malloc (sizeof (char *)); (*((char ***)field))[0] = gengetopt_strdup(default_value->string_arg); } break; default: break; } if (!(*orig_field)) { *orig_field = (char **) malloc (sizeof (char *)); (*orig_field)[0] = 0; } } } } int cmdline_parser_internal ( int argc, char **argv, struct gengetopt_args_info *args_info, struct cmdline_parser_params *params, const char *additional_error) { int c; /* Character of the parsed option. */ struct generic_list * server_list = NULL; int error_occurred = 0; struct gengetopt_args_info local_args_info; int override; int initialize; int check_required; int check_ambiguity; package_name = argv[0]; override = params->override; initialize = params->initialize; check_required = params->check_required; check_ambiguity = params->check_ambiguity; if (initialize) cmdline_parser_init (args_info); cmdline_parser_init (&local_args_info); optarg = 0; optind = 0; opterr = params->print_errors; optopt = '?'; while (1) { int option_index = 0; static struct option long_options[] = { { "help", 0, NULL, 'h' }, { "version", 0, NULL, 0 }, { "server", 1, NULL, 's' }, { "time", 1, NULL, 't' }, { "keysize", 1, NULL, 'K' }, { "valuesize", 1, NULL, 'V' }, { "records", 1, NULL, 'r' }, { "ratio", 1, NULL, 'R' }, { "connections", 1, NULL, 'c' }, { "depth", 1, NULL, 'd' }, { 0, 0, 0, 0 } }; c = getopt_long (argc, argv, "hs:t:K:V:r:R:c:d:", long_options, &option_index); if (c == -1) break; /* Exit from `while (1)' loop. */ switch (c) { case 'h': /* Print help and exit. */ cmdline_parser_print_help (); cmdline_parser_free (&local_args_info); exit (EXIT_SUCCESS); case 's': /* Memcached server hostname[:port]. Repeat to specify multiple servers.. */ if (update_multiple_arg_temp(&server_list, &(local_args_info.server_given), optarg, 0, 0, ARG_STRING, "server", 's', additional_error)) goto failure; break; case 't': /* Maximum time to run (seconds).. */ if (update_arg( (void *)&(args_info->time_arg), &(args_info->time_orig), &(args_info->time_given), &(local_args_info.time_given), optarg, 0, "5", ARG_INT, check_ambiguity, override, 0, 0, "time", 't', additional_error)) goto failure; break; case 'K': /* Length of memcached keys.. */ if (update_arg( (void *)&(args_info->keysize_arg), &(args_info->keysize_orig), &(args_info->keysize_given), &(local_args_info.keysize_given), optarg, 0, "30", ARG_INT, check_ambiguity, override, 0, 0, "keysize", 'K', additional_error)) goto failure; break; case 'V': /* Length of memcached values.. */ if (update_arg( (void *)&(args_info->valuesize_arg), &(args_info->valuesize_orig), &(args_info->valuesize_given), &(local_args_info.valuesize_given), optarg, 0, "200", ARG_INT, check_ambiguity, override, 0, 0, "valuesize", 'V', additional_error)) goto failure; break; case 'r': /* Number of memcached records to use. If multiple memcached servers are given, this number is divided by the number of servers.. */ if (update_arg( (void *)&(args_info->records_arg), &(args_info->records_orig), &(args_info->records_given), &(local_args_info.records_given), optarg, 0, "10000", ARG_INT, check_ambiguity, override, 0, 0, "records", 'r', additional_error)) goto failure; break; case 'R': /* Ratio of set/get commands.. */ if (update_arg( (void *)&(args_info->ratio_arg), &(args_info->ratio_orig), &(args_info->ratio_given), &(local_args_info.ratio_given), optarg, 0, "0.0", ARG_FLOAT, check_ambiguity, override, 0, 0, "ratio", 'R', additional_error)) goto failure; break; case 'c': /* Connections to establish per server.. */ if (update_arg( (void *)&(args_info->connections_arg), &(args_info->connections_orig), &(args_info->connections_given), &(local_args_info.connections_given), optarg, 0, "1", ARG_INT, check_ambiguity, override, 0, 0, "connections", 'c', additional_error)) goto failure; break; case 'd': /* Maximum depth to pipeline requests.. */ if (update_arg( (void *)&(args_info->depth_arg), &(args_info->depth_orig), &(args_info->depth_given), &(local_args_info.depth_given), optarg, 0, "1", ARG_INT, check_ambiguity, override, 0, 0, "depth", 'd', additional_error)) goto failure; break; case 0: /* Long option with no short option */ if (strcmp (long_options[option_index].name, "version") == 0) { cmdline_parser_print_version (); cmdline_parser_free (&local_args_info); exit (EXIT_SUCCESS); } case '?': /* Invalid option. */ /* `getopt_long' already printed an error message. */ goto failure; default: /* bug: option not considered. */ fprintf (stderr, "%s: option unknown: %c%s\n", CMDLINE_PARSER_PACKAGE, c, (additional_error ? additional_error : "")); abort (); } /* switch */ } /* while */ update_multiple_arg((void *)&(args_info->server_arg), &(args_info->server_orig), args_info->server_given, local_args_info.server_given, 0, ARG_STRING, server_list); args_info->server_given += local_args_info.server_given; local_args_info.server_given = 0; if (check_required) { error_occurred += cmdline_parser_required2 (args_info, argv[0], additional_error); } cmdline_parser_release (&local_args_info); if ( error_occurred ) return (EXIT_FAILURE); return 0; failure: free_list (server_list, 1 ); cmdline_parser_release (&local_args_info); return (EXIT_FAILURE); }
27.813102
231
0.61098
jiangyuhang17
9a30f6058ced0c8cf94fcf6103e98a2db1559815
1,469
hpp
C++
src/Helper/Buffer.hpp
Maetveis/GameTest3D
cfb6fa27ebc656c0d8cf41d18049966191b6cf6e
[ "MIT" ]
null
null
null
src/Helper/Buffer.hpp
Maetveis/GameTest3D
cfb6fa27ebc656c0d8cf41d18049966191b6cf6e
[ "MIT" ]
null
null
null
src/Helper/Buffer.hpp
Maetveis/GameTest3D
cfb6fa27ebc656c0d8cf41d18049966191b6cf6e
[ "MIT" ]
null
null
null
#ifndef BUFFER_HPP #define BUFFER_HPP #include <GL/glew.h> #include <vector> #include "../Log/Logger.h" namespace GL { class Buffer { private: GLuint id; public: Buffer() { glCreateBuffers(1, &id); Logger::Debug << "Created glBuffer with id: " << id << '\n'; } GLint GetId() const { return id; } void Bind(GLenum target) const { glBindBuffer(target, id); } void BufferData(GLuint size, const void* data, GLenum usage) { glNamedBufferData(id, size, data, usage); } template<typename T> void BufferData(const T& data, GLenum usage) { BufferData(sizeof(T), reinterpret_cast<const void *>(&data), usage); } template<typename T> void BufferData(const std::vector<T>& vector, GLenum usage) { BufferData(vector.size() * sizeof(T), reinterpret_cast<const void *>(vector.data()), usage); } void BufferSubData(GLuint offset, GLsizeiptr size, const void* data) { glNamedBufferSubData(id, offset, size, data); } template<typename T> void BufferSubData(GLuint offset, const T& data) { BufferSubData(offset, sizeof(data), reinterpret_cast<void *>(&data)); } template<typename T> void BufferSubData(GLuint offset, const std::vector<T>& vector, GLenum usage) { BufferSubData(offset, vector.size() * sizeof(T), reinterpret_cast<const void *>(vector.data())); } void InitEmpty(GLuint size, GLenum usage) { BufferData(size, nullptr, usage); } ~Buffer() { glDeleteBuffers(1, &id); } }; }// namespace GL #endif
18.135802
98
0.686862
Maetveis
9a3736f3a128d5dd2a40524552c08fc6040c1560
3,028
ipp
C++
implement/oglplus/enums/framebuffer_parameter_def.ipp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
364
2015-01-01T09:38:23.000Z
2022-03-22T05:32:00.000Z
implement/oglplus/enums/framebuffer_parameter_def.ipp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
55
2015-01-06T16:42:55.000Z
2020-07-09T04:21:41.000Z
implement/oglplus/enums/framebuffer_parameter_def.ipp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
57
2015-01-07T18:35:49.000Z
2022-03-22T05:32:04.000Z
// File implement/oglplus/enums/framebuffer_parameter_def.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/framebuffer_parameter.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2019 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif #if defined GL_FRAMEBUFFER_DEFAULT_WIDTH # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined DefaultWidth # pragma push_macro("DefaultWidth") # undef DefaultWidth OGLPLUS_ENUM_CLASS_VALUE(DefaultWidth, GL_FRAMEBUFFER_DEFAULT_WIDTH) # pragma pop_macro("DefaultWidth") # else OGLPLUS_ENUM_CLASS_VALUE(DefaultWidth, GL_FRAMEBUFFER_DEFAULT_WIDTH) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_FRAMEBUFFER_DEFAULT_HEIGHT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined DefaultHeight # pragma push_macro("DefaultHeight") # undef DefaultHeight OGLPLUS_ENUM_CLASS_VALUE(DefaultHeight, GL_FRAMEBUFFER_DEFAULT_HEIGHT) # pragma pop_macro("DefaultHeight") # else OGLPLUS_ENUM_CLASS_VALUE(DefaultHeight, GL_FRAMEBUFFER_DEFAULT_HEIGHT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_FRAMEBUFFER_DEFAULT_LAYERS # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined Layers # pragma push_macro("Layers") # undef Layers OGLPLUS_ENUM_CLASS_VALUE(Layers, GL_FRAMEBUFFER_DEFAULT_LAYERS) # pragma pop_macro("Layers") # else OGLPLUS_ENUM_CLASS_VALUE(Layers, GL_FRAMEBUFFER_DEFAULT_LAYERS) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_FRAMEBUFFER_DEFAULT_SAMPLES # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined Samples # pragma push_macro("Samples") # undef Samples OGLPLUS_ENUM_CLASS_VALUE(Samples, GL_FRAMEBUFFER_DEFAULT_SAMPLES) # pragma pop_macro("Samples") # else OGLPLUS_ENUM_CLASS_VALUE(Samples, GL_FRAMEBUFFER_DEFAULT_SAMPLES) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined FixedSampleLocations # pragma push_macro("FixedSampleLocations") # undef FixedSampleLocations OGLPLUS_ENUM_CLASS_VALUE(FixedSampleLocations, GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS) # pragma pop_macro("FixedSampleLocations") # else OGLPLUS_ENUM_CLASS_VALUE(FixedSampleLocations, GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif
30.28
96
0.824967
matus-chochlik
9a38592eaca22b74cc09627b683d4a2ae5864ee6
1,719
hpp
C++
experimental/Pomdog.Experimental/UI/DrawingContext.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/UI/DrawingContext.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/UI/DrawingContext.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog.Experimental/Rendering/Renderer.hpp" #include "Pomdog.Experimental/UI/FontSize.hpp" #include "Pomdog.Experimental/UI/FontWeight.hpp" #include "Pomdog/Experimental/Graphics/SpriteBatch.hpp" #include "Pomdog/Experimental/Graphics/SpriteFont.hpp" #include "Pomdog/Experimental/Graphics/TrueTypeFont.hpp" #include "Pomdog/Math/Color.hpp" #include "Pomdog/Math/Matrix3x2.hpp" #include "Pomdog/Math/Matrix4x4.hpp" #include "Pomdog/Math/Rectangle.hpp" #include "Pomdog/Math/Vector2.hpp" #include <Pomdog/Pomdog.hpp> #include <cstdint> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace Pomdog { class RenderCommand; class SpriteFont; } // namespace Pomdog namespace Pomdog { namespace UI { class DrawingContext final { private: Renderer renderer; std::unordered_map<std::string, std::shared_ptr<SpriteFont>> spriteFonts; std::shared_ptr<TrueTypeFont> fontRegular; std::shared_ptr<TrueTypeFont> fontBold; std::shared_ptr<GraphicsDevice> graphicsDevice; std::vector<Matrix3x2> matrixStack; int viewportWidth; int viewportHeight; public: DrawingContext( const std::shared_ptr<GraphicsDevice>& graphicsDevice, AssetManager & assets); Matrix3x2 Top() const; void Push(const Matrix3x2& matrix); void Pop(); std::shared_ptr<GraphicsCommandList> Render(); void Reset(int viewportWidth, int viewportHeight); void PushCommand(std::reference_wrapper<RenderCommand> && command); std::shared_ptr<SpriteFont> GetFont(FontWeight fontWeight, FontSize fontSize); }; } // namespace UI } // namespace Pomdog
25.656716
82
0.752182
ValtoForks
9a38decbb3987205e3495774a55ead1fd3db5d0d
13,181
cpp
C++
Engine/src/resource/MaterialSerializer.cpp
katoun/kg_engine
fdcc6ec01b191d07cedf7a8d6c274166e25401a8
[ "Unlicense" ]
2
2015-04-21T05:36:12.000Z
2017-04-16T19:31:26.000Z
Engine/src/resource/MaterialSerializer.cpp
katoun/kg_engine
fdcc6ec01b191d07cedf7a8d6c274166e25401a8
[ "Unlicense" ]
null
null
null
Engine/src/resource/MaterialSerializer.cpp
katoun/kg_engine
fdcc6ec01b191d07cedf7a8d6c274166e25401a8
[ "Unlicense" ]
null
null
null
/* ----------------------------------------------------------------------------- KG game engine (http://katoun.github.com/kg_engine) is made available under the MIT License. Copyright (c) 2006-2013 Catalin Alexandru Nastase Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include <resource/MaterialSerializer.h> #include <core/Log.h> #include <core/Utils.h> #include <core/LogDefines.h> #include <resource/ResourceManager.h> #include <render/Shader.h> #include <render/Material.h> #include <physics/Material.h> #include <tinyxml2.h> #include <string> namespace resource { render::VertexBufferType convertVertexParameterType(const std::string& param) { if (param == "vertex_position") return render::VERTEX_BUFFER_TYPE_POSITION; else if (param == "vertex_normal") return render::VERTEX_BUFFER_TYPE_NORMAL; else if (param == "vertex_binormal") return render::VERTEX_BUFFER_TYPE_BINORMAL; else if (param == "vertex_tangent") return render::VERTEX_BUFFER_TYPE_TANGENT; else if (param == "vertex_texture_coordinates") return render::VERTEX_BUFFER_TYPE_TEXTURE_COORDINATES; else { if (core::Log::getInstance() != nullptr) core::Log::getInstance()->logMessage("MaterialSerializer", "Invalid vertex parameter type, using default.", core::LOG_LEVEL_ERROR); return render::VERTEX_BUFFER_TYPE_POSITION; } } render::ShaderAutoParameterType convertAutoParameterType(const std::string& param) { if (param == "world_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_WORLD_MATRIX; else if (param == "inverse_world_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_WORLD_MATRIX; else if (param == "transpose_world_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_TRANSPOSE_WORLD_MATRIX; else if (param == "inverse_transpose_world_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_TRANSPOSE_WORLD_MATRIX; else if (param == "view_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_VIEW_MATRIX; else if (param == "inverse_view_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_VIEW_MATRIX; else if (param == "transpose_view_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_TRANSPOSE_VIEW_MATRIX; else if (param == "inverse_transpose_view_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_TRANSPOSE_VIEW_MATRIX; else if (param == "projection_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_PROJECTION_MATRIX; else if (param == "inverse_projection_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_PROJECTION_MATRIX; else if (param == "transpose_projection_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_TRANSPOSE_PROJECTION_MATRIX; else if (param == "inverse_transpose_projection_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_TRANSPOSE_PROJECTION_MATRIX; else if (param == "viewproj_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_VIEWPROJ_MATRIX; else if (param == "inverse_viewproj_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_VIEWPROJ_MATRIX; else if (param == "transpose_viewproj_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_TRANSPOSE_VIEWPROJ_MATRIX; else if (param == "inverse_transpose_viewproj_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_TRANSPOSE_VIEWPROJ_MATRIX; else if (param == "worldview_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_WORLDVIEW_MATRIX; else if (param == "inverse_worldview_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_WORLDVIEW_MATRIX; else if (param == "transpose_worldview_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_TRANSPOSE_WORLDVIEW_MATRIX; else if (param == "inverse_transpose_worldview_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX; else if (param == "worldviewproj_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_WORLDVIEWPROJ_MATRIX; else if (param == "inverse_worldviewproj_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_WORLDVIEWPROJ_MATRIX; else if (param == "transpose_worldviewproj_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_TRANSPOSE_WORLDVIEWPROJ_MATRIX; else if (param == "inverse_transpose_worldviewproj_matrix") return render::SHADER_AUTO_PARAMETER_TYPE_INVERSE_TRANSPOSE_WORLDVIEWPROJ_MATRIX; else if (param == "light_count") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_COUNT; else if (param == "light_position") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_POSITION; else if (param == "light_position_object_space") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_POSITION_OBJECT_SPACE; else if (param == "light_position_view_space") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_POSITION_VIEW_SPACE; else if (param == "light_direction") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_DIRECTION; else if (param == "light_direction_object_space") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_DIRECTION_OBJECT_SPACE; else if (param == "light_direction_view_space") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_DIRECTION_VIEW_SPACE; else if (param == "ambient_light_colour") return render::SHADER_AUTO_PARAMETER_TYPE_AMBIENT_LIGHT_COLOUR; else if (param == "light_diffuse_colour") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_DIFFUSE_COLOUR; else if (param == "light_specular_colour") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_SPECULAR_COLOUR; else if (param == "light_attenuation") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_ATTENUATION; else if (param == "light_power") return render::SHADER_AUTO_PARAMETER_TYPE_LIGHT_POWER_SCALE; else if (param == "camera_position") return render::SHADER_AUTO_PARAMETER_TYPE_CAMERA_POSITION; else if (param == "camera_position_object_space") return render::SHADER_AUTO_PARAMETER_TYPE_CAMERA_POSITION_OBJECT_SPACE; else { if (core::Log::getInstance() != nullptr) core::Log::getInstance()->logMessage("MaterialSerializer", "Invalid auto parameter type, using default.", core::LOG_LEVEL_ERROR); return render::SHADER_AUTO_PARAMETER_TYPE_NONE; } } MaterialSerializer::MaterialSerializer() { // Version number mVersion = "[MaterialSerializer_v1.00]"; } MaterialSerializer::~MaterialSerializer() {} bool MaterialSerializer::importResource(Resource* dest, const std::string& filename) { assert(dest != nullptr); if (dest == nullptr) return false; if (dest->getResourceType() != RESOURCE_TYPE_RENDER_MATERIAL && dest->getResourceType() != RESOURCE_TYPE_PHYSICS_MATERIAL) { if (core::Log::getInstance() != nullptr) core::Log::getInstance()->logMessage("MaterialSerializer", "Unable to load material - invalid resource pointer.", core::LOG_LEVEL_ERROR); return false; } render::Material* renderMaterial = nullptr; physics::Material* physicsMaterial = nullptr; if (dest->getResourceType() == RESOURCE_TYPE_RENDER_MATERIAL) { renderMaterial = static_cast<render::Material*>(dest); assert(renderMaterial != nullptr); if (renderMaterial == nullptr) return false; } if (dest->getResourceType() == RESOURCE_TYPE_PHYSICS_MATERIAL) { physicsMaterial = static_cast<physics::Material*>(dest); assert(physicsMaterial != nullptr); if (physicsMaterial == nullptr) return false; } if (resource::ResourceManager::getInstance() == nullptr) { if (core::Log::getInstance() != nullptr) core::Log::getInstance()->logMessage("MaterialSerializer", "Unable to load material - resources data path not set.", core::LOG_LEVEL_ERROR); return false; } std::string filePath = resource::ResourceManager::getInstance()->getDataPath() + "/" + filename; tinyxml2::XMLDocument doc; if (doc.LoadFile(filePath.c_str()) != tinyxml2::XML_SUCCESS) return false; tinyxml2::XMLElement* pRoot = doc.FirstChildElement("material"); if (pRoot != nullptr) { int ivalue = 0; double dvalue = 0.0; const char* svalue; std::string value; tinyxml2::XMLElement* pElement = nullptr; tinyxml2::XMLElement* pSubElement = nullptr; if (dest->getResourceType() == RESOURCE_TYPE_RENDER_MATERIAL) { std::vector<std::string> shaderkeys(3); shaderkeys[0] = "vertex_shader"; shaderkeys[1] = "fragment_shader"; shaderkeys[2] = "geometry_shader"; for (unsigned int i = 0; i < shaderkeys.size(); ++i) { pElement = pRoot->FirstChildElement(shaderkeys[i].c_str()); if (pElement != nullptr) { std::string shader; pSubElement = pElement->FirstChildElement("shader"); if (pSubElement != nullptr) { svalue = pSubElement->Attribute("value"); if (svalue != nullptr) { shader = svalue; } } if (shader.empty()) continue; render::Shader* pShader = nullptr; if (shaderkeys[i] == "vertex_shader") { renderMaterial->setVertexShader(shader); pShader = renderMaterial->getVertexShader(); } if (shaderkeys[i] == "fragment_shader") { renderMaterial->setFragmentShader(shader); pShader = renderMaterial->getFragmentShader(); } if (shaderkeys[i] == "geometry_shader") { renderMaterial->setGeometryShader(shader); pShader = renderMaterial->getGeometryShader(); } if (pShader == nullptr) continue; pSubElement = pElement->FirstChildElement("entry_point"); if (pSubElement != nullptr) { svalue = pSubElement->Attribute("value"); if (svalue != nullptr) { value = svalue; pShader->setEntryPoint(value); } } pSubElement = pElement->FirstChildElement("param_vertex"); while (pSubElement != nullptr) { render::VertexBufferType vertexType = render::VERTEX_BUFFER_TYPE_POSITION; svalue = pSubElement->Attribute("type"); if (svalue != nullptr) { value = svalue; vertexType = convertVertexParameterType(value); } svalue = pSubElement->Attribute("name"); if (svalue != nullptr) { value = svalue; } renderMaterial->addVertexParameter(value, vertexType); pSubElement = pSubElement->NextSiblingElement("param_vertex"); } pSubElement = pElement->FirstChildElement("param_auto"); while (pSubElement != nullptr) { render::ShaderAutoParameterType paramAutoType = render::SHADER_AUTO_PARAMETER_TYPE_NONE; svalue = pSubElement->Attribute("type"); if (svalue != nullptr) { value = svalue; paramAutoType = convertAutoParameterType(value); } svalue = pSubElement->Attribute("name"); if (svalue != nullptr) { value = svalue; } renderMaterial->addAutoParameter(value, paramAutoType); pSubElement = pSubElement->NextSiblingElement("param_auto"); } } } pElement = pRoot->FirstChildElement("texture_unit"); while (pElement != nullptr) { std::string texture; pSubElement = pElement->FirstChildElement("texture"); if (pSubElement != nullptr) { svalue = pSubElement->Attribute("value"); if (svalue != nullptr) { texture = svalue; } } if (!texture.empty()) { renderMaterial->addTextureUnit(texture); } pElement = pElement->NextSiblingElement("texture_unit"); } } if (dest->getResourceType() == RESOURCE_TYPE_PHYSICS_MATERIAL) { pElement = pRoot->FirstChildElement("restitution"); if (pElement != nullptr) { if (pElement->QueryDoubleAttribute("value", &dvalue) == tinyxml2::XML_SUCCESS) { physicsMaterial->setRestitution((float)dvalue); } } pElement = pRoot->FirstChildElement("static_friction"); if (pElement != nullptr) { if (pElement->QueryDoubleAttribute("value", &dvalue) == tinyxml2::XML_SUCCESS) { physicsMaterial->setStaticFriction((float)dvalue); } } pElement = pRoot->FirstChildElement("dynamic_friction"); if (pElement != nullptr) { if (pElement->QueryDoubleAttribute("value", &dvalue) == tinyxml2::XML_SUCCESS) { physicsMaterial->setDynamicFriction((float)dvalue); } } } } return true; } bool MaterialSerializer::exportResource(Resource* source, const std::string& filename) { return false; } }// end namespace resource
34.325521
183
0.731128
katoun
9a39084be0c47af8c8c21a2185d152fd88854493
866
cpp
C++
Part1/Chapter5/P2615.cpp
flics04/SSQCbook-Base-Luogu
c7ddbcfec58d6cc8f6396309daa8b511b6c8673d
[ "MIT" ]
null
null
null
Part1/Chapter5/P2615.cpp
flics04/SSQCbook-Base-Luogu
c7ddbcfec58d6cc8f6396309daa8b511b6c8673d
[ "MIT" ]
null
null
null
Part1/Chapter5/P2615.cpp
flics04/SSQCbook-Base-Luogu
c7ddbcfec58d6cc8f6396309daa8b511b6c8673d
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int n, g[40][40], x, y; int main() { cin >> n; g[1][n / 2 + 1] = 1; x = 1; y = n / 2 + 1; for (int i = 2; i <= n * n; i++) { if (x == 1 && y != n) // 第一行但不是最后一列 g[n][y + 1] = i, x = n, y++; else if (y == n && x != 1) // 最后一列但不是最后一行 g[x - 1][1] = i, x--, y = 1; else if (x == 1 && y == n) // 第一行最后一列 g[2][n] = i, x = 2; else if (x != 1 && y != n) { // 不在第一行,也不在最后一行 if (g[x - 1][y + 1] == 0) // 右上方未填数 g[x - 1][y + 1] = i, x --, y++; else g[x + 1][y] = i, x++; continue; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cout << g[i][j] << " "; } cout << endl; } return 0; }
25.470588
60
0.300231
flics04
9a3bf7d911eb7c53567fe1dfb889748e70338e66
401
hpp
C++
src/CL_SetupNetwork_stub.hpp
fccm/ocaml-clanlib
1929f1c11d4cc9fc19e7da22826238b4cce7a07d
[ "Zlib", "OLDAP-2.2.1" ]
1
2020-10-24T14:48:04.000Z
2020-10-24T14:48:04.000Z
src/CL_SetupNetwork_stub.hpp
fccm/ocaml-clanlib
1929f1c11d4cc9fc19e7da22826238b4cce7a07d
[ "Zlib", "OLDAP-2.2.1" ]
null
null
null
src/CL_SetupNetwork_stub.hpp
fccm/ocaml-clanlib
1929f1c11d4cc9fc19e7da22826238b4cce7a07d
[ "Zlib", "OLDAP-2.2.1" ]
null
null
null
#ifndef _CL_SETUPNETWORK_INC #define _CL_SETUPNETWORK_INC #include <ClanLib/Network/setupnetwork.h> #ifdef CL_WRAP_POINTERS #define Val_CL_SetupNetwork(v) (Val_ptr<CL_SetupNetwork>(v)) #define CL_SetupNetwork_val(v) (Ptr_val<CL_SetupNetwork>(v)) #else #define Val_CL_SetupNetwork(sn) ((value)(sn)) #define CL_SetupNetwork_val(sn) ((CL_SetupNetwork *)(sn)) #endif #endif // _CL_SETUPNETWORK_INC
21.105263
60
0.790524
fccm
9a3cf6c38f3658bd62dcdf33c85b250fa52dbed9
2,789
hpp
C++
aifm/DataFrame/AIFM/include/simple_time.hpp
asarthas/AIFM
aaf7113cb3ba58381174e8b86bdd7a0f1fd1acc4
[ "MIT" ]
49
2020-11-01T00:14:40.000Z
2022-03-26T07:28:12.000Z
aifm/DataFrame/AIFM/include/simple_time.hpp
asarthas/AIFM
aaf7113cb3ba58381174e8b86bdd7a0f1fd1acc4
[ "MIT" ]
12
2020-12-15T08:30:19.000Z
2022-03-13T03:54:24.000Z
aifm/DataFrame/AIFM/include/simple_time.hpp
asarthas/AIFM
aaf7113cb3ba58381174e8b86bdd7a0f1fd1acc4
[ "MIT" ]
19
2020-12-24T22:32:22.000Z
2022-03-30T01:33:43.000Z
#pragma once #include <cstdint> #include <iostream> struct SimpleTime { short year_; char month_; char day_; char hour_; char min_; char second_; SimpleTime() {} SimpleTime(short year, char month, char day, char hour, char min, char second) : year_(year), month_(month), day_(day), hour_(hour), min_(min), second_(second) { } uint64_t to_second() const { uint64_t ret = year_; ret = 12 * ret + month_; // A simple approximation on days. ret = 30 * ret + day_; ret = 24 * ret + hour_; ret = 60 * ret + min_; ret = 60 * ret + second_; return ret; } friend std::istream& operator>>(std::istream& in, SimpleTime& t) { char delim; uint16_t month, day, hour, min, second; in >> t.year_ >> delim >> month >> delim >> day >> delim >> hour >> delim >> min >> delim >> second; t.month_ = month; t.day_ = day; t.hour_ = hour; t.min_ = min; t.second_ = second; return in; } friend std::ostream& operator<<(std::ostream& out, const SimpleTime& t) { out << t.year_ << '-' << (int)t.month_ << '-' << (int)t.day_ << ' ' << (int)t.hour_ << ':' << (int)t.min_ << ':' << (int)t.second_; return out; } bool operator<(const SimpleTime& o) const { if (year_ != o.year_) return year_ < o.year_; if (month_ != o.month_) return month_ < o.month_; if (day_ != o.day_) return day_ < o.day_; if (hour_ != o.hour_) return hour_ < o.hour_; if (min_ != o.min_) return min_ < o.min_; if (second_ != o.second_) return second_ < o.second_; return false; } bool operator>(const SimpleTime& o) const { if (year_ != o.year_) return year_ > o.year_; if (month_ != o.month_) return month_ > o.month_; if (day_ != o.day_) return day_ > o.day_; if (hour_ != o.hour_) return hour_ > o.hour_; if (min_ != o.min_) return min_ > o.min_; if (second_ != o.second_) return second_ > o.second_; return false; } bool operator==(const SimpleTime& o) const { return __builtin_strncmp(reinterpret_cast<const char*>(this), reinterpret_cast<const char*>(&o), sizeof(o)) == 0; } bool operator!=(const SimpleTime& o) const { return !operator==(o); } }; template <> struct std::hash<SimpleTime> { size_t operator()(const SimpleTime& simple_time) const { uint64_t hash = 0; static_assert(sizeof(simple_time) <= sizeof(hash)); __builtin_memcpy(&hash, &simple_time, sizeof(simple_time)); return hash; } };
28.459184
100
0.538544
asarthas
9a3f2c83774d6a46e9f1db232163c1aae187c6e2
561
hpp
C++
include/intercom-party/LocationManager-inl.hpp
Wicker25/intercom-party
5b1610aa79f6242be0cd846533ba97bf6a97f304
[ "MIT" ]
1
2017-04-03T19:52:30.000Z
2017-04-03T19:52:30.000Z
include/intercom-party/LocationManager-inl.hpp
Wicker25/intercom-party
5b1610aa79f6242be0cd846533ba97bf6a97f304
[ "MIT" ]
null
null
null
include/intercom-party/LocationManager-inl.hpp
Wicker25/intercom-party
5b1610aa79f6242be0cd846533ba97bf6a97f304
[ "MIT" ]
null
null
null
/*! * Title ---- intercom-party/LocationManager-inl.hpp * Author --- Giacomo Trudu aka `Wicker25` - wicker25[at]gmail[dot]com * * Copyright (C) 2017 by Giacomo Trudu. * All rights reserved. */ #ifndef __INTERCOM_PARTY_LOCATION_MANAGER_INL_HPP__ #define __INTERCOM_PARTY_LOCATION_MANAGER_INL_HPP__ namespace intercom { // Begin main namespace inline double LocationManager::getRadians(double degrees) { return (degrees * math::constants::pi<double>()) / 180.0; } } // End of main namespace #endif /* __INTERCOM_PARTY_LOCATION_MANAGER_INL_HPP__ */
25.5
70
0.750446
Wicker25
9a441c59c4b62767eb64a9f1cb26cdf347ed8b9d
418
cpp
C++
Exercicio 60.cpp
dariooliveirajr/programming_logic
e1a61edb39f82b59da885b0469f747d3e27b02c6
[ "MIT" ]
null
null
null
Exercicio 60.cpp
dariooliveirajr/programming_logic
e1a61edb39f82b59da885b0469f747d3e27b02c6
[ "MIT" ]
null
null
null
Exercicio 60.cpp
dariooliveirajr/programming_logic
e1a61edb39f82b59da885b0469f747d3e27b02c6
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int A[10],cont,C; int B[10]; int vlr(int A[10]); int main(){ for(cont=0;cont<=9;cont++){ cout<<"Digite um valor "<<" ("<<cont<<")"<<": "; cin>>A[cont]; } vlr(A); for(cont=0;cont<=9;cont++){ cout<<"Quadrado de A["<<cont<<"]: "<<B[cont]<<endl; } system("pause"); return 0; } int vlr(int A[10]){ for(cont=0;cont<=9;cont++){ C=A[cont]; B[cont]=C*C; } }
12.294118
52
0.533493
dariooliveirajr
9a45a0004768e22a19305ff372696fdc941d561f
1,544
hpp
C++
C64/src/d64view/source/mainframe.hpp
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
1
2015-03-26T02:35:13.000Z
2015-03-26T02:35:13.000Z
C64/src/d64view/source/mainframe.hpp
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
null
null
null
C64/src/d64view/source/mainframe.hpp
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
null
null
null
/* d64view - a d64 disk image viewer Copyright (c) 2002,2003,2016 Michael Fink */ /*! \file mainframe.hpp \brief main frame for d64view application MDI (multiple document interface) frame for all view subframes that show the contents of d64 images. */ // import guard #ifndef d64view_mainframe_hpp_ #define d64view_mainframe_hpp_ // needed includes #include "wx/dnd.h" // menu commands enum { MENU_SHOW_DIR = 1, MENU_SHOW_BAM, MENU_INFO_ABOUT }; // classes //! main frame class class d64view_main_frame: public wxDocMDIParentFrame { public: //! ctor d64view_main_frame( wxDocManager* manager, wxFrame* frame, const wxString& title,const wxPoint& pos, const wxSize& size, const long style); //! dtor virtual ~d64view_main_frame(); protected: // message handler //! menu handler: Info -> About void OnMenuInfoAbout(wxCommandEvent& event); protected: //! main frame menu bar wxMenuBar* menubar; //! file menu wxMenu* filemenu; //! info menu wxMenu* infomenu; //! name of config file wxString conffile; DECLARE_EVENT_TABLE() }; //! d64 file drop target class class d64_drop_target: public wxFileDropTarget { public: //! ctor d64_drop_target(wxDocManager* manager):m_docManager(manager){} //! called when files are dropped on the main frame virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames); protected: //! document manager wxDocManager* m_docManager; }; #endif // d64view_mainframe_hpp_
17.953488
82
0.703368
vividos
9a465b7bd534ce87c440a1b6818435df8b0b4fd5
2,929
cpp
C++
code/Thistle/source/thistle_buffer.cpp
pospeselr/SiCKL
e6b3b022df168cb7b853e233967407ff28dd8d1b
[ "MIT" ]
null
null
null
code/Thistle/source/thistle_buffer.cpp
pospeselr/SiCKL
e6b3b022df168cb7b853e233967407ff28dd8d1b
[ "MIT" ]
null
null
null
code/Thistle/source/thistle_buffer.cpp
pospeselr/SiCKL
e6b3b022df168cb7b853e233967407ff28dd8d1b
[ "MIT" ]
null
null
null
#include "thistle.hpp" #include "thistle_error.hpp" #include "thistle_buffer.hpp" using ruff::translate_exceptions; RUFF_EXPORT size_t thistle_get_buffer_element_count(thistle_buffer_t* buffer, thistle_error_t** error) { return translate_exceptions(error, [&]() { RUFF_THROW_IF_NULL(buffer); return buffer->element_count; }); } RUFF_EXPORT size_t thistle_get_buffer_element_width(thistle_buffer_t* buffer, thistle_error_t** error) { return translate_exceptions(error, [&]() { RUFF_THROW_IF_NULL(buffer); return buffer->element_width; }); } RUFF_EXPORT size_t thistle_get_buffer_element_height(thistle_buffer_t* buffer, thistle_error_t** error) { return translate_exceptions(error, [&]() { RUFF_THROW_IF_NULL(buffer); return buffer->element_height; }); } RUFF_EXPORT size_t thistle_get_buffer_element_channels(thistle_buffer_t* buffer, thistle_error_t** error) { return translate_exceptions(error, [&]() { RUFF_THROW_IF_NULL(buffer); return buffer->element_channels; }); } RUFF_EXPORT void thistle_get_buffer_data(thistle_buffer_t* buffer, size_t bufferLength, float* dest, thistle_error_t** error) { return translate_exceptions(error, [&]() { RUFF_THROW_IF_NULL(buffer); RUFF_THROW_IF_NULL(dest); RUFF_THROW_IF_FALSE(bufferLength >= buffer->data.count()); buffer->data.read(dest); }); } RUFF_EXPORT void thistle_set_buffer_data(thistle_buffer* buffer, size_t bufferLength, const float* data, thistle_error_t** error) { return translate_exceptions(error, [&]() { RUFF_THROW_IF_NULL(buffer); RUFF_THROW_IF_FALSE(bufferLength >= buffer->data.count()); buffer->data.write(data); }); } RUFF_EXPORT void thistle_zero_buffer(thistle_buffer_t* buffer, thistle_error_t** error) { return translate_exceptions(error, [&]() { RUFF_THROW_IF_NULL(buffer); buffer->data.zero(); }); } RUFF_EXPORT thistle_buffer_t* thistle_create_sample_buffer(size_t width, size_t height, size_t channels, size_t batchSize, const float* data, thistle_error_t** error) { return translate_exceptions(error, [&]() { RUFF_THROW_IF_FALSE(width > 0); RUFF_THROW_IF_FALSE(height > 0); RUFF_THROW_IF_FALSE(channels > 0); RUFF_THROW_IF_FALSE(batchSize > 0); return new thistle_buffer(width, height, channels, batchSize, data); }); } RUFF_EXPORT thistle_buffer_t* thistle_create_flat_buffer(size_t count, const float* data, thistle_error_t** error) { return translate_exceptions(error, [&]() { RUFF_THROW_IF_FALSE(count > 0); return new thistle_buffer(count, 1, 1, 1, data); }); } RUFF_EXPORT void thistle_free_buffer(thistle_buffer_t* buffer, thistle_error_t** error) { return translate_exceptions(error, [&]() { delete buffer; }); }
27.632075
166
0.700239
pospeselr
9a4e64044710ad8603f59ee4c42c820d3b754945
1,070
hpp
C++
Runtime/GuiSys/CFontRenderState.hpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
267
2016-03-10T21:59:16.000Z
2021-03-28T18:21:03.000Z
Runtime/GuiSys/CFontRenderState.hpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
129
2016-03-12T10:17:32.000Z
2021-04-05T20:45:19.000Z
Runtime/GuiSys/CFontRenderState.hpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
31
2016-03-20T00:20:11.000Z
2021-03-10T21:14:11.000Z
#pragma once #include <list> #include <vector> #include "Runtime/GuiSys/CDrawStringOptions.hpp" #include "Runtime/GuiSys/CGuiTextSupport.hpp" #include "Runtime/GuiSys/CSaveableState.hpp" namespace metaforce { class CBlockInstruction; class CLineInstruction; class CFontRenderState : public CSaveableState { friend class CBlockInstruction; friend class CImageInstruction; friend class CLineInstruction; friend class CTextInstruction; friend class CWordInstruction; CBlockInstruction* x88_curBlock = nullptr; CDrawStringOptions x8c_drawOpts; s32 xd4_curX = 0; s32 xd8_curY = 0; const CLineInstruction* xdc_currentLineInst = nullptr; std::vector<u32> xe8_; std::vector<u8> xf8_; bool x108_lineInitialized = true; std::list<CSaveableState> x10c_pushedStates; public: CFontRenderState(); zeus::CColor ConvertToTextureSpace(const CTextColor& col) const; void PopState(); void PushState(); void SetColor(EColorType tp, const CTextColor& col); void RefreshPalette(); void RefreshColor(EColorType tp); }; } // namespace metaforce
25.47619
66
0.775701
Jcw87
9a544a009e0b01d8da3e13f0669d7c4e7af335dd
653
hpp
C++
patterns/builder/include/Builder.hpp
bencsikandrei/cpp-dp
8afc91956c2f35f9d1bb0a108c4a6266c47bc008
[ "MIT" ]
null
null
null
patterns/builder/include/Builder.hpp
bencsikandrei/cpp-dp
8afc91956c2f35f9d1bb0a108c4a6266c47bc008
[ "MIT" ]
null
null
null
patterns/builder/include/Builder.hpp
bencsikandrei/cpp-dp
8afc91956c2f35f9d1bb0a108c4a6266c47bc008
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <vector> class HtmlBuilder; class HtmlElement { public: friend class HtmlBuilder; static HtmlBuilder create(std::string rootName); std::string str(int indent = 0) const; private: HtmlElement(std::string root, std::string text); HtmlElement() = default; private: std::vector<HtmlElement> mElements{}; std::string mRootName{}; int mIndentSize{}; std::string mText{}; }; class HtmlBuilder { public: HtmlBuilder(std::string rootName); HtmlElement build(); HtmlBuilder &addChild(std::string name, std::string text); private: HtmlElement mRoot; };
19.205882
62
0.678407
bencsikandrei
9a55b1576b01242b62e75b34eafb5512f3b81199
1,129
hpp
C++
include/pattern/maybe.hpp
nathanmullenax83/rhizome
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
[ "MIT" ]
1
2020-07-11T14:53:38.000Z
2020-07-11T14:53:38.000Z
include/pattern/maybe.hpp
nathanmullenax83/rhizome
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
[ "MIT" ]
1
2020-07-04T16:45:49.000Z
2020-07-04T16:45:49.000Z
include/pattern/maybe.hpp
nathanmullenax83/rhizome
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
[ "MIT" ]
null
null
null
#ifndef RHIZOME_PATTERN_MAYBE_HPP #define RHIZOME_PATTERN_MAYBE_HPP #include <cassert> #include "pattern.hpp" #include "types/string.hpp" using rhizome::types::String; namespace rhizome { namespace pattern { class Maybe: public Pattern { private: IPattern *inner; public: Maybe( IPattern *inner ); ~Maybe(); virtual void reset(); virtual bool can_transition(char c) const; virtual void transition(char c); virtual bool accepted() const; virtual Thing * captured_plain() override; virtual Thing * captured_transformed() override; virtual IPattern * clone_pattern(bool withstate) const override; virtual void serialize_to( size_t level, ostream &out ) const; virtual bool has_interface( string const &name ) override; virtual string rhizome_type() const override; virtual Thing * invoke( Thing *context, string const &method, Thing *arg ) override; }; Maybe * maybe( IPattern *inner ); } } #endif
28.225
96
0.615589
nathanmullenax83
9a55fbba94b4b6ac52e33d306e20cf7cef3289c4
18,069
cpp
C++
calculator/mainwindow.cpp
xueqili02/Data-Structure-Practice
8eee219d1912d40b116c2e808ef8e9e1d2a390a8
[ "MIT" ]
null
null
null
calculator/mainwindow.cpp
xueqili02/Data-Structure-Practice
8eee219d1912d40b116c2e808ef8e9e1d2a390a8
[ "MIT" ]
null
null
null
calculator/mainwindow.cpp
xueqili02/Data-Structure-Practice
8eee219d1912d40b116c2e808ef8e9e1d2a390a8
[ "MIT" ]
null
null
null
/* Name: Li Xueqi Number: 20301110 */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "myStack.h" #include "history.h" #include <cstring> #include <cmath> #include <QFile> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); QObject::connect(this->ui->history, SIGNAL(clicked()), this, SLOT(openHistory())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_num_0_clicked() { ui -> display -> insert("0"); } void MainWindow::on_num_1_clicked() { ui -> display -> insert("1"); } void MainWindow::on_num_2_clicked() { ui -> display -> insert("2"); } void MainWindow::on_num_3_clicked() { ui -> display -> insert("3"); } void MainWindow::on_num_4_clicked() { ui -> display -> insert("4"); } void MainWindow::on_num_5_clicked() { ui -> display -> insert("5"); } void MainWindow::on_num_6_clicked() { ui -> display -> insert("6"); } void MainWindow::on_num_7_clicked() { ui -> display -> insert("7"); } void MainWindow::on_num_8_clicked() { ui -> display -> insert("8"); } void MainWindow::on_num_9_clicked() { ui -> display -> insert("9"); } void MainWindow::on_plus_clicked() { ui -> display -> insert("+"); } void MainWindow::on_subtract_clicked() { ui -> display -> insert("-"); } void MainWindow::on_multiply_clicked() { ui -> display -> insert("*"); } void MainWindow::on_devide_clicked() { ui -> display -> insert("/"); } void MainWindow::on_leftParenthesis_clicked() { ui -> display -> insert("("); } void MainWindow::on_rightParenthesis_clicked() { ui -> display -> insert(")"); } void MainWindow::on_exp_clicked() { ui -> display -> insert("^"); } void MainWindow::on_A_clicked() { ui -> display -> insert("A"); } void MainWindow::on_B_clicked() { ui -> display -> insert("B"); } void MainWindow::on_C_clicked() { ui -> display -> insert("C"); } void MainWindow::on_D_clicked() { ui -> display -> insert("D"); } void MainWindow::on_E_clicked() { ui -> display -> insert("E"); } void MainWindow::on_F_clicked() { ui -> display -> insert("F"); } void MainWindow::on_dot_clicked() { ui -> display -> insert("."); } void MainWindow::on_clear_clicked() { ui -> display -> setText(""); } bool isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')' || c == '#' || c == '^'; } int optrcmp(char a, char b) { // 1 for a > b, -1 for a < b, 0 for a = b, 2 for illegal comparison int cmp[8][8] = { {-1, -1, -1, -1, 1, 1, 1, -1}, {-1, -1, -1, -1, 1, 1, 1, -1}, {1, 1, -1, -1, 1, 1, 1, -1}, {1, 1, -1, -1, 1, 1, 1, -1}, {-1, -1, -1, -1, -1, 0, 2, 1}, {1, 1, 1, 1, 2, 1, 1, 1}, {-1, -1, -1, -1, -1, 2, 0, -1}, {1, 1, 1, 1, 1, 1, 1, -1} }; int op1, op2; switch(a) { case '+': op1 = 0;break; case '-': op1 = 1;break; case '*': op1 = 2;break; case '/': op1 = 3;break; case '(': op1 = 4;break; case ')': op1 = 5;break; case '#': op1 = 6;break; case '^': op1 = 7;break; default: op1 = -1;break; } switch(b) { case '+': op2 = 0;break; case '-': op2 = 1;break; case '*': op2 = 2;break; case '/': op2 = 3;break; case '(': op2 = 4;break; case ')': op2 = 5;break; case '#': op2 = 6;break; case '^': op2 = 7;break; default: op2 = -1;break; } return cmp[op1][op2]; } double calc(double a, double b, char optr) { switch(optr) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; case '^': { double power = pow(b, a); return power; } default: return 0; } } // transfer decimal number to binary int decToBin(int x, int* bin) { int digit = 0; for(int i = 0; i < 64; i++) { long long temp = pow(2, i) + 0.5; if((long long) x < temp) { digit = i; break; } } for(int i = digit - 1; i >= 0; i--) { if(x & (1 << i)) { bin[digit - i] = 1; } else { bin[digit - i] = 0; } } return digit; } // transfer different base numbers to decimal number int toDec(int* num, int digit, int base) { int dec = 0; for(int i = digit; i >= 1; i--) { if(num[i] >= base) { printf("ERROR\n"); return -1; } int temp = pow(base, digit - i) + 0.5; dec += temp * num[i]; } return dec; } double reciprocal(double x) { return x == 0 ? -1 : 1.0 / x; } double getNum(char expression[], int cnt, int disp){ int di = 0, dp = 0, s[100], k = 1; bool dec = false; for(int j = cnt + disp; ; j++) { fflush(stdout); if(expression[j] == ')') break; if(expression[j] == '.') { s[k++] = -1; dec = true; continue; } s[k++] = expression[j] - 48; !dec ? di++ : dp++; cnt = j; } cnt++; if(dp != 0) { double num = 0; for(int i = k - 1, j = dp; i > k - 1 - dp; i--, j--) { double t = 1; for(int k = 1; k <= j; k++) t *= 0.1; num += s[i] * t; } for(int i = k - 1 - dp - 1, j = 1; i >= 1; i--, j++) { int t = 1; for(int k = 2; k <= j; k++) t *= 10; num += (double) s[i] * t; } return num; } else { int num = 0; for(int i = k - 1, j = 1; i >= 1; i--, j++) { int t = 1; for(int k = 2; k <= j; k++) t *= 10; num += s[i] * t; } return num; } } QString getExpression(char expression[]) { myStack<double> operandStack; myStack<char> operatorStack; operatorStack.push('#'); int length = strlen(expression); expression[length] = '#'; length++; int digitInt = 0, digitPnt = 0, temp[100], m = 1; bool decimal = false; for(int cnt = 0; cnt < length; cnt++) { if(expression[cnt] == 's' && expression[cnt + 1] == 'i') { double num = getNum(expression, cnt, 4); for(int j = cnt + 4; ; j++) { if(expression[j] == ')') break; cnt = j; } cnt++; num = sin(num); operandStack.push(num); continue; } else if(expression[cnt] == 'c') { double num = getNum(expression, cnt, 4); for(int j = cnt + 4; ; j++) { if(expression[j] == ')') break; cnt = j; } cnt++; num = cos(num); operandStack.push(num); continue; } else if(expression[cnt] == 's' && expression[cnt + 1] == 'q') { double num = getNum(expression, cnt, 5); for(int j = cnt + 5; ; j++) { if(expression[j] == ')') break; cnt = j; } cnt++; if(num < 0) { break; } num = sqrt(num); operandStack.push(num); continue; } // duplicate decimal point if(decimal && expression[cnt] == '.') { continue; } if(expression[cnt] >= '0' && expression[cnt] <= '9') { temp[m++] = expression[cnt] - 48; !decimal ? digitInt++ : digitPnt++; continue; } else if(expression[cnt] == '.') { temp[m++] = -1; // -1 for point decimal = true; continue; } else { // has decimal part if(digitPnt != 0) { double num = 0; for(int i = m - 1, j = digitPnt; i > m - 1 - digitPnt; i--, j--) { double t = 1; for(int k = 1; k <= j; k++) t *= 0.1; num += temp[i] * t; } for(int i = m - 1 - digitPnt - 1, j = 1; i >= 1; i--, j++) { int t = 1; for(int k = 2; k <= j; k++) t *= 10; num += (double) temp[i] * t; } operandStack.push(num); } else if(digitInt != 0){ int num = 0; for(int i = m - 1, j = 1; i >= 1; i--, j++) { int t = 1; for(int k = 2; k <= j; k++) t *= 10; num += temp[i] * t; } operandStack.push((double) num); } decimal = false; digitPnt = 0; digitInt = 0; m = 1; if(expression[cnt] == '(') { if(expression[cnt - 1] == ')') { operatorStack.push('*'); } else if(expression[cnt + 1] == '-') { operandStack.push(0); } operatorStack.push('('); continue; } else if(expression[cnt] == ')') { char optr = operatorStack.top(); if(optr == '(') { break; } operatorStack.pop(); while(optr != '(') { if(operandStack.isEmpty()) { break; } double a = operandStack.top(); operandStack.pop(); double b = operandStack.top(); operandStack.pop(); operandStack.push(calc(a, b, optr)); optr = operatorStack.top(); if(optr == '#') { operatorStack.push('#'); break; } operatorStack.pop(); } continue; } if((expression[cnt - 1] < '0' || expression[cnt - 1] > '9') && expression[cnt - 1] != ')' && expression[cnt - 1] != '(') { operatorStack.pop(); } int cmp = optrcmp(expression[cnt], operatorStack.top()); // 1 for a > b, -1 for a < b, 0 for a = b, 2 for illegal comparison if(cmp == 1) { operatorStack.push(expression[cnt]); } else if(cmp == -1) { if(operatorStack.top() == '(') { operatorStack.push(expression[cnt]); continue; } while(cmp == -1) { if(operandStack.isEmpty()) { operatorStack.push('#'); break; } double a = operandStack.top(); operandStack.pop(); double b = operandStack.top(); operandStack.pop(); char optr = operatorStack.top(); if(optr == '(' || optr == ')') { break; } operatorStack.pop(); if(a == 0 && optr == '/') { break; } operandStack.push(calc(a, b, optr)); cmp = optrcmp(expression[cnt], operatorStack.top()); } operatorStack.push(expression[cnt]); if(expression[cnt] == '#') { operatorStack.pop(); operatorStack.pop(); } } else if(cmp == 0) { if(operandStack.size() != 1) { QString str = "ERROR\n"; return str; break; } operatorStack.pop(); } else { QString str = "ERROR\n"; return str; break; } } } if(operandStack.size() != 1 || !operatorStack.isEmpty()) { QString str = "Error\n"; return str; } else { int integer = (int) operandStack.top(); if(abs(integer - operandStack.top()) <= 0.0000001) { QString str = QString::number(integer, 10); return str; } else { QString str = QString::number(operandStack.top(), 'f', 6); return str; } } } void record(QString history, int symbol) { QFile file("C://Users//lenovo//Desktop//AlgoandDSPractice//calculator//history.txt"); if(!file.open(QIODevice::WriteOnly | QIODevice::Append)) { qDebug() << file.errorString(); } QTextStream output(&file); output << history; if(symbol == 1) { output << "\n"; } file.close(); } void MainWindow::on_equal_clicked() { QString str = ui -> display -> text(); QByteArray s = str.toLatin1(); char* expression = s.data(); record(expression, 0); ui -> display -> setText(""); QString answer = getExpression(expression); ui -> display -> setText(answer); QString temp = "="; record(temp + answer, 1); } void MainWindow::on_delete_2_clicked() { QString str = ui -> display -> text(); ui -> display -> setText(""); int length = str.size(); for(int i = 0; i < length - 1; i++) { ui -> display -> insert(str[i]); } } void MainWindow::on_rcp_clicked() { ui -> display -> insert("(1/"); } void MainWindow::on_sqrt_clicked() { ui -> display -> insert("sqrt("); } void MainWindow::on_sin_clicked() { ui -> display -> insert("sin"); } void MainWindow::on_cos_clicked() { ui -> display -> insert("cos"); } void MainWindow::on_bin_clicked() { QString str = ui -> display -> text(); record("BIN"+str, 0); int bin[100], x = str.toInt(); int digit = 0; for(int i = 0; i < 64; i++) { long long temp = pow(2, i) + 0.5; if((long long) x < temp) { digit = i; break; } } for(int i = digit - 1; i >= 0; i--) { if(x & (1 << i)) { bin[digit - i] = 1; } else { bin[digit - i] = 0; } } ui -> display ->setText(""); record("=", 0); for(int i = 1; i <= digit; i++) { ui -> display -> insert(QString::number(bin[i])); record(QString::number(bin[i]), 0); } record("", 1); } void MainWindow::on_oct_clicked() { QString str = ui -> display -> text(); record("OCT" + str, 0); int x = str.toInt(); int bin[64], digit, oct[64], m = 1; memset(oct, 0, sizeof(oct)); digit = decToBin(x, bin); for(int i = digit, cnt = 0; i >= 1; i--) { int temp = pow(2, cnt++) + 0.5; oct[m] += temp * bin[i]; if(cnt == 3) { cnt = 0; m++; } } digit % 3 == 0 ? m-- : m; ui -> display -> setText(""); record("=", 0); for(int i = m; i >= 1; i--) { ui -> display -> insert(QString::number(oct[i])); record(QString::number(oct[i]), 0); } record("", 1); } void MainWindow::on_hex_clicked() { QString str = ui -> display -> text(); record(str, 0); int x = str.toInt(); int bin[64], digit, hex[64], m = 1; memset(hex, 0, sizeof(hex)); digit = decToBin(x, bin); for(int i = digit, cnt = 0; i >= 1; i--) { int temp = pow(2, cnt++) + 0.5; hex[m] += temp * bin[i]; if(cnt == 4) { cnt = 0; m++; } } digit % 4 == 0 ? m-- : m; ui -> display -> setText(""); record("=", 0); for(int i = m; i >= 1; i--) { if(hex[i] < 10) { ui -> display -> insert(QString::number(hex[i])); record(QString::number(hex[i]), 0); } else { switch(hex[i]) { case 10: ui -> display -> insert("A"); record("A", 0); break; case 11: ui -> display -> insert("B"); record("B", 0); break; case 12: ui -> display -> insert("C"); record("C", 0); break; case 13: ui -> display -> insert("D"); record("D", 0); break; case 14: ui -> display -> insert("E"); record("E", 0); break; case 15: ui -> display -> insert("F"); record("F", 0); break; } } } record("", 1); } void MainWindow::on_dec_clicked() { QString str = ui -> display -> text(); int length = str.length(); str[length - 1] = str[length - 1].toLower(); int num[100]; for(int i = 0; i < length - 1; i++) { if(str[i] >= 'A' && str[i] <= 'F') { num[i + 1] = str[i].toLatin1() - 'A' + 10; } else { num[i + 1] = str[i].toLatin1() - '0'; } } ui -> display -> setText(""); int x; if(str[length - 1] == 'b') { x = toDec(num, length - 1, 2); } else if(str[length - 1] == 'o') { x = toDec(num, length - 1, 8); } else if(str[length - 1] == 'h') { x = toDec(num, length - 1, 16); } else { ui -> display -> insert("ERROR"); return ; } x == -1 ? ui -> display -> insert("ERROR") : ui -> display -> insert(QString::number(x)); } void MainWindow::openHistory() { History* his = new History(); his -> show(); } // 6*(2+3)/5+7 // 11.2+3*(5.1-0.5) // 1.5.5 // 1++2 // 1/0 // 1+(-2)(2+3)
27.294562
105
0.41336
xueqili02
9a5727ccef4bba0e4e54dafc414e9d185c050b7f
3,787
cpp
C++
SarkLibrary/PNGResource.cpp
alleysark/SarkEngine_forExperiment
9e27ddc37242cf739d67ee7efc2ff2b24d3c4811
[ "Apache-2.0" ]
2
2015-07-20T08:57:02.000Z
2018-11-02T13:42:49.000Z
SarkLibrary/PNGResource.cpp
alleysark/SarkEngine_forExperiment
9e27ddc37242cf739d67ee7efc2ff2b24d3c4811
[ "Apache-2.0" ]
null
null
null
SarkLibrary/PNGResource.cpp
alleysark/SarkEngine_forExperiment
9e27ddc37242cf739d67ee7efc2ff2b24d3c4811
[ "Apache-2.0" ]
null
null
null
#include "PNGResource.h" #include "Debug.h" #include <png.h> #include <fcntl.h> namespace sark { PNGResource::PNGResource() : mWidth(0), mHeight(0), mPixels(NULL) {} PNGResource::~PNGResource() { if (mPixels != NULL) { delete[] mPixels; } } const integer PNGResource::GetWidth() const { return mWidth; } const integer PNGResource::GetHeight() const { return mHeight; } const integer PNGResource::GetDepth() const { return 0; } Texture::Format PNGResource::GetPixelFormat() const { return mFormat; } Texture::PixelType PNGResource::GetPixelType() const { return mPixelType; } const void* PNGResource::GetPixels() const { return mPixels; } s_ptr<PNGResource> PNGResource::LoadImp(const std::string& name) { png_structp png_ptr = NULL; png_infop info_ptr = NULL; FILE *fp = NULL; // temporary clear macro #define CLEAR_MEM() do {\ if (png_ptr != NULL && info_ptr != NULL) {\ png_destroy_read_struct(&png_ptr, &info_ptr, NULL); \ }\ if (fp != NULL) { fclose(fp); }\ }while (0) // 8 is the maximum size that can be checked const uinteger HEADER_SIZE = 8; char header[HEADER_SIZE]; // open file and test for it being a png fopen_s(&fp, name.c_str(), "rb"); if (!fp) { LogError("failed to open png file"); CLEAR_MEM(); return NULL; } fread_s(header, HEADER_SIZE, 1, HEADER_SIZE, fp); if (png_sig_cmp((png_const_bytep)header, 0, HEADER_SIZE)) { LogError("file is not recognized as a PNG format"); CLEAR_MEM(); return NULL; } // initialize stuff png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { LogError("png_create_read_struct failed"); CLEAR_MEM(); return NULL; } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { LogError("png_create_info_struct failed"); CLEAR_MEM(); return NULL; } if (setjmp(png_jmpbuf(png_ptr))) { LogError("Error during init_io"); CLEAR_MEM(); return NULL; } png_init_io(png_ptr, fp); png_set_sig_bytes(png_ptr, HEADER_SIZE); png_read_info(png_ptr, info_ptr); png_uint_32 width, height; png_int_32 color_type; png_int_32 bit_depth; //bit per channel png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); // pixel format and type check Texture::Format pngPixelFormat; Texture::PixelType pngPixelType; if (color_type == PNG_COLOR_TYPE_RGB) pngPixelFormat = Texture::Format::RGB; else if (color_type == PNG_COLOR_TYPE_RGBA) pngPixelFormat = Texture::Format::RGBA; else { LogError("it only supports PNG_COLOR_TYPE_RGB or PNG_COLOR_TYPE_RGBA"); CLEAR_MEM(); return NULL; } if (bit_depth == 8) pngPixelType = Texture::PixelType::UNSIGNED_BYTE; else if (bit_depth == 16) pngPixelType = Texture::PixelType::UNSIGNED_SHORT; else { LogError("invalid bit depth"); CLEAR_MEM(); return NULL; } // prepare to read image integer number_of_passes = png_set_interlace_handling(png_ptr); png_read_update_info(png_ptr, info_ptr); if (setjmp(png_jmpbuf(png_ptr))) { LogError("Error during read_image"); CLEAR_MEM(); return NULL; } // read image s_ptr<PNGResource> png = s_ptr<PNGResource>(new PNGResource()); png->mWidth = width; png->mHeight = height; png->mFormat = pngPixelFormat; png->mPixelType = pngPixelType; png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); png->mPixels = new uint8[rowbytes * height]; png_bytep* row_pointers = new png_bytep[height]; for (integer i = 0; i < height; i++) row_pointers[i] = png->mPixels + i*rowbytes; png_read_image(png_ptr, row_pointers); png_read_end(png_ptr, NULL); CLEAR_MEM(); delete[] row_pointers; return png; #undef CLEAR_MEM } }
23.233129
94
0.686823
alleysark
9a57e3fb13019cc5ea24ae414f3db8798e28fc74
828
cpp
C++
RAS/Dialog_EcodeToMark.cpp
simonyhong/Blip
49b280b061470037edb672d4d2a7d434909dc039
[ "Unlicense" ]
null
null
null
RAS/Dialog_EcodeToMark.cpp
simonyhong/Blip
49b280b061470037edb672d4d2a7d434909dc039
[ "Unlicense" ]
null
null
null
RAS/Dialog_EcodeToMark.cpp
simonyhong/Blip
49b280b061470037edb672d4d2a7d434909dc039
[ "Unlicense" ]
null
null
null
// EcodeToMark.cpp : implementation file // #include "stdafx.h" #include "RAS.h" #include "Dialog_EcodeToMark.h" #include "afxdialogex.h" // CEcodeToMark dialog IMPLEMENT_DYNAMIC(CEcodeToMark, CDialogEx) CEcodeToMark::CEcodeToMark(CWnd* pParent /*=NULL*/) : CDialogEx(CEcodeToMark::IDD, pParent) , m_EcodeToMark(0) , m_0_TheFirstRadioEnabled(0) { } CEcodeToMark::~CEcodeToMark() { } void CEcodeToMark::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, m_EcodeToMark); DDX_Radio(pDX, IDC_RADIO1, m_0_TheFirstRadioEnabled);//This links the radio button (this one is the only one having the "grup" property activated) to the variable. } BEGIN_MESSAGE_MAP(CEcodeToMark, CDialogEx) END_MESSAGE_MAP() // CEcodeToMark message handlers
21.230769
165
0.733092
simonyhong
9a5944d3a631ccd235bfeeb8019b67963f91a393
477
cpp
C++
gym/102297/G.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
1
2021-07-16T19:59:39.000Z
2021-07-16T19:59:39.000Z
gym/102297/G.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
gym/102297/G.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define endl '\n' typedef long long ll; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; for(int cases = 1; cases <= t; cases++){ cout << "Grid #" << cases << ": "; ll k, n; cin >> k >> n; ll mx = (n - 1) * (n - 1) + 1; if(k > mx) cout << "impossible" << endl << endl; else cout << k * (n - 1) * 2 << endl << endl; } // cout << flush,system("pause"); return 0; }
15.387097
43
0.492662
albexl
9a61b3bceaf35766755781d1afca0465bd7d6c5a
3,022
cpp
C++
UVA Solved Problem/11080 - Place the Guards/11080 - Place the Guards .cpp
ahmed-dinar/UVA
5cb43864744475ed7ac94e6cb6cae50ad80603c7
[ "MIT" ]
null
null
null
UVA Solved Problem/11080 - Place the Guards/11080 - Place the Guards .cpp
ahmed-dinar/UVA
5cb43864744475ed7ac94e6cb6cae50ad80603c7
[ "MIT" ]
null
null
null
UVA Solved Problem/11080 - Place the Guards/11080 - Place the Guards .cpp
ahmed-dinar/UVA
5cb43864744475ed7ac94e6cb6cae50ad80603c7
[ "MIT" ]
null
null
null
#include<cstdio> #include<sstream> #include<cstdlib> #include<cctype> #include<cmath> #include<algorithm> #include<set> #include<queue> #include<deque> #include<stack> #include<list> #include<iostream> #include<fstream> #include<numeric> #include<string> #include<vector> #include<cstring> #include<map> #include<iterator> using namespace std; #define filein freopen("in.txt","r",stdin) #define fileout freopen("out.txt","w",stdout) #define cs(x) printf("Case %d: ",x) #define csn(x) printf("Case %d:\n",x) #define nFind(v,n) find(all(v),n)==v.end() #define Find(v,n) find(all(v),n)!=v.end() #define all(x) x.begin(),x.end() #define mp make_pair #define pb push_back #define sz size() #define cl clear() #define em empty() #define ss second #define fi first #define sc(n) scanf("%d",&n) #define scd(n,m) scanf("%d %d",&n,&m) #define sct(n,m,v) scanf("%d %d %d",&n,&m,&v) #define nl puts("") #define REP(i,n) for(__typeof(n) i = 0; i < (n); ++i) #define FOR(i,k,n) for(__typeof(n) i = (k); i <= (n); ++i) #define For(i,k,n) for(__typeof(n) i = (k); i < (n); ++i) #define EPS 1e-9 #define pi acos(-1.0) #define MAX 205 #define oo 2000000000.0 #define MOD 1000000007 typedef long long i64; typedef pair<int,int> pri; typedef vector<int> vci; typedef vector<pri> vcp; template<class T>bool iseq(T a,T b){return fabs(a-b)<EPS;} template<class T>T sq(T a){ return (a*a); } template<class T>T gcd(T a,T b){ return (b==0) ? a : gcd(b,a%b); } template<class T>T lcm(T a,T b){ return (a/gcd(a,b))*b; } template<class T>T Pow(T n,T p) { T res=n; for(T i=1;i<p; i++){ res *= n; } return res; } template<class T>bool isPrime(T n){ for(T i=2; i*i<=n; i++){ if(n%i==0) return false; } return true; } vci g[MAX]; int gurd[MAX]; int bfs(int src){ if(g[src].sz==0) return 1; queue<int>q; q.push(src); int a=0,b=1; gurd[src]=1; while(!q.em){ int u=q.front(); q.pop(); REP(i,g[u].sz){ int v=g[u][i]; if(!gurd[v]){ if(gurd[u]==1) gurd[v]=2,a++; else gurd[v]=1,b++; q.push(v); } else if(gurd[u]==gurd[v]) return -1; } } return min(a,b); } int main(){ // filein; int t,T=0; scanf("%d",&t); while(t--){ int n,m,u,v; scanf("%d %d",&n,&m); while(m--){ scanf("%d %d",&u,&v); g[u].pb(v); g[v].pb(u); } memset(&gurd,0,sizeof(gurd)); int gurds=0,impossible=0; REP(i,n){ if(!gurd[i]){ int total=bfs(i); if(total==-1){ impossible=1; break; } else gurds+=total; } } printf("%d\n",impossible ? -1 : gurds); REP(i,n) g[i].cl; } return 0; }
24.176
103
0.498015
ahmed-dinar
9a6aa38e106910d501b2cc6178ab84d84b4fa3f7
5,573
cpp
C++
Programs/QuickEd/Classes/Modules/IssueNavigatorModule/IssueNavigatorModule.cpp
BlitzModder/dava.engine
0c7a16e627fc0d12309250d6e5e207333b35361e
[ "BSD-3-Clause" ]
4
2019-11-15T11:30:00.000Z
2021-12-27T21:16:31.000Z
Programs/QuickEd/Classes/Modules/IssueNavigatorModule/IssueNavigatorModule.cpp
TTopox/dava.engine
0c7a16e627fc0d12309250d6e5e207333b35361e
[ "BSD-3-Clause" ]
null
null
null
Programs/QuickEd/Classes/Modules/IssueNavigatorModule/IssueNavigatorModule.cpp
TTopox/dava.engine
0c7a16e627fc0d12309250d6e5e207333b35361e
[ "BSD-3-Clause" ]
4
2017-04-07T04:32:41.000Z
2021-12-27T21:55:49.000Z
#include "Classes/Modules/IssueNavigatorModule/IssueNavigatorModule.h" #include "Classes/Modules/IssueNavigatorModule/IssueData.h" #include "Classes/Modules/IssueNavigatorModule/IssueNavigatorData.h" #include "Classes/Modules/IssueNavigatorModule/LayoutIssueHandler.h" #include "Classes/Modules/IssueNavigatorModule/NamingIssuesHandler.h" #include "Classes/Modules/IssueNavigatorModule/EventsIssuesHandler.h" #include "Classes/Modules/IssueNavigatorModule/RichContentIssuesHandler.h" #include "Application/QEGlobal.h" #include <TArc/WindowSubSystem/UI.h> #include <TArc/Utils/ModuleCollection.h> #include <TArc/Controls/TableView.h> DAVA_VIRTUAL_REFLECTION_IMPL(IssueNavigatorModule) { DAVA::ReflectionRegistrator<IssueNavigatorModule>::Begin() .ConstructorByPointer() .Field("header", &IssueNavigatorModule::headerDescription) .Field("issues", &IssueNavigatorModule::GetValues, nullptr) .Field("current", &IssueNavigatorModule::GetCurrentValue, &IssueNavigatorModule::SetCurrentValue) .Method("OnIssueActivated", &IssueNavigatorModule::OnIssueAvitvated) .End(); } DAVA_REFLECTION_IMPL(IssueNavigatorModule::HeaderDescription) { DAVA::ReflectionRegistrator<IssueNavigatorModule::HeaderDescription>::Begin() .Field("message", &IssueNavigatorModule::HeaderDescription::message)[DAVA::M::DisplayName("Message")] .Field("pathToControl", &IssueNavigatorModule::HeaderDescription::pathToControl)[DAVA::M::DisplayName("Path To Control")] .Field("packagePath", &IssueNavigatorModule::HeaderDescription::packagePath)[DAVA::M::DisplayName("Package Path")] .Field("propertyName", &IssueNavigatorModule::HeaderDescription::propertyName)[DAVA::M::DisplayName("Property Name")] .End(); } void IssueNavigatorModule::PostInit() { using namespace DAVA; const char* title = "Issue Navigator"; DockPanelInfo panelInfo; panelInfo.title = title; panelInfo.area = Qt::BottomDockWidgetArea; PanelKey key(title, panelInfo); TableView::Params params(GetAccessor(), GetUI(), DAVA::mainWindowKey); params.fields[TableView::Fields::Header] = "header"; params.fields[TableView::Fields::Values] = "issues"; params.fields[TableView::Fields::CurrentValue] = "current"; params.fields[TableView::Fields::ItemActivated] = "OnIssueActivated"; TableView* tableView = new TableView(params, GetAccessor(), DAVA::Reflection::Create(DAVA::ReflectedObject(this))); GetUI()->AddView(DAVA::mainWindowKey, key, tableView->ToWidgetCast()); std::unique_ptr<IssueNavigatorData> data = std::make_unique<IssueNavigatorData>(); DAVA::int32 sectionId = 0; data->handlers.push_back(std::make_unique<LayoutIssueHandler>(GetAccessor(), sectionId++, &data->indexGenerator)); data->handlers.push_back(std::make_unique<NamingIssuesHandler>(GetAccessor(), sectionId++, &data->indexGenerator)); data->handlers.push_back(std::make_unique<EventsIssuesHandler>(GetAccessor(), sectionId++, &data->indexGenerator)); data->handlers.push_back(std::make_unique<RichContentIssuesHandler>(GetAccessor(), sectionId++, &data->indexGenerator)); GetAccessor()->GetGlobalContext()->CreateData(std::move(data)); } void IssueNavigatorModule::OnWindowClosed(const DAVA::WindowKey& key) { if (key == DAVA::mainWindowKey) { GetAccessor()->GetGlobalContext()->DeleteData<IssueNavigatorData>(); } } void IssueNavigatorModule::OnContextCreated(DAVA::DataContext* context) { context->CreateData(std::make_unique<IssueData>()); } void IssueNavigatorModule::OnContextWillBeChanged(DAVA::DataContext* current, DAVA::DataContext* newOne) { if (current != nullptr) { IssueData* issueData = current->GetData<IssueData>(); issueData->RemoveAllIssues(); } } void IssueNavigatorModule::OnIssueAvitvated(DAVA::int32 index) { const DAVA::DataContext* context = GetAccessor()->GetActiveContext(); if (context) { DVASSERT(index != -1); IssueData* issueData = context->GetData<IssueData>(); if (issueData) { const IssueData::Issue& issue = issueData->GetIssues()[index]; const QString& path = QString::fromStdString(DAVA::FilePath(issue.packagePath).GetAbsolutePathname()); const QString& name = QString::fromStdString(issue.pathToControl); InvokeOperation(QEGlobal::SelectControl.ID, path, name); } } } const DAVA::Vector<IssueData::Issue>& IssueNavigatorModule::GetValues() const { const DAVA::DataContext* context = GetAccessor()->GetActiveContext(); if (context) { IssueData* issueData = context->GetData<IssueData>(); DVASSERT(issueData); return issueData->GetIssues(); } static DAVA::Vector<IssueData::Issue> empty; return empty; } void IssueNavigatorModule::OnContextDeleted(DAVA::DataContext* context) { const DAVA::DataContext* globalContext = GetAccessor()->GetGlobalContext(); if (globalContext) { IssueNavigatorData* data = globalContext->GetData<IssueNavigatorData>(); DVASSERT(data); for (const std::unique_ptr<IssueHandler>& handler : data->handlers) { handler->OnContextDeleted(context); } } } DAVA::Any IssueNavigatorModule::GetCurrentValue() const { return current; } void IssueNavigatorModule::SetCurrentValue(const DAVA::Any& currentValue) { if (currentValue.IsEmpty()) { current = 0; } else { current = currentValue.Cast<DAVA::int32>(); } } DECL_TARC_MODULE(IssueNavigatorModule);
36.907285
125
0.724027
BlitzModder
9a6c24dd6b7371d57d7d088df8a5a45c953cfaed
680
hpp
C++
Modules/Vulkan/Public/Toon/Vulkan/VulkanMesh.hpp
benjinx/Toon
f21032b2f9ad5fbc9a3618a7719c33159257d954
[ "MIT" ]
2
2021-01-28T03:08:08.000Z
2021-01-28T03:08:21.000Z
Modules/Vulkan/Public/Toon/Vulkan/VulkanMesh.hpp
benjinx/Toon
f21032b2f9ad5fbc9a3618a7719c33159257d954
[ "MIT" ]
null
null
null
Modules/Vulkan/Public/Toon/Vulkan/VulkanMesh.hpp
benjinx/Toon
f21032b2f9ad5fbc9a3618a7719c33159257d954
[ "MIT" ]
null
null
null
#ifndef TOON_VULKAN_MESH_HPP #define TOON_VULKAN_MESH_HPP #include <Toon/Vulkan/VulkanConfig.hpp> #include <Toon/Mesh.hpp> namespace Toon::Vulkan { #define TOON_VULKAN_MESH(x) (dynamic_cast<Toon::Vulkan::VulkanMesh *>(x)) class TOON_VULKAN_API VulkanMesh : public Mesh { public: DISALLOW_COPY_AND_ASSIGN(VulkanMesh) VulkanMesh() = default; virtual ~VulkanMesh() = default; bool Initialize() override; void Terminate() override; bool Create(); void Destroy(); void Render(RenderContext * ctx) override; private: VkDescriptorSet _vkDescriptorSet; }; // class VulkanMesh } // namespace Toon::Vulkan #endif // TOON_VULKAN_MESH_HPP
17
73
0.725
benjinx
9a7052e3d4ad7450e54cdecfb00f8865590747eb
4,105
cpp
C++
src/IOChannels/IO_Channel_Hw_PiFace.cpp
dajuly20/ControlPi
e03ed36eb062007051ac9d35cde01f441d82bde7
[ "MIT" ]
null
null
null
src/IOChannels/IO_Channel_Hw_PiFace.cpp
dajuly20/ControlPi
e03ed36eb062007051ac9d35cde01f441d82bde7
[ "MIT" ]
null
null
null
src/IOChannels/IO_Channel_Hw_PiFace.cpp
dajuly20/ControlPi
e03ed36eb062007051ac9d35cde01f441d82bde7
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: IO_Channel_Hw_PiFace.cpp * Author: julian * * Created on December 19, 2018, 11:39 PM */ #include "IO_Channel_Hw_PiFace.h" #include <utility> #include <iostream> #include <functional> #include "pifacedigitalcpp.h" uint8_t inputs; //IO_Channel_Hw_PiFace::IO_Channel_Hw_PiFace(PiFaceDigital* pfd_init) : pfd(pfd_init) { // this->init_pfd_object(); //} IO_Channel_Hw_PiFace::IO_Channel_Hw_PiFace(configEntity* _conf) { // Create Instance of pfd conf = _conf; token = _conf->private_token; // Parameters for PiFace Object.. will soon be emoved because initialising piface will be moved into IO_Channel_PiFaceDigital. static int hw_addr = 0; static int enable_interrupts = 1; pfdsp = PiFacePtr(new PiFaceDigital(hw_addr, enable_interrupts, PiFaceDigital::EXITVAL_ZERO) ); if(!pfdsp->init_success()){ throw std::invalid_argument("Error: Could not open PiFaceDigital. Is the device properly attached?"); } this->init_pfd_object(); } void IO_Channel_Hw_PiFace::init_pfd_object(){ for(auto const& x : conf->entity_detail){ std::cout << x.first << ": Read:" << x.second->perm_read << " Write:" << x.second->perm_write << " Kind: " << x.second->entityKind << std::endl; int kind = x.second->entityKind; //ChannelEntitySP entity; switch(kind){ case (Channel_Entity::ENTITY_INPUT): input = ChannelEntitySP ( new Channel_Entity_PiFace_Inputs (pfdsp, /*Channel_Entity::exp_none, Channel_Entity::exp_none*/ x.second->perm_read, x.second->perm_write)); chEntities.insert ( std::make_pair(x.first ,input) ); break; case (Channel_Entity::ENTITY_OUTPUT): output = ChannelEntitySP( new Channel_Entity_PiFace_Outputs(pfdsp, /*Channel_Entity::exp_none, Channel_Entity::exp_none*/ x.second->perm_read, x.second->perm_write)); chEntities.insert ( std::make_pair(x.first ,output) ); break; case (Channel_Entity::ENTITY_DUPLEX): // fallthrough case (Channel_Entity::ENTITY_ERROR): // fallthrough default: throw std::invalid_argument("Err: Invalid Config for HardwarePiface. Use inputEntityKey or outputEntityKey"); break; } } // ChannelEntitySP output ( new Channel_Entity_PiFace_Outputs(pfdsp, Channel_Entity::exp_public, Channel_Entity::exp_none)); // ChannelEntitySP input ( new Channel_Entity_PiFace_Inputs (pfdsp, Channel_Entity::exp_public, Channel_Entity::exp_none)); //// // chEntities.insert ( std::make_pair('o',output) ); // chEntities.insert ( std::make_pair('i',input) ); } //IO_Channel_Hw_PiFace::IO_Channel_Hw_PiFace(const IO_Channel_Hw_PiFace& orig) {} IO_Channel_Hw_PiFace::~IO_Channel_Hw_PiFace() { //delete this->pfd; // for (auto chEntity : chEntities) { // delete chEntity; // } // // for (std::pair<char,Channel_Entity*> chEntity : chEntities) { // delete chEntity.second; // } } bool IO_Channel_Hw_PiFace::interrupts_enabled(){ // cast to bool return (bool) pfdsp->interrupts_enabled(); } bool IO_Channel_Hw_PiFace::wait_for_interrupt(){ //if (pifacedigital_wait_for_input(&inputs, -1, hw_addr) > 0) bool ret = (pfdsp->wait_for_input(&inputs, -1) > 0); // printf("Input values are: "+inputs); //pfd->flush(); return ret; } void IO_Channel_Hw_PiFace::caching_enable(){ printf("Caching enable called"); pfdsp->caching_enable(); } void IO_Channel_Hw_PiFace::caching_disable(){ printf("Caching disable called"); pfdsp->caching_disable();} void IO_Channel_Hw_PiFace::flush(){ pfdsp->flush();}
35.387931
183
0.640682
dajuly20
9a890161b577010bd90bce57b8381ce8761f64fe
55,603
cpp
C++
test/fast_recompression_test.cpp
christopherosthues/recompression
1932cc5aa77a533d9994dbe0c80dbb889a4d25ec
[ "ECL-2.0", "Apache-2.0" ]
5
2019-07-18T12:48:14.000Z
2022-01-04T13:54:13.000Z
test/fast_recompression_test.cpp
christopherosthues/recompression
1932cc5aa77a533d9994dbe0c80dbb889a4d25ec
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
test/fast_recompression_test.cpp
christopherosthues/recompression
1932cc5aa77a533d9994dbe0c80dbb889a4d25ec
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #define private public #include "recompression/fast_recompression.hpp" #include "recompression/util.hpp" using namespace recomp; typedef recompression_fast<var_t>::text_t text_t; typedef recompression_fast<var_t>::adj_list_t adj_list_t; typedef recompression_fast<var_t>::partition_t partition_t; typedef recompression_fast<var_t>::alphabet_t alphabet_t; typedef recompression_fast<var_t>::bv_t bv_t; TEST(replace_letters, 212141323141341323141321) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 1, 2, 1, 4, 1, 3, 2, 3, 1, 4, 1, 3, 4, 1, 3, 2, 3, 1, 4, 1, 3, 2, 1}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 5; rlslp.terminals = 5; std::vector<var_t> mapping; recomp.replace_letters(text, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 3, 0, 2, 1, 2, 0, 3, 0, 2, 3, 0, 2, 1, 2, 0, 3, 0, 2, 1, 0}); std::vector<var_t> exp_mapping = {1, 2, 3, 4}; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; term_t exp_alphabet_size = 4; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); } TEST(replace_letters, 212141323181341323141321) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 1, 2, 1, 4, 1, 3, 2, 3, 1, 8, 1, 3, 4, 1, 3, 2, 3, 1, 4, 1, 3, 2, 1}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 9; rlslp.terminals = 9; std::vector<var_t> mapping; recomp.replace_letters(text, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 3, 0, 2, 1, 2, 0, 4, 0, 2, 3, 0, 2, 1, 2, 0, 3, 0, 2, 1, 0}); std::vector<var_t> exp_mapping = {1, 2, 3, 4, 8}; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 9; exp_rlslp.root = 0; term_t exp_alphabet_size = 5; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); } TEST(replace_letters, 21214441332311413334133231141321) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 1, 2, 1, 4, 4, 4, 1, 3, 3, 2, 3, 1, 1, 4, 1, 3, 3, 3, 4, 1, 3, 3, 2, 3, 1, 1, 4, 1, 3, 2, 1}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 5; rlslp.terminals = 5; std::vector<var_t> mapping; recomp.replace_letters(text, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 3, 3, 3, 0, 2, 2, 1, 2, 0, 0, 3, 0, 2, 2, 2, 3, 0, 2, 2, 1, 2, 0, 0, 3, 0, 2, 1, 0}); std::vector<var_t> exp_mapping = {1, 2, 3, 4}; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; term_t exp_alphabet_size = 4; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); } TEST(replace_letters, 222222222222222222222) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; rlslp.terminals = 3; std::vector<var_t> mapping; recomp.replace_letters(text, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); std::vector<var_t> exp_mapping = {2}; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 3; exp_rlslp.root = 0; term_t exp_alphabet_size = 1; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); } TEST(replace_letters, 22222222211111112222) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; rlslp.terminals = 3; std::vector<var_t> mapping; recomp.replace_letters(text, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1}); std::vector<var_t> exp_mapping = {1, 2}; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 3; exp_rlslp.root = 0; term_t exp_alphabet_size = 2; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); } TEST(replace_letters, 2222222221111111222200) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; rlslp.terminals = 3; std::vector<var_t> mapping; recomp.replace_letters(text, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0}); std::vector<var_t> exp_mapping = {0, 1, 2}; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 3; exp_rlslp.root = 0; term_t exp_alphabet_size = 3; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); } TEST(fast_bcomp, no_block) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 1, 2, 1, 4, 1, 3, 2, 3, 1, 4, 1, 3, 4, 1, 3, 2, 3, 1, 4, 1, 3, 2, 1}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 5; std::vector<var_t> mapping; bv_t bv; rlslp.terminals = 5; recomp.replace_letters(text, alphabet_size, mapping); recomp.bcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 3, 0, 2, 1, 2, 0, 3, 0, 2, 3, 0, 2, 1, 2, 0, 3, 0, 2, 1, 0}); std::vector<var_t> exp_mapping = {1, 2, 3, 4}; term_t exp_alphabet_size = 4; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 3, 0, 2, 1, 2, 0, 3, 0, 2, 3, 0, 2, 1, 2, 0, 3, 0, 2, 1, 0}); std::vector<var_t> exp_mapping_alpha = {1, 2, 3, 4}; term_t exp_alphabet_size_alpha = 4; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; bv_t exp_bv; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_bcomp, 21214441332311413334133231141321) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 1, 2, 1, 4, 4, 4, 1, 3, 3, 2, 3, 1, 1, 4, 1, 3, 3, 3, 4, 1, 3, 3, 2, 3, 1, 1, 4, 1, 3, 2, 1}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 5; std::vector<var_t> mapping; bv_t bv; rlslp.terminals = 5; recomp.replace_letters(text, alphabet_size, mapping); recomp.bcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 7, 0, 5, 1, 2, 4, 3, 0, 6, 3, 0, 5, 1, 2, 4, 3, 0, 2, 1, 0}); std::vector<var_t> exp_mapping = {1, 2, 3, 4, 5, 6, 7, 8}; term_t exp_alphabet_size = 8; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 7, 0, 5, 1, 2, 4, 3, 0, 6, 3, 0, 5, 1, 2, 4, 3, 0, 2, 1, 0}); std::vector<var_t> exp_mapping_alpha = {1, 2, 3, 4, 5, 6, 7, 8}; term_t exp_alphabet_size_alpha = 8; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; exp_rlslp.resize(4); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; exp_rlslp.blocks = 4; bv_t exp_bv = {true, true, true, true}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_bcomp, 991261051171161051139) { text_t text = util::create_ui_vector(std::vector<var_t>{4, 4, 7, 2, 5, 1, 6, 3, 6, 2, 5, 1, 6, 0, 4}); std::vector<var_t> mapping{3, 5, 6, 7, 9, 10, 11, 12}; bv_t bv = {true, true, true, true, false, false, false, false}; rlslp<var_t> rlslp; rlslp.terminals = 5; rlslp.root = 0; rlslp.resize(8); rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; rlslp.blocks = 8; recompression_fast<var_t> recomp; term_t alphabet_size = 8; recomp.bcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{8, 7, 2, 5, 1, 6, 3, 6, 2, 5, 1, 6, 0, 4}); std::vector<var_t> exp_mapping{3, 5, 6, 7, 9, 10, 11, 12, 13}; term_t exp_alphabet_size = 9; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{8, 7, 2, 5, 1, 6, 3, 6, 2, 5, 1, 6, 0, 4}); std::vector<var_t> exp_mapping_alpha = {3, 5, 6, 7, 9, 10, 11, 12, 13}; term_t exp_alphabet_size_alpha = 9; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; exp_rlslp.resize(9); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; exp_rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; exp_rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; exp_rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; exp_rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; exp_rlslp.non_terminals[8] = non_terminal<var_t>{9, 2, 4}; exp_rlslp.blocks = 9; bv_t exp_bv = {true, true, true, true, false, false, false, false, true}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_bcomp, 222222222222222222222) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; std::vector<var_t> mapping; bv_t bv; rlslp.terminals = 3; recomp.replace_letters(text, alphabet_size, mapping); recomp.bcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{1}); std::vector<var_t> exp_mapping = {2, 3}; term_t exp_alphabet_size = 2; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{0}); std::vector<var_t> exp_mapping_alpha = {3}; term_t exp_alphabet_size_alpha = 1; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 3; exp_rlslp.root = 0; exp_rlslp.resize(1); exp_rlslp.non_terminals[0] = non_terminal<var_t>{2, 21, 21}; exp_rlslp.blocks = 1; bv_t exp_bv = {true}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_bcomp, 22222222211111112222) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; std::vector<var_t> mapping; bv_t bv; rlslp.terminals = 3; recomp.replace_letters(text, alphabet_size, mapping); recomp.bcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{4, 2, 3}); std::vector<var_t> exp_mapping = {1, 2, 3, 4, 5}; term_t exp_alphabet_size = 5; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{2, 0, 1}); std::vector<var_t> exp_mapping_alpha = {3, 4, 5}; term_t exp_alphabet_size_alpha = 3; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 3; exp_rlslp.root = 0; exp_rlslp.resize(3); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 7, 7}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{2, 4, 4}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{2, 9, 9}; exp_rlslp.blocks = 3; bv_t exp_bv = {true, true, true}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_bcomp, 2222222221111111222200) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; std::vector<var_t> mapping; bv_t bv; rlslp.terminals = 3; recomp.replace_letters(text, alphabet_size, mapping); recomp.bcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{6, 4, 5, 3}); std::vector<var_t> exp_mapping = {0, 1, 2, 3, 4, 5, 6}; term_t exp_alphabet_size = 7; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{3, 1, 2, 0}); std::vector<var_t> exp_mapping_alpha = {3, 4, 5, 6}; term_t exp_alphabet_size_alpha = 4; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 3; exp_rlslp.root = 0; exp_rlslp.resize(4); exp_rlslp.non_terminals[0] = non_terminal<var_t>{0, 2, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{1, 7, 7}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{2, 4, 4}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{2, 9, 9}; exp_rlslp.blocks = 4; bv_t exp_bv = {true, true, true, true}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_adj_list, 212181623541741623541321) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 7, 0, 5, 1, 2, 4, 3, 0, 6, 3, 0, 5, 1, 2, 4, 3, 0, 2, 1, 0}); term_t alphabet_size = 8; adj_list_t adj_list(alphabet_size); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); adj_list_t exp_adj_list(alphabet_size); exp_adj_list[1][0] = std::make_pair(3, 1); exp_adj_list[2][0] = std::make_pair(0, 1); exp_adj_list[2][1] = std::make_pair(1, 2); exp_adj_list[3][0] = std::make_pair(3, 0); exp_adj_list[4][2] = std::make_pair(0, 2); exp_adj_list[4][3] = std::make_pair(2, 0); exp_adj_list[5][0] = std::make_pair(0, 2); exp_adj_list[5][1] = std::make_pair(2, 0); exp_adj_list[6][0] = std::make_pair(0, 1); exp_adj_list[6][3] = std::make_pair(1, 0); exp_adj_list[7][0] = std::make_pair(1, 1); ASSERT_EQ(exp_adj_list, adj_list); ASSERT_EQ(exp_adj_list.size(), adj_list.size()); } TEST(fast_adj_list, 131261051171161051139) { text_t text = util::create_ui_vector(std::vector<var_t>{8, 7, 2, 5, 1, 6, 3, 6, 2, 5, 1, 6, 0, 4}); term_t alphabet_size = 9; adj_list_t adj_list(alphabet_size); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); adj_list_t exp_adj_list(alphabet_size); exp_adj_list[4][0] = std::make_pair(0, 1); exp_adj_list[5][1] = std::make_pair(2, 0); exp_adj_list[5][2] = std::make_pair(0, 2); exp_adj_list[6][0] = std::make_pair(1, 0); exp_adj_list[6][1] = std::make_pair(0, 2); exp_adj_list[6][2] = std::make_pair(1, 0); exp_adj_list[6][3] = std::make_pair(1, 1); exp_adj_list[7][2] = std::make_pair(1, 0); exp_adj_list[8][7] = std::make_pair(1, 0); ASSERT_EQ(exp_adj_list, adj_list); ASSERT_EQ(exp_adj_list.size(), adj_list.size()); } TEST(fast_adj_list, 18161517161514) { text_t text = util::create_ui_vector(std::vector<var_t>{4, 2, 1, 3, 2, 1, 0}); term_t alphabet_size = 5; adj_list_t adj_list(alphabet_size); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); adj_list_t exp_adj_list(alphabet_size); exp_adj_list[1][0] = std::make_pair(1, 0); exp_adj_list[2][1] = std::make_pair(2, 0); exp_adj_list[3][1] = std::make_pair(0, 1); exp_adj_list[3][2] = std::make_pair(1, 0); exp_adj_list[4][2] = std::make_pair(1, 0); ASSERT_EQ(exp_adj_list, adj_list); ASSERT_EQ(exp_adj_list.size(), adj_list.size()); } TEST(fast_adj_list, 21201619) { text_t text = util::create_ui_vector(std::vector<var_t>{3, 2, 0, 1}); term_t alphabet_size = 4; adj_list_t adj_list(alphabet_size); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); adj_list_t exp_adj_list(alphabet_size); exp_adj_list[1][0] = std::make_pair(0, 1); exp_adj_list[2][0] = std::make_pair(1, 0); exp_adj_list[3][2] = std::make_pair(1, 0); ASSERT_EQ(exp_adj_list, adj_list); ASSERT_EQ(exp_adj_list.size(), adj_list.size()); } TEST(fast_adj_list, 2322) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0}); term_t alphabet_size = 2; adj_list_t adj_list(alphabet_size); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); adj_list_t exp_adj_list(alphabet_size); exp_adj_list[1][0] = std::make_pair(1, 0); ASSERT_EQ(exp_adj_list, adj_list); ASSERT_EQ(exp_adj_list.size(), adj_list.size()); } TEST(fast_compute_partition, repreated_pair) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0}); term_t alphabet_size = 2; adj_list_t adj_list(alphabet_size); partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); recomp.compute_partition(adj_list, partition); partition_t exp_partition(alphabet_size, false); exp_partition[1] = true; ASSERT_EQ(exp_partition, partition); } TEST(fast_compute_partition, repreated_pair_same_occ) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}); term_t alphabet_size = 2; adj_list_t adj_list(alphabet_size); partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); recomp.compute_partition(adj_list, partition); partition_t exp_partition(alphabet_size, false); exp_partition[1] = true; ASSERT_EQ(exp_partition, partition); } TEST(fast_compute_partition, 212181623541741623541321) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 7, 0, 5, 1, 2, 4, 3, 0, 6, 3, 0, 5, 1, 2, 4, 3, 0, 2, 1, 0}); term_t alphabet_size = 8; adj_list_t adj_list(alphabet_size); partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); recomp.compute_partition(adj_list, partition); partition_t exp_partition(alphabet_size, false); exp_partition[1] = true; exp_partition[3] = true; exp_partition[7] = true; ASSERT_EQ(exp_partition, partition); } TEST(fast_compute_partition, 131261051171161051139) { text_t text = util::create_ui_vector(std::vector<var_t>{8, 7, 2, 5, 1, 6, 3, 6, 2, 5, 1, 6, 0, 4}); term_t alphabet_size = 9; adj_list_t adj_list(alphabet_size); partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); recomp.compute_partition(adj_list, partition); partition_t exp_partition(alphabet_size, false); exp_partition[4] = true; exp_partition[5] = true; exp_partition[6] = true; exp_partition[7] = true; ASSERT_EQ(exp_partition, partition); } TEST(fast_compute_partition, 18161517161514) { text_t text = util::create_ui_vector(std::vector<var_t>{4, 2, 1, 3, 2, 1, 0}); term_t alphabet_size = 5; adj_list_t adj_list(alphabet_size); partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); recomp.compute_partition(adj_list, partition); partition_t exp_partition(alphabet_size, false); exp_partition[1] = true; exp_partition[4] = true; ASSERT_EQ(exp_partition, partition); } TEST(fast_compute_partition, 21201619) { text_t text = util::create_ui_vector(std::vector<var_t>{3, 2, 0, 1}); term_t alphabet_size = 4; adj_list_t adj_list(alphabet_size); partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); recomp.compute_partition(adj_list, partition); partition_t exp_partition(alphabet_size, false); exp_partition[1] = true; exp_partition[2] = true; ASSERT_EQ(exp_partition, partition); } TEST(fast_compute_partition, 2322) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0}); term_t alphabet_size = 2; adj_list_t adj_list(alphabet_size); partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.compute_adj_list(text, adj_list); recomp.compute_partition(adj_list, partition); partition_t exp_partition(alphabet_size, false); exp_partition[1] = true; ASSERT_EQ(exp_partition, partition); } TEST(fast_partition, repreated_pair) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0}); term_t alphabet_size = 2; partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.partition(text, alphabet_size, partition); partition_t exp_partition(alphabet_size, false); exp_partition[0] = true; ASSERT_EQ(exp_partition, partition); } TEST(fast_partition, repreated_pair_same_occ) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}); term_t alphabet_size = 2; partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.partition(text, alphabet_size, partition); partition_t exp_partition(alphabet_size, false); exp_partition[1] = true; ASSERT_EQ(exp_partition, partition); } TEST(fast_partition, 212181623541741623541321) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 7, 0, 5, 1, 2, 4, 3, 0, 6, 3, 0, 5, 1, 2, 4, 3, 0, 2, 1, 0}); term_t alphabet_size = 8; partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.partition(text, alphabet_size, partition); partition_t exp_partition(alphabet_size, false); exp_partition[0] = true; exp_partition[1] = false; exp_partition[2] = true; exp_partition[3] = false; exp_partition[4] = true; exp_partition[5] = true; exp_partition[6] = true; exp_partition[7] = false; ASSERT_EQ(exp_partition, partition); } TEST(fast_partition, 131261051171161051139) { text_t text = util::create_ui_vector(std::vector<var_t>{8, 7, 2, 5, 1, 6, 3, 6, 2, 5, 1, 6, 0, 4}); term_t alphabet_size = 9; partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.partition(text, alphabet_size, partition); partition_t exp_partition(alphabet_size, false); exp_partition[0] = false; exp_partition[1] = false; exp_partition[2] = false; exp_partition[3] = false; exp_partition[4] = true; exp_partition[5] = true; exp_partition[6] = true; exp_partition[7] = true; exp_partition[8] = false; ASSERT_EQ(exp_partition, partition); } TEST(fast_partition, 18161517161514) { text_t text = util::create_ui_vector(std::vector<var_t>{4, 2, 1, 3, 2, 1, 0}); term_t alphabet_size = 5; partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.partition(text, alphabet_size, partition); partition_t exp_partition(alphabet_size, false); exp_partition[0] = true; exp_partition[1] = false; exp_partition[2] = true; exp_partition[3] = true; exp_partition[4] = false; ASSERT_EQ(exp_partition, partition); } TEST(fast_partition, 21201619) { text_t text = util::create_ui_vector(std::vector<var_t>{3, 2, 0, 1}); term_t alphabet_size = 4; partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.partition(text, alphabet_size, partition); partition_t exp_partition(alphabet_size, false); exp_partition[0] = false; exp_partition[1] = true; exp_partition[2] = true; exp_partition[3] = false; ASSERT_EQ(exp_partition, partition); } TEST(fast_partition, 2322) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0}); term_t alphabet_size = 2; partition_t partition(alphabet_size, false); recompression_fast<var_t> recomp; recomp.partition(text, alphabet_size, partition); partition_t exp_partition(alphabet_size, false); exp_partition[0] = true; exp_partition[1] = false; ASSERT_EQ(exp_partition, partition); } TEST(fast_pcomp, repeated_pair) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0}); std::vector<var_t> mapping = {1, 2}; term_t alphabet_size = 2; rlslp<var_t> rlslp; recompression_fast<var_t> recomp; rlslp.terminals = 3; bv_t bv; recomp.pcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}); std::vector<var_t> exp_mapping = {1, 2, 3}; term_t exp_alphabet_size = 3; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); std::vector<var_t> exp_mapping_alpha = {3}; term_t exp_alphabet_size_alpha = 1; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 3; exp_rlslp.root = 0; exp_rlslp.resize(1); exp_rlslp.non_terminals[0] = non_terminal<var_t>{2, 1, 2}; exp_rlslp.blocks = 0; bv_t exp_bv = {false}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_pcomp, repeated_pair_same_occ) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}); std::vector<var_t> mapping = {1, 2}; term_t alphabet_size = 2; rlslp<var_t> rlslp; recompression_fast<var_t> recomp; rlslp.terminals = 3; bv_t bv; recomp.pcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}); std::vector<var_t> exp_mapping = {1, 2, 3}; term_t exp_alphabet_size = 3; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}); std::vector<var_t> exp_mapping_alpha = {2, 3}; term_t exp_alphabet_size_alpha = 2; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 3; exp_rlslp.root = 0; exp_rlslp.resize(1); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.blocks = 0; bv_t exp_bv = {false}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_pcomp, 212181623541741623541321) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0, 1, 0, 7, 0, 5, 1, 2, 4, 3, 0, 6, 3, 0, 5, 1, 2, 4, 3, 0, 2, 1, 0}); std::vector<var_t> mapping = {1, 2, 3, 4, 5, 6, 7, 8}; term_t alphabet_size = 8; rlslp<var_t> rlslp; recompression_fast<var_t> recomp; rlslp.terminals = 5; rlslp.resize(4); rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; rlslp.blocks = 4; bv_t bv = {true, true, true, true}; recomp.pcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{8, 8, 11, 5, 9, 4, 10, 6, 10, 5, 9, 4, 10, 2, 8}); std::vector<var_t> exp_mapping = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; term_t exp_alphabet_size = 12; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{4, 4, 7, 2, 5, 1, 6, 3, 6, 2, 5, 1, 6, 0, 4}); std::vector<var_t> exp_mapping_alpha = {3, 5, 6, 7, 9, 10, 11, 12}; term_t exp_alphabet_size_alpha = 8; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; exp_rlslp.resize(8); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; exp_rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; exp_rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; exp_rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; exp_rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; exp_rlslp.blocks = 4; bv_t exp_bv = {true, true, true, true, false, false, false, false}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_pcomp, 131261051171161051139) { text_t text = util::create_ui_vector(std::vector<var_t>{8, 7, 2, 5, 1, 6, 3, 6, 2, 5, 1, 6, 0, 4}); std::vector<var_t> mapping = {3, 5, 6, 7, 9, 10, 11, 12, 13}; term_t alphabet_size = 9; rlslp<var_t> rlslp; recompression_fast<var_t> recomp; rlslp.terminals = 5; rlslp.resize(9); rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; rlslp.non_terminals[8] = non_terminal<var_t>{9, 2, 4}; rlslp.blocks = 5; bv_t bv = {true, true, true, true, false, false, false, false, true}; recomp.pcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{13, 11, 10, 12, 11, 10, 9}); std::vector<var_t> exp_mapping = {3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}; term_t exp_alphabet_size = 14; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{4, 2, 1, 3, 2, 1, 0}); std::vector<var_t> exp_mapping_alpha = {14, 15, 16, 17, 18}; term_t exp_alphabet_size_alpha = 5; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; exp_rlslp.resize(14); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; exp_rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; exp_rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; exp_rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; exp_rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; exp_rlslp.non_terminals[8] = non_terminal<var_t>{9, 2, 4}; exp_rlslp.non_terminals[9] = non_terminal<var_t>{3, 9, 3}; exp_rlslp.non_terminals[10] = non_terminal<var_t>{5, 11, 4}; exp_rlslp.non_terminals[11] = non_terminal<var_t>{6, 10, 4}; exp_rlslp.non_terminals[12] = non_terminal<var_t>{7, 11, 5}; exp_rlslp.non_terminals[13] = non_terminal<var_t>{13, 12, 8}; exp_rlslp.blocks = 5; bv_t exp_bv = {true, true, true, true, false, false, false, false, true, false, false, false, false, false}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_pcomp, 18161517161514) { text_t text = util::create_ui_vector(std::vector<var_t>{4, 2, 1, 3, 2, 1, 0}); std::vector<var_t> mapping = {14, 15, 16, 17, 18}; term_t alphabet_size = 5; rlslp<var_t> rlslp; recompression_fast<var_t> recomp; rlslp.terminals = 5; rlslp.resize(14); rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; rlslp.non_terminals[8] = non_terminal<var_t>{9, 2, 4}; rlslp.non_terminals[9] = non_terminal<var_t>{3, 9, 3}; rlslp.non_terminals[10] = non_terminal<var_t>{5, 11, 4}; rlslp.non_terminals[11] = non_terminal<var_t>{6, 10, 4}; rlslp.non_terminals[12] = non_terminal<var_t>{7, 11, 5}; rlslp.non_terminals[13] = non_terminal<var_t>{13, 12, 8}; rlslp.blocks = 5; bv_t bv = {true, true, true, true, false, false, false, false, true, false, false, false, false, false}; recomp.pcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{7, 6, 2, 5}); std::vector<var_t> exp_mapping = {14, 15, 16, 17, 18, 19, 20, 21}; term_t exp_alphabet_size = 8; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{3, 2, 0, 1}); std::vector<var_t> exp_mapping_alpha = {16, 19, 20, 21}; term_t exp_alphabet_size_alpha = 4; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; exp_rlslp.resize(17); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; exp_rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; exp_rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; exp_rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; exp_rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; exp_rlslp.non_terminals[8] = non_terminal<var_t>{9, 2, 4}; exp_rlslp.non_terminals[9] = non_terminal<var_t>{3, 9, 3}; exp_rlslp.non_terminals[10] = non_terminal<var_t>{5, 11, 4}; exp_rlslp.non_terminals[11] = non_terminal<var_t>{6, 10, 4}; exp_rlslp.non_terminals[12] = non_terminal<var_t>{7, 11, 5}; exp_rlslp.non_terminals[13] = non_terminal<var_t>{13, 12, 8}; exp_rlslp.non_terminals[14] = non_terminal<var_t>{15, 14, 7}; exp_rlslp.non_terminals[15] = non_terminal<var_t>{15, 17, 9}; exp_rlslp.non_terminals[16] = non_terminal<var_t>{18, 16, 12}; exp_rlslp.blocks = 5; bv_t exp_bv = {true, true, true, true, false, false, false, false, true, false, false, false, false, false, false, false, false}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_pcomp, 21201619) { text_t text = util::create_ui_vector(std::vector<var_t>{3, 2, 0, 1}); std::vector<var_t> mapping = {16, 19, 20, 21}; term_t alphabet_size = 4; rlslp<var_t> rlslp; recompression_fast<var_t> recomp; rlslp.terminals = 5; rlslp.resize(17); rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; rlslp.non_terminals[8] = non_terminal<var_t>{9, 2, 4}; rlslp.non_terminals[9] = non_terminal<var_t>{3, 9, 3}; rlslp.non_terminals[10] = non_terminal<var_t>{5, 11, 4}; rlslp.non_terminals[11] = non_terminal<var_t>{6, 10, 4}; rlslp.non_terminals[12] = non_terminal<var_t>{7, 11, 5}; rlslp.non_terminals[13] = non_terminal<var_t>{13, 12, 8}; rlslp.non_terminals[14] = non_terminal<var_t>{15, 14, 7}; rlslp.non_terminals[15] = non_terminal<var_t>{15, 17, 9}; rlslp.non_terminals[16] = non_terminal<var_t>{18, 16, 12}; rlslp.blocks = 5; bv_t bv = {true, true, true, true, false, false, false, false, true, false, false, false, false, false, false, false, false}; recomp.pcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{5, 4}); std::vector<var_t> exp_mapping = {16, 19, 20, 21, 22, 23}; term_t exp_alphabet_size = 6; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{1, 0}); std::vector<var_t> exp_mapping_alpha = {22, 23}; term_t exp_alphabet_size_alpha = 2; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; exp_rlslp.resize(19); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; exp_rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; exp_rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; exp_rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; exp_rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; exp_rlslp.non_terminals[8] = non_terminal<var_t>{9, 2, 4}; exp_rlslp.non_terminals[9] = non_terminal<var_t>{3, 9, 3}; exp_rlslp.non_terminals[10] = non_terminal<var_t>{5, 11, 4}; exp_rlslp.non_terminals[11] = non_terminal<var_t>{6, 10, 4}; exp_rlslp.non_terminals[12] = non_terminal<var_t>{7, 11, 5}; exp_rlslp.non_terminals[13] = non_terminal<var_t>{13, 12, 8}; exp_rlslp.non_terminals[14] = non_terminal<var_t>{15, 14, 7}; exp_rlslp.non_terminals[15] = non_terminal<var_t>{15, 17, 9}; exp_rlslp.non_terminals[16] = non_terminal<var_t>{18, 16, 12}; exp_rlslp.non_terminals[17] = non_terminal<var_t>{16, 19, 11}; exp_rlslp.non_terminals[18] = non_terminal<var_t>{21, 20, 21}; exp_rlslp.blocks = 5; bv_t exp_bv = {true, true, true, true, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_pcomp, 2322) { text_t text = util::create_ui_vector(std::vector<var_t>{1, 0}); std::vector<var_t> mapping = {22, 23}; term_t alphabet_size = 2; rlslp<var_t> rlslp; recompression_fast<var_t> recomp; rlslp.terminals = 5; rlslp.resize(19); rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; rlslp.non_terminals[8] = non_terminal<var_t>{9, 2, 4}; rlslp.non_terminals[9] = non_terminal<var_t>{3, 9, 3}; rlslp.non_terminals[10] = non_terminal<var_t>{5, 11, 4}; rlslp.non_terminals[11] = non_terminal<var_t>{6, 10, 4}; rlslp.non_terminals[12] = non_terminal<var_t>{7, 11, 5}; rlslp.non_terminals[13] = non_terminal<var_t>{13, 12, 8}; rlslp.non_terminals[14] = non_terminal<var_t>{15, 14, 7}; rlslp.non_terminals[15] = non_terminal<var_t>{15, 17, 9}; rlslp.non_terminals[16] = non_terminal<var_t>{18, 16, 12}; rlslp.non_terminals[17] = non_terminal<var_t>{16, 19, 11}; rlslp.non_terminals[18] = non_terminal<var_t>{21, 20, 21}; rlslp.blocks = 5; bv_t bv = {true, true, true, true, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false}; recomp.pcomp(text, rlslp, bv, alphabet_size, mapping); text_t exp_text = util::create_ui_vector(std::vector<var_t>{2}); std::vector<var_t> exp_mapping = {22, 23, 24}; term_t exp_alphabet_size = 3; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_alphabet_size, alphabet_size); ASSERT_EQ(exp_mapping, mapping); recomp.compute_alphabet(text, alphabet_size, mapping); text_t exp_text_alpha = util::create_ui_vector(std::vector<var_t>{0}); std::vector<var_t> exp_mapping_alpha = {24}; term_t exp_alphabet_size_alpha = 1; recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 0; exp_rlslp.resize(20); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{3, 2, 2}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{3, 3, 3}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{4, 3, 3}; exp_rlslp.non_terminals[4] = non_terminal<var_t>{2, 1, 2}; exp_rlslp.non_terminals[5] = non_terminal<var_t>{2, 3, 2}; exp_rlslp.non_terminals[6] = non_terminal<var_t>{4, 1, 2}; exp_rlslp.non_terminals[7] = non_terminal<var_t>{8, 1, 4}; exp_rlslp.non_terminals[8] = non_terminal<var_t>{9, 2, 4}; exp_rlslp.non_terminals[9] = non_terminal<var_t>{3, 9, 3}; exp_rlslp.non_terminals[10] = non_terminal<var_t>{5, 11, 4}; exp_rlslp.non_terminals[11] = non_terminal<var_t>{6, 10, 4}; exp_rlslp.non_terminals[12] = non_terminal<var_t>{7, 11, 5}; exp_rlslp.non_terminals[13] = non_terminal<var_t>{13, 12, 8}; exp_rlslp.non_terminals[14] = non_terminal<var_t>{15, 14, 7}; exp_rlslp.non_terminals[15] = non_terminal<var_t>{15, 17, 9}; exp_rlslp.non_terminals[16] = non_terminal<var_t>{18, 16, 12}; exp_rlslp.non_terminals[17] = non_terminal<var_t>{16, 19, 11}; exp_rlslp.non_terminals[18] = non_terminal<var_t>{21, 20, 21}; exp_rlslp.non_terminals[19] = non_terminal<var_t>{23, 22, 32}; exp_rlslp.blocks = 5; bv_t exp_bv = {true, true, true, true, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false}; ASSERT_EQ(exp_text_alpha, text); ASSERT_EQ(exp_rlslp, rlslp); ASSERT_EQ(exp_alphabet_size_alpha, alphabet_size); ASSERT_EQ(exp_mapping_alpha, mapping); ASSERT_EQ(exp_bv, bv); } TEST(fast_recomp, empty) { text_t text = util::create_ui_vector(std::vector<var_t>{}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 0; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 0; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, terminal) { text_t text = util::create_ui_vector(std::vector<var_t>{112}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 113; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 112; exp_rlslp.is_empty = false; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, short_block2) { text_t text = util::create_ui_vector(std::vector<var_t>{112, 112}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 113; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 113; exp_rlslp.resize(1); exp_rlslp.non_terminals[0] = non_terminal<var_t>{112, 2, 2}; exp_rlslp.is_empty = false; exp_rlslp.blocks = 0; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, short_block3) { text_t text = util::create_ui_vector(std::vector<var_t>{112, 112, 112}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 113; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 113; exp_rlslp.resize(1); exp_rlslp.non_terminals[0] = non_terminal<var_t>{112, 3, 3}; exp_rlslp.is_empty = false; exp_rlslp.blocks = 0; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, recompression) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 1, 2, 1, 4, 4, 4, 1, 3, 3, 2, 3, 1, 1, 4, 1, 3, 3, 3, 4, 1, 3, 3, 2, 3, 1, 1, 4, 1, 3, 2, 1}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 5; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = 5; exp_rlslp.root = 19; exp_rlslp.resize(20); exp_rlslp.non_terminals[0] = non_terminal<var_t>{2, 1, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{2, 3, 2}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{4, 1, 2}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{23, 1, 4}; exp_rlslp.non_terminals[4] = non_terminal<var_t>{3, 5, 3}; exp_rlslp.non_terminals[5] = non_terminal<var_t>{20, 7, 4}; exp_rlslp.non_terminals[6] = non_terminal<var_t>{21, 6, 4}; exp_rlslp.non_terminals[7] = non_terminal<var_t>{22, 7, 5}; exp_rlslp.non_terminals[8] = non_terminal<var_t>{24, 8, 8}; exp_rlslp.non_terminals[9] = non_terminal<var_t>{10, 9, 7}; exp_rlslp.non_terminals[10] = non_terminal<var_t>{10, 12, 9}; exp_rlslp.non_terminals[11] = non_terminal<var_t>{13, 11, 12}; exp_rlslp.non_terminals[12] = non_terminal<var_t>{11, 14, 11}; exp_rlslp.non_terminals[13] = non_terminal<var_t>{16, 15, 21}; exp_rlslp.non_terminals[14] = non_terminal<var_t>{18, 17, 32}; exp_rlslp.non_terminals[15] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.non_terminals[16] = non_terminal<var_t>{3, 2, 2}; exp_rlslp.non_terminals[17] = non_terminal<var_t>{3, 3, 3}; exp_rlslp.non_terminals[18] = non_terminal<var_t>{4, 3, 3}; exp_rlslp.non_terminals[19] = non_terminal<var_t>{5, 2, 4}; exp_rlslp.blocks = 15; exp_rlslp.is_empty = false; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, one_block) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 3; exp_rlslp.resize(1); exp_rlslp.non_terminals[0] = non_terminal<var_t>{2, 21, 21}; exp_rlslp.blocks = 0; exp_rlslp.is_empty = false; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, two_blocks) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 3; exp_rlslp.resize(3); exp_rlslp.non_terminals[0] = non_terminal<var_t>{5, 4, 16}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{1, 7, 7}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{2, 9, 9}; exp_rlslp.blocks = 1; exp_rlslp.is_empty = false; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, three_blocks) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 4; exp_rlslp.resize(5); exp_rlslp.non_terminals[0] = non_terminal<var_t>{5, 6, 11}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{7, 3, 20}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{1, 7, 7}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{2, 4, 4}; exp_rlslp.non_terminals[4] = non_terminal<var_t>{2, 9, 9}; exp_rlslp.blocks = 2; exp_rlslp.is_empty = false; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, four_blocks) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 5; exp_rlslp.resize(7); exp_rlslp.non_terminals[0] = non_terminal<var_t>{8, 6, 6}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{9, 7, 16}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{4, 3, 22}; exp_rlslp.non_terminals[3] = non_terminal<var_t>{0, 2, 2}; exp_rlslp.non_terminals[4] = non_terminal<var_t>{1, 7, 7}; exp_rlslp.non_terminals[5] = non_terminal<var_t>{2, 4, 4}; exp_rlslp.non_terminals[6] = non_terminal<var_t>{2, 9, 9}; exp_rlslp.blocks = 3; exp_rlslp.is_empty = false; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, repeated_pair) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 4; exp_rlslp.resize(2); exp_rlslp.non_terminals[0] = non_terminal<var_t>{2, 1, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{3, 11, 22}; exp_rlslp.blocks = 1; exp_rlslp.is_empty = false; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); } TEST(fast_recomp, repeated_pair_same_occ) { text_t text = util::create_ui_vector(std::vector<var_t>{2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2}); rlslp<var_t> rlslp; recompression_fast<var_t> recomp; term_t alphabet_size = 3; recomp.recomp(text, rlslp, alphabet_size, 4); text_t exp_text = util::create_ui_vector(std::vector<var_t>{0}); recomp::rlslp<var_t> exp_rlslp; exp_rlslp.terminals = alphabet_size; exp_rlslp.root = 4; exp_rlslp.resize(3); exp_rlslp.non_terminals[0] = non_terminal<var_t>{1, 2, 2}; exp_rlslp.non_terminals[1] = non_terminal<var_t>{2, 5, 23}; exp_rlslp.non_terminals[2] = non_terminal<var_t>{3, 11, 22}; exp_rlslp.blocks = 2; exp_rlslp.is_empty = false; ASSERT_EQ(exp_text, text); ASSERT_EQ(exp_rlslp, rlslp); }
39.212271
161
0.670881
christopherosthues
893f4502ca312cfb3040a32bcf9002d7eba00e3d
1,138
cpp
C++
Classes/SoundGame.cpp
PhamDinhTri/Bomberman
66d73167c42a05efb5829f4db244d1ffad0bb083
[ "MIT" ]
null
null
null
Classes/SoundGame.cpp
PhamDinhTri/Bomberman
66d73167c42a05efb5829f4db244d1ffad0bb083
[ "MIT" ]
null
null
null
Classes/SoundGame.cpp
PhamDinhTri/Bomberman
66d73167c42a05efb5829f4db244d1ffad0bb083
[ "MIT" ]
1
2021-10-20T14:22:57.000Z
2021-10-20T14:22:57.000Z
#include "SoundGame.h" #include "cocos2d.h" #include "SimpleAudioEngine.h" #include "common.h" USING_NS_CC; using namespace CocosDenshion; static SoundGame *instance = nullptr; void SoundGame::playMusic(const char* file, bool loop) { if(UserDefault::getInstance()->getBoolForKey(KEY_SOUND, true)) { SimpleAudioEngine::getInstance()->playBackgroundMusic(file, loop); } } void SoundGame::stopMusic() { SimpleAudioEngine::getInstance()->stopBackgroundMusic(); } unsigned int SoundGame::playEffect(const char* file, bool loop) { if(UserDefault::getInstance()->getBoolForKey(KEY_SOUND, true)) { return SimpleAudioEngine::getInstance()->playEffect(file, loop); } else { return -1; } } void SoundGame::stopAllEffects() { SimpleAudioEngine::getInstance()->stopAllEffects(); } void SoundGame::stopEffect(unsigned int id ) { SimpleAudioEngine::getInstance()->stopEffect(id); } void SoundGame::resumMusic() { SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); } SoundGame* SoundGame::getInstance() { if (!instance) { instance = new SoundGame(); } return instance; }
23.708333
69
0.711775
PhamDinhTri
893fc2e7ff00c844850ca791c612a17bc34dec27
4,528
hxx
C++
Modules/Components/itkImageRegistrationMethodv4/include/selxItkANTSNeighborhoodCorrelationImageToImageMetricv4Component.hxx
FBerendsen/SuperElastix-1
69d97589e34f6f2109621e917792ce18e32442fe
[ "Apache-2.0" ]
null
null
null
Modules/Components/itkImageRegistrationMethodv4/include/selxItkANTSNeighborhoodCorrelationImageToImageMetricv4Component.hxx
FBerendsen/SuperElastix-1
69d97589e34f6f2109621e917792ce18e32442fe
[ "Apache-2.0" ]
null
null
null
Modules/Components/itkImageRegistrationMethodv4/include/selxItkANTSNeighborhoodCorrelationImageToImageMetricv4Component.hxx
FBerendsen/SuperElastix-1
69d97589e34f6f2109621e917792ce18e32442fe
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright Leiden University Medical Center, Erasmus University Medical * Center and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "selxItkANTSNeighborhoodCorrelationImageToImageMetricv4Component.h" #include "selxCheckTemplateProperties.h" #include "itkImageMaskSpatialObject.h" namespace selx { template< int Dimensionality, class TPixel > ItkANTSNeighborhoodCorrelationImageToImageMetricv4Component< Dimensionality, TPixel >::ItkANTSNeighborhoodCorrelationImageToImageMetricv4Component( const std::string & name, LoggerImpl & logger ) : Superclass( name, logger ) { m_theItkFilter = TheItkFilterType::New(); //TODO: instantiating the filter in the constructor might be heavy for the use in component selector factory, since all components of the database are created during the selection process. // we could choose to keep the component light weighted (for checking criteria such as names and connections) until the settings are passed to the filter, but this requires an additional initialization step. } template< int Dimensionality, class TPixel > ItkANTSNeighborhoodCorrelationImageToImageMetricv4Component< Dimensionality, TPixel >::~ItkANTSNeighborhoodCorrelationImageToImageMetricv4Component() { } template< int Dimensionality, class TPixel > int ItkANTSNeighborhoodCorrelationImageToImageMetricv4Component< Dimensionality, TPixel >::Accept(typename itkImageFixedMaskInterface< Dimensionality, unsigned char >::Pointer component) { auto fixedMaskImage = component->GetItkImageFixedMask(); // connect the itk pipeline auto fixedMaskSpatialObject = itk::ImageMaskSpatialObject< Dimensionality >::New(); fixedMaskSpatialObject->SetImage( fixedMaskImage ); this->m_theItkFilter->SetFixedImageMask(fixedMaskSpatialObject); return 0; } template< int Dimensionality, class TPixel > int ItkANTSNeighborhoodCorrelationImageToImageMetricv4Component< Dimensionality, TPixel >::Accept(typename itkImageMovingMaskInterface< Dimensionality, unsigned char >::Pointer component) { auto movingMaskImage = component->GetItkImageMovingMask(); // connect the itk pipeline auto movingMaskSpatialObject = itk::ImageMaskSpatialObject< Dimensionality >::New(); movingMaskSpatialObject->SetImage(movingMaskImage); this->m_theItkFilter->SetMovingImageMask(movingMaskSpatialObject); return 0; } template< int Dimensionality, class TPixel > typename ItkANTSNeighborhoodCorrelationImageToImageMetricv4Component< Dimensionality, TPixel >::ItkMetricv4Pointer ItkANTSNeighborhoodCorrelationImageToImageMetricv4Component< Dimensionality, TPixel >::GetItkMetricv4() { return (ItkMetricv4Pointer)this->m_theItkFilter; } template< int Dimensionality, class TPixel > bool ItkANTSNeighborhoodCorrelationImageToImageMetricv4Component< Dimensionality, TPixel > ::MeetsCriterion( const ComponentBase::CriterionType & criterion ) { auto status = CheckTemplateProperties( this->TemplateProperties(), criterion ); if( status == CriterionStatus::Satisfied ) { return true; } else if( status == CriterionStatus::Failed ) { return false; } // else: CriterionStatus::Unknown else if( criterion.first == "Radius" ) //Supports this? { if( criterion.second.size() != 1 ) { return false; //itkExceptionMacro("The criterion Sigma may have only 1 value"); } else { auto const & criterionValue = *criterion.second.begin(); try { //TODO radius should be a vector in criteria typename TheItkFilterType::RadiusType radius; radius.Fill( std::stod( criterionValue ) ); this->m_theItkFilter->SetRadius( radius ); return true; } catch( itk::ExceptionObject & err ) { //TODO log the error message? return false; } } } return false; } } //end namespace selx
38.372881
209
0.737853
FBerendsen
8940b7ebeb3610dccec898952aa471c6575ba9f0
179
cpp
C++
third-party/Empirical/tests/datastructs/StringMap.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/tests/datastructs/StringMap.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/tests/datastructs/StringMap.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "third-party/Catch/single_include/catch2/catch.hpp" #include "emp/datastructs/StringMap.hpp" TEST_CASE("Test StringMap", "[datastructs]") { }
19.888889
60
0.776536
koellingh
894409e84fde8d291b0395da0ff264c66c36d45f
1,242
hpp
C++
Libraries/Engine/ArchetypeRebuilder.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Engine/ArchetypeRebuilder.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Engine/ArchetypeRebuilder.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once #include "DataSource.hpp" namespace Zero { // Forward Declarations. class MetaSelection; class CogRestoreState; // Cog Replace Event namespace Events { // Sent on the space when an Archetype object is rebuilt DeclareEvent(CogReplaced); } // namespace Events /// Sent on the Space when an object is rebuilt. class CogReplaceEvent : public DataReplaceEvent { public: ZilchDeclareType(CogReplaceEvent, TypeCopyMode::ReferenceType); CogReplaceEvent(Cog* oldCog, Cog* newCog); Cog* mOldCog; Cog* mNewCog; }; // Archetype Rebuilder /// To rebuild an Archetype, we serialize the object to a string, create a new /// object from that string, then destroy the old object. /// The new object is then updated in all Selections and is updated in the /// operation map. class ArchetypeRebuilder { public: // Rebuild all archetypes in all GameSessions. static void RebuildArchetypes(Archetype* modifiedArchetype, Cog* ignore = nullptr, Array<CogRestoreState*>* restoreStates = nullptr); static Cog* RebuildCog(Cog* cog); static Cog* RebuildCog(Cog* cog, HashSet<MetaSelection*>* modifiedSelections); }; } // namespace Zero
27
82
0.718196
RyanTylerRae
894f53a62887855cf495edabd45687a05cd3200e
1,327
hpp
C++
AlertQueue.hpp
vikchopde/AlertDispatcher
f9ed546511ea193a8db31feac774d441cf5b0140
[ "MIT" ]
null
null
null
AlertQueue.hpp
vikchopde/AlertDispatcher
f9ed546511ea193a8db31feac774d441cf5b0140
[ "MIT" ]
null
null
null
AlertQueue.hpp
vikchopde/AlertDispatcher
f9ed546511ea193a8db31feac774d441cf5b0140
[ "MIT" ]
null
null
null
#ifndef ZEROTOHERO_ALERTQUEUE_HPP #define ZEROTOHERO_ALERTQUEUE_HPP #include <queue> #include <mutex> #include <condition_variable> #include <memory> template<typename T> class threadsafe_queue { private: mutable std::mutex mut; std::queue<T> data_queue; std::condition_variable data_cond; public: threadsafe_queue() {} void push(T new_value) { std::lock_guard<std::mutex> lk(mut); data_queue.push(std::move(new_value)); data_cond.notify_one(); } void wait_and_pop(T& value) { std::unique_lock<std::mutex> lk(mut); data_cond.wait(lk,[this]{return !data_queue.empty();}); value=std::move(data_queue.front()); data_queue.pop(); } T wait_and_pop() { std::unique_lock<std::mutex> lk(mut); data_cond.wait(lk,[this]{return !data_queue.empty();}); T res(data_queue.front()); data_queue.pop(); return res; } bool try_pop(T& value) { std::lock_guard<std::mutex> lk(mut); if(data_queue.empty()) return false; value=std::move(data_queue.front()); data_queue.pop(); } bool empty() const { std::lock_guard<std::mutex> lk(mut); return data_queue.empty(); } }; #endif //ZEROTOHERO_ALERTQUEUE_HPP
21.063492
63
0.605124
vikchopde
895430d327ef886f7ff487f654e3fa6c305fbeba
4,979
cpp
C++
soundlib/UMXTools.cpp
extrowerk/openmpt
99cb32168f6500dfbb238f305fef6b5e58fbac1d
[ "BSD-3-Clause" ]
6
2017-04-19T19:06:03.000Z
2022-01-11T14:44:14.000Z
soundlib/UMXTools.cpp
glowcoil/microplug
5c2708b89837dbc38a1f0e7cd793e5e53838e4a4
[ "BSD-3-Clause" ]
4
2018-04-04T20:27:32.000Z
2020-04-25T10:46:21.000Z
soundlib/UMXTools.cpp
glowcoil/microplug
5c2708b89837dbc38a1f0e7cd793e5e53838e4a4
[ "BSD-3-Clause" ]
2
2018-06-08T15:20:48.000Z
2020-08-19T14:24:21.000Z
/* * UMXTools.h * ------------ * Purpose: UMX/UAX (Unreal) helper functions * Notes : None. * Authors: Johannes Schultz (inspired by code from http://wiki.beyondunreal.com/Legacy:Package_File_Format) * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "Loaders.h" #include "UMXTools.h" OPENMPT_NAMESPACE_BEGIN bool UMXFileHeader::IsValid() const { return !std::memcmp(magic, "\xC1\x83\x2A\x9E", 4) && nameCount != 0 && exportCount != 0 && importCount != 0; } // Read compressed unreal integers - similar to MIDI integers, but signed values are possible. template <typename Tfile> static int32 ReadUMXIndexImpl(Tfile &chunk) { enum { signMask = 0x80, // Highest bit of first byte indicates if value is signed valueMask1 = 0x3F, // Low 6 bits of first byte are actual value continueMask1 = 0x40, // Second-highest bit of first byte indicates if further bytes follow valueMask = 0x7F, // Low 7 bits of following bytes are actual value continueMask = 0x80, // Highest bit of following bytes indicates if further bytes follow }; // Read first byte uint8 b = chunk.ReadUint8(); bool isSigned = (b & signMask) != 0; int32 result = (b & valueMask1); int shift = 6; if(b & continueMask1) { // Read remaining bytes do { b = chunk.ReadUint8(); int32 data = static_cast<int32>(b) & valueMask; data <<= shift; result |= data; shift += 7; } while((b & continueMask) != 0 && (shift < 32)); } if(isSigned) { result = -result; } return result; } int32 ReadUMXIndex(FileReader &chunk) { return ReadUMXIndexImpl(chunk); } // Returns true if the given nme exists in the name table. template <typename TFile> static bool FindUMXNameTableEntryImpl(TFile &file, const UMXFileHeader &fileHeader, const char *name) { if(!name) { return false; } std::size_t name_len = std::strlen(name); if(name_len == 0) { return false; } bool result = false; const FileReader::off_t oldpos = file.GetPosition(); if(file.Seek(fileHeader.nameOffset)) { for(uint32 i = 0; i < fileHeader.nameCount && file.CanRead(4); i++) { if(fileHeader.packageVersion >= 64) { int32 length = ReadUMXIndexImpl(file); if(length <= 0) { continue; } } bool match = true; std::size_t pos = 0; char c = 0; while((c = file.ReadUint8()) != 0) { c = mpt::ToLowerCaseAscii(c); if(pos < name_len) { match = match && (c == name[pos]); } pos++; } if(pos != name_len) { match = false; } if(match) { result = true; } file.Skip(4); // Object flags } } file.Seek(oldpos); return result; } bool FindUMXNameTableEntry(FileReader &file, const UMXFileHeader &fileHeader, const char *name) { return FindUMXNameTableEntryImpl(file, fileHeader, name); } bool FindUMXNameTableEntryMemory(MemoryFileReader &file, const UMXFileHeader &fileHeader, const char *name) { return FindUMXNameTableEntryImpl(file, fileHeader, name); } // Read an entry from the name table. std::string ReadUMXNameTableEntry(FileReader &chunk, uint16 packageVersion) { std::string name; if(packageVersion >= 64) { // String length int32 length = ReadUMXIndex(chunk); if(length <= 0) { return ""; } name.reserve(length); } // Simple zero-terminated string uint8 chr; while((chr = chunk.ReadUint8()) != 0) { // Convert string to lower case if(chr >= 'A' && chr <= 'Z') { chr = chr - 'A' + 'a'; } name.append(1, static_cast<char>(chr)); } chunk.Skip(4); // Object flags return name; } // Read complete name table. std::vector<std::string> ReadUMXNameTable(FileReader &file, const UMXFileHeader &fileHeader) { std::vector<std::string> names; if(!file.Seek(fileHeader.nameOffset)) { return names; } names.reserve(fileHeader.nameCount); for(uint32 i = 0; i < fileHeader.nameCount && file.CanRead(4); i++) { names.push_back(ReadUMXNameTableEntry(file, fileHeader.packageVersion)); } return names; } // Read an entry from the import table. int32 ReadUMXImportTableEntry(FileReader &chunk, uint16 packageVersion) { ReadUMXIndex(chunk); // Class package ReadUMXIndex(chunk); // Class name if(packageVersion >= 60) { chunk.Skip(4); // Package } else { ReadUMXIndex(chunk); // ?? } return ReadUMXIndex(chunk); // Object name (offset into the name table) } // Read an entry from the export table. void ReadUMXExportTableEntry(FileReader &chunk, int32 &objClass, int32 &objOffset, int32 &objSize, int32 &objName, uint16 packageVersion) { objClass = ReadUMXIndex(chunk); // Object class ReadUMXIndex(chunk); // Object parent if(packageVersion >= 60) { chunk.Skip(4); // Internal package / group of the object } objName = ReadUMXIndex(chunk); // Object name (offset into the name table) chunk.Skip(4); // Object flags objSize = ReadUMXIndex(chunk); if(objSize > 0) { objOffset = ReadUMXIndex(chunk); } } OPENMPT_NAMESPACE_END
22.427928
137
0.675437
extrowerk
8955c9bd06cc521286e017bef3232d5137193391
15,046
cpp
C++
gtkmm/MainWindow.cpp
tsabelmann/canviewer
332b722460a3ec544442b0703cca5bbe1ac34e8f
[ "MIT" ]
null
null
null
gtkmm/MainWindow.cpp
tsabelmann/canviewer
332b722460a3ec544442b0703cca5bbe1ac34e8f
[ "MIT" ]
1
2021-10-10T20:43:43.000Z
2022-02-23T10:50:14.000Z
gtkmm/MainWindow.cpp
tsabelmann/canviewer
332b722460a3ec544442b0703cca5bbe1ac34e8f
[ "MIT" ]
1
2022-03-29T12:43:47.000Z
2022-03-29T12:43:47.000Z
#include "MainWindow.hpp" namespace gtkmm { MainWindow::MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& builder) : Gtk::Window(cobject) { //treeview Gtk::TreeView *tree; builder->get_widget("treeview", tree); this->treeview = std::unique_ptr<Gtk::TreeView>{tree}; this->treemodel = std::make_unique<TreeModel>(); this->treestore = Gtk::TreeStore::create(*this->treemodel); this->treeview->set_model(this->treestore); //treeview this->treeview->append_column("id", this->treemodel->id); this->treeview->append_column("message", this->treemodel->m_name); this->treeview->append_column("variable", this->treemodel->v_name); this->treeview->append_column("data", this->treemodel->data); this->treeview->append_column("phys-unit", this->treemodel->phys_unit); this->treeview->append_column("format", this->treemodel->id_type); this->treeview->append_column("interface", this->treemodel->interface); this->treeview->append_column("count", this->treemodel->count); this->treeview->append_column("cycle-time", this->treemodel->cycle_time); //listview Gtk::TreeView *list; builder->get_widget("listview", list); this->listview = std::unique_ptr<Gtk::TreeView>{list}; this->listmodel = std::make_unique<ListModel>(); this->liststore = Gtk::ListStore::create(*this->listmodel); this->listview->set_model(this->liststore); //listview this->listview->append_column("interface", this->listmodel->interface_name); this->listview->append_column_editable("active", this->listmodel->active); //start, stop, clear button Gtk::ToolButton *start; builder->get_widget("start_view", start); this->start_view = std::unique_ptr<Gtk::ToolButton>{start}; Gtk::ToolButton *stop; builder->get_widget("stop_view", stop); this->stop_view = std::unique_ptr<Gtk::ToolButton>{stop}; Gtk::ToolButton *clear; builder->get_widget("clear_store", clear); this->clear_store = std::unique_ptr<Gtk::ToolButton>{clear}; //add, delete, refresh interface list Gtk::Button *add; builder->get_widget("add_interface", add); this->add_interface = std::unique_ptr<Gtk::Button>{add}; Gtk::Button *del; builder->get_widget("delete_interface", del); this->delete_interface = std::unique_ptr<Gtk::Button>{del}; Gtk::Button *refresh; builder->get_widget("refresh_interface", refresh); this->refresh_interface = std::unique_ptr<Gtk::Button>{refresh}; Gtk::Entry *entry; builder->get_widget("interface_field", entry); this->interface_field = std::unique_ptr<Gtk::Entry>{entry}; //menue entry Gtk::ImageMenuItem *open; builder->get_widget("open_file", open); this->open_file = std::unique_ptr<Gtk::ImageMenuItem>{open}; Gtk::ImageMenuItem *open_add; builder->get_widget("open_add_file", open_add); this->open_add_file = std::unique_ptr<Gtk::ImageMenuItem>{open_add}; Gtk::ImageMenuItem *close; builder->get_widget("close_window", close); this->close_window = std::unique_ptr<Gtk::ImageMenuItem>{close}; Gtk::ImageMenuItem *op_dialog; builder->get_widget("open_dialog", op_dialog); this->open_about_dialog = std::unique_ptr<Gtk::ImageMenuItem>{op_dialog}; //aboutdialog Gtk::AboutDialog *about; builder->get_widget("about_dialog", about); this->about_dialog = std::unique_ptr<Gtk::AboutDialog>{about}; //register functions this->start_view->signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_start_view)); this->stop_view->signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_stop_view)); this->clear_store->signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_clear_store)); this->add_interface->signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_add_interface)); this->delete_interface->signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_delete_interface)); this->refresh_interface->signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_refresh_interface)); this->open_file->signal_activate().connect(sigc::mem_fun(*this, &MainWindow::on_open_file)); this->open_add_file->signal_activate().connect(sigc::mem_fun(*this, &MainWindow::on_open_add_file)); this->close_window->signal_activate().connect(sigc::mem_fun(*this, &MainWindow::on_close_window)); this->open_about_dialog->signal_activate().connect(sigc::mem_fun(*this, &MainWindow::on_open_about_dialog)); //set button this->stop_view->set_sensitive(false); //treeview // this->treeview->signal_row_activated().connect([&, this](const auto& path, const auto& column) // { // if(path) // { // std::cout << path.to_string() << std::endl; // } // }); // this->treeview->set_activate_on_single_click(true); } void MainWindow::on_start_view() { this->start_view->set_sensitive(false); this->stop_view->set_sensitive(true); this->running = true; for(auto& iter : this->liststore->children()) { auto row = *iter; if(row[this->listmodel->active]) { std::thread{[&, this](std::string interface){ bool run{true}; can::linux_socket s{interface}; while(run) { auto fr = s.receive(); if(fr) { std::lock_guard<std::shared_timed_mutex> guard{this->frames_mutex}; { auto iter = this->frames.find(fr->can_id()); if(iter != this->frames.end()) { auto& [f, i, c, t1, t2, b] = iter->second; f = *fr; c++; t1 = t2; t2 = hr_clock::now(); b = true; } else { tuple_t tuple = std::make_tuple(*fr, interface, 1, hr_clock::now(), hr_clock::now(), true); this->frames.insert(std::make_pair(fr->can_id(), tuple)); } } } { std::shared_lock<std::shared_timed_mutex> guard{this->running_mutex}; run = this->running; } } }, std::string{row[this->listmodel->interface_name]}}.detach(); } } this->connection = Glib::signal_timeout().connect(sigc::mem_fun(*this, &MainWindow::on_timeout), 50); } void MainWindow::on_stop_view() { this->connection.disconnect(); { std::lock_guard<std::shared_timed_mutex> guard{this->running_mutex}; this->running = false; } this->start_view->set_sensitive(true); this->stop_view->set_sensitive(false); } void MainWindow::on_clear_store() { this->on_stop_view(); { std::lock_guard<std::shared_timed_mutex> guard{this->frames_mutex}; this->frames.clear(); this->treestore->clear(); this->rows_with_no_message.clear(); this->rows_with_message.clear(); this->rows_with_variable.clear(); } } bool MainWindow::on_timeout() { std::shared_lock guard{this->frames_mutex}; for(auto& iter : this->frames) { auto& [fr, i, c, t1, t2, active] = iter.second; if(active) { active = false; auto found_message = this->messages.find(fr.can_id()); if(found_message != this->messages.end()) { auto found_row_with_message = this->rows_with_message.find(fr.can_id()); if(found_row_with_message != this->rows_with_message.end()) { auto iter = found_row_with_message->second; if(fr.format() == can::frame::Format::Standard) { iter->set_value(this->treemodel->id_type, std::string{"Standard"}); } else { iter->set_value(this->treemodel->id_type, std::string{"Extended"}); } iter->set_value(this->treemodel->count, std::to_string(c)); iter->set_value(this->treemodel->cycle_time, std::to_string(std::chrono::duration_cast<std::chrono::duration<uint32_t, std::ratio<1, 1000>>>(t2 - t1).count())); auto range = this->rows_with_variable.equal_range(fr.can_id()); for(auto first = range.first; first != range.second && first != rows_with_variable.end(); ++first) { auto& [v, e, row_iter] = first->second; if(v) { auto intermediate = std::visit(can::to_intermediate{fr}, v->var()); if(e) { auto string = std::visit(can::to_string{*e}, intermediate); row_iter->set_value(this->treemodel->data, string); } else { auto string = std::visit(can::to_string{}, intermediate); row_iter->set_value(this->treemodel->data, string); } } } } else { auto message_iter = this->treestore->append(); std::stringstream ss; ss << std::uppercase << std::hex << fr.can_id(); message_iter->set_value(this->treemodel->id, ss.str()); message_iter->set_value(this->treemodel->m_name, found_message->second.name()); if(fr.format() == can::frame::Format::Standard) { message_iter->set_value(this->treemodel->id_type, std::string{"Standard"}); } else { message_iter->set_value(this->treemodel->id_type, std::string{"Extended"}); } message_iter->set_value(this->treemodel->interface, i); message_iter->set_value(this->treemodel->count, std::to_string(c)); message_iter->set_value(this->treemodel->cycle_time, std::to_string(std::chrono::duration_cast<std::chrono::duration<uint32_t, std::ratio<1, 1000>>>(t2 - t1).count())); this->rows_with_message.insert(std::make_pair(fr.can_id(), message_iter)); for(auto& var : found_message->second.variables()) { Gtk::TreeModel::iterator variable_iter = this->treestore->append(message_iter->children()); variable_iter->set_value(this->treemodel->v_name, var.second.name()); variable_iter->set_value(this->treemodel->phys_unit, var.second.phys_unit()); auto intermediate = std::visit(can::to_intermediate{fr}, var.second.var()); auto found_enum = this->enums.find(var.second.enum_name()); if(found_enum != this->enums.end()) { auto string = std::visit(can::to_string{found_enum->second}, intermediate); variable_iter->set_value(this->treemodel->data, string); auto tuple = std::make_tuple(&var.second, &found_enum->second, variable_iter); this->rows_with_variable.insert(std::make_pair(fr.can_id(), tuple)); } else { auto string = std::visit(can::to_string{}, intermediate); variable_iter->set_value(this->treemodel->data, string); auto tuple = std::make_tuple(&var.second, nullptr, variable_iter); this->rows_with_variable.insert(std::make_pair(fr.can_id(), tuple)); } } } } else { //update row without message auto found_row_with_no_message = this->rows_with_no_message.find(fr.can_id()); if(found_row_with_no_message != this->rows_with_no_message.end()) { auto iter = found_row_with_no_message->second; std::stringstream data; for(uint8_t i = 0; i < fr.size(); ++i) { data << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << +fr[i].value_or(0) << " "; } if(fr.format() == can::frame::Format::Standard) { iter->set_value(this->treemodel->id_type, std::string{"Standard"}); } else { iter->set_value(this->treemodel->id_type, std::string{"Extended"}); } iter->set_value(this->treemodel->data, data.str()); iter->set_value(this->treemodel->count, std::to_string(c)); iter->set_value(this->treemodel->cycle_time, std::to_string(std::chrono::duration_cast<std::chrono::duration<uint32_t, std::ratio<1, 1000>>>(t2 - t1).count())); } //add iter to row with no message else { auto iter = this->treestore->append(); std::stringstream ss; ss << std::uppercase << std::hex << fr.can_id(); iter->set_value(this->treemodel->id, ss.str()); std::stringstream data; for(uint8_t i = 0; i < fr.size(); ++i) { data << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << +fr[i].value_or(0) << " "; } iter->set_value(this->treemodel->data, data.str()); if(fr.format() == can::frame::Format::Standard) { iter->set_value(this->treemodel->id_type, std::string{"Standard"}); } else { iter->set_value(this->treemodel->id_type, std::string{"Extended"}); } iter->set_value(this->treemodel->interface, i); iter->set_value(this->treemodel->count, std::to_string(c)); iter->set_value(this->treemodel->cycle_time, std::to_string(std::chrono::duration_cast<std::chrono::duration<uint32_t, std::ratio<1, 1000>>>(t2 - t1).count())); this->rows_with_no_message.insert(std::make_pair(fr.can_id(), iter)); } } } } return true; } void MainWindow::on_add_interface() { std::string can_interface_name = this->interface_field->get_text(); if(!can_interface_name.empty()) { for(auto iter : this->liststore->children()) { auto row = *iter; std::string name = row[this->listmodel->interface_name]; if(name == can_interface_name) return; } auto row = *(this->liststore->append()); row[this->listmodel->interface_name] = can_interface_name; row[this->listmodel->active] = false; } } void MainWindow::on_delete_interface() { auto selection = this->listview->get_selection(); auto iter = selection->get_selected(); if(iter) { this->liststore->erase(iter); } } void MainWindow::on_refresh_interface() { std::string ip_link_show = "ip link show"; std::array<char, 128> buffer; std::string result; std::shared_ptr<FILE> pipe(popen(ip_link_show.c_str(), "r"), pclose); if (!pipe) throw std::runtime_error("popen() failed!"); while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != nullptr) result += buffer.data(); } std::regex r{R"(\bv?can\d+\b)"}; std::smatch match; do { if(std::regex_search(result, match, r)) { for(const auto& i : match) { std::string t = i; auto row = *(this->liststore->append()); row[this->listmodel->interface_name] = t; row[this->listmodel->active] = false; } result = match.suffix(); } else { break; } }while(!match.empty()); } void MainWindow::on_open_file() { try { Gtk::FileChooserDialog dialog("Chose a *.json file:"); dialog.set_transient_for(*this); dialog.add_button("Abort", Gtk::RESPONSE_CLOSE); dialog.add_button("Select", Gtk::RESPONSE_OK); Glib::RefPtr<Gtk::FileFilter> f = Gtk::FileFilter::create(); f->add_pattern("*.json"); dialog.set_filter(f); dialog.run(); auto file = dialog.get_file(); auto path = file->get_path(); can::json json{path}; this->messages = json.messages(); this->enums = json.enums(); } catch(std::exception& e) { // this->error_label->set_text(e.what()); } } void MainWindow::on_open_add_file() { } void MainWindow::on_close_window() { this->hide(); } void MainWindow::on_open_about_dialog() { this->about_dialog->run(); } }
31.609244
174
0.639373
tsabelmann
8955d2183cd2efe1d704d38e6dd7c9a3e52d22ef
7,410
cpp
C++
src/DiMP/Graph/Avoid.cpp
ytazz/DiMP
71e680a18ed82a3a3cdacd7fcc5c165bd21f167d
[ "MIT" ]
null
null
null
src/DiMP/Graph/Avoid.cpp
ytazz/DiMP
71e680a18ed82a3a3cdacd7fcc5c165bd21f167d
[ "MIT" ]
null
null
null
src/DiMP/Graph/Avoid.cpp
ytazz/DiMP
71e680a18ed82a3a3cdacd7fcc5c165bd21f167d
[ "MIT" ]
null
null
null
#include <DiMP/Graph/Avoid.h> #include <DiMP/Graph/Geometry.h> #include <DiMP/Graph/Object.h> #include <DiMP/Graph/Graph.h> #include <DiMP/Render/Config.h> #include <sbtimer.h> static Timer timer; #include <omp.h> namespace DiMP{; const real_t inf = numeric_limits<real_t>::max(); //------------------------------------------------------------------------------------------------- // AvoidKey AvoidKey::AvoidKey(){ con_p = 0; con_v = 0; } void AvoidKey::AddCon(Solver* solver){ AvoidTask* task = (AvoidTask*)node; /*int ngeo0 = obj0->geoInfos.size(); int ngeo1 = obj1->geoInfos.size(); geoPairs.resize(ngeo0 * ngeo1); for(int i0 = 0; i0 < ngeo0; i0++)for(int i1 = 0; i1 < ngeo1; i1++){ GeometryPair& gp = geoPairs[ngeo1*i0 + i1]; gp.info0 = &obj0->geoInfos[i0]; gp.info1 = &obj1->geoInfos[i1]; }*/ con_p = new AvoidConP(solver, name + "_p", this, 0, node->graph->scale.pos_t); con_v = new AvoidConV(solver, name + "_v", this, 0, node->graph->scale.vel_t); solver->AddCostCon(con_p, tick->idx); solver->AddCostCon(con_v, tick->idx); con_p->enabled = task->param.avoid_p; con_v->enabled = task->param.avoid_v; } void AvoidKey::Prepare(){ TaskKey::Prepare(); if(!con_p->enabled && !con_v->enabled) return; AvoidTask* task = (AvoidTask*)node; if( relation == Inside ){ int nocttree = 0; int nsphere = 0; int nbox = 0; int ngjk = 0; int nactive = 0; GeometryPair* gpmax = 0; real_t dmax = 0.0; /*ptimer.CountUS(); ExtractGeometryPairs( obj0->geoInfos, obj0->edgeInfos, obj1->geoInfos, obj1->edgeInfos, geoPairs); int timeExtract = ptimer.CountUS(); */ //DSTR << "geo0: " << obj0->geoInfos.size() << " geo1: " << obj1->geoInfos.size() << " geo pair: " << geoPairs.size() << endl; timer.CountUS(); for(int gp_idx = 0; gp_idx < geoPairs.size(); gp_idx++){ GeometryPair& gp = geoPairs[gp_idx]; // octtreeで判定 //if( !gp.info0->octNode->IsAncestor(gp.info1->octNode) ){ // gp.cullOcttree = true; // nocttree++; // continue; //} // bsphereで判定 real_t d = (gp.info0->bsphereCenterAbs - gp.info1->bsphereCenterAbs).norm(); real_t rsum = gp.info0->geo->bsphereRadius + gp.info1->geo->bsphereRadius; gp.cullSphere = (d - rsum > task->param.dmin); if(gp.cullSphere){ nsphere++; continue; } // bboxで判定 gp.cullBox = false; for(int i = 0; i < 3; i++){ if( gp.info0->bbmin[i] > gp.info1->bbmax[i] + task->param.dmin || gp.info1->bbmin[i] > gp.info0->bbmax[i] + task->param.dmin ){ gp.cullBox = true; break; } } if(gp.cullBox){ nbox++; continue; } CalcNearest( gp.info0->geo, gp.info1->geo, gp.info0->poseAbs, gp.info1->poseAbs, gp.sup0, gp.sup1, gp.dist ); gp.cullGjk = (gp.dist > task->param.dmin); if(gp.cullGjk){ ngjk++; } else{ const real_t eps = 1.0e-10; vec3_t diff = gp.sup1 - gp.sup0; real_t dnorm = diff.norm(); if(dnorm > eps){ gp.normal = diff/dnorm; nactive++; if(dnorm > dmax){ gpmax = &gp; dmax = dnorm; } } } } int timeEnum = timer.CountUS(); if(gpmax){ con_p->gp = gpmax; con_v->gp = gpmax; con_p->active = true; con_v->active = true; } else{ con_p->active = false; con_v->active = false; } //DSTR << "bsphere: " << nsphere << " bbox: " << nbox << " gjk: " << ngjk << " active: " << nactive << endl; if(gpmax){ DSTR << " dist: " << gpmax->dist << " normal: " << gpmax->normal << endl; } //DSTR << "timeExtract: " << timeExtract << " timeEnum: " << timeEnum << endl; } else{ con_p->active = false; con_v->active = false; } } void AvoidKey::Draw(Render::Canvas* canvas, Render::Config* conf){ Vec3f p0, p1; if(relation == Inside && conf->Set(canvas, Render::Item::Avoid, node)){ for(auto& gp : geoPairs){ // bsphereで枝刈りされておらず,かつ交差もしていない場合にsupport pointを結ぶ線を描画 if(!gp.cullSphere && !gp.cullBox && !gp.cullGjk){ p0 = gp.sup0; p1 = gp.sup1; canvas->Line(p0, p1); } } } } //------------------------------------------------------------------------------------------------- // AvoidTask AvoidTask::Param::Param(){ avoid_p = true; avoid_v = true; dmin = 0.0; } AvoidTask::AvoidTask(Object* _obj0, Object* _obj1, TimeSlot* _time, const string& n) :Task(_obj0, _obj1, _time, n){ graph->avoids.Add(this); } AvoidTask::~AvoidTask(){ graph->avoids.Remove(this); } void AvoidTask::Prepare(){ // if either object is stationary, broad-phase collision detection is executed here //ptimer.CountUS(); //ExtractGeometryPairs( // obj0->geoInfos, obj0->edgeInfos, // obj1->geoInfos, obj1->edgeInfos, // geoPairs); //int timeExtract = ptimer.CountUS(); Task::Prepare(); } //------------------------------------------------------------------------------------------------- // constructors AvoidCon::AvoidCon(Solver* solver, ID id, AvoidKey* _key, GeometryPair* _gp, real_t _scale):Constraint(solver, 1, id, Constraint::Type::InequalityPenalty, _scale){ key = _key; gp = _gp; } AvoidConP::AvoidConP(Solver* solver, const string& _name, AvoidKey* _key, GeometryPair* _gp, real_t _scale): AvoidCon(solver, ID(ConTag::AvoidP, _key->node, _key->tick, _name), _key, _gp, _scale){ // translational, position, scalar constraint ObjectKey::OptionS opt; opt.tp = true ; opt.rp = true ; opt.tv = false; opt.rv = false; key->obj0->AddLinks(this, opt); key->obj1->AddLinks(this, opt); } AvoidConV::AvoidConV(Solver* solver, const string& _name, AvoidKey* _key, GeometryPair* _gp, real_t _scale): AvoidCon(solver, ID(ConTag::AvoidV, _key->node, _key->tick, _name), _key, _gp, _scale){ // translational, velocity, scalar constraint ObjectKey::OptionS opt; opt.tp = false; opt.rp = false; opt.tv = true ; opt.rv = true ; key->obj0->AddLinks(this, opt); key->obj1->AddLinks(this, opt); } //------------------------------------------------------------------------------------------------- // CalcCoef void AvoidConP::CalcCoef(){ if(!active) return; uint i = 0; ObjectKey::OptionS opt; opt.tp = true ; opt.rp = true ; opt.tv = false; opt.rv = false; opt.k_tp = -gp->normal; opt.k_rp = -(gp->sup0 - key->obj0->pos_t->val) % gp->normal; key->obj0->CalcCoef(this, opt, i); opt.k_tp = gp->normal, opt.k_rp = (gp->sup1 - key->obj1->pos_t->val) % gp->normal; key->obj1->CalcCoef(this, opt, i); } void AvoidConV::CalcCoef(){ if(!active) return; uint i = 0; ObjectKey::OptionS opt; opt.tp = true ; opt.rp = true ; opt.tv = false; opt.rv = false; opt.k_tv = -gp->normal; opt.k_rv = -(gp->sup0 - key->obj0->pos_t->val) % gp->normal; key->obj0->CalcCoef(this, opt, i); opt.k_tv = gp->normal; opt.k_rv = (gp->sup1 - key->obj1->pos_t->val) % gp->normal; key->obj1->CalcCoef(this, opt, i); } //------------------------------------------------------------------------------------------------- // CalcDeviation void AvoidConP::CalcDeviation(){ if(!active){ y[0] = 0.0; return; } y[0] = gp->dist - ((AvoidTask*)key->node)->param.dmin; } void AvoidConV::CalcDeviation(){ if(!active){ y[0] = 0.0; return; } Constraint::CalcDeviation(); } //------------------------------------------------------------------------------------------------- // Projection void AvoidConP::Project(real_t& l, uint k){ if(l < 0.0) l = 0.0; } void AvoidConV::Project(real_t& l, uint k){ if(l < 0.0) l = 0.0; } }
25.290102
163
0.57031
ytazz
8957b5bf25d342414128634cba97d8fee63e7006
921
cpp
C++
SprintEverywhere/SprintEverywhere/SprintEverywhere.cpp
XMDS/SprintEverywhere
f029da407d71035633291a0961d3e40bef73dc8e
[ "MIT" ]
null
null
null
SprintEverywhere/SprintEverywhere/SprintEverywhere.cpp
XMDS/SprintEverywhere
f029da407d71035633291a0961d3e40bef73dc8e
[ "MIT" ]
null
null
null
SprintEverywhere/SprintEverywhere/SprintEverywhere.cpp
XMDS/SprintEverywhere
f029da407d71035633291a0961d3e40bef73dc8e
[ "MIT" ]
null
null
null
#include <unistd.h> #ifdef AML //use AML #include "AML/amlmod.h" #include "AML/logger.h" MYMOD(net.xmds.SprintEverywhere, SprintEverywhere, 1.0, XMDS) #else #include "CLEO_SDK/cleo.h" //use CLEO sdk #endif #include "ARMHook/ARMHook.h" uintptr_t LibAddr; int ret() { return 0; } #ifdef AML //AML plugin entrance extern "C" void OnModLoad() { logger->SetTag("SprintEverywhere"); logger->Info("'SprintEverywhere.so' init!!!"); LibAddr = ARMHook::GetLibraryAddress("libGTASA.so"); ARMHook::HookPLTInternal((void*)(LibAddr + 0x0066FD60), (void*)ret, NULL); } #else //cleo plugin entrance extern "C" __attribute__((visibility("default"))) void plugin_init(cleo_ifs_t * ifs) { cleo_ifs_t* cleo = ifs; cleo->PrintToCleoLog("'SprintEverywhere.so' init!!!"); LibAddr = reinterpret_cast<uintptr_t>(cleo->GetMainLibraryLoadAddress()); ARMHook::HookPLTInternal((void*)(LibAddr + 0x0066FD60), (void*)ret, NULL); } #endif
24.891892
84
0.723127
XMDS
895e3754d3688516e5cc021d5b7dad27d0295d34
2,635
cpp
C++
snippets/cpp/VS_Snippets_CLR_System/system.Globalization.CultureInfo.GetCultures/CPP/getcultures.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-02-22T09:30:21.000Z
2021-08-02T23:44:31.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Globalization.CultureInfo.GetCultures/CPP/getcultures.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Globalization.CultureInfo.GetCultures/CPP/getcultures.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// The following code example displays several properties of the neutral cultures. // <snippet1> using namespace System; using namespace System::Globalization; int main() { // Displays several properties of the neutral cultures. Console::WriteLine( "CULTURE ISO ISO WIN DISPLAYNAME ENGLISHNAME" ); System::Collections::IEnumerator^ enum0 = CultureInfo::GetCultures( CultureTypes::NeutralCultures )->GetEnumerator(); while ( enum0->MoveNext() ) { CultureInfo^ ci = safe_cast<CultureInfo^>(enum0->Current); Console::Write( "{0,-7}", ci->Name ); Console::Write( " {0,-3}", ci->TwoLetterISOLanguageName ); Console::Write( " {0,-3}", ci->ThreeLetterISOLanguageName ); Console::Write( " {0,-3}", ci->ThreeLetterWindowsLanguageName ); Console::Write( " {0,-40}", ci->DisplayName ); Console::WriteLine( " {0,-40}", ci->EnglishName ); } } /* This code produces the following output. This output has been cropped for brevity. CULTURE ISO ISO WIN DISPLAYNAME ENGLISHNAME ar ar ara ARA Arabic Arabic bg bg bul BGR Bulgarian Bulgarian ca ca cat CAT Catalan Catalan zh-Hans zh zho CHS Chinese (Simplified) Chinese (Simplified) cs cs ces CSY Czech Czech da da dan DAN Danish Danish de de deu DEU German German el el ell ELL Greek Greek en en eng ENU English English es es spa ESP Spanish Spanish fi fi fin FIN Finnish Finnish zh zh zho CHS Chinese Chinese zh-Hant zh zho CHT Chinese (Traditional) Chinese (Traditional) zh-CHS zh zho CHS Chinese (Simplified) Legacy Chinese (Simplified) Legacy zh-CHT zh zho CHT Chinese (Traditional) Legacy Chinese (Traditional) Legacy */ // </snippet1>
57.282609
120
0.450474
BohdanMosiyuk
895fbcf610a6b6a12a96f697759753749dd1e30c
6,205
cc
C++
aegir-brewd/src/Message.cc
gczuczy/aegir
1275ca41bfe4a56347eb2531211df4c70933fb96
[ "BSD-3-Clause" ]
null
null
null
aegir-brewd/src/Message.cc
gczuczy/aegir
1275ca41bfe4a56347eb2531211df4c70933fb96
[ "BSD-3-Clause" ]
11
2020-06-04T20:31:02.000Z
2022-02-26T01:39:26.000Z
aegir-brewd/src/Message.cc
gczuczy/aegir
1275ca41bfe4a56347eb2531211df4c70933fb96
[ "BSD-3-Clause" ]
1
2020-12-10T19:19:41.000Z
2020-12-10T19:19:41.000Z
#include "Message.hh" #include <string.h> #include <algorithm> #include "Exception.hh" namespace aegir { const std::string hexdump(const msgstring &_msg) { return hexdump(_msg.data(), _msg.length()); } const std::string hexdump(const uint8_t *_msg, int _size) { std::string hex; for (int i=0; i<_size; ++i ) { char buff[8]; int len; len = snprintf(buff, 4, " %02x", _msg[i]); hex += std::string(buff, len); } return hex; } MessageFactoryReg PinStateReg(MessageType::PINSTATE, PinStateMessage::create); MessageFactoryReg ThermoReadingReg(MessageType::THERMOREADING, ThermoReadingMessage::create); /* * MessageFactoryReg */ MessageFactoryReg::MessageFactoryReg(MessageType _type, ffunc_t _ffunc) { MessageFactory::getInstance().registerCtor(_type, _ffunc); } /* * MessageFactory */ MessageFactory::MessageFactory() { } MessageFactory::~MessageFactory() { } MessageFactory &MessageFactory::getInstance() { static MessageFactory instance; return instance; } void MessageFactory::registerCtor(MessageType _type, ffunc_t _ctor) { c_ctors[(int)_type] = _ctor; } std::shared_ptr<Message> MessageFactory::create(const msgstring &_msg) { int idx = (int)_msg[0]; if ( c_ctors[idx] == nullptr ) throw Exception("Unknown message type %i", (int)_msg[0]); return c_ctors[idx](_msg); } /* * Message */ Message::~Message() = default; std::string Message::hexdebug() const { return hexdump(this->serialize()); } /* * PinStateMessage * Format is: * MessageType: 1 byte * Name: 1) stringsize: 1 byte + 2) stringsize-bytes * State: 1 byte * cycletime: 4 bytes (sizeof float) * onratio: 4 bytes (sizeof float) */ PinStateMessage::PinStateMessage(const msgstring &_msg) { #ifdef AEGIR_DEBUG printf("PinStateMessage(L:%lu '%s') called: ", _msg.length(), hexdump(_msg).c_str()); #endif // _msg[0] is the type, but we're already here int msglen = _msg.length(); uint32_t offset = 1; uint8_t namelen = _msg[offset++]; c_name = std::string((char*)_msg.data()+offset, namelen); offset += namelen; c_state = (PINState)(_msg[offset++]); c_cycletime = *((float*)((char*)_msg.data()+offset)); offset += 4; c_onratio = *((float*)((char*)_msg.data()+offset)); #ifdef AEGIR_DEBUG printf(" name:'%s' state:%hhu CT:%.3f OR:%.3f\n", c_name.c_str(), (uint8_t)c_state, c_cycletime, c_onratio); #endif } PinStateMessage::PinStateMessage(const std::string &_name, PINState _state, float _cycletime, float _onratio): c_name(_name), c_state(_state), c_cycletime(_cycletime), c_onratio(_onratio) { #ifdef AEGIR_DEBUG printf("PinStateMessage('%s', %hhu, %.3f, %.3f) called: ", _name.c_str(), (uint8_t)_state, _cycletime, _onratio); #endif // cycletime checks if ( _state == PINState::Pulsate ) { if ( _cycletime < 0.2f ) throw Exception("PinStateMessage() cycletime must be greater than 0.2"); if ( _cycletime > 10.0f ) throw Exception("PinStateMessage() cycletime must be less than 10"); // on ratio checks if ( _onratio < 0.0f ) c_state = PINState::Off; if ( _onratio > 1.0f ) c_state = PINState::On; } #ifdef AEGIR_DEBUG printf("'%s'\n", hexdump(serialize()).c_str()); #endif } PinStateMessage::~PinStateMessage() { } msgstring PinStateMessage::serialize() const { uint8_t strsize(std::min((uint32_t)c_name.length(), (uint32_t)255)); uint32_t len(3+8+strsize); msgstring buffer(len, 0); uint8_t *data = (uint8_t*)buffer.c_str(); data[0] = (uint8_t)type(); data[1] = (uint8_t)strsize; int offset = 2; memcpy((void*)(data+2), (void*)c_name.data(), strsize); offset += strsize; data[offset++] = (int8_t)c_state; *(float*)(data+offset) = c_cycletime; offset += 4; *(float*)(data+offset) = c_onratio; return buffer; } MessageType PinStateMessage::type() const { return MessageType::PINSTATE; } std::shared_ptr<Message> PinStateMessage::create(const msgstring &_msg) { return std::make_shared<PinStateMessage>(_msg); } /* * ThermoReadingMessage * Format is: * MessageType: 1 byte * Name: 1) stringsize: 1 byte + 2) stringsize-bytes * Temp: sizeof(float) * Timestamp: 4 byte, uint32_t */ ThermoReadingMessage::ThermoReadingMessage(const msgstring &_msg) { #ifdef AEGIR_DEBUG printf("ThermoReadingMessage(L:%lu '%s') called\n", _msg.length(), hexdump(_msg).c_str()); #endif // _msg[0] is the type, but we're already here int msglen = _msg.length(); uint8_t *data = (uint8_t*)_msg.data(); uint8_t namelen = _msg[1]; c_name = std::string((char*)data+2, namelen); int offset = 3+namelen; c_temp = *(float*)(data+offset); offset += sizeof(float); c_timestamp = *(uint32_t*)(data+offset); #ifdef AEGIR_DEBUG printf("ThermoReadingMessage(L:%lu '%s') decoded: Name:'%s' Temp:%.2f Time:%u\n", _msg.length(), hexdump(_msg).c_str(), c_name.c_str(), c_temp, c_timestamp); #endif } ThermoReadingMessage::ThermoReadingMessage(const std::string &_name, float _temp, uint32_t _timestamp): c_name(_name), c_temp(_temp), c_timestamp(_timestamp) { } ThermoReadingMessage::~ThermoReadingMessage() = default; msgstring ThermoReadingMessage::serialize() const { uint32_t len(3); uint32_t strsize(std::min((uint32_t)c_name.length(), (uint32_t)255)); len += strsize; len += sizeof(float) + sizeof(uint32_t); msgstring buffer(len, 0); uint8_t *data = (uint8_t*)buffer.data(); data[0] = (uint8_t)type(); data[1] = (uint8_t)strsize; memcpy((void*)(data+2), (void*)c_name.data(), strsize); int offset = strsize + 3; // c_temp is float *(float*)(data+offset) = c_temp; offset += sizeof(float); // c_timestamp is uint32_t *(uint32_t*)(data+offset) = c_timestamp; return buffer; } MessageType ThermoReadingMessage::type() const { return MessageType::THERMOREADING; } std::shared_ptr<Message> ThermoReadingMessage::create(const msgstring &_msg) { return std::make_shared<ThermoReadingMessage>(_msg); } }
27.09607
123
0.653989
gczuczy
8967621485c55c4b155038dbee2d572208e7732b
258
hh
C++
day10/solver.hh
ovove/aoc20
6cb819e35d64fe704c918275f50f76652133b5a4
[ "Unlicense" ]
null
null
null
day10/solver.hh
ovove/aoc20
6cb819e35d64fe704c918275f50f76652133b5a4
[ "Unlicense" ]
null
null
null
day10/solver.hh
ovove/aoc20
6cb819e35d64fe704c918275f50f76652133b5a4
[ "Unlicense" ]
null
null
null
#pragma once #include <istream> #include <vector> #include <tuple> using JoltData = std::vector<unsigned>; using JoltRatings = std::tuple<unsigned, unsigned, unsigned>; JoltData read_adapters(std::istream&); JoltRatings rate_adapters(const JoltData&);
17.2
61
0.755814
ovove
896837b2f45c0d0265a565c26787b1ae747db743
1,946
cpp
C++
SpatialGDK/Source/SpatialGDKFunctionalTests/SpatialGDK/SpatialTestCharacterMovement/TestMovementCharacter.cpp
Bowbee/GDKPrebuilt
420b3fa19fdc36755a43e655c057b5624264407a
[ "MIT" ]
363
2018-07-30T12:57:42.000Z
2022-03-25T14:30:28.000Z
SpatialGDK/Source/SpatialGDKFunctionalTests/SpatialGDK/SpatialTestCharacterMovement/TestMovementCharacter.cpp
Bowbee/GDKPrebuilt
420b3fa19fdc36755a43e655c057b5624264407a
[ "MIT" ]
1,634
2018-07-30T14:30:25.000Z
2022-03-03T01:55:15.000Z
SpatialGDK/Source/SpatialGDKFunctionalTests/SpatialGDK/SpatialTestCharacterMovement/TestMovementCharacter.cpp
Bowbee/GDKPrebuilt
420b3fa19fdc36755a43e655c057b5624264407a
[ "MIT" ]
153
2018-07-31T13:45:02.000Z
2022-03-03T05:20:24.000Z
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "TestMovementCharacter.h" #include "Engine/Classes/Camera/CameraComponent.h" #include "Components/StaticMeshComponent.h" #include "Materials/Material.h" #include "Net/UnrealNetwork.h" #include "Components/CapsuleComponent.h" ATestMovementCharacter::ATestMovementCharacter() { bReplicates = true; #if ENGINE_MINOR_VERSION < 24 bReplicateMovement = true; #else SetReplicatingMovement(true); #endif GetCapsuleComponent()->InitCapsuleSize(38.0f, 38.0f); SphereComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SphereComponent")); SphereComponent->SetStaticMesh(LoadObject<UStaticMesh>(nullptr, TEXT("StaticMesh'/Engine/BasicShapes/Sphere.Sphere'"))); SphereComponent->SetMaterial(0, LoadObject<UMaterial>(nullptr, TEXT("Material'/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial'"))); SphereComponent->SetVisibility(true); SphereComponent->SetupAttachment(GetCapsuleComponent()); FVector CameraLocation = FVector(300.0f, 0.0f, 75.0f); FRotator CameraRotation = FRotator::MakeFromEuler(FVector(0.0f, -10.0f, 180.0f)); CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent")); #if ENGINE_MINOR_VERSION < 24 CameraComponent->bAbsoluteLocation = false; CameraComponent->bAbsoluteRotation = false; CameraComponent->RelativeLocation = CameraLocation; CameraComponent->RelativeRotation = CameraRotation; #else CameraComponent->SetUsingAbsoluteLocation(false); CameraComponent->SetUsingAbsoluteRotation(false); CameraComponent->SetRelativeLocation(CameraLocation); CameraComponent->SetRelativeRotation(CameraRotation); #endif CameraComponent->SetupAttachment(GetCapsuleComponent()); } void ATestMovementCharacter::UpdateCameraLocationAndRotation_Implementation(FVector NewLocation, FRotator NewRotation) { CameraComponent->SetRelativeLocation(NewLocation); CameraComponent->SetRelativeRotation(NewRotation); }
38.156863
142
0.820144
Bowbee
896c4de46ee3e6cfb144e6cbda628ff333c613fe
7,268
cpp
C++
src/ZGStdinSession.cpp
ruurdadema/zg_choir
6de0e8be497974c0e56bb87139b18f0d6f5b4ee3
[ "BSD-3-Clause" ]
4
2018-03-08T17:59:15.000Z
2021-12-16T18:36:36.000Z
src/ZGStdinSession.cpp
ruurdadema/zg_choir
6de0e8be497974c0e56bb87139b18f0d6f5b4ee3
[ "BSD-3-Clause" ]
null
null
null
src/ZGStdinSession.cpp
ruurdadema/zg_choir
6de0e8be497974c0e56bb87139b18f0d6f5b4ee3
[ "BSD-3-Clause" ]
4
2018-05-01T22:39:03.000Z
2021-09-04T18:06:55.000Z
#include "dataio/StdinDataIO.h" #include "iogateway/PlainTextMessageIOGateway.h" #include "system/SystemInfo.h" // for PrintBuildFlags() #include "util/NetworkUtilityFunctions.h" #include "util/StringTokenizer.h" #include "zg/ZGStdinSession.h" namespace zg { ZGStdinSession :: ZGStdinSession(ITextCommandReceiver & target, bool endServerOnClose) : _target(target), _endServerOnClose(endServerOnClose), _calledEndServer(false) { /* empty */ } DataIORef ZGStdinSession :: CreateDataIO(const ConstSocketRef &) { DataIO * dio = newnothrow StdinDataIO(false); if (dio == NULL) MWARN_OUT_OF_MEMORY; return DataIORef(dio); } bool ZGStdinSession :: IsReallyStdin() const { const AbstractMessageIOGateway * gw = GetGateway()(); return ((gw)&&(dynamic_cast<StdinDataIO *>(gw->GetDataIO()()) != NULL)); } bool ZGStdinSession :: ClientConnectionClosed() { bool isReallyStdin = IsReallyStdin(); if (_endServerOnClose) { if (isReallyStdin) LogTime(MUSCLE_LOG_DEBUG, "ZGStdinSession: stdin was closed -- this process will end shortly!\n"); EndServer(); // we want our process to go away if we lose the stdin/stdout connection to the parent process _calledEndServer = true; } else if (isReallyStdin) LogTime(MUSCLE_LOG_DEBUG, "ZGStdinSession: stdin was closed, but this process will continue running anyway.\n"); return AbstractReflectSession::ClientConnectionClosed(); } bool ZGStdinSession :: IsReadyForInput() const { return ((AbstractReflectSession::IsReadyForInput())&&(_target.IsReadyForTextCommands())); } AbstractMessageIOGatewayRef ZGStdinSession :: CreateGateway() { AbstractMessageIOGateway * gw = newnothrow PlainTextMessageIOGateway; if (gw == NULL) MWARN_OUT_OF_MEMORY; return AbstractMessageIOGatewayRef(gw); } void ZGStdinSession :: MessageReceivedFromGateway(const MessageRef & msg, void * /*ptr*/) { if ((msg())&&(msg()->what == PR_COMMAND_TEXT_STRINGS)) { String nextCmd; for (int32 i=0; msg()->FindString(PR_NAME_TEXT_LINE, i, nextCmd).IsOK(); i++) { nextCmd = nextCmd.Trim(); StringTokenizer tok(nextCmd(), ";", NULL); const char * t; while((t = tok()) != NULL) { String nc = t; nc = nc.Trim(); // yes, the Trim() is necessary! if ((nc == "quit")||(nc == "exit")) { if (IsReallyStdin()) printf("To close a stdin session, press Control-D.\n"); else { printf("Closing command session...\n"); EndSession(); } } else if ((_target.TextCommandReceived(nc) == false)&&(nc.HasChars())) printf("ZGStdinSession: Could not parse stdin command string [%s] (cmdLen=" UINT32_FORMAT_SPEC ")\n", nc(), nc.Length()); } } } } static void LogAux(const String & s, uint32 sev) { String logText = s.Substring(s.IndexOf(' ')+1); if ((logText.Length() >= 2)&&(logText.StartsWith("/"))) { for (uint32 i=0; i<NUM_MUSCLE_LOGLEVELS; i++) { if (logText[1] == GetLogLevelKeyword(i)[0]) { sev = i; logText = logText.Substring(2); break; } } } LogTime(sev, "%s\n", logText()); } static bool HandleSetLogLevelCommand(const char * p, bool isDisplay) { while((*p)&&(muscleInRange(*p, 'A', 'Z') == false)&&(muscleInRange(*p, 'a', 'z') == false)) p++; uint32 logLevel = NUM_MUSCLE_LOGLEVELS; String lvl = p; lvl = lvl.Trim(); if (lvl.HasChars()) { for (uint32 i=0; i<NUM_MUSCLE_LOGLEVELS; i++) { if (String(GetLogLevelKeyword(i)).StartsWithIgnoreCase(lvl)) { logLevel = i; break; } } } if (logLevel == NUM_MUSCLE_LOGLEVELS) { LogTime(MUSCLE_LOG_ERROR, "Could not parse %s level keyword [%s]\n", isDisplay?"display":"log", lvl()); return false; } else { if (isDisplay) SetConsoleLogLevel(logLevel); else SetFileLogLevel(logLevel); return true; } } bool ITextCommandReceiver :: ParseGenericTextCommand(const String & s) { if (s.StartsWith("echo ")) printf("echoing: [%s]\n", s.Substring(5).Trim()()); else if (s.StartsWith("crit")) LogAux(s, MUSCLE_LOG_CRITICALERROR); else if (s.StartsWith("err")) LogAux(s, MUSCLE_LOG_ERROR); else if (s.StartsWith("warn")) LogAux(s, MUSCLE_LOG_WARNING); else if (s.StartsWith("log")) LogAux(s, MUSCLE_LOG_INFO); else if (s.StartsWith("debug")) LogAux(s, MUSCLE_LOG_DEBUG); else if (s.StartsWith("trace")) LogAux(s, MUSCLE_LOG_TRACE); else if (s.StartsWith("sleep")) { uint64 micros = ParseHumanReadableTimeIntervalString(s.Substring(5).Trim()); const char * preposition = (micros==MUSCLE_TIME_NEVER)?"":"for "; LogTime(MUSCLE_LOG_INFO, "Sleeping %s%s...\n", preposition, GetHumanReadableTimeIntervalString(micros)()); Snooze64(micros); LogTime(MUSCLE_LOG_INFO, "Awoke after sleeping %s%s\n", preposition, GetHumanReadableTimeIntervalString(micros)()); } else if (s.StartsWith("spin")) { uint64 micros = ParseHumanReadableTimeIntervalString(s.Substring(5).Trim()); LogTime(MUSCLE_LOG_INFO, "Spinning for %s...\n", GetHumanReadableTimeIntervalString(micros)()); uint64 endTime = (micros == MUSCLE_TIME_NEVER) ? MUSCLE_TIME_NEVER : (GetRunTime64()+micros); while(GetRunTime64()<endTime) {/* spin, my little process, spin! */} LogTime(MUSCLE_LOG_INFO, "Finished spinning for %s\n", GetHumanReadableTimeIntervalString(micros)()); } else if (s == "print object counts") PrintCountedObjectInfo(); else if (s == "print all network interfaces") { printf("List of all network interfaces known to this host:\n"); Queue<NetworkInterfaceInfo> niis; (void) GetNetworkInterfaceInfos(niis); for (uint32 i=0; i<niis.GetNumItems(); i++) { const NetworkInterfaceInfo & nii = niis[i]; printf(UINT32_FORMAT_SPEC ". %s\n", i, nii.ToString()()); } } else if (s.StartsWith("set displaylevel")) return HandleSetLogLevelCommand(s()+16, true); else if (s.StartsWith("set loglevel")) return HandleSetLogLevelCommand(s()+12, false); else if (s == "sdt") return HandleSetLogLevelCommand("trace", true); else if (s == "sdd") return HandleSetLogLevelCommand("debug", true); else if (s == "sdi") return HandleSetLogLevelCommand("info", true); else if (s == "sdw") return HandleSetLogLevelCommand("warn", true); else if (s == "sde") return HandleSetLogLevelCommand("error", true); else if (s == "sdc") return HandleSetLogLevelCommand("critical", true); else if (s == "crash") { LogTime(MUSCLE_LOG_CRITICALERROR, "Forcing this process to crash, ka-BOOM!\n"); Crash(); } else if (s == "print build flags") { printf("This executable was compiled using MUSCLE version %s.\n", MUSCLE_VERSION_STRING); PrintBuildFlags(); } else if (s == "print stack trace") PrintStackTrace(); else return false; return true; } }; // end namespace zg
37.854167
204
0.63126
ruurdadema
896c8a9c52fd105ca3e9bedb6ba6d4d91bf8fd79
3,629
cpp
C++
src/persistent_json_storage.cpp
aahmed-2/telemetry
7e098e93ef0974739459d296f99ddfab54722c23
[ "Apache-2.0" ]
4
2019-11-14T10:41:34.000Z
2021-12-09T23:54:52.000Z
src/persistent_json_storage.cpp
aahmed-2/telemetry
7e098e93ef0974739459d296f99ddfab54722c23
[ "Apache-2.0" ]
2
2021-10-04T20:12:53.000Z
2021-12-14T18:13:03.000Z
src/persistent_json_storage.cpp
aahmed-2/telemetry
7e098e93ef0974739459d296f99ddfab54722c23
[ "Apache-2.0" ]
2
2021-09-28T06:45:53.000Z
2021-12-13T15:30:33.000Z
#include "persistent_json_storage.hpp" #include <phosphor-logging/log.hpp> #include <fstream> #include <stdexcept> PersistentJsonStorage::PersistentJsonStorage(const DirectoryPath& directory) : directory(directory) {} void PersistentJsonStorage::store(const FilePath& filePath, const nlohmann::json& data) { try { const auto path = join(directory, filePath); std::error_code ec; phosphor::logging::log<phosphor::logging::level::DEBUG>( "Store to file", phosphor::logging::entry("PATH=%s", path.c_str())); std::filesystem::create_directories(path.parent_path(), ec); if (ec) { throw std::runtime_error( "Unable to create directory for file: " + path.string() + ", ec=" + std::to_string(ec.value()) + ": " + ec.message()); } std::ofstream file(path); file << data; if (!file) { throw std::runtime_error("Unable to create file: " + path.string()); } limitPermissions(path.parent_path()); limitPermissions(path); } catch (...) { remove(filePath); throw; } } bool PersistentJsonStorage::remove(const FilePath& filePath) { const auto path = join(directory, filePath); std::error_code ec; auto removed = std::filesystem::remove(path, ec); if (!removed) { phosphor::logging::log<phosphor::logging::level::ERR>( "Unable to remove file", phosphor::logging::entry("PATH=%s", path.c_str()), phosphor::logging::entry("ERROR_CODE=%d", ec.value())); return false; } /* removes directory only if it is empty */ std::filesystem::remove(path.parent_path(), ec); return true; } std::optional<nlohmann::json> PersistentJsonStorage::load(const FilePath& filePath) const { const auto path = join(directory, filePath); if (!std::filesystem::exists(path)) { return std::nullopt; } nlohmann::json result; try { std::ifstream file(path); file >> result; } catch (const std::exception& e) { phosphor::logging::log<phosphor::logging::level::ERR>(e.what()); return std::nullopt; } return result; } std::vector<interfaces::JsonStorage::FilePath> PersistentJsonStorage::list() const { std::vector<interfaces::JsonStorage::FilePath> result; if (!std::filesystem::exists(directory)) { return result; } for (const auto& p : std::filesystem::recursive_directory_iterator(directory)) { if (p.is_regular_file()) { auto item = std::filesystem::relative(p.path(), directory); result.emplace_back(std::move(item)); } } return result; } std::filesystem::path PersistentJsonStorage::join(const std::filesystem::path& left, const std::filesystem::path& right) { return left / right; } void PersistentJsonStorage::limitPermissions(const std::filesystem::path& path) { constexpr auto filePerms = std::filesystem::perms::owner_read | std::filesystem::perms::owner_write; constexpr auto dirPerms = filePerms | std::filesystem::perms::owner_exec; std::filesystem::permissions( path, std::filesystem::is_directory(path) ? dirPerms : filePerms, std::filesystem::perm_options::replace); } bool PersistentJsonStorage::exist(const FilePath& subPath) const { return std::filesystem::exists(join(directory, subPath)); }
26.489051
80
0.603472
aahmed-2
896fd44db6b257ce9fbf86c1c25786090d3cbbad
298
cpp
C++
Disruptor.Tests/SleepingWaitStrategyTests.cpp
GregGodin/Disruptor-cpp
aa06c37b94dfae3b9859bfbeaf1cd66ea27fac6b
[ "Apache-2.0" ]
4
2019-07-22T04:04:00.000Z
2022-01-18T11:25:48.000Z
Disruptor.Tests/SleepingWaitStrategyTests.cpp
GregGodin/Disruptor-cpp
aa06c37b94dfae3b9859bfbeaf1cd66ea27fac6b
[ "Apache-2.0" ]
null
null
null
Disruptor.Tests/SleepingWaitStrategyTests.cpp
GregGodin/Disruptor-cpp
aa06c37b94dfae3b9859bfbeaf1cd66ea27fac6b
[ "Apache-2.0" ]
2
2019-07-25T13:03:16.000Z
2019-10-25T06:23:15.000Z
#include "stdafx.h" #include "Disruptor/SleepingWaitStrategy.h" #include "WaitStrategyTestUtil.h" using namespace Disruptor; using namespace Disruptor::Tests; TEST(ShouldWaitForValue, SleepingWaitStrategyTests) { assertWaitForWithDelayOf(50, std::make_shared< SleepingWaitStrategy >()); }
19.866667
77
0.795302
GregGodin
8970f34deb48f288806cc3abca4be81f6e3b68fb
1,144
hpp
C++
libraries/plugins/rc/include/bears/plugins/rc/resource_count.hpp
nnnarvaez/bears
f446e2aa2865baf6623cb90d39efb760c224a404
[ "MIT" ]
null
null
null
libraries/plugins/rc/include/bears/plugins/rc/resource_count.hpp
nnnarvaez/bears
f446e2aa2865baf6623cb90d39efb760c224a404
[ "MIT" ]
null
null
null
libraries/plugins/rc/include/bears/plugins/rc/resource_count.hpp
nnnarvaez/bears
f446e2aa2865baf6623cb90d39efb760c224a404
[ "MIT" ]
2
2020-08-16T05:32:03.000Z
2022-01-11T00:18:11.000Z
#pragma once #include <bears/protocol/types.hpp> #include <fc/int_array.hpp> #include <fc/reflect/reflect.hpp> #include <vector> #define BEARS_NUM_RESOURCE_TYPES 5 namespace bears { namespace protocol { struct signed_transaction; } } // bears::protocol namespace bears { namespace plugins { namespace rc { enum rc_resource_types { resource_history_bytes, resource_new_accounts, resource_market_bytes, resource_state_bytes, resource_execution_time }; typedef fc::int_array< int64_t, BEARS_NUM_RESOURCE_TYPES > resource_count_type; struct count_resources_result { resource_count_type resource_count; }; void count_resources( const bears::protocol::signed_transaction& tx, count_resources_result& result ); } } } // bears::plugins::rc FC_REFLECT_ENUM( bears::plugins::rc::rc_resource_types, (resource_history_bytes) (resource_new_accounts) (resource_market_bytes) (resource_state_bytes) (resource_execution_time) ) FC_REFLECT( bears::plugins::rc::count_resources_result, (resource_count) ) FC_REFLECT_TYPENAME( bears::plugins::rc::resource_count_type )
22
79
0.750874
nnnarvaez
8971fdd08184492b846eb1cd9abcfc423d6eda06
995
hpp
C++
include/netlib/ssl_context.hpp
axilmar/netlib
ab1ad27bd8adaffbcb4c481b7972324202c8882e
[ "Apache-2.0" ]
null
null
null
include/netlib/ssl_context.hpp
axilmar/netlib
ab1ad27bd8adaffbcb4c481b7972324202c8882e
[ "Apache-2.0" ]
null
null
null
include/netlib/ssl_context.hpp
axilmar/netlib
ab1ad27bd8adaffbcb4c481b7972324202c8882e
[ "Apache-2.0" ]
null
null
null
#ifndef NETLIB_SSL_CONTEXT_HPP #define NETLIB_SSL_CONTEXT_HPP #include <memory> struct ssl_ctx_st; namespace netlib::ssl { /** * Base class for SSL contexts. */ class context { public: /** * The destructor. * Virtual due to inheritance. */ virtual ~context() { } /** * Returns the pointer to the SSL context. */ const std::shared_ptr<ssl_ctx_st>& ctx() const { return m_ctx; } protected: /** * Constructor. * @param ctx context. * @param certificate_file certificate file. * @param key_file key file. * @exception ssl_error thrown if there was an error. */ context(const std::shared_ptr<ssl_ctx_st>& ctx, const char* certificate_file, const char* key_file); private: std::shared_ptr<ssl_ctx_st> m_ctx; }; } //namespace netlib::ssl #endif //NETLIB_SSL_CONTEXT_HPP
19.134615
108
0.567839
axilmar
8974deb354205fb9beb5f1e9c092280b1802e545
3,240
hpp
C++
include/Application.hpp
jimmiebergmann/Space
ab65113a5fd026128efbd94eaba8ab9940d5668d
[ "Zlib" ]
null
null
null
include/Application.hpp
jimmiebergmann/Space
ab65113a5fd026128efbd94eaba8ab9940d5668d
[ "Zlib" ]
null
null
null
include/Application.hpp
jimmiebergmann/Space
ab65113a5fd026128efbd94eaba8ab9940d5668d
[ "Zlib" ]
null
null
null
// Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com // // This software is provided 'as-is', without any express or // implied warranty. In no event will the authors be held // liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute // it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but // is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any // source distribution. // /////////////////////////////////////////////////////////////////////////// #pragma once #include <Bit/Build.hpp> #include <Bit/Window/RenderWindow.hpp> #include <Renderer.hpp> #include <Space.hpp> #include <InputController.hpp> #include <vector> namespace Game { //////////////////////////////////////////////////////////////// /// \brief Application class. /// //////////////////////////////////////////////////////////////// class BIT_API Application { public: //////////////////////////////////////////////////////////////// /// \brief Default constructor /// //////////////////////////////////////////////////////////////// Application(); //////////////////////////////////////////////////////////////// /// \brief Run the application(game). /// //////////////////////////////////////////////////////////////// int Run(const int p_Argc, char ** p_Argv); private: // Private functions //////////////////////////////////////////////////////////////// /// \brief Load the application. /// //////////////////////////////////////////////////////////////// Bit::Bool Load(const int p_Argc, char ** p_Argv); //////////////////////////////////////////////////////////////// /// \brief Unload the application. /// //////////////////////////////////////////////////////////////// Bit::Bool Unload(); //////////////////////////////////////////////////////////////// /// \brief Render to the applicaiton window. /// //////////////////////////////////////////////////////////////// void Render(); //////////////////////////////////////////////////////////////// /// \brief Handle window inputs. /// //////////////////////////////////////////////////////////////// void HandleInputs(const Bit::Event & p_Event); //////////////////////////////////////////////////////////////// /// \brief Send event to all input controllers /// //////////////////////////////////////////////////////////////// void CallAllInputControllers(const Bit::Event & p_Event); // Private typedefs typedef std::vector<InputController *> InputControllerVector; // Private varaibles Bit::RenderWindow * m_pRenderWindow; Renderer * m_pRenderer; InputControllerVector m_InputControllers; Space * m_pSpace; }; }
32.079208
78
0.454321
jimmiebergmann
8978eae69d112724a260a249ff6322045bdcf17a
518
hpp
C++
include/raptor/file_size.hpp
kiron1/raptor
578c08a1ad475ee1210fedd74af12ce88d7d5c69
[ "BSL-1.0" ]
null
null
null
include/raptor/file_size.hpp
kiron1/raptor
578c08a1ad475ee1210fedd74af12ce88d7d5c69
[ "BSL-1.0" ]
null
null
null
include/raptor/file_size.hpp
kiron1/raptor
578c08a1ad475ee1210fedd74af12ce88d7d5c69
[ "BSL-1.0" ]
null
null
null
//============================================================================= // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================= #ifndef RAPTOR_UTILITY_FILE_SIZE_HPP_INCLUDED #define RAPTOR_UTILITY_FILE_SIZE_HPP_INCLUDED #include <istream> namespace raptor { std::istream::pos_type file_size ( std::istream& file ); } #endif
25.9
79
0.53861
kiron1
897a0c50f850d561242800b7874ab090af06b58d
352
cc
C++
kattis/falling.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
kattis/falling.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
kattis/falling.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://open.kattis.com/problems/falling #include<bits/stdc++.h> using namespace std; using ll=long long; int main(){ ios::sync_with_stdio(0); cin.tie(0); ll d; cin>>d; for(ll i=0;(i+1)*(i+1)-i*i<=d;i++){ ll n2=d+i*i; ll n=sqrt(n2); if(n*n==n2){ cout<<i<<" "<<n<<"\n"; return 0; } } cout<<"impossible\n"; }
17.6
43
0.53125
Ashindustry007
897b04a434c890d2e0ed6b57e17d0229fdc8bcb8
1,779
hpp
C++
include/jsgrep/functional/filter.hpp
amireh/jsq
270273e6a57615a53671fac97b22c321b167d74b
[ "MIT" ]
2
2019-07-29T01:31:35.000Z
2020-06-18T07:23:03.000Z
include/jsgrep/functional/filter.hpp
amireh/jsgrep
270273e6a57615a53671fac97b22c321b167d74b
[ "MIT" ]
1
2017-08-06T09:44:14.000Z
2017-08-06T09:44:14.000Z
include/jsgrep/functional/filter.hpp
amireh/jsgrep
270273e6a57615a53671fac97b22c321b167d74b
[ "MIT" ]
null
null
null
#ifndef H_JSGREP_FUNCTIONAL_FILTER_H #define H_JSGREP_FUNCTIONAL_FILTER_H #include "jsgrep/types.hpp" #include <algorithm> #include <vector> #include <math.h> #include <fnmatch.h> namespace jsgrep { namespace functional { using std::vector; typedef vector<string_t> patterns_t; static bool matches(const string_t& pattern, const string_t &string) { return 0 == fnmatch(pattern.c_str(), string.c_str(), 0); } static bool matches_any(const patterns_t& patterns, const string_t& string) { for (const auto pattern : patterns) { if (matches(pattern, string)) { return true; } } return false; } static const vector<string_t> EXCLUDE_NONE; static const vector<string_t> INCLUDE_ALL({ "*" }); static const vector<string_t> INCLUDE_JS_FILES({ "*.js", "*.jsx" }); static vector<string_t> filter( vector<string_t> const &files, vector<string_t> const &file_includes = INCLUDE_ALL, vector<string_t> const &file_excludes = EXCLUDE_NONE, vector<string_t> const &dir_excludes = EXCLUDE_NONE ) { vector<string_t> fnmatch_dir_excludes; for (const auto pattern : dir_excludes) { fnmatch_dir_excludes.push_back("*" + string_t(pattern) + "/*"); } vector<string_t> included_files; std::copy_if( files.begin(), files.end(), std::back_inserter(included_files), [&](const string_t &file) { return ( !matches_any(file_excludes, file) && !matches_any(fnmatch_dir_excludes, file) && matches_any(file_includes, file) ); } ); return included_files; } } // end of namespace functional } // end of namespace jsgrep #endif
26.552239
81
0.634064
amireh
897d673f9029b41b21688fa47a7af2dd45a7800e
274
cpp
C++
Part1/Examples/First.cpp
praseedpai/CPPForClubHouse
20e721081a4c370fd1136ae811d9ee0c231ad49c
[ "MIT" ]
6
2021-08-01T07:00:35.000Z
2021-09-09T15:32:51.000Z
Part1/Examples/First.cpp
praseedpai/CPPForClubHouse
20e721081a4c370fd1136ae811d9ee0c231ad49c
[ "MIT" ]
null
null
null
Part1/Examples/First.cpp
praseedpai/CPPForClubHouse
20e721081a4c370fd1136ae811d9ee0c231ad49c
[ "MIT" ]
null
null
null
#include <stdio.h> //---- argc => argument count //---- argv => argument vector // int main( int argc , char **argv ) // int main ( int argc, char *argv[] ) // int main ( int argc, char argv[][] ) int main( int argc, char **argv ) { printf("Hello World....\n"); }
21.076923
41
0.558394
praseedpai
897e25aa6451cced54651b4bc3b41741516f8f35
764
cpp
C++
Letter Combinations of a Phone Number.cpp
dishanp/Coding-In-C-and-C-
889985ac136826cf9be88d6c5455f79fd805a069
[ "BSD-2-Clause" ]
2
2021-10-01T04:20:04.000Z
2021-10-01T04:20:06.000Z
Letter Combinations of a Phone Number.cpp
dishanp/Coding-In-C-and-C-
889985ac136826cf9be88d6c5455f79fd805a069
[ "BSD-2-Clause" ]
null
null
null
Letter Combinations of a Phone Number.cpp
dishanp/Coding-In-C-and-C-
889985ac136826cf9be88d6c5455f79fd805a069
[ "BSD-2-Clause" ]
8
2021-10-01T04:20:38.000Z
2022-03-19T17:05:05.000Z
class Solution { public: void util(vector<string>&res,vector<string>dic,string digits,int ind,string output){ if(ind==digits.size()) { res.push_back(output); return; } int no=digits[ind]-'0'; string temp=dic[no]; for(int i=0;i<temp.size();i++){ output.push_back(temp[i]); util(res,dic,digits,ind+1,output); output.pop_back(); } } vector<string> letterCombinations(string digits) { vector<string>res; if(digits.size()==0) return res; vector<string>dic={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; int ind=0; util(res,dic,digits,ind,""); return res; } };
28.296296
88
0.509162
dishanp
8980722dfdff57ad03a343ab0609c9a17f4ce2dc
1,027
cpp
C++
SPOJ/OFFSIDE(Simple math).cpp
abusomani/DS-Algo
b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba
[ "Unlicense" ]
null
null
null
SPOJ/OFFSIDE(Simple math).cpp
abusomani/DS-Algo
b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba
[ "Unlicense" ]
null
null
null
SPOJ/OFFSIDE(Simple math).cpp
abusomani/DS-Algo
b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba
[ "Unlicense" ]
null
null
null
//Sometimes I feel like giving up, then I remember I have a lot of motherfuckers to prove wrong! //@BEGIN OF SOURCE CODE ( By Abhishek Somani) #include <bits/stdc++.h> using namespace std; #define fastio \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0) typedef long long ll; const ll MOD = 1000000007; int main() { fastio; //freopen('input.txt','r',stdin); //freopen('output.txt','w',stdout); ll N, M, x; while (cin >> N >> M, N, M) { ll minA = MOD, minB = MOD, minC = MOD; for (int i = 0; i < N; i++) cin >> x, minA = min(minA, x); for (int i = 0; i < M; i++) { cin >> x; if (x < minB) minC = minB, minB = x; else if (x >= minB and x <= minC) minC = x; } if (minA < minB or minA < minC) cout << "Y" << endl; else cout << "N" << endl; } return 0; } // END OF SOURCE CODE
24.452381
96
0.463486
abusomani
89832f49b59bc0b3f7303f5759009df3708cfffa
1,072
hpp
C++
src/ctti/attr/base.hpp
PiotrMoscicki/s4_rtti
8d22f42f84eb0a831b2472349d2d97b4cb351e07
[ "MIT" ]
null
null
null
src/ctti/attr/base.hpp
PiotrMoscicki/s4_rtti
8d22f42f84eb0a831b2472349d2d97b4cb351e07
[ "MIT" ]
3
2021-12-18T16:50:24.000Z
2021-12-18T16:53:54.000Z
src/ctti/attr/base.hpp
PiotrMoscicki/s4_rtti
8d22f42f84eb0a831b2472349d2d97b4cb351e07
[ "MIT" ]
null
null
null
#pragma once #include "ctti.hpp" namespace ctti::attr { //********************************************************************************************* //********************************************************************************************* //********************************************************************************************* template<typename... Bases> class Base { public: constexpr size_t size() const { return sizeof...(Bases); } template <typename T> constexpr bool has() const { return false; } // @todo implement get for templates template <size_t idx = 0> constexpr auto get() const { return get_base_at<idx, Bases...>(); } private: template <size_t idx, typename T, typename... Args> constexpr auto get_base_at() const { if constexpr (idx == 0) return ctti::constecpr_type<T>(); else return get_base_at<Args...>(idx - 1); } }; // class Base } // namespace ctti::attr
30.628571
99
0.399254
PiotrMoscicki
89860072375b7ceb0805c08295930cbbea3aee7d
391
cpp
C++
question_solution/first_time/1036.cpp
xiaoland/CaiojSolution
a12c505235d70b414071ea894fa72cddbcfabc6d
[ "Apache-2.0" ]
1
2020-09-24T13:35:45.000Z
2020-09-24T13:35:45.000Z
question_solution/first_time/1036.cpp
xiaoland/CaiojSolution
a12c505235d70b414071ea894fa72cddbcfabc6d
[ "Apache-2.0" ]
null
null
null
question_solution/first_time/1036.cpp
xiaoland/CaiojSolution
a12c505235d70b414071ea894fa72cddbcfabc6d
[ "Apache-2.0" ]
null
null
null
#include <cstdio> int n, s; void dg(int a, int b, int c) { if(c >= n) { s++; return ; } // ATTENTION: use if! not else if! if (a > 0 && b < n) { dg(a-1, b+1, c); } if (b > 0 && c < n) { dg(a, b-1, c+1); } } int main() { scanf("%d", &n); s = 0; dg(n, 0, 0); printf("%d", s); return 0; }
13.482759
61
0.337596
xiaoland
898d1f2365821689c0ec9c60d958e3e96d98c21c
392
cpp
C++
cse419/LightOJ/1045/22419752_AC_0ms_0kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
2
2020-09-02T12:07:47.000Z
2020-11-17T11:17:16.000Z
cse419/LightOJ/1045/22419752_AC_0ms_0kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
null
null
null
cse419/LightOJ/1045/22419752_AC_0ms_0kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
4
2020-08-11T14:23:34.000Z
2020-11-17T10:52:31.000Z
#include <bits/stdc++.h> #define le 1000006 using namespace std; double n[le]; void fnc(){ n[0] = 0.0; for(int i = 1; i < le; i++){ n[i] = n[i - 1] + log10(i * 1.0); } } int main(){ fnc(); int t, co = 0, a, b; for(scanf("%d", &t); t--; ){ scanf("%d %d", &a, &b); double ans = n[a] / log10(b * 1.0); printf("Case %d: %lld\n", ++co, (int)ans + 1); } return 0; }
18.666667
50
0.464286
cosmicray001
89907c78d897e9941164f7d276c05d0f491e3d65
8,205
cpp
C++
ewsclient/ewsid.cpp
KrissN/akonadi-ews
05ce7e24547fbdb559de55dabda86d337716cfba
[ "RSA-MD" ]
122
2016-03-01T12:53:43.000Z
2021-11-06T21:14:21.000Z
ewsclient/ewsid.cpp
KrissN/akonadi-ews
05ce7e24547fbdb559de55dabda86d337716cfba
[ "RSA-MD" ]
54
2016-05-02T10:05:47.000Z
2022-02-01T18:10:38.000Z
ewsclient/ewsid.cpp
KrissN/akonadi-ews
05ce7e24547fbdb559de55dabda86d337716cfba
[ "RSA-MD" ]
17
2016-05-18T21:02:08.000Z
2022-01-27T20:33:26.000Z
/* This file is part of Akonadi EWS Resource Copyright (C) 2015-2017 Krzysztof Nowicki <krissn@op.pl> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "ewsid.h" #include <QString> #include <QXmlStreamReader> #include <QXmlStreamWriter> #include <QDebug> #include "ewsclient.h" #include "ewsclient_debug.h" static const QString distinguishedIdNames[] = { QStringLiteral("calendar"), QStringLiteral("contacts"), QStringLiteral("deleteditems"), QStringLiteral("drafts"), QStringLiteral("inbox"), QStringLiteral("journal"), QStringLiteral("notes"), QStringLiteral("outbox"), QStringLiteral("sentitems"), QStringLiteral("tasks"), QStringLiteral("msgfolderroot"), QStringLiteral("root"), QStringLiteral("junkemail"), QStringLiteral("searchfolders"), QStringLiteral("voicemail"), QStringLiteral("recoverableitemsroot"), QStringLiteral("recoverableitemsdeletions"), QStringLiteral("recoverableitemsversions"), QStringLiteral("recoverableitemspurges"), QStringLiteral("archiveroot"), QStringLiteral("archivemsgfolderroot"), QStringLiteral("archivedeleteditems"), QStringLiteral("archiverecoverableitemsroot"), QStringLiteral("archiverecoverableitemsdeletions"), QStringLiteral("archiverecoverableitemsversions"), QStringLiteral("archiverecoverableitemspurges") }; class EwsIdComparatorRegistrar { public: EwsIdComparatorRegistrar() { QMetaType::registerComparators<EwsId>(); }; }; const EwsIdComparatorRegistrar ewsIdComparatorRegistrar; /* * Current Akonadi mail filter agent determines which folders to filter for incoming mail by * checking if their remote ID is "INBOX". This is very IMAP-centric and obviously will not work * with EWS, which uses Base64 folder identifiers. * Until Akonadi is fixed pretend that the remote identifier for the inbox folder is "INBOX" and * hide the real identifier in a global variable. */ #ifdef HAVE_INBOX_FILTERING_WORKAROUND static QString inboxId; #endif EwsId::EwsId(QXmlStreamReader &reader) : mDid(EwsDIdCalendar) { // Don't check for this element's name as a folder id may be contained in several elements // such as "FolderId" or "ParentFolderId". const QXmlStreamAttributes &attrs = reader.attributes(); QStringRef idRef = attrs.value(QStringLiteral("Id")); QStringRef changeKeyRef = attrs.value(QStringLiteral("ChangeKey")); if (idRef.isNull()) return; mId = idRef.toString(); if (!changeKeyRef.isNull()) mChangeKey = changeKeyRef.toString(); #ifdef HAVE_INBOX_FILTERING_WORKAROUND if (mId == inboxId) { mId = QStringLiteral("INBOX"); } #endif mType = Real; } EwsId::EwsId(QString id, QString changeKey) : mType(Real), mId(id), mChangeKey(changeKey), mDid(EwsDIdCalendar) { #ifdef HAVE_INBOX_FILTERING_WORKAROUND if (mId == inboxId) { mId = QStringLiteral("INBOX"); } #endif } EwsId& EwsId::operator=(const EwsId &other) { mType = other.mType; if (mType == Distinguished) { mDid = other.mDid; } else if (mType == Real) { mId = other.mId; mChangeKey = other.mChangeKey; } return *this; } EwsId& EwsId::operator=(EwsId &&other) { mType = other.mType; if (mType == Distinguished) { mDid = other.mDid; } else if (mType == Real) { mId = std::move(other.mId); mChangeKey = std::move(other.mChangeKey); } return *this; } bool EwsId::operator==(const EwsId &other) const { if (mType != other.mType) return false; if (mType == Distinguished) { return (mDid == other.mDid); } else if (mType == Real) { return (mId == other.mId && mChangeKey == other.mChangeKey); } return true; } bool EwsId::operator<(const EwsId &other) const { if (mType != other.mType) return mType < other.mType; if (mType == Distinguished) { return (mDid < other.mDid); } else if (mType == Real) { return (mId < other.mId && mChangeKey < other.mChangeKey); } return false; } void EwsId::writeFolderIds(QXmlStreamWriter &writer) const { if (mType == Distinguished) { writer.writeStartElement(ewsTypeNsUri, QStringLiteral("DistinguishedFolderId")); writer.writeAttribute(QStringLiteral("Id"), distinguishedIdNames[mDid]); writer.writeEndElement(); } else if (mType == Real) { #ifdef HAVE_INBOX_FILTERING_WORKAROUND if (mId == QStringLiteral("INBOX")) { if (inboxId.isEmpty()) { writer.writeStartElement(ewsTypeNsUri, QStringLiteral("DistinguishedFolderId")); writer.writeAttribute(QStringLiteral("Id"), distinguishedIdNames[EwsDIdInbox]); } else { writer.writeStartElement(ewsTypeNsUri, QStringLiteral("FolderId")); writer.writeAttribute(QStringLiteral("Id"), inboxId); } } else { writer.writeStartElement(ewsTypeNsUri, QStringLiteral("FolderId")); writer.writeAttribute(QStringLiteral("Id"), mId); } #else writer.writeStartElement(ewsTypeNsUri, QStringLiteral("FolderId")); writer.writeAttribute(QStringLiteral("Id"), mId); #endif if (!mChangeKey.isEmpty()) { writer.writeAttribute(QStringLiteral("ChangeKey"), mChangeKey); } writer.writeEndElement(); } } void EwsId::writeItemIds(QXmlStreamWriter &writer) const { if (mType == Real) { writer.writeStartElement(ewsTypeNsUri, QStringLiteral("ItemId")); #ifdef HAVE_INBOX_FILTERING_WORKAROUND if (mId == QStringLiteral("INBOX")) { writer.writeAttribute(QStringLiteral("Id"), inboxId); } else { writer.writeAttribute(QStringLiteral("Id"), mId); } #else writer.writeAttribute(QStringLiteral("Id"), mId); #endif if (!mChangeKey.isEmpty()) { writer.writeAttribute(QStringLiteral("ChangeKey"), mChangeKey); } writer.writeEndElement(); } } void EwsId::writeAttributes(QXmlStreamWriter &writer) const { if (mType == Real) { #ifdef HAVE_INBOX_FILTERING_WORKAROUND if (mId == QStringLiteral("INBOX")) { writer.writeAttribute(QStringLiteral("Id"), inboxId); } else { writer.writeAttribute(QStringLiteral("Id"), mId); } #else writer.writeAttribute(QStringLiteral("Id"), mId); #endif if (!mChangeKey.isEmpty()) { writer.writeAttribute(QStringLiteral("ChangeKey"), mChangeKey); } } } QDebug operator<<(QDebug debug, const EwsId &id) { QDebugStateSaver saver(debug); QDebug d = debug.nospace().noquote(); d << QStringLiteral("EwsId("); switch (id.mType) { case EwsId::Distinguished: d << QStringLiteral("Distinguished: ") << distinguishedIdNames[id.mDid]; break; case EwsId::Real: { QString name = EwsClient::folderHash.value(id.mId, ewsHash(id.mId)); d << name << QStringLiteral(", ") << ewsHash(id.mChangeKey); break; } default: break; } d << ')'; return debug; } uint qHash(const EwsId &id, uint seed) { return qHash(id.id(), seed) ^ qHash(id.changeKey(), seed) ^ static_cast<uint>(id.type()); } #ifdef HAVE_INBOX_FILTERING_WORKAROUND void EwsId::setInboxId(EwsId id) { if (inboxId.isEmpty()) { inboxId = id.mId; } } #endif
29.945255
96
0.66362
KrissN
8990d6e45644bf48b8217099b86f8e58795e99d2
395
cpp
C++
C++/20-kth-root.cpp
ni30kp/sorting-algorithms
5d7a87bb377aad387980b71f97c2c80035a37152
[ "MIT" ]
null
null
null
C++/20-kth-root.cpp
ni30kp/sorting-algorithms
5d7a87bb377aad387980b71f97c2c80035a37152
[ "MIT" ]
null
null
null
C++/20-kth-root.cpp
ni30kp/sorting-algorithms
5d7a87bb377aad387980b71f97c2c80035a37152
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long int void binary_search_root(ll n, ll k){ // mid^k = n ll s = 0, e = n, mid, ans; while(s<=e){ mid = (s+e)/2; if(pow(mid,k)<=n){ ans = mid; s = mid + 1; }else e = mid - 1; } cout<<ans<<endl; } int main(){ ll t, a, b; cin>>t; while(t--){ cin>>a>>b; binary_search_root(a,b); } return 0; } /* */
11.285714
36
0.518987
ni30kp
89a3ff6cc4407c6d27a5f041c30f407aa319adb9
1,719
cpp
C++
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch10/Exercise10.32.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch10/Exercise10.32.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch10/Exercise10.32.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
// Exercise10.32.cpp // Ad // Rewrite the bookstore program from p.24 using a vector to hold the transactions and various algorithms to do the processing. // Use sort with your compareIsbn function to arrange the transactions in order, and then use find and accumulate to do the sum. #include <iostream> #include <vector> #include <string> #include <algorithm> #include <numeric> #include <iterator> // class ----------------------------------------------------------------------- class Sales_data { public: Sales_data() = default; Sales_data(std::string s) : bookNum(s) {} std::string isbn() const { return bookNum; } private: std::string bookNum; }; // function -------------------------------------------------------------------- bool compareIsbn(const Sales_data &dat1, const Sales_data &dat2) { return dat1.isbn() < dat2.isbn(); } // ----------------------------------------------------------------------------- int main(int argc, char *argv[]) { // note that without operator overloading this program does not work std::istream_iterator<Sales_data> inIter{std::cin}, eof; std::vector<Sales_data> svec{inIter, eof}; std::sort(svec.begin(), svec.end(), compareIsbn); std::ostream_iterator<Sales_data> outIter{std::cout, "\n"}; auto iter0{svec.begin()}, iter1{svec.begin()}; while (iter1 != svec.end()) { iter1 = std::find_if(svec.begin(), svec.end(), [&iter1](const Sales_data &d) { return d.isbn() != iter1->isbn(); }); std::accumulate(iter0, iter1, outIter); iter0 = iter1; } // pause system("pause"); return 0; }
28.65
128
0.542176
alaxion
89a4db47365eebe3db864a7b8c50ce47208a8f33
870
hpp
C++
src/include/Snake.hpp
iluvpy/Minigames
f04dc78a24368f9a6021f02584c1989204ba10b6
[ "MIT" ]
null
null
null
src/include/Snake.hpp
iluvpy/Minigames
f04dc78a24368f9a6021f02584c1989204ba10b6
[ "MIT" ]
null
null
null
src/include/Snake.hpp
iluvpy/Minigames
f04dc78a24368f9a6021f02584c1989204ba10b6
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <utility> #include "Renderer.hpp" #include "Types.hpp" #include "Structs.hpp" #include "InputHandler.hpp" #define SNAKE_COLOR Color(0, 180, 40) #define SNAKE_MOVEMENT_INTERVAL 0.25f // snake moves 1 tile each INTERVAL seconds #define SNAKE_HEAD_COLOR Color(0, 250, 40) // forward declaration class SnakeGame; class Snake { public: Snake(); void Init(Renderer *renderer, InputHandler *kbHandler, uint length, int head_x, int head_y); void Draw() const; void Grow(SnakeGame *game); void AddSnakeToGame(SnakeGame *game); void Shrink(); void Update(); bool IsAlive() const; ~Snake(); private: Renderer *m_renderer; InputHandler *m_input; std::vector<Point> m_snakePositions; Direction2d m_direction; Clock_t m_lastMovementUpdate; uint m_length; bool m_isAlive; };
23.513514
96
0.709195
iluvpy
89abdc24be80eeaca63169b24912f9cf3bce8325
230
cpp
C++
ares/sfc/coprocessor/dip/dip.cpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
ares/sfc/coprocessor/dip/dip.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
ares/sfc/coprocessor/dip/dip.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
//DIP switch //used for Nintendo Super System emulation DIP dip; #include "serialization.cpp" auto DIP::power() -> void { } auto DIP::read(uint24, uint8) -> uint8 { return value; } auto DIP::write(uint24, uint8) -> void { }
14.375
42
0.669565
moon-chilled
89b24335a16ebc58f011abb418389508f322c614
8,116
cc
C++
tensorflow/lite/kernels/gradient/bcast_grad_args_test.cc
massimobernava/tensorflow
0a68ff9a205e14dd80fa0c51a0f6954d965f825e
[ "Apache-2.0" ]
1
2022-03-29T11:36:50.000Z
2022-03-29T11:36:50.000Z
tensorflow/lite/kernels/gradient/bcast_grad_args_test.cc
massimobernava/tensorflow
0a68ff9a205e14dd80fa0c51a0f6954d965f825e
[ "Apache-2.0" ]
1
2020-08-01T05:40:12.000Z
2020-08-01T05:40:12.000Z
tensorflow/lite/kernels/gradient/bcast_grad_args_test.cc
massimobernava/tensorflow
0a68ff9a205e14dd80fa0c51a0f6954d965f825e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/kernels/gradient/bcast_grad_args.h" #include <cstdint> #include <vector> #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/kernels/test_util.h" #include "tensorflow/lite/testing/util.h" namespace tflite { namespace ops { namespace custom { namespace { using testing::ElementsAreArray; class BcastGradArgsInt32OpModel : public SingleOpModel { public: BcastGradArgsInt32OpModel(const TensorData& input1, const TensorData& input2, const TensorData& output1, const TensorData& output2) { input1_ = AddInput(input1); input2_ = AddInput(input2); output1_ = AddOutput(output1); output2_ = AddOutput(output2); std::vector<uint8_t> custom_option; SetCustomOp("BroadcastGradientArgs", custom_option, Register_BROADCAST_GRADIENT_ARGS); BuildInterpreter({GetShape(input1_), GetShape(input2_)}); } void SetInput1(const std::vector<int>& data) { PopulateTensor(input1_, data); } void SetInput2(const std::vector<int>& data) { PopulateTensor(input2_, data); } std::vector<int> GetOutput1() { return ExtractVector<int>(output1_); } std::vector<int> GetOutput1Shape() { return GetTensorShape(output1_); } std::vector<int> GetOutput2() { return ExtractVector<int>(output2_); } std::vector<int> GetOutput2Shape() { return GetTensorShape(output2_); } protected: int input1_; int input2_; int output1_; int output2_; }; TEST(BcastGradArgsInt32OpModel, AllEqualsInt32DTypes) { BcastGradArgsInt32OpModel model( /*input1=*/{TensorType_INT32, {4}}, /*input2=*/{TensorType_INT32, {4}}, /*output1=*/{TensorType_INT32, {}}, /*output2=*/{TensorType_INT32, {}}); model.SetInput1({3, 1, 2, 3}); model.SetInput2({3, 1, 2, 3}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput1().size(), 0); EXPECT_THAT(model.GetOutput2().size(), 0); } TEST(BcastGradArgsInt32OpModel, BroadcastableDimAtInput1Int32DTypes) { BcastGradArgsInt32OpModel model( /*input1=*/{TensorType_INT32, {4}}, /*input2=*/{TensorType_INT32, {4}}, /*output1=*/{TensorType_INT32, {}}, /*output2=*/{TensorType_INT32, {}}); model.SetInput1({3, 4, 1, 3}); model.SetInput2({3, 4, 2, 3}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput1(), ElementsAreArray({2})); EXPECT_THAT(model.GetOutput2().size(), 0); } TEST(BcastGradArgsInt32OpModel, BroadcastableDimAtInput2Int32DTypes) { BcastGradArgsInt32OpModel model( /*input1=*/{TensorType_INT32, {4}}, /*input2=*/{TensorType_INT32, {4}}, /*output1=*/{TensorType_INT32, {}}, /*output2=*/{TensorType_INT32, {}}); model.SetInput1({3, 4, 2, 3}); model.SetInput2({3, 1, 2, 3}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput1().size(), 0); EXPECT_THAT(model.GetOutput2(), ElementsAreArray({1})); } TEST(BcastGradArgsInt32OpModel, DifferentInputSizesInt32DTypes) { BcastGradArgsInt32OpModel model( /*input1=*/{TensorType_INT32, {4}}, /*input2=*/{TensorType_INT32, {3}}, /*output1=*/{TensorType_INT32, {}}, /*output2=*/{TensorType_INT32, {}}); model.SetInput1({3, 4, 2, 3}); model.SetInput2({4, 2, 3}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput1().size(), 0); EXPECT_THAT(model.GetOutput2(), ElementsAreArray({0})); } TEST(BcastGradArgsInt32OpModel, NonBroadcastableDimsInt32DTypes) { BcastGradArgsInt32OpModel model( /*input1=*/{TensorType_INT32, {4}}, /*input2=*/{TensorType_INT32, {4}}, /*output1=*/{TensorType_INT32, {}}, /*output2=*/{TensorType_INT32, {}}); model.SetInput1({3, 4, 2, 3}); model.SetInput2({9, 9, 9, 9}); EXPECT_THAT(model.InvokeUnchecked(), kTfLiteError); } class BcastGradArgsInt64OpModel : public SingleOpModel { public: BcastGradArgsInt64OpModel(const TensorData& input1, const TensorData& input2, const TensorData& output1, const TensorData& output2) { input1_ = AddInput(input1); input2_ = AddInput(input2); output1_ = AddOutput(output1); output2_ = AddOutput(output2); std::vector<uint8_t> custom_option; SetCustomOp("BroadcastGradientArgs", custom_option, Register_BROADCAST_GRADIENT_ARGS); BuildInterpreter({GetShape(input1_), GetShape(input2_)}); } void SetInput1(const std::vector<int64_t>& data) { PopulateTensor(input1_, data); } void SetInput2(const std::vector<int64_t>& data) { PopulateTensor(input2_, data); } std::vector<int64_t> GetOutput1() { return ExtractVector<int64_t>(output1_); } std::vector<int> GetOutput1Shape() { return GetTensorShape(output1_); } std::vector<int64_t> GetOutput2() { return ExtractVector<int64_t>(output2_); } std::vector<int> GetOutput2Shape() { return GetTensorShape(output2_); } protected: int input1_; int input2_; int output1_; int output2_; }; TEST(BcastGradArgsInt32OpModel, AllEqualsInt64DTypes) { BcastGradArgsInt64OpModel model( /*input1=*/{TensorType_INT64, {4}}, /*input2=*/{TensorType_INT64, {4}}, /*output1=*/{TensorType_INT64, {}}, /*output2=*/{TensorType_INT64, {}}); model.SetInput1({3, 1, 2, 3}); model.SetInput2({3, 1, 2, 3}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput1().size(), 0); EXPECT_THAT(model.GetOutput2().size(), 0); } TEST(BcastGradArgsInt32OpModel, BroadcastableDimAtInput1Int64DTypes) { BcastGradArgsInt64OpModel model( /*input1=*/{TensorType_INT64, {4}}, /*input2=*/{TensorType_INT64, {4}}, /*output1=*/{TensorType_INT64, {}}, /*output2=*/{TensorType_INT64, {}}); model.SetInput1({3, 4, 1, 3}); model.SetInput2({3, 4, 2, 3}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput1(), ElementsAreArray({2})); EXPECT_THAT(model.GetOutput2().size(), 0); } TEST(BcastGradArgsInt32OpModel, BroadcastableDimAtInput2Int64DTypes) { BcastGradArgsInt64OpModel model( /*input1=*/{TensorType_INT64, {4}}, /*input2=*/{TensorType_INT64, {4}}, /*output1=*/{TensorType_INT64, {}}, /*output2=*/{TensorType_INT64, {}}); model.SetInput1({3, 4, 2, 3}); model.SetInput2({3, 1, 2, 3}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput1().size(), 0); EXPECT_THAT(model.GetOutput2(), ElementsAreArray({1})); } TEST(BcastGradArgsInt32OpModel, DifferentInputSizesInt64DTypes) { BcastGradArgsInt64OpModel model( /*input1=*/{TensorType_INT64, {4}}, /*input2=*/{TensorType_INT64, {3}}, /*output1=*/{TensorType_INT64, {}}, /*output2=*/{TensorType_INT64, {}}); model.SetInput1({3, 4, 2, 3}); model.SetInput2({4, 2, 3}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput1().size(), 0); EXPECT_THAT(model.GetOutput2(), ElementsAreArray({0})); } TEST(BcastGradArgsInt32OpModel, NonBroadcastableDimsInt64DTypes) { BcastGradArgsInt64OpModel model( /*input1=*/{TensorType_INT64, {4}}, /*input2=*/{TensorType_INT64, {4}}, /*output1=*/{TensorType_INT64, {}}, /*output2=*/{TensorType_INT64, {}}); model.SetInput1({3, 4, 2, 3}); model.SetInput2({9, 9, 9, 9}); EXPECT_THAT(model.InvokeUnchecked(), kTfLiteError); } } // namespace } // namespace custom } // namespace ops } // namespace tflite
33.676349
80
0.679276
massimobernava
89b24a1bbc3e38d0edbf9f39423e9c61bbecdfb1
5,661
cpp
C++
src/Core/Bindings/obe/System/Exceptions/Exceptions.cpp
BestEggplant/ObEngine
4543ff027cc05de0eddede8f55b28f0cf1138189
[ "MIT" ]
1
2020-07-23T14:23:59.000Z
2020-07-23T14:23:59.000Z
src/Core/Bindings/obe/System/Exceptions/Exceptions.cpp
BestEggplant/ObEngine
4543ff027cc05de0eddede8f55b28f0cf1138189
[ "MIT" ]
null
null
null
src/Core/Bindings/obe/System/Exceptions/Exceptions.cpp
BestEggplant/ObEngine
4543ff027cc05de0eddede8f55b28f0cf1138189
[ "MIT" ]
null
null
null
#include <Bindings/obe/System/Exceptions/Exceptions.hpp> #include <System/Exceptions.hpp> #include <Bindings/Config.hpp> namespace obe::System::Exceptions::Bindings { void LoadClassInvalidMouseButtonEnumValue(sol::state_view state) { sol::table ExceptionsNamespace = state["obe"]["System"]["Exceptions"].get<sol::table>(); sol::usertype<obe::System::Exceptions::InvalidMouseButtonEnumValue> bindInvalidMouseButtonEnumValue = ExceptionsNamespace.new_usertype< obe::System::Exceptions::InvalidMouseButtonEnumValue>( "InvalidMouseButtonEnumValue", sol::call_constructor, sol::constructors<obe::System::Exceptions::InvalidMouseButtonEnumValue( int, obe::DebugInfo)>(), sol::base_classes, sol::bases<obe::Exception>()); } void LoadClassMountablePathIndexOverflow(sol::state_view state) { sol::table ExceptionsNamespace = state["obe"]["System"]["Exceptions"].get<sol::table>(); sol::usertype<obe::System::Exceptions::MountablePathIndexOverflow> bindMountablePathIndexOverflow = ExceptionsNamespace.new_usertype< obe::System::Exceptions::MountablePathIndexOverflow>( "MountablePathIndexOverflow", sol::call_constructor, sol::constructors<obe::System::Exceptions::MountablePathIndexOverflow( std::size_t, std::size_t, const std::vector<std::string>&, obe::DebugInfo)>(), sol::base_classes, sol::bases<obe::Exception>()); } void LoadClassMountFileMissing(sol::state_view state) { sol::table ExceptionsNamespace = state["obe"]["System"]["Exceptions"].get<sol::table>(); sol::usertype<obe::System::Exceptions::MountFileMissing> bindMountFileMissing = ExceptionsNamespace.new_usertype<obe::System::Exceptions::MountFileMissing>( "MountFileMissing", sol::call_constructor, sol::constructors<obe::System::Exceptions::MountFileMissing( std::string_view, obe::DebugInfo)>(), sol::base_classes, sol::bases<obe::Exception>()); } void LoadClassPackageAlreadyInstalled(sol::state_view state) { sol::table ExceptionsNamespace = state["obe"]["System"]["Exceptions"].get<sol::table>(); sol::usertype<obe::System::Exceptions::PackageAlreadyInstalled> bindPackageAlreadyInstalled = ExceptionsNamespace .new_usertype<obe::System::Exceptions::PackageAlreadyInstalled>( "PackageAlreadyInstalled", sol::call_constructor, sol::constructors<obe::System::Exceptions::PackageAlreadyInstalled( std::string_view, obe::DebugInfo)>(), sol::base_classes, sol::bases<obe::Exception>()); } void LoadClassPackageFileNotFound(sol::state_view state) { sol::table ExceptionsNamespace = state["obe"]["System"]["Exceptions"].get<sol::table>(); sol::usertype<obe::System::Exceptions::PackageFileNotFound> bindPackageFileNotFound = ExceptionsNamespace .new_usertype<obe::System::Exceptions::PackageFileNotFound>( "PackageFileNotFound", sol::call_constructor, sol::constructors<obe::System::Exceptions::PackageFileNotFound( std::string_view, obe::DebugInfo)>(), sol::base_classes, sol::bases<obe::Exception>()); } void LoadClassResourceNotFound(sol::state_view state) { sol::table ExceptionsNamespace = state["obe"]["System"]["Exceptions"].get<sol::table>(); sol::usertype<obe::System::Exceptions::ResourceNotFound> bindResourceNotFound = ExceptionsNamespace.new_usertype<obe::System::Exceptions::ResourceNotFound>( "ResourceNotFound", sol::call_constructor, sol::constructors<obe::System::Exceptions::ResourceNotFound( std::string_view, std::vector<std::string>, obe::DebugInfo)>(), sol::base_classes, sol::bases<obe::Exception>()); } void LoadClassUnknownPackage(sol::state_view state) { sol::table ExceptionsNamespace = state["obe"]["System"]["Exceptions"].get<sol::table>(); sol::usertype<obe::System::Exceptions::UnknownPackage> bindUnknownPackage = ExceptionsNamespace.new_usertype<obe::System::Exceptions::UnknownPackage>( "UnknownPackage", sol::call_constructor, sol::constructors<obe::System::Exceptions::UnknownPackage( std::string_view, const std::vector<std::string>&, obe::DebugInfo)>(), sol::base_classes, sol::bases<obe::Exception>()); } void LoadClassUnknownWorkspace(sol::state_view state) { sol::table ExceptionsNamespace = state["obe"]["System"]["Exceptions"].get<sol::table>(); sol::usertype<obe::System::Exceptions::UnknownWorkspace> bindUnknownWorkspace = ExceptionsNamespace.new_usertype<obe::System::Exceptions::UnknownWorkspace>( "UnknownWorkspace", sol::call_constructor, sol::constructors<obe::System::Exceptions::UnknownWorkspace( std::string_view, const std::vector<std::string>&, obe::DebugInfo)>(), sol::base_classes, sol::bases<obe::Exception>()); } };
54.432692
91
0.615262
BestEggplant
89b43f11f561dfcbd669008fdd556a9a850a25b4
1,552
cpp
C++
src/chapter_06_algorithms_and_data_structures/problem_053_average_rating_of_movies.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
src/chapter_06_algorithms_and_data_structures/problem_053_average_rating_of_movies.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
src/chapter_06_algorithms_and_data_structures/problem_053_average_rating_of_movies.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
#include "chapter_06_algorithms_and_data_structures/problem_053_average_rating_of_movies.h" #include <algorithm> // sort #include <fmt/ostream.h> #include <iostream> // cout #include <numeric> // accumulate double average_rating(ratings rs) { if (rs.empty()) { return double{ 0.0 }; } std::sort(begin(rs), end(rs)); size_t ratings_to_remove{ static_cast<size_t>(rs.size() * 0.1 + 0.5) }; // removing a 10% instead of a 5% rs.erase(begin(rs), begin(rs) + ratings_to_remove); rs.erase(end(rs) - ratings_to_remove, end(rs)); return std::accumulate(begin(rs), end(rs), 0.0) / rs.size(); } void problem_53_main(std::ostream& os) { movie_ratings mr = { { "The Godfather", { 10, 8, 7, 9, 9, 9, 3, 10, 6 } }, { "The Godfather II", { 10, 9, 9, 8, 8, 10, 2, 4, 6 } }, { "The Godfather III", { 9, 7, 7, 8, 8, 9, 8, 4, 5 } } }; fmt::print(os, "Average rating of movies:\n"); for (const auto& m : mr) { fmt::print(os, "\t{}: {:.1f}\n", m.first, average_rating(m.second)); } fmt::print(os, "\n"); } // Average rating of movies // // Write a program that calculates and prints the average rating of a list of movies. // Each movie has a list of ratings from 1 to 10 (where 1 is the lowest and 10 is the highest rating). // In order to compute the rating, you must remove 5% of the highest and lowest ratings before computing their average. // The result must be displayed with a single decimal point. void problem_53_main() { problem_53_main(std::cout); }
32.333333
119
0.632732
rturrado
89b71d41119dd061bc200f3655c7d22d8acee956
3,928
cpp
C++
lib/malloy/controller.cpp
madmongo1/malloy
69e383d319d4d090888cab21b0c33e3c1499d8ab
[ "MIT" ]
null
null
null
lib/malloy/controller.cpp
madmongo1/malloy
69e383d319d4d090888cab21b0c33e3c1499d8ab
[ "MIT" ]
null
null
null
lib/malloy/controller.cpp
madmongo1/malloy
69e383d319d4d090888cab21b0c33e3c1499d8ab
[ "MIT" ]
null
null
null
#include "controller.hpp" #include "listener.hpp" #include "http/routing/router.hpp" #if MALLOY_FEATURE_TLS #include "tls/manager.hpp" #endif #include <boost/asio/io_context.hpp> #include <spdlog/logger.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <memory> using namespace malloy::server; controller::~controller() { stop().wait(); } bool controller::init(config cfg, std::shared_ptr<boost::asio::io_context> io_ctx) { // Don't re-initialize if (m_init_done) return false; m_init_done = true; // Create a logger if none was provided if (not cfg.logger) { auto log_level = spdlog::level::debug; // Sink auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); console_sink->set_level(log_level); // Create logger cfg.logger = std::make_shared<spdlog::logger>("", spdlog::sinks_init_list{ console_sink }); cfg.logger->set_level(log_level); } // Sanity check number of threads if (cfg.num_threads < 1) { cfg.logger->error("num_threads must be >= 1"); return false; } // Grab the config m_cfg = std::move(cfg); // Create the I/O context (if necessary) m_io_ctx = std::move(io_ctx); if (not m_io_ctx) m_io_ctx = std::make_shared<boost::asio::io_context>(); // Create the top-level router m_router = std::make_shared<malloy::http::server::router>(m_cfg.logger->clone("router")); return true; } #if MALLOY_FEATURE_TLS bool controller::init_tls( const std::filesystem::path& cert_path, const std::filesystem::path& key_path ) { // Sanity check cert if (not std::filesystem::is_regular_file(cert_path)) { m_cfg.logger->critical("could not create TLS context: invalid certificate file path: {}", cert_path.string()); return false; } // Sanity check key_path if (not std::filesystem::is_regular_file(key_path)) { m_cfg.logger->critical("could not create TLS context: invalid key file path: {}", key_path.string()); } // Create the context m_tls_ctx = tls::manager::make_context(cert_path, key_path); return true; } #endif bool controller::start() { // Must be initialized if (not m_init_done) return false; // Sanity check assert(m_io_ctx); // Create the listener m_listener = std::make_shared<malloy::server::listener>( m_cfg.logger->clone("listener"), *m_io_ctx, m_tls_ctx, boost::asio::ip::tcp::endpoint{ boost::asio::ip::make_address(m_cfg.interface), m_cfg.port }, m_router, std::make_shared<std::filesystem::path>(m_cfg.doc_root), m_websocket_handler ); // Run the listener m_listener->run(); // Create the I/O context threads m_threads.reserve(m_cfg.num_threads - 1); for (std::size_t i = 0; i < m_cfg.num_threads; i++) { m_threads.emplace_back( [this] { m_io_ctx->run(); } ); } // Log m_cfg.logger->info("starting server."); // Start the I/O context m_io_ctx->run(); return true; } std::future<void> controller::stop() { // Stop the `io_context`. This will cause `run()` // to return immediately, eventually destroying the // `io_context` and all of the sockets in it. m_io_ctx->stop(); // Wait for all I/O context threads to finish... return std::async( [this] { m_cfg.logger->info("waiting for I/O threads to stop..."); for (auto& thread : m_threads) thread.join(); m_cfg.logger->info("all I/O threads stopped."); } ); } void controller::set_websocket_handler(malloy::websocket::handler_type handler) { m_websocket_handler = std::move(handler); }
25.506494
122
0.611507
madmongo1
89d01d3a6aa8427dc534557bfa3afd70cb9a15a6
9,004
cpp
C++
src/student/archimedes/simulation.cpp
Tagglink/archimedes-principle
93a2ce101bc8f3ac2653da667887c8d36a6e86a7
[ "MIT" ]
null
null
null
src/student/archimedes/simulation.cpp
Tagglink/archimedes-principle
93a2ce101bc8f3ac2653da667887c8d36a6e86a7
[ "MIT" ]
null
null
null
src/student/archimedes/simulation.cpp
Tagglink/archimedes-principle
93a2ce101bc8f3ac2653da667887c8d36a6e86a7
[ "MIT" ]
null
null
null
#include "simulation.h" #include <iostream> #include <memory> #include <string> #include "SF_src/DemoHandler.h" #include "student/archimedes/pointmass.h" #include "student/archimedes/slicer.h" #include "student/geometry.h" #include "student/plane.h" #include "student/vector.h" namespace { template <typename T> auto Contains(const std::vector<T>& elements, const T& value) -> bool { for (T element : elements) { if (element == value) { return true; } } return false; } } // namespace namespace student::archimedes { Simulation::Simulation() : time_step_(1.0f / 60.0f) , damping_(0.00f) , bodies_() , liquids_() , gravity_acceleration_(9.82f) , user_force_(100.0f) { InitializeSimulation(); } void Simulation::update(DemoHandler* handler) { for (int i = 0; i < liquids_.size(); i++) { SimulateLiquid(liquids_.at(i)); liquids_.at(i)->Draw(handler); } for (int i = 0; i < bodies_.size(); i++) { bodies_.at(i)->AddForce( Vector(0.0f, -gravity_acceleration_, 0.0f) * bodies_.at(i)->GetMass(), bodies_.at(i)->GetPosition()); bodies_.at(i)->Update(time_step_, damping_); bodies_.at(i)->Draw(handler); bodies_.at(i)->ClearForce(); } static bool mouse_held_left = false; static bool mouse_held_middle = false; static Point mouse_left_click_position = 0.0f; static Point mouse_middle_click_position = 0.0f; // click-drag functionality for the left mouse button, slicing objects if (mouse_held_left) { handler->drawLine(mouse_left_click_position, handler->getMouseLocation(), Color::MAGENTA, 0.01f); if (!handler->isMouseDown() && bodies_.size() > 0) { HandleSlicing(mouse_left_click_position, handler->getMouseLocation()); mouse_held_left = false; } } else if (!mouse_held_left && handler->isMouseDown()) { mouse_left_click_position = handler->getMouseLocation(); mouse_held_left = true; } // click-drag functionality for the middle mouse button, pushing objects if (mouse_held_middle) { handler->drawLine(mouse_middle_click_position, handler->getMouseLocation(), Color::PINK, 0.01f); if (!handler->isMouseDown(Button::MIDDLE) && bodies_.size() > 0) { HandlePushing(mouse_middle_click_position, handler->getMouseLocation()); mouse_held_middle = false; } } else if (!mouse_held_middle && handler->isMouseDown(Button::MIDDLE)) { mouse_middle_click_position = handler->getMouseLocation(); mouse_held_middle = true; } // R resets if (handler->keyTyped('r')) { ResetSimulation(); } if (handler->keyTyped('w')) { for (auto liquid : liquids_) { liquid->SetDensity(liquid->GetDensity() + 0.5f); } } else if (handler->keyTyped('s')) { for (auto liquid : liquids_) { liquid->SetDensity(liquid->GetDensity() - 0.5f); } } if (handler->keyTyped('e')) { damping_ += 0.01f; if (damping_ > 1.0f) { damping_ = 1.0f; } } else if (handler->keyTyped('d')) { damping_ -= 0.01f; if (damping_ < 0.0f) { damping_ = 0.0f; } } for (int i = 0; i < liquids_.size(); i++) { handler->drawText( Point(0.0f, 10.0f - (i * 0.5f), 0.0f), "liquid density: " + std::to_string(liquids_.at(i)->GetDensity())); } handler->drawText( Point(0.0f, 10.5f, 0.0f), "damping: " + std::to_string(damping_)); } auto Simulation::getName() -> const std::string { return "Simulation of archimedes principle"; } auto Simulation::getInfo() -> const std::string { return "Press W to increase liquid density, and S to decrease it.\n" "Press E to increase damping and D to decrease it."; } void Simulation::InitializeSimulation() { auto body1 = std::make_shared<PointmassBody2D>( std::vector<Point>{Point(26.0f, 0.0f, 0.0f), Point(25.0f, 0.0f, 0.0f), Point(24.75f, 0.75f, 0.0f), Point(25.5f, 1.5f, 0.0f), Point(26.25f, 0.75f, 0.0f)}, 1.0f, Color::BLUE); auto body2 = std::make_shared<PointmassBody2D>( std::vector<Point>{Point(14.0f, 4.0f, 0.0f), Point(16.0f, 4.0f, 0.0f), Point(16.0f, 6.0f, 0.0f), Point(14.0f, 6.0f, 0.0f)}, 2.0f, Color::YELLOW); auto body3 = std::make_shared<PointmassBody2D>( std::vector<Point>{Point(9.0f, 6.0f, 0.0f), Point(8.0f, 4.0f, 0.0f), Point(9.0f, 2.0f, 0.0f), Point(10.0f, 4.0f, 0.0f)}, 3.0f, Color::RED); auto body4 = std::make_shared<PointmassBody2D>( std::vector<Point>{ Point(2.0f, 0.0f, 0.0f), Point(4.0f, 0.0f, 0.0f), Point(6.0f, 2.0f, 0.0f), Point(6.0f, 4.0f, 0.0f), Point(4.0f, 6.0f, 0.0f), Point(2.0f, 6.0f, 0.0f), Point(0.0f, 4.0f, 0.0f), Point(0.0f, 2.0f, 0.0f), }, 4.0f, Color::GREEN); bodies_.push_back(body1); bodies_.push_back(body2); bodies_.push_back(body3); bodies_.push_back(body4); auto liquid1 = std::make_shared<LiquidBody2D>( 31.0f, 40.0f, Point(15.0f, -55.0f, 0.0f), 4.2f); liquids_.push_back(liquid1); } void Simulation::ResetSimulation() { bodies_.clear(); liquids_.clear(); InitializeSimulation(); } void Simulation::SimulateLiquid(const std::shared_ptr<LiquidBody2D>& liquid) { std::vector<std::shared_ptr<PointmassBody2D>> bodies_to_simulate; auto horizontal_bounds = liquid->GetHorisontalBounds(); auto vertical_bounds = liquid->GetVerticalBounds(); for (int i = 0; i < bodies_.size(); i++) { auto shape = bodies_.at(i)->GetShape(); if (slicer::IsWithinBounds( horizontal_bounds[0], horizontal_bounds[1], shape) && slicer::IsWithinBounds( vertical_bounds[0], vertical_bounds[1], shape)) { bodies_to_simulate.push_back(bodies_.at(i)); } } liquid->HandleBodies(bodies_to_simulate, gravity_acceleration_); } void Simulation::HandleSlicing(const Point& point_a, const Point& point_b) { std::vector<std::shared_ptr<PointmassBody2D>> new_bodies; std::vector<int> erased_bodies; auto slicing_planes = GetSlicingData(point_a, point_b); for (int i = 0; i < bodies_.size(); i++) { std::vector<Point> polygon_shape = bodies_.at(i)->GetShape(); if (slicer::IsStrictlyWithinBounds( slicing_planes[1], slicing_planes[2], polygon_shape) && slicer::Intersects(slicing_planes[0], polygon_shape)) { auto resulting_bodies = SliceBody(bodies_.at(i), slicing_planes[0]); erased_bodies.push_back(i); resulting_bodies[0]->SetAngularSpeed(bodies_.at(i)->GetAngularSpeed()); resulting_bodies[0]->SetVelocity( bodies_.at(i)->GetVelocity(bodies_.at(i)->GetPosition())); resulting_bodies[1]->SetAngularSpeed(bodies_.at(i)->GetAngularSpeed()); resulting_bodies[1]->SetVelocity( bodies_.at(i)->GetVelocity(bodies_.at(i)->GetPosition())); new_bodies.push_back(resulting_bodies[0]); new_bodies.push_back(resulting_bodies[1]); } } for (int i = 0; i < bodies_.size(); i++) { if (!::Contains(erased_bodies, i)) { new_bodies.push_back(bodies_.at(i)); } } bodies_ = new_bodies; } void Simulation::HandlePushing(const Point& point_a, const Point& point_b) { for (auto body : bodies_) { if (geometry::PointOverlapsConvexPolygonXY(point_a, body->GetShape())) { body->AddForce((point_b - point_a) * user_force_, point_a); } } } auto Simulation::SliceBody( const std::shared_ptr<PointmassBody2D>& body_to_slice, const Plane& slicing_plane) -> std::array<std::shared_ptr<PointmassBody2D>, 2> { auto resulting_polys = slicer::SlicePolygon(body_to_slice->GetShape(), slicing_plane); return {std::make_shared<PointmassBody2D>(resulting_polys[0], body_to_slice->GetDensity(), body_to_slice->GetColor()), std::make_shared<PointmassBody2D>(resulting_polys[1], body_to_slice->GetDensity(), body_to_slice->GetColor())}; } auto Simulation::GetSlicingData(Point slice_a, Point slice_b) -> std::array<Plane, 3> { Vector slicing_line = slice_b - slice_a; Vector slicing_line_normal = Vector(-slicing_line.y, slicing_line.x, 0.0f).Normalized(); Vector slicing_line_normalized = slicing_line.Normalized(); Plane slicing_plane = Plane(slice_a, slicing_line_normal); Plane bounding_plane_a = Plane(slice_a, slicing_line_normalized); Plane bounding_plane_b = Plane(slice_b, -slicing_line_normalized); return {slicing_plane, bounding_plane_a, bounding_plane_b}; } } // namespace student::archimedes
30.418919
78
0.618725
Tagglink
89da23d68c86eb8b7585cf1c1c2948a0552388b9
380
cpp
C++
DeckBuildCardGame/Model/Cards/Card/Duchy.cpp
eagle-shop/DeckBuildCardGame
77cc0b9a4feae34b2f2e36053449a2e2ec66b877
[ "MIT" ]
1
2017-11-19T09:22:10.000Z
2017-11-19T09:22:10.000Z
DeckBuildCardGame/Model/Cards/Card/Duchy.cpp
eagle-shop/DeckBuildCardGame
77cc0b9a4feae34b2f2e36053449a2e2ec66b877
[ "MIT" ]
null
null
null
DeckBuildCardGame/Model/Cards/Card/Duchy.cpp
eagle-shop/DeckBuildCardGame
77cc0b9a4feae34b2f2e36053449a2e2ec66b877
[ "MIT" ]
null
null
null
#include <iostream> #include "General.hpp" #include "Duchy.hpp" using namespace std; Duchy::Duchy(){ cout << "create " << DUCHY << endl; } Duchy::~Duchy(){ cout << "delete " << DUCHY << endl; } ActionDone Duchy::action(PLAYERCARD_CONCRETECARD_IO *p){ cout << "action " << DUCHY << endl; return ACTIONUNDONE; } const string* Duchy::who(){ return &DUCHY; }
16.521739
56
0.623684
eagle-shop
89df030912c113b3161e4f76e9d4c744279355a5
3,095
cpp
C++
src/algorithm/grin/AlgoCuckatoo31Cl.cpp
oldas1/Riner
492804079eb223e6d4ffd5f5f44283162eaf421b
[ "MIT" ]
null
null
null
src/algorithm/grin/AlgoCuckatoo31Cl.cpp
oldas1/Riner
492804079eb223e6d4ffd5f5f44283162eaf421b
[ "MIT" ]
null
null
null
src/algorithm/grin/AlgoCuckatoo31Cl.cpp
oldas1/Riner
492804079eb223e6d4ffd5f5f44283162eaf421b
[ "MIT" ]
null
null
null
#include "AlgoCuckatoo31Cl.h" #include <src/common/Endian.h> #include <src/common/OpenCL.h> #include <src/crypto/blake2.h> #include <src/pool/WorkCuckoo.h> namespace miner { AlgoCuckatoo31Cl::AlgoCuckatoo31Cl(AlgoConstructionArgs args) : terminate_(false), args_(std::move(args)) { for (auto &assignedDeviceRef : args_.assignedDevices) { auto &assignedDevice = assignedDeviceRef.get(); optional<cl::Device> deviceOr = args.compute.getDeviceOpenCL(assignedDevice.id); if (!deviceOr) { continue; } cl::Device device = *deviceOr; workers_.emplace_back([this, &assignedDevice, device] { cl::Context context(device); CuckatooSolver::Options opts {assignedDevice, tasks}; opts.n = 31; opts.context = context; opts.device = device; opts.programLoader = &args_.compute.getProgramLoaderOpenCL(); CuckatooSolver solver(std::move(opts)); run(context, solver); }); } } AlgoCuckatoo31Cl::~AlgoCuckatoo31Cl() { terminate_ = true; for (auto& worker : workers_) { worker.join(); } } /* static */SiphashKeys AlgoCuckatoo31Cl::calculateKeys(const WorkCuckatoo31& header) { SiphashKeys keys; std::vector<uint8_t> h = header.prePow; uint64_t nonce = header.nonce; VLOG(0) << "nonce = " << nonce; size_t len = h.size(); h.resize(len + sizeof(nonce)); *reinterpret_cast<uint64_t*>(&h[len]) = htobe64(nonce); uint64_t keyArray[4]; blake2b(keyArray, sizeof(keyArray), h.data(), h.size(), 0, 0); keys.k0 = htole64(keyArray[0]); keys.k1 = htole64(keyArray[1]); keys.k2 = htole64(keyArray[2]); keys.k3 = htole64(keyArray[3]); return keys; } void AlgoCuckatoo31Cl::run(cl::Context& context, CuckatooSolver& solver) { while (!terminate_) { auto work = std::shared_ptr<WorkCuckatoo31>( args_.workProvider.tryGetWork<WorkCuckatoo31>()); if (!work) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); continue; } solver.solve( calculateKeys(*work), [&, work](std::vector<CuckatooSolver::Cycle> cycles) { solver.getDevice().records.reportScannedNoncesAmount(1); LOG(INFO)<< "Found " << cycles.size() << " cycles of target length."; // TODO sha pow and compare to difficulty for (auto& cycle : cycles) { solver.getDevice().records.reportWorkUnit(1., true); auto pow = work->makeWorkSolution<WorkSolutionCuckatoo31>(); pow->nonce = work->nonce; pow->pow = std::move(cycle.edges); args_.workProvider.submitSolution(std::move(pow)); } }, [this, work] { return !work->valid() || terminate_.load(std::memory_order_relaxed); }); } } } /* namespace miner */
34.775281
89
0.575121
oldas1
89e22dc4f41d5328002b5b1c645e6bdef784430e
3,981
cpp
C++
spine-cocos2dx/MBSpineFramework/cocos2d-x-3.17.2/cocos/scripting/js-bindings/manual/localstorage/js_bindings_system_functions.cpp
BowenCoder/spine-cocos2dx
cfac5100b78782b2d4ce84b472a435f46aff4da9
[ "MIT" ]
1
2022-02-14T01:34:02.000Z
2022-02-14T01:34:02.000Z
spine-cocos2dx/MBSpineFramework/cocos2d-x-3.17.2/cocos/scripting/js-bindings/manual/localstorage/js_bindings_system_functions.cpp
BowenCoder/spine-cocos2dx
cfac5100b78782b2d4ce84b472a435f46aff4da9
[ "MIT" ]
null
null
null
spine-cocos2dx/MBSpineFramework/cocos2d-x-3.17.2/cocos/scripting/js-bindings/manual/localstorage/js_bindings_system_functions.cpp
BowenCoder/spine-cocos2dx
cfac5100b78782b2d4ce84b472a435f46aff4da9
[ "MIT" ]
2
2019-07-02T05:35:25.000Z
2021-02-08T06:19:33.000Z
/**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /* * AUTOGENERATED FILE. DO NOT EDIT IT * Generated by "generate_js_bindings.py -c system_jsb.ini" on 2012-12-17 * Script version: v0.5 */ #include "scripting/js-bindings/manual/localstorage/js_bindings_system_functions.h" #include "scripting/js-bindings/manual/js_bindings_config.h" #include "scripting/js-bindings/manual/js_bindings_core.h" #include "scripting/js-bindings/manual/js_manual_conversions.h" #include "scripting/js-bindings/manual/ScriptingCore.h" #include "storage/local-storage/LocalStorage.h" USING_NS_CC; // Arguments: char* // Ret value: const char* bool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); bool ok = true; std::string arg0; ok &= jsval_to_std_string( cx, args.get(0), &arg0 ); JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); std::string ret_val; ok = localStorageGetItem(arg0, &ret_val); if (ok) { jsval ret_jsval = std_string_to_jsval(cx, ret_val); args.rval().set(ret_jsval); } else { args.rval().set(JSVAL_NULL); } return true; } // Arguments: char* // Ret value: void bool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); bool ok = true; std::string arg0; ok &= jsval_to_std_string( cx, args.get(0), &arg0 ); JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); localStorageRemoveItem(arg0); args.rval().setUndefined(); return true; } // Arguments: char*, char* // Ret value: void bool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); bool ok = true; std::string arg0; std::string arg1; ok &= jsval_to_std_string( cx, args.get(0), &arg0 ); ok &= jsval_to_std_string( cx, args.get(1), &arg1 ); if( ok ) { localStorageSetItem(arg0 , arg1); } else { log("JSB_localStorageSetItem:Error processing arguments"); } args.rval().setUndefined(); return true; } // Arguments: char*, char* // Ret value: void bool JSB_localStorageClear(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); localStorageClear(); args.rval().setUndefined(); return true; } //#endif // JSB_INCLUDE_SYSTEM
35.544643
83
0.682994
BowenCoder
89e7e1516a88ba308ff941138cefae6fc8efaca0
12,330
hpp
C++
include/GlobalNamespace/BeatmapObjectCallbackController.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/BeatmapObjectCallbackController.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/BeatmapObjectCallbackController.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Including type: IBeatmapObjectCallbackController #include "GlobalNamespace/IBeatmapObjectCallbackController.hpp" // Including type: BeatmapEventType #include "GlobalNamespace/BeatmapEventType.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IAudioTimeSource class IAudioTimeSource; // Forward declaring type: EnvironmentKeywords class EnvironmentKeywords; // Forward declaring type: BeatmapObjectData class BeatmapObjectData; // Forward declaring type: BeatmapEventData class BeatmapEventData; // Forward declaring type: BeatmapObjectCallbackData class BeatmapObjectCallbackData; // Forward declaring type: BeatmapEventCallbackData class BeatmapEventCallbackData; // Forward declaring type: IReadonlyBeatmapData class IReadonlyBeatmapData; // Forward declaring type: BeatmapObjectCallback class BeatmapObjectCallback; // Forward declaring type: BeatmapEventCallback class BeatmapEventCallback; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: HashSet`1<T> template<typename T> class HashSet_1; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: Action class Action; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x70 #pragma pack(push, 1) // Autogenerated type: BeatmapObjectCallbackController class BeatmapObjectCallbackController : public UnityEngine::MonoBehaviour/*, public GlobalNamespace::IBeatmapObjectCallbackController*/ { public: // Nested type: GlobalNamespace::BeatmapObjectCallbackController::InitData class InitData; // [InjectAttribute] Offset: 0xE18D44 // private readonly BeatmapObjectCallbackController/InitData _initData // Size: 0x8 // Offset: 0x18 GlobalNamespace::BeatmapObjectCallbackController::InitData* initData; // Field size check static_assert(sizeof(GlobalNamespace::BeatmapObjectCallbackController::InitData*) == 0x8); // [InjectAttribute] Offset: 0xE18D54 // private readonly IAudioTimeSource _audioTimeSource // Size: 0x8 // Offset: 0x20 GlobalNamespace::IAudioTimeSource* audioTimeSource; // Field size check static_assert(sizeof(GlobalNamespace::IAudioTimeSource*) == 0x8); // [InjectAttribute] Offset: 0xE18D64 // private readonly EnvironmentKeywords _environmentKeywords // Size: 0x8 // Offset: 0x28 GlobalNamespace::EnvironmentKeywords* environmentKeywords; // Field size check static_assert(sizeof(GlobalNamespace::EnvironmentKeywords*) == 0x8); // private readonly System.Collections.Generic.List`1<BeatmapObjectData> _beatmapObjectDataCallbackCacheList // Size: 0x8 // Offset: 0x30 System::Collections::Generic::List_1<GlobalNamespace::BeatmapObjectData*>* beatmapObjectDataCallbackCacheList; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<GlobalNamespace::BeatmapObjectData*>*) == 0x8); // [CompilerGeneratedAttribute] Offset: 0xE18D74 // private System.Action`1<BeatmapEventData> beatmapEventDidTriggerEvent // Size: 0x8 // Offset: 0x38 System::Action_1<GlobalNamespace::BeatmapEventData*>* beatmapEventDidTriggerEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::BeatmapEventData*>*) == 0x8); // [CompilerGeneratedAttribute] Offset: 0xE18D84 // private System.Action callbacksForThisFrameWereProcessedEvent // Size: 0x8 // Offset: 0x40 System::Action* callbacksForThisFrameWereProcessedEvent; // Field size check static_assert(sizeof(System::Action*) == 0x8); // private readonly System.Collections.Generic.List`1<BeatmapObjectCallbackData> _beatmapObjectCallbackData // Size: 0x8 // Offset: 0x48 System::Collections::Generic::List_1<GlobalNamespace::BeatmapObjectCallbackData*>* beatmapObjectCallbackData; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<GlobalNamespace::BeatmapObjectCallbackData*>*) == 0x8); // private readonly System.Collections.Generic.List`1<BeatmapEventCallbackData> _beatmapEventCallbackData // Size: 0x8 // Offset: 0x50 System::Collections::Generic::List_1<GlobalNamespace::BeatmapEventCallbackData*>* beatmapEventCallbackData; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<GlobalNamespace::BeatmapEventCallbackData*>*) == 0x8); // private System.Int32 _nextEventIndex // Size: 0x4 // Offset: 0x58 int nextEventIndex; // Field size check static_assert(sizeof(int) == 0x4); // private System.Single _spawningStartTime // Size: 0x4 // Offset: 0x5C float spawningStartTime; // Field size check static_assert(sizeof(float) == 0x4); // private IReadonlyBeatmapData _beatmapData // Size: 0x8 // Offset: 0x60 GlobalNamespace::IReadonlyBeatmapData* beatmapData; // Field size check static_assert(sizeof(GlobalNamespace::IReadonlyBeatmapData*) == 0x8); // private readonly System.Collections.Generic.HashSet`1<BeatmapEventType> _validEvents // Size: 0x8 // Offset: 0x68 System::Collections::Generic::HashSet_1<GlobalNamespace::BeatmapEventType>* validEvents; // Field size check static_assert(sizeof(System::Collections::Generic::HashSet_1<GlobalNamespace::BeatmapEventType>*) == 0x8); // Creating value type constructor for type: BeatmapObjectCallbackController BeatmapObjectCallbackController(GlobalNamespace::BeatmapObjectCallbackController::InitData* initData_ = {}, GlobalNamespace::IAudioTimeSource* audioTimeSource_ = {}, GlobalNamespace::EnvironmentKeywords* environmentKeywords_ = {}, System::Collections::Generic::List_1<GlobalNamespace::BeatmapObjectData*>* beatmapObjectDataCallbackCacheList_ = {}, System::Action_1<GlobalNamespace::BeatmapEventData*>* beatmapEventDidTriggerEvent_ = {}, System::Action* callbacksForThisFrameWereProcessedEvent_ = {}, System::Collections::Generic::List_1<GlobalNamespace::BeatmapObjectCallbackData*>* beatmapObjectCallbackData_ = {}, System::Collections::Generic::List_1<GlobalNamespace::BeatmapEventCallbackData*>* beatmapEventCallbackData_ = {}, int nextEventIndex_ = {}, float spawningStartTime_ = {}, GlobalNamespace::IReadonlyBeatmapData* beatmapData_ = {}, System::Collections::Generic::HashSet_1<GlobalNamespace::BeatmapEventType>* validEvents_ = {}) noexcept : initData{initData_}, audioTimeSource{audioTimeSource_}, environmentKeywords{environmentKeywords_}, beatmapObjectDataCallbackCacheList{beatmapObjectDataCallbackCacheList_}, beatmapEventDidTriggerEvent{beatmapEventDidTriggerEvent_}, callbacksForThisFrameWereProcessedEvent{callbacksForThisFrameWereProcessedEvent_}, beatmapObjectCallbackData{beatmapObjectCallbackData_}, beatmapEventCallbackData{beatmapEventCallbackData_}, nextEventIndex{nextEventIndex_}, spawningStartTime{spawningStartTime_}, beatmapData{beatmapData_}, validEvents{validEvents_} {} // Creating interface conversion operator: operator GlobalNamespace::IBeatmapObjectCallbackController operator GlobalNamespace::IBeatmapObjectCallbackController() noexcept { return *reinterpret_cast<GlobalNamespace::IBeatmapObjectCallbackController*>(this); } // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // public System.Void add_beatmapEventDidTriggerEvent(System.Action`1<BeatmapEventData> value) // Offset: 0x107A5E8 void add_beatmapEventDidTriggerEvent(System::Action_1<GlobalNamespace::BeatmapEventData*>* value); // public System.Void remove_beatmapEventDidTriggerEvent(System.Action`1<BeatmapEventData> value) // Offset: 0x107A68C void remove_beatmapEventDidTriggerEvent(System::Action_1<GlobalNamespace::BeatmapEventData*>* value); // public System.Void add_callbacksForThisFrameWereProcessedEvent(System.Action value) // Offset: 0x107A730 void add_callbacksForThisFrameWereProcessedEvent(System::Action* value); // public System.Void remove_callbacksForThisFrameWereProcessedEvent(System.Action value) // Offset: 0x107A7D4 void remove_callbacksForThisFrameWereProcessedEvent(System::Action* value); // public System.Boolean get_isPaused() // Offset: 0x107A878 bool get_isPaused(); // protected System.Void Start() // Offset: 0x107A898 void Start(); // protected System.Void LateUpdate() // Offset: 0x107B064 void LateUpdate(); // public BeatmapObjectCallbackData AddBeatmapObjectCallback(BeatmapObjectCallback callback, System.Single aheadTime) // Offset: 0x107BEB4 GlobalNamespace::BeatmapObjectCallbackData* AddBeatmapObjectCallback(GlobalNamespace::BeatmapObjectCallback* callback, float aheadTime); // public System.Void RemoveBeatmapObjectCallback(BeatmapObjectCallbackData callbackData) // Offset: 0x107C108 void RemoveBeatmapObjectCallback(GlobalNamespace::BeatmapObjectCallbackData* callbackData); // public BeatmapEventCallbackData AddBeatmapEventCallback(BeatmapEventCallback callback, System.Single aheadTime) // Offset: 0x107C17C GlobalNamespace::BeatmapEventCallbackData* AddBeatmapEventCallback(GlobalNamespace::BeatmapEventCallback* callback, float aheadTime); // public System.Void RemoveBeatmapEventCallback(BeatmapEventCallbackData callbackData) // Offset: 0x107C21C void RemoveBeatmapEventCallback(GlobalNamespace::BeatmapEventCallbackData* callbackData); // public System.Void SendBeatmapEventDidTriggerEvent(BeatmapEventData beatmapEventData) // Offset: 0x107BE18 void SendBeatmapEventDidTriggerEvent(GlobalNamespace::BeatmapEventData* beatmapEventData); // public System.Void SetNewBeatmapData(IReadonlyBeatmapData beatmapData) // Offset: 0x107A8C8 void SetNewBeatmapData(GlobalNamespace::IReadonlyBeatmapData* beatmapData); // public System.Void Pause() // Offset: 0x107C290 void Pause(); // public System.Void Resume() // Offset: 0x107C29C void Resume(); // public System.Void .ctor() // Offset: 0x107C2A8 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static BeatmapObjectCallbackController* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::BeatmapObjectCallbackController::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<BeatmapObjectCallbackController*, creationType>())); } }; // BeatmapObjectCallbackController #pragma pack(pop) static check_size<sizeof(BeatmapObjectCallbackController), 104 + sizeof(System::Collections::Generic::HashSet_1<GlobalNamespace::BeatmapEventType>*)> __GlobalNamespace_BeatmapObjectCallbackControllerSizeCheck; static_assert(sizeof(BeatmapObjectCallbackController) == 0x70); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BeatmapObjectCallbackController*, "", "BeatmapObjectCallbackController");
57.083333
1,505
0.760341
darknight1050
89ec26f902c440f9e734c1e01b9daedad008941c
365
cpp
C++
C++/uva11799.cpp
MrinmoiHossain/Uva-Solution
85602085b7c8e1d4711e679b8f5636678459b2c5
[ "MIT" ]
1
2017-04-17T21:51:54.000Z
2017-04-17T21:51:54.000Z
C++/uva11799.cpp
MrinmoiHossain/Uva-Solution
85602085b7c8e1d4711e679b8f5636678459b2c5
[ "MIT" ]
1
2020-06-24T23:43:11.000Z
2020-06-24T23:43:11.000Z
C++/uva11799.cpp
MrinmoiHossain/Uva-Solution
85602085b7c8e1d4711e679b8f5636678459b2c5
[ "MIT" ]
2
2018-12-14T12:57:51.000Z
2020-01-03T09:00:07.000Z
//Accepted #include <iostream> #include <algorithm> using namespace std; int main(void) { int T, N; cin >> T; for(int i = 1; i <= T; i++){ cin >> N; int arr[N]; for(int j = 0; j < N; j++) cin >> arr[j]; sort(arr, arr + N); cout << "Case " << i << ": " << arr[N - 1] << endl; } return 0; }
15.869565
59
0.416438
MrinmoiHossain
8857e23c99edad4d1300b38f7ecf7c0a7d24c45e
31
cpp
C++
RenderSystemDX12/RenderDeviceDX12.cpp
dmhud/asteroids_d3d12
3ecbb78d40408ac9e60a38ed59fc53f30fe86640
[ "Apache-2.0" ]
null
null
null
RenderSystemDX12/RenderDeviceDX12.cpp
dmhud/asteroids_d3d12
3ecbb78d40408ac9e60a38ed59fc53f30fe86640
[ "Apache-2.0" ]
null
null
null
RenderSystemDX12/RenderDeviceDX12.cpp
dmhud/asteroids_d3d12
3ecbb78d40408ac9e60a38ed59fc53f30fe86640
[ "Apache-2.0" ]
null
null
null
#include "RenderDeviceDX12.h"
15.5
30
0.774194
dmhud
8859996be0134cd0138ae0a69d4713bd0fb147f8
2,054
cc
C++
code/render/coregraphics/d3d9/d3d9memorytextureloader.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/render/coregraphics/d3d9/d3d9memorytextureloader.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/render/coregraphics/d3d9/d3d9memorytextureloader.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
#include "stdneb.h" #include "coregraphics/pixelformat.h" #include "coregraphics/streamtextureloader.h" #include "coregraphics/texture.h" #include "coregraphics/renderdevice.h" #include "MemoryTextureLoader.h" #include "win360/d3d9types.h" using namespace Win360; using namespace Resources; namespace Direct3D9 { __ImplementClass(Direct3D9::D3D9MemoryTextureLoader,'D9TL',Resources::ResourceLoader); //------------------------------------------------------------------------------ /** */ void D3D9MemoryTextureLoader::SetImageBuffer(const void* buffer, SizeT width, SizeT height, CoreGraphics::PixelFormat::Code format) { HRESULT hr; IDirect3DDevice9* d3d9Device = RenderDevice::Instance()->GetDirect3DDevice(); n_assert(0 != d3d9Device); d3d9Texture = 0; hr = D3DXCreateTexture(d3d9Device,width,height,5,D3DUSAGE_DYNAMIC|D3DUSAGE_AUTOGENMIPMAP,D3D9Types::AsD3D9PixelFormat(format),D3DPOOL_DEFAULT,&d3d9Texture); if (FAILED(hr)) { n_error("MemoryTextureLoader: D3DXCreateTexture() failed"); return; } IDirect3DBaseTexture9 *baseTexture; hr=d3d9Texture->QueryInterface(IID_IDirect3DBaseTexture9, (void**) &(baseTexture)); D3DLOCKED_RECT d3dLockedRect={ 0 }; hr=d3d9Texture->LockRect(0, &d3dLockedRect, NULL, D3DLOCK_NO_DIRTY_UPDATE); for(int y=0; y<height; y++) { // pitch is measured in bytes memcpy(((unsigned char *)d3dLockedRect.pBits)+(y*d3dLockedRect.Pitch), ((unsigned int*)buffer)+(y*width), sizeof(unsigned int)*width); } d3d9Texture->UnlockRect(0); baseTexture->SetAutoGenFilterType(D3DTEXF_LINEAR); baseTexture->GenerateMipSubLevels(); } //------------------------------------------------------------------------------ /** */ bool D3D9MemoryTextureLoader::OnLoadRequested() { n_assert(this->resource->IsA(Texture::RTTI)); n_assert(this->d3d9Texture != NULL); const Ptr<Texture>& res = this->resource.downcast<Texture>(); n_assert(!res->IsLoaded()); res->SetupFromD3D9Texture(d3d9Texture); res->SetState(Resource::Loaded); SetState(Resource::Loaded); return true; } } // namespace Direct3D9
28.929577
157
0.703505
gscept
885f839d8c306b52a4b4704a0374234a9b1fed1b
1,365
cpp
C++
modules/cuda/src/MetaObject/cuda/MemoryBlock.cpp
dtmoodie/MetaObject
8238d143d578ff9c0c6506e7e627eca15e42369e
[ "MIT" ]
2
2017-10-26T04:41:49.000Z
2018-02-09T05:12:19.000Z
modules/cuda/src/MetaObject/cuda/MemoryBlock.cpp
dtmoodie/MetaObject
8238d143d578ff9c0c6506e7e627eca15e42369e
[ "MIT" ]
null
null
null
modules/cuda/src/MetaObject/cuda/MemoryBlock.cpp
dtmoodie/MetaObject
8238d143d578ff9c0c6506e7e627eca15e42369e
[ "MIT" ]
3
2017-01-08T21:09:48.000Z
2018-02-10T04:27:32.000Z
#include "MemoryBlock.hpp" #include "common.hpp" #include <MetaObject/logging/logging.hpp> #include <cuda_runtime_api.h> namespace mo { namespace cuda { uint8_t* CUDA::allocate(const uint64_t size, const int32_t) { void* ptr = nullptr; cudaError_t err = cudaMalloc(&ptr, size); MO_ASSERT_FMT(err == cudaSuccess, "Unable to allocate {} on device due to {}", size, err); return static_cast<uint8_t*>(ptr); } void CUDA::deallocate(void* data, const uint64_t) { cudaError_t err = cudaFree(data); MO_ASSERT_FMT(err == cudaSuccess, "Unable to free device memory due to {}", err); } uint8_t* HOST::allocate(const uint64_t size, const int32_t) { void* ptr = nullptr; cudaError_t err = cudaMallocHost(&ptr, size); MO_ASSERT_FMT(err == cudaSuccess, "Unable to allocate {} on device due to {}", size, err); return static_cast<uint8_t*>(ptr); } void HOST::deallocate(void* data, const uint64_t) { cudaError_t err = cudaFreeHost(data); MO_ASSERT_FMT(err == cudaSuccess, "Unable to free host pinned memory due to {}", err); } } template struct MemoryBlock<cuda::CUDA>; template struct MemoryBlock<cuda::HOST>; }
31.022727
102
0.594139
dtmoodie
8864e9c87b6fef03e5eb2da97637472364ac2133
992
cpp
C++
game/friend/friend.cpp
ooeyusea/game
2ebac104e0e0c4281b025b4ad32f8c3b06bc54bd
[ "MIT" ]
null
null
null
game/friend/friend.cpp
ooeyusea/game
2ebac104e0e0c4281b025b4ad32f8c3b06bc54bd
[ "MIT" ]
null
null
null
game/friend/friend.cpp
ooeyusea/game
2ebac104e0e0c4281b025b4ad32f8c3b06bc54bd
[ "MIT" ]
1
2019-07-04T03:24:22.000Z
2019-07-04T03:24:22.000Z
#include "friend.h" #include "initializor.h" #include "XmlReader.h" #include "servernode.h" #include <thread> #include "mysqlmgr.h" #include "object_holder.h" #include "dbdefine.h" #define DEFAULT_POOL_SIZE (1024 * 1024) #define DEFAULT_BATCH (8 * 1024) Friend g_friend; Friend::Friend() { InitializorMgr::Instance().AddStep("Friend#Init", [this]() { return Initialize(); }); InitializorMgr::Instance().AddStep("Friend#LoadDB", [this]() { return LoadDB(); }); } bool Friend::Initialize() { return true; } bool Friend::LoadDB() { try { olib::XmlReader conf; if (!conf.LoadXml(_conf.c_str())) { return false; } const char * dsn = conf.Root()["mysql"][0]["friend_data"][0].GetAttributeString("dsn"); auto * executor = MysqlMgr::Instance().Open(dsn); if (!executor) { return false; } Holder<MysqlExecutor, db_def::FRIEND> holder(executor); } catch (std::exception& e) { hn_error("Load Cache Config : {}", e.what()); return false; } return true; }
19.45098
89
0.663306
ooeyusea
88741b18c04ba9fc6944452527db1ca0f14dc15c
2,521
cpp
C++
napi/algorithms/onedirection.cpp
graeme-hill/snakebot
21059e4b5e3153ada5e74ba2e1331c10b5142b2f
[ "MIT", "Unlicense" ]
8
2018-06-26T05:42:17.000Z
2021-10-20T23:19:20.000Z
napi/algorithms/onedirection.cpp
graeme-hill/snakebot
21059e4b5e3153ada5e74ba2e1331c10b5142b2f
[ "MIT", "Unlicense" ]
null
null
null
napi/algorithms/onedirection.cpp
graeme-hill/snakebot
21059e4b5e3153ada5e74ba2e1331c10b5142b2f
[ "MIT", "Unlicense" ]
5
2019-06-01T15:34:07.000Z
2022-02-12T06:10:16.000Z
#include "onedirection.hpp" #include "cautious.hpp" #include "../movement.hpp" #include "../astar.hpp" #include <functional> #include <unordered_map> #include <sstream> std::unordered_map<std::string, bool> OneDirection::_finishMap; OneDirection::OneDirection(Direction direction) : _direction(direction) { } Metadata OneDirection::meta() { std::string left = "http://www.clker.com/cliparts/d/3/0/b/1206569743961899636pitr_green_arrows_set_4.svg.med.png"; std::string right = "http://weclipart.com/gimg/6B83AEBB1C202B97/large-Arrow-Right-66.6-2393.png"; std::string up = "http://www.clker.com/cliparts/e/v/b/X/Q/t/arrow-up-md.png"; std::string down = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Gtk-go-down.svg/120px-Gtk-go-down.svg.png"; std::string img = _direction == Direction::Left ? left : _direction == Direction::Right ? right : _direction == Direction::Up ? up : down; return { "#008888", "#FFFFFF", img, "OneDirection", "Yum", "pixel", "pixel" }; } void OneDirection::start(std::string id) { _finishMap[id] = false; } MaybeDirection tryMove(Direction direction, GameState &state) { Point current = state.mySnake()->head(); Point destination = coordAfterMove(current, direction); bool oob = outOfBounds(destination, state); if (!oob && state.map().turnsUntilVacant(destination) == 0) { return MaybeDirection::just(direction); } return MaybeDirection::none(); } Direction OneDirection::move(GameState &state) { return move(state, 0); } Direction OneDirection::move(GameState &state, uint32_t branchId) { std::stringstream ss; ss << state.gameId() << "_" << branchId; std::string key = ss.str(); // If already finished moving in this direction then switch to cautious. auto finishIter = _finishMap.find(key); if (finishIter != _finishMap.end() && finishIter->second) { Cautious cautious; return cautious.move(state); } // Should already be in the dictionary from call to start() but just make // sure in case server restarts or something. _finishMap[key] = false; // Try to move in specified direction. MaybeDirection attempt = tryMove(_direction, state); if (attempt.hasValue) return attempt.value; // Can't move in this direction anymore so change to backup algorithm. _finishMap[key] = true; Cautious cautious; return cautious.move(state); }
28.977011
125
0.666799
graeme-hill
887c5da5873c1fd70248f9eab83fb32d18e17203
1,572
cpp
C++
src/cfile.cpp
joeferner/node-shark
88309cad7369781096b552eb36e1cdca2471bb42
[ "MIT" ]
44
2015-03-19T14:19:12.000Z
2022-02-19T17:34:08.000Z
src/cfile.cpp
joeferner/node-shark
88309cad7369781096b552eb36e1cdca2471bb42
[ "MIT" ]
null
null
null
src/cfile.cpp
joeferner/node-shark
88309cad7369781096b552eb36e1cdca2471bb42
[ "MIT" ]
9
2015-07-19T20:40:40.000Z
2021-02-06T18:21:49.000Z
/* cfile.c * capture_file GUI-independent manipulation * Vassilii Khachaturov <vassilii@tarunz.org> * * $Id: cfile.c 36881 2011-04-27 02:54:44Z guy $ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <glib.h> #include <epan/packet.h> extern "C" { #include "cfile.h" } void cap_file_init(capture_file *cf) { /* Initialize the capture file struct */ memset(cf, 0, sizeof(capture_file)); cf->filename = NULL; cf->source = NULL; cf->is_tempfile = FALSE; cf->count = 0; cf->has_snap = FALSE; cf->snap = WTAP_MAX_PACKET_SIZE; cf->wth = NULL; cf->rfcode = NULL; cf->dfilter = NULL; cf->redissecting = FALSE; cf->frames = NULL; }
28.581818
78
0.679389
joeferner
887e7dc339c4fed9e2120b142ab3d28ad05d879b
6,981
cpp
C++
src/gfx/opengl/mg_buffer_texture.cpp
Magnutic/mg-engine
09862497bf99198281acc8227b135777491c58d3
[ "BSD-3-Clause" ]
null
null
null
src/gfx/opengl/mg_buffer_texture.cpp
Magnutic/mg-engine
09862497bf99198281acc8227b135777491c58d3
[ "BSD-3-Clause" ]
null
null
null
src/gfx/opengl/mg_buffer_texture.cpp
Magnutic/mg-engine
09862497bf99198281acc8227b135777491c58d3
[ "BSD-3-Clause" ]
null
null
null
//************************************************************************************************** // This file is part of Mg Engine. Copyright (c) 2020, Magnus Bergsten. // Mg Engine is made available under the terms of the 3-Clause BSD License. // See LICENSE.txt in the project's root directory. //************************************************************************************************** #include "mg/gfx/mg_buffer_texture.h" #include "mg/core/mg_log.h" #include "mg/core/mg_runtime_error.h" #include "mg/gfx/mg_gfx_debug_group.h" #include "mg_gl_debug.h" #include "mg_glad.h" namespace Mg::gfx { uint32_t buffer_texture_type_to_gl_enums(BufferTexture::Type type) { using Channels = BufferTexture::Channels; using Fmt = BufferTexture::Format; using BitDepth = BufferTexture::BitDepth; switch (type.channels) { case Channels::R: switch (type.fmt) { case Fmt::UNSIGNED_NORMALISED: switch (type.bit_depth) { case BitDepth::BITS_8: return GL_R8; case BitDepth::BITS_16: return GL_R16; case BitDepth::BITS_32: MG_ASSERT(false && "Unsupported combination"); break; } break; case Fmt::SIGNED: switch (type.bit_depth) { case BitDepth::BITS_8: return GL_R8I; case BitDepth::BITS_16: return GL_R16I; case BitDepth::BITS_32: return GL_R32I; } break; case Fmt::UNSIGNED: switch (type.bit_depth) { case BitDepth::BITS_8: return GL_R8UI; case BitDepth::BITS_16: return GL_R16UI; case BitDepth::BITS_32: return GL_R32UI; } break; case Fmt::FLOAT: switch (type.bit_depth) { case BitDepth::BITS_8: MG_ASSERT(false && "Unsupported combination"); break; case BitDepth::BITS_16: return GL_R16F; case BitDepth::BITS_32: return GL_R32F; } break; } break; case Channels::RG: switch (type.fmt) { case Fmt::UNSIGNED_NORMALISED: switch (type.bit_depth) { case BitDepth::BITS_8: return GL_RG8; case BitDepth::BITS_16: return GL_RG16; case BitDepth::BITS_32: MG_ASSERT(false && "Unsupported combination"); break; } break; case Fmt::SIGNED: switch (type.bit_depth) { case BitDepth::BITS_8: return GL_RG8I; case BitDepth::BITS_16: return GL_RG16I; case BitDepth::BITS_32: return GL_RG32I; } break; case Fmt::UNSIGNED: switch (type.bit_depth) { case BitDepth::BITS_8: return GL_RG8UI; case BitDepth::BITS_16: return GL_RG16UI; case BitDepth::BITS_32: return GL_RG32UI; } break; case Fmt::FLOAT: switch (type.bit_depth) { case BitDepth::BITS_8: MG_ASSERT(false && "Unsupported combination"); break; case BitDepth::BITS_16: return GL_RG16F; case BitDepth::BITS_32: return GL_RG32F; } break; } break; case Channels::RGB: MG_ASSERT(type.bit_depth == BitDepth::BITS_32); switch (type.fmt) { case Fmt::UNSIGNED_NORMALISED: MG_ASSERT(false && "Unsupported combination"); break; case Fmt::SIGNED: return GL_RGB32I; case Fmt::UNSIGNED: return GL_RGB32UI; case Fmt::FLOAT: return GL_RGB32F; } break; case Channels::RGBA: switch (type.fmt) { case Fmt::UNSIGNED_NORMALISED: switch (type.bit_depth) { case BitDepth::BITS_8: return GL_RGBA8; case BitDepth::BITS_16: return GL_RGBA16; case BitDepth::BITS_32: MG_ASSERT(false && "Unsupported combination"); break; } break; case Fmt::SIGNED: switch (type.bit_depth) { case BitDepth::BITS_8: return GL_RGBA8I; case BitDepth::BITS_16: return GL_RGBA16I; case BitDepth::BITS_32: return GL_RGBA32I; } break; case Fmt::UNSIGNED: switch (type.bit_depth) { case BitDepth::BITS_8: return GL_RGBA8UI; case BitDepth::BITS_16: return GL_RGBA16UI; case BitDepth::BITS_32: return GL_RGBA32UI; } break; case Fmt::FLOAT: switch (type.bit_depth) { case BitDepth::BITS_8: MG_ASSERT(false && "Unsupported combination"); break; case BitDepth::BITS_16: return GL_RGBA16F; case BitDepth::BITS_32: return GL_RGBA32F; } break; } break; } log.error("Unexpected BufferTexture::Type."); throw RuntimeError(); } BufferTexture::BufferTexture(Type type, size_t buffer_size) : m_buffer_size(buffer_size) { MG_GFX_DEBUG_GROUP("BufferTexture::BufferTexture"); GLuint buf_id = 0; GLuint tex_id = 0; // Create data buffer and allocate storage glGenBuffers(1, &buf_id); glBindBuffer(GL_TEXTURE_BUFFER, buf_id); glBufferData(GL_TEXTURE_BUFFER, narrow<GLintptr>(buffer_size), nullptr, GL_STREAM_DRAW); // Create texture object glGenTextures(1, &tex_id); glBindTexture(GL_TEXTURE_BUFFER, tex_id); // Associate data buffer to texture object glTexBuffer(GL_TEXTURE_BUFFER, buffer_texture_type_to_gl_enums(type), buf_id); m_tex_id.set(tex_id); m_buf_id.set(buf_id); MG_CHECK_GL_ERROR(); } BufferTexture::~BufferTexture() { MG_GFX_DEBUG_GROUP("BufferTexture::~BufferTexture"); const auto buf_id = m_buf_id.as_gl_id(); const auto tex_id = m_tex_id.as_gl_id(); glDeleteTextures(1, &tex_id); glDeleteBuffers(1, &buf_id); } void BufferTexture::set_data(span<const std::byte> data) noexcept { MG_GFX_DEBUG_GROUP("BufferTexture::set_data"); MG_ASSERT(data.size_bytes() <= m_buffer_size); // Update data buffer contents const auto buf_id = m_buf_id.as_gl_id(); glBindBuffer(GL_TEXTURE_BUFFER, buf_id); glBufferSubData(GL_TEXTURE_BUFFER, 0, narrow<GLsizeiptr>(data.size_bytes()), data.data()); } } // namespace Mg::gfx
30.220779
100
0.529724
Magnutic
8880abbc556ddb6f7baa500a24ea40ae938650d3
426,038
cpp
C++
src/ints/bios.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
3
2022-02-20T11:06:29.000Z
2022-03-11T08:16:55.000Z
src/ints/bios.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
null
null
null
src/ints/bios.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2002-2021 The DOSBox Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <assert.h> #include "control.h" #include "dosbox.h" #include "mem.h" #include "cpu.h" #include "bios.h" #include "regs.h" #include "timer.h" #include "cpu.h" #include "callback.h" #include "inout.h" #include "pic.h" #include "hardware.h" #include "pci_bus.h" #include "joystick.h" #include "mouse.h" #include "callback.h" #include "setup.h" #include "bios_disk.h" #include "serialport.h" #include "mapper.h" #include "vga.h" #include "jfont.h" #include "shiftjis.h" #include "pc98_gdc.h" #include "pc98_gdc_const.h" #include "regionalloctracking.h" #include "build_timestamp.h" extern bool PS1AudioCard; #include "parport.h" #include "dma.h" #include "shell.h" #include "render.h" #include "sdlmain.h" #include <time.h> #include <sys/stat.h> #if defined(DB_HAVE_CLOCK_GETTIME) && ! defined(WIN32) //time.h is already included #else #include <sys/timeb.h> #endif #if C_EMSCRIPTEN # include <emscripten.h> #endif #if defined(_MSC_VER) # pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ # pragma warning(disable:4305) /* truncation from double to float */ #endif #if defined(WIN32) && !defined(S_ISREG) # define S_ISREG(x) ((x & S_IFREG) == S_IFREG) #endif std::string ibm_rom_basic; size_t ibm_rom_basic_size = 0; uint32_t ibm_rom_basic_base = 0; /* NTS: The "Epson check" code in Windows 2.1 only compares up to the end of "NEC Corporation" */ const std::string pc98_copyright_str = "Copyright (C) 1983 by NEC Corporation / Microsoft Corp.\x0D\x0A"; /* more strange data involved in the "Epson check" */ const unsigned char pc98_epson_check_2[0x27] = { 0x26,0x8A,0x05,0xA8,0x10,0x75,0x11,0xC6,0x06,0xD6,0x09,0x1B,0xC6,0x06,0xD7,0x09, 0x4B,0xC6,0x06,0xD8,0x09,0x48,0xEB,0x0F,0xC6,0x06,0xD6,0x09,0x1A,0xC6,0x06,0xD7 , 0x09,0x70,0xC6,0x06,0xD8,0x09,0x71 }; bool enable_pc98_copyright_string = false; /* mouse.cpp */ extern bool pc98_40col_text; extern bool en_bios_ps2mouse; extern bool rom_bios_8x8_cga_font; extern bool pcibus_enable; extern bool enable_fpu; uint32_t Keyb_ig_status(); bool VM_Boot_DOSBox_Kernel(); uint32_t MEM_get_address_bits(); Bitu bios_post_parport_count(); Bitu bios_post_comport_count(); void pc98_update_cpu_page_ptr(void); bool KEYBOARD_Report_BIOS_PS2Mouse(); bool gdc_5mhz_according_to_bios(void); void pc98_update_display_page_ptr(void); void pc98_update_palette(void); bool MEM_map_ROM_alias_physmem(Bitu start,Bitu end); void MOUSE_Startup(Section *sec); void change_output(int output); void runBoot(const char *str); void SetIMPosition(void); bool isDBCSCP(); Bitu INT60_Handler(void); Bitu INT6F_Handler(void); #if defined(USE_TTF) void ttf_switch_on(bool ss), ttf_switch_off(bool ss), ttf_setlines(int cols, int lins); #endif bool bochs_port_e9 = false; bool isa_memory_hole_512kb = false; bool int15_wait_force_unmask_irq = false; int unhandled_irq_method = UNHANDLED_IRQ_SIMPLE; unsigned int reset_post_delay = 0; Bitu call_irq_default = 0; uint16_t biosConfigSeg=0; Bitu BIOS_DEFAULT_IRQ0_LOCATION = ~0u; // (RealMake(0xf000,0xfea5)) Bitu BIOS_DEFAULT_IRQ1_LOCATION = ~0u; // (RealMake(0xf000,0xe987)) Bitu BIOS_DEFAULT_IRQ07_DEF_LOCATION = ~0u; // (RealMake(0xf000,0xff55)) Bitu BIOS_DEFAULT_IRQ815_DEF_LOCATION = ~0u; // (RealMake(0xf000,0xe880)) Bitu BIOS_DEFAULT_HANDLER_LOCATION = ~0u; // (RealMake(0xf000,0xff53)) Bitu BIOS_DEFAULT_INT5_LOCATION = ~0u; // (RealMake(0xf000,0xff54)) Bitu BIOS_VIDEO_TABLE_LOCATION = ~0u; // RealMake(0xf000,0xf0a4) Bitu BIOS_VIDEO_TABLE_SIZE = 0u; Bitu BIOS_DEFAULT_RESET_LOCATION = ~0u; // RealMake(0xf000,0xe05b) Bitu BIOS_DEFAULT_RESET_CODE_LOCATION = ~0u; bool allow_more_than_640kb = false; unsigned int APM_BIOS_connected_minor_version = 0;// what version the OS connected to us with. default to 1.0 unsigned int APM_BIOS_minor_version = 2; // what version to emulate e.g to emulate 1.2 set this to 2 /* default bios type/version/date strings */ const char* const bios_type_string = "IBM COMPATIBLE BIOS for DOSBox-X"; const char* const bios_version_string = "DOSBox-X BIOS v1.0"; const char* const bios_date_string = "01/01/92"; bool APM_inactivity_timer = true; RegionAllocTracking rombios_alloc; Bitu rombios_minimum_location = 0xF0000; /* minimum segment allowed */ Bitu rombios_minimum_size = 0x10000; bool MEM_map_ROM_physmem(Bitu start,Bitu end); bool MEM_unmap_physmem(Bitu start,Bitu end); static std::string bochs_port_e9_line; static void bochs_port_e9_flush() { if (!bochs_port_e9_line.empty()) { LOG_MSG("Bochs port E9h: %s",bochs_port_e9_line.c_str()); bochs_port_e9_line.clear(); } } void bochs_port_e9_write(Bitu port,Bitu val,Bitu /*iolen*/) { (void)port;//UNUSED if (val == '\n' || val == '\r') { bochs_port_e9_flush(); } else { bochs_port_e9_line += (char)val; if (bochs_port_e9_line.length() >= 256) bochs_port_e9_flush(); } } void ROMBIOS_DumpMemory() { rombios_alloc.logDump(); } void ROMBIOS_SanityCheck() { rombios_alloc.sanityCheck(); } Bitu ROMBIOS_MinAllocatedLoc() { Bitu r = rombios_alloc.getMinAddress(); if (r > (0x100000u - rombios_minimum_size)) r = (0x100000u - rombios_minimum_size); return r & ~0xFFFu; } void ROMBIOS_FreeUnusedMinToLoc(Bitu phys) { Bitu new_phys; if (rombios_minimum_location & 0xFFF) E_Exit("ROMBIOS: FreeUnusedMinToLoc minimum location not page aligned"); phys &= ~0xFFFUL; new_phys = rombios_alloc.freeUnusedMinToLoc(phys) & (~0xFFFUL); assert(new_phys >= phys); if (phys < new_phys) MEM_unmap_physmem(phys,new_phys-1); rombios_minimum_location = new_phys; ROMBIOS_SanityCheck(); ROMBIOS_DumpMemory(); } bool ROMBIOS_FreeMemory(Bitu phys) { return rombios_alloc.freeMemory(phys); } Bitu ROMBIOS_GetMemory(Bitu bytes,const char *who,Bitu alignment,Bitu must_be_at) { return rombios_alloc.getMemory(bytes,who,alignment,must_be_at); } void ROMBIOS_InitForCustomBIOS(void) { rombios_alloc.initSetRange(0xD8000,0xE0000); } static IO_Callout_t dosbox_int_iocallout = IO_Callout_t_none; static unsigned char dosbox_int_register_shf = 0; static uint32_t dosbox_int_register = 0; static unsigned char dosbox_int_regsel_shf = 0; static uint32_t dosbox_int_regsel = 0; static bool dosbox_int_error = false; static bool dosbox_int_busy = false; static const char *dosbox_int_version = "DOSBox-X integration device v1.0"; static const char *dosbox_int_ver_read = NULL; struct dosbox_int_saved_state { unsigned char dosbox_int_register_shf; uint32_t dosbox_int_register; unsigned char dosbox_int_regsel_shf; uint32_t dosbox_int_regsel; bool dosbox_int_error; bool dosbox_int_busy; }; #define DOSBOX_INT_SAVED_STATE_MAX 4 struct dosbox_int_saved_state dosbox_int_saved[DOSBOX_INT_SAVED_STATE_MAX]; int dosbox_int_saved_sp = -1; /* for use with interrupt handlers in DOS/Windows that need to save IG state * to ensure that IG state is restored on return in order to not interfere * with anything userspace is doing (as an alternative to wrapping all access * in CLI/STI or PUSHF/CLI/POPF) */ bool dosbox_int_push_save_state(void) { if (dosbox_int_saved_sp >= (DOSBOX_INT_SAVED_STATE_MAX-1)) return false; struct dosbox_int_saved_state *ss = &dosbox_int_saved[++dosbox_int_saved_sp]; ss->dosbox_int_register_shf = dosbox_int_register_shf; ss->dosbox_int_register = dosbox_int_register; ss->dosbox_int_regsel_shf = dosbox_int_regsel_shf; ss->dosbox_int_regsel = dosbox_int_regsel; ss->dosbox_int_error = dosbox_int_error; ss->dosbox_int_busy = dosbox_int_busy; return true; } bool dosbox_int_pop_save_state(void) { if (dosbox_int_saved_sp < 0) return false; struct dosbox_int_saved_state *ss = &dosbox_int_saved[dosbox_int_saved_sp--]; dosbox_int_register_shf = ss->dosbox_int_register_shf; dosbox_int_register = ss->dosbox_int_register; dosbox_int_regsel_shf = ss->dosbox_int_regsel_shf; dosbox_int_regsel = ss->dosbox_int_regsel; dosbox_int_error = ss->dosbox_int_error; dosbox_int_busy = ss->dosbox_int_busy; return true; } bool dosbox_int_discard_save_state(void) { if (dosbox_int_saved_sp < 0) return false; dosbox_int_saved_sp--; return true; } extern bool user_cursor_locked; extern int user_cursor_x,user_cursor_y; extern int user_cursor_sw,user_cursor_sh; extern int master_cascade_irq,bootdrive; extern bool enable_slave_pic; extern bool bootguest, use_quick_reboot; bool bootvm = false, bootfast = false; static std::string dosbox_int_debug_out; void VGA_SetCaptureStride(uint32_t v); void VGA_SetCaptureAddress(uint32_t v); void VGA_SetCaptureState(uint32_t v); SDL_Rect &VGA_CaptureRectCurrent(void); SDL_Rect &VGA_CaptureRectFromGuest(void); uint32_t VGA_QueryCaptureAddress(void); uint32_t VGA_QueryCaptureState(void); uint32_t VGA_QuerySizeIG(void); uint32_t Mixer_MIXQ(void); uint32_t Mixer_MIXC(void); void Mixer_MIXC_Write(uint32_t v); PhysPt Mixer_MIXWritePos(void); void Mixer_MIXWritePos_Write(PhysPt np); void Mixer_MIXWriteBegin_Write(PhysPt np); void Mixer_MIXWriteEnd_Write(PhysPt np); /* read triggered, update the regsel */ void dosbox_integration_trigger_read() { dosbox_int_error = false; switch (dosbox_int_regsel) { case 0: /* Identification */ dosbox_int_register = 0xD05B0740; break; case 1: /* test */ break; case 2: /* version string */ if (dosbox_int_ver_read == NULL) dosbox_int_ver_read = dosbox_int_version; dosbox_int_register = 0; for (Bitu i=0;i < 4;i++) { if (*dosbox_int_ver_read == 0) { dosbox_int_ver_read = dosbox_int_version; break; } dosbox_int_register += ((uint32_t)((unsigned char)(*dosbox_int_ver_read++))) << (uint32_t)(i * 8); } break; case 3: /* version number */ dosbox_int_register = (0x01U/*major*/) + (0x00U/*minor*/ << 8U) + (0x00U/*subver*/ << 16U) + (0x01U/*bump*/ << 24U); break; case 4: /* current emulator time as 16.16 fixed point */ dosbox_int_register = (uint32_t)(PIC_FullIndex() * 0x10000); break; case 0x5158494D: /* query mixer output 'MIXQ' */ /* bits [19:0] = sample rate in Hz or 0 if mixer is not mixing AT ALL * bits [23:20] = number of channels (at this time, always 2 aka stereo) * bits [29:29] = 1=swap stereo 0=normal * bits [30:30] = 1=muted 0=not muted * bits [31:31] = 1=sound 0=nosound */ dosbox_int_register = Mixer_MIXQ(); break; case 0x4358494D: /* query mixer output 'MIXC' */ dosbox_int_register = Mixer_MIXC(); break; case 0x5058494D: /* query mixer output 'MIXP' */ dosbox_int_register = Mixer_MIXWritePos(); break; case 0x4258494D: /* query mixer output 'MIXB' */ break; case 0x4558494D: /* query mixer output 'MIXE' */ break; case 0x6845C0: /* query VGA display size */ dosbox_int_register = VGA_QuerySizeIG(); break; case 0x6845C1: /* query VGA capture state */ dosbox_int_register = VGA_QueryCaptureState(); break; case 0x6845C2: /* query VGA capture address (what is being captured to NOW) */ dosbox_int_register = VGA_QueryCaptureAddress(); break; case 0x6845C3: /* query VGA capture current crop rectangle (position) will not reflect new rectangle until VGA capture finishes capture. */ { const SDL_Rect &r = VGA_CaptureRectCurrent(); dosbox_int_register = ((uint32_t)r.y << (uint32_t)16ul) + (uint32_t)r.x; } break; case 0x6845C4: /* query VGA capture current crop rectangle (size). will not reflect new rectangle until VGA capture finishes capture. */ { const SDL_Rect &r = VGA_CaptureRectCurrent(); dosbox_int_register = ((uint32_t)r.h << (uint32_t)16ul) + (uint32_t)r.w; } break; case 0x825901: /* PIC configuration */ /* bits [7:0] = cascade interrupt or 0xFF if none * bit [8:8] = primary PIC present * bit [9:9] = secondary PIC present */ if (master_cascade_irq >= 0) dosbox_int_register = ((unsigned int)master_cascade_irq & 0xFFu); else dosbox_int_register = 0xFFu; dosbox_int_register |= 0x100; // primary always present if (enable_slave_pic) dosbox_int_register |= 0x200; break; case 0x823780: /* ISA DMA injection, single byte/word (read from memory) */ break; // case 0x804200: /* keyboard input injection -- not supposed to read */ // break; case 0x804201: /* keyboard status */ dosbox_int_register = Keyb_ig_status(); break; case 0x434D54: /* read user mouse status */ dosbox_int_register = (user_cursor_locked ? (1UL << 0UL) : 0UL); /* bit 0 = mouse capture lock */ break; case 0x434D55: /* read user mouse cursor position */ dosbox_int_register = (uint32_t((uint16_t)user_cursor_y & 0xFFFFUL) << 16UL) | uint32_t((uint16_t)user_cursor_x & 0xFFFFUL); break; case 0x434D56: { /* read user mouse cursor position (normalized for Windows 3.x) */ signed long long x = ((signed long long)user_cursor_x << 16LL) / (signed long long)(user_cursor_sw-1); signed long long y = ((signed long long)user_cursor_y << 16LL) / (signed long long)(user_cursor_sh-1); if (x < 0x0000LL) x = 0x0000LL; if (x > 0xFFFFLL) x = 0xFFFFLL; if (y < 0x0000LL) y = 0x0000LL; if (y > 0xFFFFLL) y = 0xFFFFLL; dosbox_int_register = ((unsigned int)y << 16UL) | (unsigned int)x; } break; case 0xC54010: /* Screenshot/capture trigger */ /* TODO: This should also be hidden behind an enable switch, so that rogue DOS development * can't retaliate if the user wants to capture video or screenshots. */ #if (C_SSHOT) dosbox_int_register = 0x00000000; // available if (CaptureState & CAPTURE_IMAGE) dosbox_int_register |= 1 << 0; // Image capture is in progress if (CaptureState & CAPTURE_VIDEO) dosbox_int_register |= 1 << 1; // Video capture is in progress if (CaptureState & CAPTURE_WAVE) dosbox_int_register |= 1 << 2; // WAVE capture is in progress #else dosbox_int_register = 0xC0000000; // not available (bit 31 set), not enabled (bit 30 set) #endif break; case 0xAA55BB66UL: /* interface reset result */ break; default: dosbox_int_register = 0xAA55AA55; dosbox_int_error = true; break; } LOG(LOG_MISC,LOG_DEBUG)("DOSBox-X integration read 0x%08lx got 0x%08lx (err=%u)\n", (unsigned long)dosbox_int_regsel, (unsigned long)dosbox_int_register, dosbox_int_error?1:0); } bool watchdog_set = false; void Watchdog_Timeout_Event(Bitu /*val*/) { LOG_MSG("Watchdog timeout occurred"); CPU_Raise_NMI(); } void Watchdog_Timer_Clear(void) { if (watchdog_set) { PIC_RemoveEvents(Watchdog_Timeout_Event); watchdog_set = false; } } void Watchdog_Timer_Set(uint32_t timeout_ms) { Watchdog_Timer_Clear(); if (timeout_ms != 0) { watchdog_set = true; PIC_AddEvent(Watchdog_Timeout_Event,(double)timeout_ms); } } unsigned int mouse_notify_mode = 0; // 0 = off // 1 = trigger as PS/2 mouse interrupt /* write triggered */ void dosbox_integration_trigger_write() { dosbox_int_error = false; LOG(LOG_MISC,LOG_DEBUG)("DOSBox-X integration write 0x%08lx val 0x%08lx\n", (unsigned long)dosbox_int_regsel, (unsigned long)dosbox_int_register); switch (dosbox_int_regsel) { case 1: /* test */ break; case 2: /* version string */ dosbox_int_ver_read = NULL; break; case 0xDEB0: /* debug output (to log) */ for (unsigned int b=0;b < 4;b++) { unsigned char c = (unsigned char)(dosbox_int_register >> (b * 8U)); if (c == '\n' || dosbox_int_debug_out.length() >= 200) { LOG_MSG("Client debug message: %s\n",dosbox_int_debug_out.c_str()); dosbox_int_debug_out.clear(); } else if (c != 0) { dosbox_int_debug_out += ((char)c); } else { break; } } dosbox_int_register = 0; break; case 0xDEB1: /* debug output clear */ dosbox_int_debug_out.clear(); break; case 0x6845C1: /* query VGA capture state */ VGA_SetCaptureState(dosbox_int_register); break; case 0x6845C2: /* set VGA capture address, will be applied to next capture */ VGA_SetCaptureAddress(dosbox_int_register); break; case 0x6845C3: /* set VGA capture crop rectangle (position), will be applied to next capture */ { SDL_Rect &r = VGA_CaptureRectFromGuest(); r.x = (int)(dosbox_int_register & 0xFFFF); r.y = (int)(dosbox_int_register >> 16ul); } break; case 0x6845C4: /* set VGA capture crop rectangle (size), will be applied to next capture */ { SDL_Rect &r = VGA_CaptureRectFromGuest(); r.w = (int)(dosbox_int_register & 0xFFFF); r.h = (int)(dosbox_int_register >> 16ul); } break; case 0x6845C5: /* set VGA capture stride (bytes per scan line) */ VGA_SetCaptureStride(dosbox_int_register); break; case 0x52434D: /* release mouse capture 'MCR' */ void GFX_ReleaseMouse(void); GFX_ReleaseMouse(); break; case 0x5158494D: /* query mixer output 'MIXQ' */ break; case 0x4358494D: /* query mixer output 'MIXC' */ Mixer_MIXC_Write(dosbox_int_register); break; case 0x5058494D: /* query mixer output 'MIXP' */ Mixer_MIXWritePos_Write(dosbox_int_register); break; case 0x4258494D: /* query mixer output 'MIXB' */ Mixer_MIXWriteBegin_Write(dosbox_int_register); break; case 0x4558494D: /* query mixer output 'MIXE' */ Mixer_MIXWriteEnd_Write(dosbox_int_register); break; case 0x57415444: /* Set/clear watchdog timer 'WATD' */ Watchdog_Timer_Set(dosbox_int_register); break; case 0x808602: /* NMI (INT 02h) interrupt injection */ { dosbox_int_register_shf = 0; dosbox_int_regsel_shf = 0; CPU_Raise_NMI(); } break; case 0x825900: /* PIC interrupt injection */ { dosbox_int_register_shf = 0; dosbox_int_regsel_shf = 0; /* bits [7:0] = IRQ to signal (must be 0-15) * bit [8:8] = 1=raise 0=lower IRQ */ uint8_t IRQ = dosbox_int_register&0xFFu; bool raise = (dosbox_int_register>>8u)&1u; if (IRQ < 16) { if (raise) PIC_ActivateIRQ(IRQ); else PIC_DeActivateIRQ(IRQ); } } break; case 0x823700: /* ISA DMA injection, single byte/word (write to memory) */ { dosbox_int_register_shf = 0; dosbox_int_regsel_shf = 0; /* bits [7:0] = data byte if 8-bit DNA * bits [15:0] = data word if 16-bit DMA * bits [18:16] = DMA channel to send to */ DmaChannel *ch = GetDMAChannel(((unsigned int)dosbox_int_register>>16u)&7u); if (ch != NULL) { unsigned char tmp[2]; tmp[0] = (unsigned char)( dosbox_int_register & 0xFFu); tmp[1] = (unsigned char)((dosbox_int_register >> 8u) & 0xFFu); /* NTS: DMA channel write will write tmp[0] if 8-bit, tmp[0]/tmp[1] if 16-bit */ if (ch->Write(1/*one unit of transfer*/,tmp) == 1) { dosbox_int_register = 0; dosbox_int_error = false; } else { dosbox_int_register = 0x823700; dosbox_int_error = true; } } else { dosbox_int_register = 0x8237FF; dosbox_int_error = true; } } break; case 0x823780: /* ISA DMA injection, single byte/word (read from memory) */ { dosbox_int_register_shf = 0; dosbox_int_regsel_shf = 0; /* bits [18:16] = DMA channel to send to */ DmaChannel *ch = GetDMAChannel(((unsigned int)dosbox_int_register>>16u)&7u); if (ch != NULL) { unsigned char tmp[2]; /* NTS: DMA channel write will write tmp[0] if 8-bit, tmp[0]/tmp[1] if 16-bit */ tmp[0] = tmp[1] = 0; if (ch->Read(1/*one unit of transfer*/,tmp) == 1) { dosbox_int_register = ((unsigned int)tmp[1] << 8u) + (unsigned int)tmp[0]; dosbox_int_error = false; } else { dosbox_int_register = 0x823700; dosbox_int_error = true; } } else { dosbox_int_register = 0x8237FF; dosbox_int_error = true; } } break; case 0x804200: /* keyboard input injection */ void Mouse_ButtonPressed(uint8_t button); void Mouse_ButtonReleased(uint8_t button); void pc98_keyboard_send(const unsigned char b); void Mouse_CursorMoved(float xrel,float yrel,float x,float y,bool emulate); void KEYBOARD_AUX_Event(float x,float y,Bitu buttons,int scrollwheel); void KEYBOARD_AddBuffer(uint16_t data); switch ((dosbox_int_register>>8)&0xFF) { case 0x00: // keyboard if (IS_PC98_ARCH) pc98_keyboard_send(dosbox_int_register&0xFF); else KEYBOARD_AddBuffer(dosbox_int_register&0xFF); break; case 0x01: // AUX if (!IS_PC98_ARCH) KEYBOARD_AddBuffer((dosbox_int_register&0xFF)|0x100/*AUX*/); else // no such interface in PC-98 mode dosbox_int_error = true; break; case 0x08: // mouse button injection if (dosbox_int_register&0x80) Mouse_ButtonPressed(dosbox_int_register&0x7F); else Mouse_ButtonReleased(dosbox_int_register&0x7F); break; case 0x09: // mouse movement injection (X) Mouse_CursorMoved(((dosbox_int_register>>16UL) / 256.0f) - 1.0f,0,0,0,true); break; case 0x0A: // mouse movement injection (Y) Mouse_CursorMoved(0,((dosbox_int_register>>16UL) / 256.0f) - 1.0f,0,0,true); break; case 0x0B: // mouse scrollwheel injection // TODO break; default: dosbox_int_error = true; break; } break; // case 0x804201: /* keyboard status do not write */ // break; /* this command is used to enable notification of mouse movement over the windows even if the mouse isn't captured */ case 0x434D55: /* read user mouse cursor position */ case 0x434D56: /* read user mouse cursor position (normalized for Windows 3.x) */ mouse_notify_mode = dosbox_int_register & 0xFF; LOG(LOG_MISC,LOG_DEBUG)("Mouse notify mode=%u",mouse_notify_mode); break; case 0xC54010: /* Screenshot/capture trigger */ #if (C_SSHOT) void CAPTURE_ScreenShotEvent(bool pressed); void CAPTURE_VideoEvent(bool pressed); #endif void CAPTURE_WaveEvent(bool pressed); /* TODO: It would be wise to grant/deny access to this register through another dosbox-x.conf option * so that rogue DOS development cannot shit-spam the capture folder */ #if (C_SSHOT) if (dosbox_int_register & 1) CAPTURE_ScreenShotEvent(true); if (dosbox_int_register & 2) CAPTURE_VideoEvent(true); #endif if (dosbox_int_register & 4) CAPTURE_WaveEvent(true); break; default: dosbox_int_register = 0x55AA55AA; dosbox_int_error = true; break; } } /* PORT 0x28: Index * 0x29: Data * 0x2A: Status(R) or Command(W) * 0x2B: Not yet assigned * * Registers are 32-bit wide. I/O to index and data rotate through the * bytes of the register depending on I/O length, meaning that one 32-bit * I/O read will read the entire register, while four 8-bit reads will * read one byte out of 4. */ static Bitu dosbox_integration_port00_index_r(Bitu port,Bitu iolen) { (void)port;//UNUSED Bitu retb = 0; Bitu ret = 0; while (iolen > 0) { ret += ((dosbox_int_regsel >> (dosbox_int_regsel_shf * 8)) & 0xFFU) << (retb * 8); if ((++dosbox_int_regsel_shf) >= 4) dosbox_int_regsel_shf = 0; iolen--; retb++; } return ret; } static void dosbox_integration_port00_index_w(Bitu port,Bitu val,Bitu iolen) { (void)port;//UNUSED while (iolen > 0) { uint32_t msk = 0xFFU << (dosbox_int_regsel_shf * 8); dosbox_int_regsel = (dosbox_int_regsel & ~msk) + ((val & 0xFF) << (dosbox_int_regsel_shf * 8)); if ((++dosbox_int_regsel_shf) >= 4) dosbox_int_regsel_shf = 0; val >>= 8U; iolen--; } } static Bitu dosbox_integration_port01_data_r(Bitu port,Bitu iolen) { (void)port;//UNUSED Bitu retb = 0; Bitu ret = 0; while (iolen > 0) { if (dosbox_int_register_shf == 0) dosbox_integration_trigger_read(); ret += ((dosbox_int_register >> (dosbox_int_register_shf * 8)) & 0xFFU) << (retb * 8); if ((++dosbox_int_register_shf) >= 4) dosbox_int_register_shf = 0; iolen--; retb++; } return ret; } static void dosbox_integration_port01_data_w(Bitu port,Bitu val,Bitu iolen) { (void)port;//UNUSED while (iolen > 0) { uint32_t msk = 0xFFU << (dosbox_int_register_shf * 8); dosbox_int_register = (dosbox_int_register & ~msk) + ((val & 0xFF) << (dosbox_int_register_shf * 8)); if ((++dosbox_int_register_shf) >= 4) dosbox_int_register_shf = 0; if (dosbox_int_register_shf == 0) dosbox_integration_trigger_write(); val >>= 8U; iolen--; } } static Bitu dosbox_integration_port02_status_r(Bitu port,Bitu iolen) { (void)iolen;//UNUSED (void)port;//UNUSED /* status */ /* 7:6 = regsel byte index * 5:4 = register byte index * 3:2 = reserved * 1 = error * 0 = busy */ return ((unsigned int)dosbox_int_regsel_shf << 6u) + ((unsigned int)dosbox_int_register_shf << 4u) + (dosbox_int_error ? 2u : 0u) + (dosbox_int_busy ? 1u : 0u); } static void dosbox_integration_port02_command_w(Bitu port,Bitu val,Bitu iolen) { (void)port; (void)iolen; switch (val) { case 0x00: /* reset latch */ dosbox_int_register_shf = 0; dosbox_int_regsel_shf = 0; break; case 0x01: /* flush write */ if (dosbox_int_register_shf != 0) { dosbox_integration_trigger_write(); dosbox_int_register_shf = 0; } break; case 0x20: /* push state */ if (dosbox_int_push_save_state()) { dosbox_int_register_shf = 0; dosbox_int_regsel_shf = 0; dosbox_int_error = false; dosbox_int_busy = false; dosbox_int_regsel = 0xAA55BB66; dosbox_int_register = 0xD05B0C5; LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG state saved"); } else { LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG unable to push state, stack overflow"); dosbox_int_error = true; } break; case 0x21: /* pop state */ if (dosbox_int_pop_save_state()) { LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG state restored"); } else { LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG unable to pop state, stack underflow"); dosbox_int_error = true; } break; case 0x22: /* discard state */ if (dosbox_int_discard_save_state()) { LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG state discarded"); } else { LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG unable to discard state, stack underflow"); dosbox_int_error = true; } break; case 0x23: /* discard all state */ while (dosbox_int_discard_save_state()); break; case 0xFE: /* clear error */ dosbox_int_error = false; break; case 0xFF: /* reset interface */ dosbox_int_busy = false; dosbox_int_error = false; dosbox_int_regsel = 0xAA55BB66; dosbox_int_register = 0xD05B0C5; break; default: dosbox_int_error = true; break; } } static IO_ReadHandler* const dosbox_integration_cb_ports_r[4] = { dosbox_integration_port00_index_r, dosbox_integration_port01_data_r, dosbox_integration_port02_status_r, NULL }; static IO_ReadHandler* dosbox_integration_cb_port_r(IO_CalloutObject &co,Bitu port,Bitu iolen) { (void)co; (void)iolen; return dosbox_integration_cb_ports_r[port&3]; } static IO_WriteHandler* const dosbox_integration_cb_ports_w[4] = { dosbox_integration_port00_index_w, dosbox_integration_port01_data_w, dosbox_integration_port02_command_w, NULL }; static IO_WriteHandler* dosbox_integration_cb_port_w(IO_CalloutObject &co,Bitu port,Bitu iolen) { (void)co; (void)iolen; return dosbox_integration_cb_ports_w[port&3]; } /* if mem_systems 0 then size_extended is reported as the real size else * zero is reported. ems and xms can increase or decrease the other_memsystems * counter using the BIOS_ZeroExtendedSize call */ static uint16_t size_extended; static unsigned int ISA_PNP_WPORT = 0x20B; static unsigned int ISA_PNP_WPORT_BIOS = 0; static IO_ReadHandleObject *ISAPNP_PNP_READ_PORT = NULL; /* 0x200-0x3FF range */ static IO_WriteHandleObject *ISAPNP_PNP_ADDRESS_PORT = NULL; /* 0x279 */ static IO_WriteHandleObject *ISAPNP_PNP_DATA_PORT = NULL; /* 0xA79 */ static IO_WriteHandleObject *BOCHS_PORT_E9 = NULL; //static unsigned char ISA_PNP_CUR_CSN = 0; static unsigned char ISA_PNP_CUR_ADDR = 0; static unsigned char ISA_PNP_CUR_STATE = 0; enum { ISA_PNP_WAIT_FOR_KEY=0, ISA_PNP_SLEEP, ISA_PNP_ISOLATE, ISA_PNP_CONFIG }; const unsigned char isa_pnp_init_keystring[32] = { 0x6A,0xB5,0xDA,0xED,0xF6,0xFB,0x7D,0xBE, 0xDF,0x6F,0x37,0x1B,0x0D,0x86,0xC3,0x61, 0xB0,0x58,0x2C,0x16,0x8B,0x45,0xA2,0xD1, 0xE8,0x74,0x3A,0x9D,0xCE,0xE7,0x73,0x39 }; static RealPt INT15_apm_pmentry=0; static unsigned char ISA_PNP_KEYMATCH=0; static Bits other_memsystems=0; static bool apm_realmode_connected = false; void CMOS_SetRegister(Bitu regNr, uint8_t val); //For setting equipment word bool enable_integration_device_pnp=false; bool enable_integration_device=false; bool ISAPNPBIOS=false; bool APMBIOS=false; bool APMBIOS_pnp=false; bool APMBIOS_allow_realmode=false; bool APMBIOS_allow_prot16=false; bool APMBIOS_allow_prot32=false; int APMBIOS_connect_mode=0; enum { APMBIOS_CONNECT_REAL=0, APMBIOS_CONNECT_PROT16, APMBIOS_CONNECT_PROT32 }; unsigned int APMBIOS_connected_already_err() { switch (APMBIOS_connect_mode) { case APMBIOS_CONNECT_REAL: return 0x02; case APMBIOS_CONNECT_PROT16: return 0x05; case APMBIOS_CONNECT_PROT32: return 0x07; } return 0x00; } ISAPnPDevice::ISAPnPDevice() { memset(ident,0,sizeof(ident)); } bool ISAPnPDevice::alloc(size_t sz) { if (sz == alloc_sz) return true; if (alloc_res == resource_data) { resource_data_len = 0; resource_data_pos = 0; resource_data = NULL; } if (alloc_res != NULL) delete[] alloc_res; alloc_res = NULL; alloc_write = 0; alloc_sz = 0; if (sz == 0) return true; if (sz > 65536) return false; alloc_res = new unsigned char[sz]; if (alloc_res == NULL) return false; memset(alloc_res,0xFF,sz); alloc_sz = sz; return true; } ISAPnPDevice::~ISAPnPDevice() { ISAPnPDevice::alloc(0); } void ISAPnPDevice::begin_write_res() { if (alloc_res == NULL) return; resource_data_pos = 0; resource_data_len = 0; resource_data = NULL; alloc_write = 0; } void ISAPnPDevice::write_byte(const unsigned char c) { if (alloc_res == NULL || alloc_write >= alloc_sz) return; alloc_res[alloc_write++] = c; } void ISAPnPDevice::write_begin_SMALLTAG(const ISAPnPDevice::SmallTags stag,unsigned char len) { if (len >= 8 || (unsigned int)stag >= 0x10) return; write_byte(((unsigned char)stag << 3) + len); } void ISAPnPDevice::write_begin_LARGETAG(const ISAPnPDevice::LargeTags stag,unsigned int len) { if (len >= 4096) return; write_byte(0x80 + ((unsigned char)stag)); write_byte(len & 0xFF); write_byte(len >> 8); } void ISAPnPDevice::write_Device_ID(const char c1,const char c2,const char c3,const char c4,const char c5,const char c6,const char c7) { write_byte((((unsigned char)c1 & 0x1FU) << 2) + (((unsigned char)c2 & 0x18U) >> 3)); write_byte((((unsigned char)c2 & 0x07U) << 5) + ((unsigned char)c3 & 0x1FU)); write_byte((((unsigned char)c4 & 0x0FU) << 4) + ((unsigned char)c5 & 0x0FU)); write_byte((((unsigned char)c6 & 0x0FU) << 4) + ((unsigned char)c7 & 0x0FU)); } void ISAPnPDevice::write_Logical_Device_ID(const char c1,const char c2,const char c3,const char c4,const char c5,const char c6,const char c7) { write_begin_SMALLTAG(SmallTags::LogicalDeviceID,5); write_Device_ID(c1,c2,c3,c4,c5,c6,c7); write_byte(0x00); } void ISAPnPDevice::write_Compatible_Device_ID(const char c1,const char c2,const char c3,const char c4,const char c5,const char c6,const char c7) { write_begin_SMALLTAG(SmallTags::CompatibleDeviceID,4); write_Device_ID(c1,c2,c3,c4,c5,c6,c7); } void ISAPnPDevice::write_IRQ_Format(const uint16_t IRQ_mask,const unsigned char IRQ_signal_type) { bool write_irq_info = (IRQ_signal_type != 0); write_begin_SMALLTAG(SmallTags::IRQFormat,write_irq_info?3:2); write_byte(IRQ_mask & 0xFF); write_byte(IRQ_mask >> 8); if (write_irq_info) write_byte(((unsigned char)IRQ_signal_type & 0x0F)); } void ISAPnPDevice::write_DMA_Format(const uint8_t DMA_mask,const unsigned char transfer_type_preference,const bool is_bus_master,const bool byte_mode,const bool word_mode,const unsigned char speed_supported) { write_begin_SMALLTAG(SmallTags::DMAFormat,2); write_byte(DMA_mask); write_byte( (transfer_type_preference & 0x03) | (is_bus_master ? 0x04 : 0x00) | (byte_mode ? 0x08 : 0x00) | (word_mode ? 0x10 : 0x00) | ((speed_supported & 3) << 5)); } void ISAPnPDevice::write_IO_Port(const uint16_t min_port,const uint16_t max_port,const uint8_t count,const uint8_t alignment,const bool full16bitdecode) { write_begin_SMALLTAG(SmallTags::IOPortDescriptor,7); write_byte((full16bitdecode ? 0x01 : 0x00)); write_byte(min_port & 0xFF); write_byte(min_port >> 8); write_byte(max_port & 0xFF); write_byte(max_port >> 8); write_byte(alignment); write_byte(count); } void ISAPnPDevice::write_Dependent_Function_Start(const ISAPnPDevice::DependentFunctionConfig cfg,const bool force) { bool write_cfg_byte = force || (cfg != ISAPnPDevice::DependentFunctionConfig::AcceptableDependentConfiguration); write_begin_SMALLTAG(SmallTags::StartDependentFunctions,write_cfg_byte ? 1 : 0); if (write_cfg_byte) write_byte((unsigned char)cfg); } void ISAPnPDevice::write_End_Dependent_Functions() { write_begin_SMALLTAG(SmallTags::EndDependentFunctions,0); } void ISAPnPDevice::write_nstring(const char *str,const size_t l) { (void)l; if (alloc_res == NULL || alloc_write >= alloc_sz) return; while (*str != 0 && alloc_write < alloc_sz) alloc_res[alloc_write++] = (unsigned char)(*str++); } void ISAPnPDevice::write_Identifier_String(const char *str) { const size_t l = strlen(str); if (l > 4096) return; write_begin_LARGETAG(LargeTags::IdentifierStringANSI,(unsigned int)l); if (l != 0) write_nstring(str,l); } void ISAPnPDevice::write_ISAPnP_version(unsigned char major,unsigned char minor,unsigned char vendor) { write_begin_SMALLTAG(SmallTags::PlugAndPlayVersionNumber,2); write_byte((major << 4) + minor); write_byte(vendor); } void ISAPnPDevice::write_END() { unsigned char sum = 0; size_t i; write_begin_SMALLTAG(SmallTags::EndTag,/*length*/1); for (i=0;i < alloc_write;i++) sum += alloc_res[i]; write_byte((0x100 - sum) & 0xFF); } void ISAPnPDevice::end_write_res() { if (alloc_res == NULL) return; write_END(); if (alloc_write >= alloc_sz) LOG(LOG_MISC,LOG_WARN)("ISA PNP generation overflow"); resource_data_pos = 0; resource_data_len = alloc_sz; // the device usually has a reason for allocating the fixed size it does resource_data = alloc_res; alloc_write = 0; } void ISAPnPDevice::config(Bitu val) { (void)val; } void ISAPnPDevice::wakecsn(Bitu val) { (void)val; ident_bp = 0; ident_2nd = 0; resource_data_pos = 0; resource_ident = 0; } void ISAPnPDevice::select_logical_device(Bitu val) { (void)val; } void ISAPnPDevice::checksum_ident() { unsigned char checksum = 0x6a,bit; int i,j; for (i=0;i < 8;i++) { for (j=0;j < 8;j++) { bit = (ident[i] >> j) & 1; checksum = ((((checksum ^ (checksum >> 1)) & 1) ^ bit) << 7) | (checksum >> 1); } } ident[8] = checksum; } void ISAPnPDevice::on_pnp_key() { resource_ident = 0; } uint8_t ISAPnPDevice::read(Bitu addr) { (void)addr; return 0x00; } void ISAPnPDevice::write(Bitu addr,Bitu val) { (void)addr; (void)val; } #define MAX_ISA_PNP_DEVICES 64 #define MAX_ISA_PNP_SYSDEVNODES 256 static ISAPnPDevice *ISA_PNP_selected = NULL; static ISAPnPDevice *ISA_PNP_devs[MAX_ISA_PNP_DEVICES] = {NULL}; /* FIXME: free objects on shutdown */ static Bitu ISA_PNP_devnext = 0; static const unsigned char ISAPnPIntegrationDevice_sysdev[] = { ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x28,0x28, /* min-max range I/O port */ 0x04,0x04), /* align=4 length=4 */ ISAPNP_END }; class ISAPnPIntegrationDevice : public ISAPnPDevice { public: ISAPnPIntegrationDevice() : ISAPnPDevice() { resource_ident = 0; resource_data = (unsigned char*)ISAPnPIntegrationDevice_sysdev; resource_data_len = sizeof(ISAPnPIntegrationDevice_sysdev); host_writed(ident+0,ISAPNP_ID('D','O','S',0x1,0x2,0x3,0x4)); /* DOS1234 test device */ host_writed(ident+4,0xFFFFFFFFUL); checksum_ident(); } }; ISAPnPIntegrationDevice *isapnpigdevice = NULL; class ISAPNP_SysDevNode { public: ISAPNP_SysDevNode(const unsigned char *ir,size_t len,bool already_alloc=false) { if (already_alloc) { raw = (unsigned char*)ir; raw_len = len; own = false; } else { if (len > 65535) E_Exit("ISAPNP_SysDevNode data too long"); raw = new unsigned char[(size_t)len+1u]; if (ir == NULL) E_Exit("ISAPNP_SysDevNode cannot allocate buffer"); else memcpy(raw, ir, (size_t)len); raw_len = len; raw[len] = 0; own = true; } } virtual ~ISAPNP_SysDevNode() { if (own) delete[] raw; } unsigned char* raw; size_t raw_len; bool own; }; static ISAPNP_SysDevNode* ISAPNP_SysDevNodes[MAX_ISA_PNP_SYSDEVNODES] = {NULL}; static Bitu ISAPNP_SysDevNodeLargest=0; static Bitu ISAPNP_SysDevNodeCount=0; void ISA_PNP_FreeAllSysNodeDevs() { Bitu i; for (i=0;i < MAX_ISA_PNP_SYSDEVNODES;i++) { if (ISAPNP_SysDevNodes[i] != NULL) delete ISAPNP_SysDevNodes[i]; ISAPNP_SysDevNodes[i] = NULL; } ISAPNP_SysDevNodeLargest=0; ISAPNP_SysDevNodeCount=0; } void ISA_PNP_FreeAllDevs() { Bitu i; for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { if (ISA_PNP_devs[i] != NULL) { delete ISA_PNP_devs[i]; ISA_PNP_devs[i] = NULL; } } for (i=0;i < MAX_ISA_PNP_SYSDEVNODES;i++) { if (ISAPNP_SysDevNodes[i] != NULL) delete ISAPNP_SysDevNodes[i]; ISAPNP_SysDevNodes[i] = NULL; } ISAPNP_SysDevNodeLargest=0; ISAPNP_SysDevNodeCount=0; } void ISA_PNP_devreg(ISAPnPDevice *x) { if (ISA_PNP_devnext < MAX_ISA_PNP_DEVICES) { if (ISA_PNP_WPORT_BIOS == 0) ISA_PNP_WPORT_BIOS = ISA_PNP_WPORT; ISA_PNP_devs[ISA_PNP_devnext++] = x; x->CSN = ISA_PNP_devnext; } } static Bitu isapnp_read_port(Bitu port,Bitu /*iolen*/) { (void)port;//UNUSED Bitu ret=0xff; switch (ISA_PNP_CUR_ADDR) { case 0x01: /* serial isolation */ if (ISA_PNP_selected && ISA_PNP_selected->CSN == 0) { if (ISA_PNP_selected->ident_bp < 72) { if (ISA_PNP_selected->ident[ISA_PNP_selected->ident_bp>>3] & (1 << (ISA_PNP_selected->ident_bp&7))) ret = ISA_PNP_selected->ident_2nd ? 0xAA : 0x55; else ret = 0xFF; if (++ISA_PNP_selected->ident_2nd >= 2) { ISA_PNP_selected->ident_2nd = 0; ISA_PNP_selected->ident_bp++; } } } else { ret = 0xFF; } break; case 0x04: /* read resource data */ if (ISA_PNP_selected) { if (ISA_PNP_selected->resource_ident < 9) ret = ISA_PNP_selected->ident[ISA_PNP_selected->resource_ident++]; else { /* real-world hardware testing shows that devices act as if there was some fixed block of ROM, * that repeats every 128, 256, 512, or 1024 bytes if you just blindly read from this port. */ if (ISA_PNP_selected->resource_data_pos < ISA_PNP_selected->resource_data_len) ret = ISA_PNP_selected->resource_data[ISA_PNP_selected->resource_data_pos++]; /* that means that if you read enough bytes the ROM loops back to returning the ident */ if (ISA_PNP_selected->resource_data_pos >= ISA_PNP_selected->resource_data_len) { ISA_PNP_selected->resource_data_pos = 0; ISA_PNP_selected->resource_ident = 0; } } } break; case 0x05: /* read resource status */ if (ISA_PNP_selected) { /* real-world hardware testing shows that devices act as if there was some fixed block of ROM, * that repeats every 128, 256, 512, or 1024 bytes if you just blindly read from this port. * therefore, there's always a byte to return. */ ret = 0x01; /* TODO: simulate hardware slowness */ } break; case 0x06: /* card select number */ if (ISA_PNP_selected) ret = ISA_PNP_selected->CSN; break; case 0x07: /* logical device number */ if (ISA_PNP_selected) ret = ISA_PNP_selected->logical_device; break; default: /* pass the rest down to the class */ if (ISA_PNP_selected) ret = ISA_PNP_selected->read(ISA_PNP_CUR_ADDR); break; } // if (1) LOG_MSG("PnP read(%02X) = %02X\n",ISA_PNP_CUR_ADDR,ret); return ret; } void isapnp_write_port(Bitu port,Bitu val,Bitu /*iolen*/) { Bitu i; if (port == 0x279) { // if (1) LOG_MSG("PnP addr(%02X)\n",val); if (val == isa_pnp_init_keystring[ISA_PNP_KEYMATCH]) { if (++ISA_PNP_KEYMATCH == 32) { // LOG_MSG("ISA PnP key -> going to sleep\n"); ISA_PNP_CUR_STATE = ISA_PNP_SLEEP; ISA_PNP_KEYMATCH = 0; for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { if (ISA_PNP_devs[i] != NULL) { ISA_PNP_devs[i]->on_pnp_key(); } } } } else { ISA_PNP_KEYMATCH = 0; } ISA_PNP_CUR_ADDR = val; } else if (port == 0xA79) { // if (1) LOG_MSG("PnP write(%02X) = %02X\n",ISA_PNP_CUR_ADDR,val); switch (ISA_PNP_CUR_ADDR) { case 0x00: { /* RD_DATA */ unsigned int np = ((val & 0xFF) << 2) | 3; if (np != ISA_PNP_WPORT) { if (ISAPNP_PNP_READ_PORT != NULL) { ISAPNP_PNP_READ_PORT = NULL; delete ISAPNP_PNP_READ_PORT; } if (np >= 0x200 && np <= 0x3FF) { /* allowable port I/O range according to spec */ LOG_MSG("PNP OS changed I/O read port to 0x%03X (from 0x%03X)\n",np,ISA_PNP_WPORT); ISA_PNP_WPORT = np; ISAPNP_PNP_READ_PORT = new IO_ReadHandleObject; ISAPNP_PNP_READ_PORT->Install(ISA_PNP_WPORT,isapnp_read_port,IO_MB); } else { LOG_MSG("PNP OS I/O read port disabled\n"); ISA_PNP_WPORT = 0; } if (ISA_PNP_selected != NULL) { ISA_PNP_selected->ident_bp = 0; ISA_PNP_selected->ident_2nd = 0; ISA_PNP_selected->resource_data_pos = 0; } } } break; case 0x02: /* config control */ if (val & 4) { /* ALL CARDS RESET CSN to 0 */ for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { if (ISA_PNP_devs[i] != NULL) { ISA_PNP_devs[i]->CSN = 0; } } } if (val & 2) ISA_PNP_CUR_STATE = ISA_PNP_WAIT_FOR_KEY; if ((val & 1) && ISA_PNP_selected) ISA_PNP_selected->config(val); for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { if (ISA_PNP_devs[i] != NULL) { ISA_PNP_devs[i]->ident_bp = 0; ISA_PNP_devs[i]->ident_2nd = 0; ISA_PNP_devs[i]->resource_data_pos = 0; } } break; case 0x03: { /* wake[CSN] */ ISA_PNP_selected = NULL; for (i=0;ISA_PNP_selected == NULL && i < MAX_ISA_PNP_DEVICES;i++) { if (ISA_PNP_devs[i] == NULL) continue; if (ISA_PNP_devs[i]->CSN == val) { ISA_PNP_selected = ISA_PNP_devs[i]; ISA_PNP_selected->wakecsn(val); } } if (val == 0) ISA_PNP_CUR_STATE = ISA_PNP_ISOLATE; else ISA_PNP_CUR_STATE = ISA_PNP_CONFIG; } break; case 0x06: /* card select number */ if (ISA_PNP_selected) ISA_PNP_selected->CSN = val; break; case 0x07: /* logical device number */ if (ISA_PNP_selected) ISA_PNP_selected->select_logical_device(val); break; default: /* pass the rest down to the class */ if (ISA_PNP_selected) ISA_PNP_selected->write(ISA_PNP_CUR_ADDR,val); break; } } } // IBM PC/AT CTRL+BREAK interrupt, called by IRQ1 handler. // Not applicable to PC-98 mode, of course. Bitu INT1B_Break_Handler(void) { // BIOS DATA AREA 40:71 bit 7 is set when Break key is pressed. // This is already implemented by IRQ1 handler in src/ints/bios_keyboard.cpp. // Ref: [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/Computers/IBM/PS%e2%88%952/IBM%20Personal%20System%e2%88%952%20and%20Personal%20Computer%20BIOS%20Interface%20Technical%20Reference%20%281991%2d09%29%20First%20Edition%2c%20part%203%2epdf] return CBRET_NONE; } static Bitu INT15_Handler(void); // FIXME: This initializes both APM BIOS and ISA PNP emulation! // Need to separate APM BIOS init from ISA PNP init from ISA PNP BIOS init! // It might also be appropriate to move this into the BIOS init sequence. void ISAPNP_Cfg_Reset(Section *sec) { (void)sec;//UNUSED const Section_prop* section = static_cast<Section_prop*>(control->GetSection("cpu")); LOG(LOG_MISC,LOG_DEBUG)("Initializing ISA PnP emulation"); enable_integration_device = section->Get_bool("integration device"); enable_integration_device_pnp = section->Get_bool("integration device pnp"); ISAPNPBIOS = section->Get_bool("isapnpbios"); APMBIOS = section->Get_bool("apmbios"); APMBIOS_pnp = section->Get_bool("apmbios pnp"); APMBIOS_allow_realmode = section->Get_bool("apmbios allow realmode"); APMBIOS_allow_prot16 = section->Get_bool("apmbios allow 16-bit protected mode"); APMBIOS_allow_prot32 = section->Get_bool("apmbios allow 32-bit protected mode"); std::string apmbiosver = section->Get_string("apmbios version"); /* PC-98 does not have the IBM PC/AT APM BIOS interface */ if (IS_PC98_ARCH) { APMBIOS = false; APMBIOS_pnp = false; } if (apmbiosver == "1.0") APM_BIOS_minor_version = 0; else if (apmbiosver == "1.1") APM_BIOS_minor_version = 1; else if (apmbiosver == "1.2") APM_BIOS_minor_version = 2; else//auto APM_BIOS_minor_version = 2; /* PC-98 does not have APM. * I *think* it has Plug & Play, but probably different from ISA PnP and specific to the C-Bus interface, * which I have no information on at this time --J.C. */ if (IS_PC98_ARCH) return; LOG(LOG_MISC,LOG_DEBUG)("APM BIOS allow: real=%u pm16=%u pm32=%u version=1.%u", APMBIOS_allow_realmode, APMBIOS_allow_prot16, APMBIOS_allow_prot32, APM_BIOS_minor_version); if (APMBIOS && (APMBIOS_allow_prot16 || APMBIOS_allow_prot32) && INT15_apm_pmentry == 0) { Bitu cb,base; /* NTS: This is... kind of a terrible hack. It basically tricks Windows into executing our * INT 15h handler as if the APM entry point. Except that instead of an actual INT 15h * triggering the callback, a FAR CALL triggers the callback instead (CB_RETF not CB_IRET). */ /* TODO: We should really consider moving the APM BIOS code in INT15_Handler() out into it's * own function, then having the INT15_Handler() call it as well as directing this callback * directly to it. If you think about it, this hack also lets the "APM entry point" invoke * other arbitrary INT 15h calls which is not valid. */ cb = CALLBACK_Allocate(); INT15_apm_pmentry = CALLBACK_RealPointer(cb); LOG_MSG("Allocated APM BIOS pm entry point at %04x:%04x\n",INT15_apm_pmentry>>16,INT15_apm_pmentry&0xFFFF); CALLBACK_Setup(cb,INT15_Handler,CB_RETF,"APM BIOS protected mode entry point"); /* NTS: Actually INT15_Handler is written to act like an interrupt (IRETF) type callback. * Prior versions hacked this into something that responds by CB_RETF, however some * poking around reveals that CALLBACK_SCF and friends still assume an interrupt * stack, thus, the cause of random crashes in Windows was simply that we were * flipping flag bits in the middle of the return address on the stack. The other * source of random crashes is that the CF/ZF manipulation in INT 15h wasn't making * it's way back to Windows, meaning that when APM BIOS emulation intended to return * an error (by setting CF), Windows didn't get the memo (CF wasn't set on return) * and acted as if the call succeeded, or worse, CF happened to be set on entry and * was never cleared by APM BIOS emulation. * * So what we need is: * * PUSHF ; put flags in right place * PUSH BP ; dummy FAR pointer * PUSH BP ; again * <callback> * POP BP ; drop it * POP BP ; drop it * POPF * RETF * * Then CALLBACK_SCF can work normally this way. * * NTS: We *still* need to separate APM BIOS calls from the general INT 15H emulation though... */ base = Real2Phys(INT15_apm_pmentry); LOG_MSG("Writing code to %05x\n",(unsigned int)base); phys_writeb(base+0x00,0x9C); /* pushf */ phys_writeb(base+0x01,0x55); /* push (e)bp */ phys_writeb(base+0x02,0x55); /* push (e)bp */ phys_writeb(base+0x03,(uint8_t)0xFE); //GRP 4 phys_writeb(base+0x04,(uint8_t)0x38); //Extra Callback instruction phys_writew(base+0x05,(uint16_t)cb); //The immediate word phys_writeb(base+0x07,0x5D); /* pop (e)bp */ phys_writeb(base+0x08,0x5D); /* pop (e)bp */ phys_writeb(base+0x09,0x9D); /* popf */ phys_writeb(base+0x0A,0xCB); /* retf */ } } void ISAPNP_Cfg_Init() { AddVMEventFunction(VM_EVENT_RESET,AddVMEventFunctionFuncPair(ISAPNP_Cfg_Reset)); } /* the PnP callback registered two entry points. One for real, one for protected mode. */ static Bitu PNPentry_real,PNPentry_prot; static bool ISAPNP_Verify_BiosSelector(Bitu seg) { if (!cpu.pmode || (reg_flags & FLAG_VM)) { return (seg == 0xF000); } else if (seg == 0) return 0; else { #if 1 /* FIXME: Always return true. But figure out how to ask DOSBox the linear->phys mapping to determine whether the segment's base address maps to 0xF0000. In the meantime disabling this check makes PnP BIOS emulation work with Windows 95 OSR2 which appears to give us a segment mapped to a virtual address rather than linearly mapped to 0xF0000 as Windows 95 original did. */ return true; #else Descriptor desc; cpu.gdt.GetDescriptor(seg,desc); /* TODO: Check desc.Type() to make sure it's a writeable data segment */ return (desc.GetBase() == 0xF0000); #endif } } static bool ISAPNP_CPU_ProtMode() { if (!cpu.pmode || (reg_flags & FLAG_VM)) return 0; return 1; } static Bitu ISAPNP_xlate_address(Bitu far_ptr) { if (!cpu.pmode || (reg_flags & FLAG_VM)) return Real2Phys(far_ptr); else { Descriptor desc; cpu.gdt.GetDescriptor(far_ptr >> 16,desc); /* TODO: Check desc.Type() to make sure it's a writeable data segment */ return (desc.GetBase() + (far_ptr & 0xFFFF)); } } static const unsigned char ISAPNP_sysdev_Keyboard[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0x3,0x0,0x3), /* PNP0303 IBM Enhanced 101/102 key with PS/2 */ ISAPNP_TYPE(0x09,0x00,0x00), /* type: input, keyboard */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x60,0x60, /* min-max range I/O port */ 0x01,0x01), /* align=1 length=1 */ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x64,0x64, /* min-max range I/O port */ 0x01,0x01), /* align=1 length=1 */ ISAPNP_IRQ_SINGLE( 1, /* IRQ 1 */ 0x09), /* HTE=1 LTL=1 */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; static const unsigned char ISAPNP_sysdev_Mouse[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0xF,0x0,0xE), /* PNP0F0E Microsoft compatible PS/2 */ ISAPNP_TYPE(0x09,0x02,0x00), /* type: input, keyboard */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IRQ_SINGLE( 12, /* IRQ 12 */ 0x09), /* HTE=1 LTL=1 */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; static const unsigned char ISAPNP_sysdev_DMA_Controller[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0x2,0x0,0x0), /* PNP0200 AT DMA controller */ ISAPNP_TYPE(0x08,0x01,0x00), /* type: input, keyboard */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x00,0x00, /* min-max range I/O port (DMA channels 0-3) */ 0x10,0x10), /* align=16 length=16 */ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x81,0x81, /* min-max range I/O port (DMA page registers) */ 0x01,0x0F), /* align=1 length=15 */ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0xC0,0xC0, /* min-max range I/O port (AT DMA channels 4-7) */ 0x20,0x20), /* align=32 length=32 */ ISAPNP_DMA_SINGLE( 4, /* DMA 4 */ 0x01), /* 8/16-bit transfers, compatible speed */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; static const unsigned char ISAPNP_sysdev_PIC[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0x0,0x0,0x0), /* PNP0000 Interrupt controller */ ISAPNP_TYPE(0x08,0x00,0x01), /* type: ISA interrupt controller */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x20,0x20, /* min-max range I/O port */ 0x01,0x02), /* align=1 length=2 */ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0xA0,0xA0, /* min-max range I/O port */ 0x01,0x02), /* align=1 length=2 */ ISAPNP_IRQ_SINGLE( 2, /* IRQ 2 */ 0x09), /* HTE=1 LTL=1 */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; static const unsigned char ISAPNP_sysdev_Timer[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0x1,0x0,0x0), /* PNP0100 Timer */ ISAPNP_TYPE(0x08,0x02,0x01), /* type: ISA timer */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x40,0x40, /* min-max range I/O port */ 0x04,0x04), /* align=4 length=4 */ ISAPNP_IRQ_SINGLE( 0, /* IRQ 0 */ 0x09), /* HTE=1 LTL=1 */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; static const unsigned char ISAPNP_sysdev_RTC[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0xB,0x0,0x0), /* PNP0B00 Real-time clock */ ISAPNP_TYPE(0x08,0x03,0x01), /* type: ISA real-time clock */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x70,0x70, /* min-max range I/O port */ 0x01,0x02), /* align=1 length=2 */ ISAPNP_IRQ_SINGLE( 8, /* IRQ 8 */ 0x09), /* HTE=1 LTL=1 */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; static const unsigned char ISAPNP_sysdev_PC_Speaker[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0x8,0x0,0x0), /* PNP0800 PC speaker */ ISAPNP_TYPE(0x04,0x01,0x00), /* type: PC speaker */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x61,0x61, /* min-max range I/O port */ 0x01,0x01), /* align=1 length=1 */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; static const unsigned char ISAPNP_sysdev_Numeric_Coprocessor[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x4), /* PNP0C04 Numeric Coprocessor */ ISAPNP_TYPE(0x0B,0x80,0x00), /* type: FPU */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0xF0,0xF0, /* min-max range I/O port */ 0x10,0x10), /* align=16 length=16 */ ISAPNP_IRQ_SINGLE( 13, /* IRQ 13 */ 0x09), /* HTE=1 LTL=1 */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; static const unsigned char ISAPNP_sysdev_System_Board[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x1), /* PNP0C01 System board */ ISAPNP_TYPE(0x08,0x80,0x00), /* type: System peripheral, Other */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x24,0x24, /* min-max range I/O port */ 0x04,0x04), /* align=4 length=4 */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; /* NTS: If some of my late 1990's laptops are any indication, this resource list can be used * as a hint that the motherboard supports Intel EISA/PCI controller DMA registers that * allow ISA DMA to extend to 32-bit addresses instead of being limited to 24-bit */ static const unsigned char ISAPNP_sysdev_General_ISAPNP[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x2), /* PNP0C02 General ID for reserving resources */ ISAPNP_TYPE(0x08,0x80,0x00), /* type: System peripheral, Other */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_IO_RANGE( 0x01, /* decodes 16-bit ISA addr */ 0x208,0x208, /* min-max range I/O port */ 0x04,0x04), /* align=4 length=4 */ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; /* PnP system entry to tell Windows 95 the obvious: That there's an ISA bus present */ /* NTS: Examination of some old laptops of mine shows that these devices do not list any resources, * or at least, an old Toshiba of mine lists the PCI registers 0xCF8-0xCFF as motherboard resources * and defines no resources for the PCI Bus PnP device. */ static const unsigned char ISAPNP_sysdev_ISA_BUS[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0xA,0x0,0x0), /* PNP0A00 ISA Bus */ ISAPNP_TYPE(0x06,0x04,0x00), /* type: System device, peripheral bus */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; /* PnP system entry to tell Windows 95 the obvious: That there's a PCI bus present */ static const unsigned char ISAPNP_sysdev_PCI_BUS[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0xA,0x0,0x3), /* PNP0A03 PCI Bus */ ISAPNP_TYPE(0x06,0x04,0x00), /* type: System device, peripheral bus */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; /* to help convince Windows 95 that the APM BIOS is present */ static const unsigned char ISAPNP_sysdev_APM_BIOS[] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x5), /* PNP0C05 APM BIOS */ ISAPNP_TYPE(0x08,0x80,0x00), /* type: FIXME is this right?? I can't find any examples or documentation */ 0x0001 | 0x0002), /* can't disable, can't configure */ /*----------allocated--------*/ ISAPNP_END, /*----------possible--------*/ ISAPNP_END, /*----------compatible--------*/ ISAPNP_END }; bool ISAPNP_RegisterSysDev(const unsigned char *raw,Bitu len,bool already) { if (ISAPNP_SysDevNodeCount >= MAX_ISA_PNP_SYSDEVNODES) return false; ISAPNP_SysDevNodes[ISAPNP_SysDevNodeCount] = new ISAPNP_SysDevNode(raw,len,already); if (ISAPNP_SysDevNodes[ISAPNP_SysDevNodeCount] == NULL) return false; ISAPNP_SysDevNodeCount++; if (ISAPNP_SysDevNodeLargest < (len+3)) ISAPNP_SysDevNodeLargest = len+3; return true; } /* ISA PnP function calls have their parameters stored on the stack "C" __cdecl style. Parameters * are either int, long, or FAR pointers. Like __cdecl an assembly language implementation pushes * the function arguments on the stack BACKWARDS */ static Bitu ISAPNP_Handler(bool protmode /* called from protected mode interface == true */) { Bitu arg; Bitu func,BiosSelector; /* I like how the ISA PnP spec says that the 16-bit entry points (real and protected) are given 16-bit data segments * which implies that all segments involved might as well be 16-bit. * * Right? * * Well, guess what Windows 95 gives us when calling this entry point: * * Segment SS = DS = 0x30 base=0 limit=0xFFFFFFFF * SS:SP = 0x30:0xC138BADF or something like that from within BIOS.VXD * * Yeah... for a 16-bit code segment call. Right. Typical Microsoft. >:( * * This might also explain why my early experiments with Bochs always had the perpetual * APM BIOS that never worked but was always detected. * * ------------------------------------------------------------------------ * Windows 95 OSR2: * * Windows 95 OSR2 however uses a 16-bit stack (where the stack segment is based somewhere * around 0xC1xxxxxx), all we have to do to correctly access it is work through the page tables. * This is within spec, but now Microsoft sends us a data segment that is based at virtual address * 0xC2xxxxxx, which is why I had to disable the "verify selector" routine */ arg = SegPhys(ss) + (reg_esp&cpu.stack.mask) + (2*2); /* entry point (real and protected) is 16-bit, expected to RETF (skip CS:IP) */ if (protmode != ISAPNP_CPU_ProtMode()) { //LOG_MSG("ISA PnP %s entry point called from %s. On real BIOSes this would CRASH\n",protmode ? "Protected mode" : "Real mode", // ISAPNP_CPU_ProtMode() ? "Protected mode" : "Real mode"); reg_ax = 0x84;/* BAD_PARAMETER */ return 0; } func = mem_readw(arg); // LOG_MSG("PnP prot=%u DS=%04x (base=0x%08lx) SS:ESP=%04x:%04x (base=0x%08lx phys=0x%08lx) function=0x%04x\n", // (unsigned int)protmode,(unsigned int)SegValue(ds),(unsigned long)SegPhys(ds), // (unsigned int)SegValue(ss),(unsigned int)reg_esp,(unsigned long)SegPhys(ss), // (unsigned long)arg,(unsigned int)func); /* every function takes the form * * int __cdecl FAR (*entrypoint)(int Function...); * * so the first argument on the stack is an int that we read to determine what the caller is asking * * Dont forget in the real-mode world: * sizeof(int) == 16 bits * sizeof(long) == 32 bits */ switch (func) { case 0: { /* Get Number of System Nodes */ /* int __cdecl FAR (*entrypoint)(int Function,unsigned char FAR *NumNodes,unsigned int FAR *NodeSize,unsigned int BiosSelector); * ^ +0 ^ +2 ^ +6 ^ +10 = 12 */ Bitu NumNodes_ptr = mem_readd(arg+2); Bitu NodeSize_ptr = mem_readd(arg+6); BiosSelector = mem_readw(arg+10); if (!ISAPNP_Verify_BiosSelector(BiosSelector)) goto badBiosSelector; if (NumNodes_ptr != 0) mem_writeb(ISAPNP_xlate_address(NumNodes_ptr),ISAPNP_SysDevNodeCount); if (NodeSize_ptr != 0) mem_writew(ISAPNP_xlate_address(NodeSize_ptr),ISAPNP_SysDevNodeLargest); reg_ax = 0x00;/* SUCCESS */ } break; case 1: { /* Get System Device Node */ /* int __cdecl FAR (*entrypoint)(int Function,unsigned char FAR *Node,struct DEV_NODE FAR *devNodeBuffer,unsigned int Control,unsigned int BiosSelector); * ^ +0 ^ +2 ^ +6 ^ +10 ^ +12 = 14 */ Bitu Node_ptr = mem_readd(arg+2); Bitu devNodeBuffer_ptr = mem_readd(arg+6); Bitu Control = mem_readw(arg+10); BiosSelector = mem_readw(arg+12); unsigned char Node; Bitu i=0; if (!ISAPNP_Verify_BiosSelector(BiosSelector)) goto badBiosSelector; /* control bits 0-1 must be '01' or '10' but not '00' or '11' */ if (Control == 0 || (Control&3) == 3) { LOG_MSG("ISAPNP Get System Device Node: Invalid Control value 0x%04x\n",(int)Control); reg_ax = 0x84;/* BAD_PARAMETER */ break; } devNodeBuffer_ptr = ISAPNP_xlate_address(devNodeBuffer_ptr); Node_ptr = ISAPNP_xlate_address(Node_ptr); Node = mem_readb(Node_ptr); if (Node >= ISAPNP_SysDevNodeCount) { LOG_MSG("ISAPNP Get System Device Node: Invalid Node 0x%02x (max 0x%04x)\n",(int)Node,(int)ISAPNP_SysDevNodeCount); reg_ax = 0x84;/* BAD_PARAMETER */ break; } const ISAPNP_SysDevNode *nd = ISAPNP_SysDevNodes[Node]; mem_writew(devNodeBuffer_ptr+0,(uint16_t)(nd->raw_len+3)); /* Length */ mem_writeb(devNodeBuffer_ptr+2,Node); /* on most PnP BIOS implementations I've seen "handle" is set to the same value as Node */ for (i=0;i < (Bitu)nd->raw_len;i++) mem_writeb(devNodeBuffer_ptr+i+3,nd->raw[i]); // LOG_MSG("ISAPNP OS asked for Node 0x%02x\n",Node); if (++Node >= ISAPNP_SysDevNodeCount) Node = 0xFF; /* no more nodes */ mem_writeb(Node_ptr,Node); reg_ax = 0x00;/* SUCCESS */ } break; case 4: { /* Send Message */ /* int __cdecl FAR (*entrypoint)(int Function,unsigned int Message,unsigned int BiosSelector); * ^ +0 ^ +2 ^ +4 = 6 */ Bitu Message = mem_readw(arg+2); BiosSelector = mem_readw(arg+4); if (!ISAPNP_Verify_BiosSelector(BiosSelector)) goto badBiosSelector; switch (Message) { case 0x41: /* POWER_OFF */ LOG_MSG("Plug & Play OS requested power off.\n"); reg_ax = 0; throw 1; /* NTS: Based on the Reboot handler code, causes DOSBox-X to cleanly shutdown and exit */ break; case 0x42: /* PNP_OS_ACTIVE */ LOG_MSG("Plug & Play OS reports itself active\n"); reg_ax = 0; break; case 0x43: /* PNP_OS_INACTIVE */ LOG_MSG("Plug & Play OS reports itself inactive\n"); reg_ax = 0; break; default: LOG_MSG("Unknown ISA PnP message 0x%04x\n",(int)Message); reg_ax = 0x82;/* FUNCTION_NOT_SUPPORTED */ break; } } break; case 0x40: { /* Get PnP ISA configuration */ /* int __cdecl FAR (*entrypoint)(int Function,unsigned char far *struct,unsigned int BiosSelector); * ^ +0 ^ +2 ^ +6 = 8 */ Bitu struct_ptr = mem_readd(arg+2); BiosSelector = mem_readw(arg+6); if (!ISAPNP_Verify_BiosSelector(BiosSelector)) goto badBiosSelector; /* struct isapnp_pnp_isa_cfg { uint8_t revision; uint8_t total_csn; uint16_t isa_pnp_port; uint16_t reserved; }; */ if (struct_ptr != 0) { Bitu ph = ISAPNP_xlate_address(struct_ptr); mem_writeb(ph+0,0x01); /* ->revision = 0x01 */ mem_writeb(ph+1,ISA_PNP_devnext); /* ->total_csn */ mem_writew(ph+2,ISA_PNP_WPORT_BIOS); /* ->isa_pnp_port */ mem_writew(ph+4,0); /* ->reserved */ } reg_ax = 0x00;/* SUCCESS */ } break; default: //LOG_MSG("Unsupported ISA PnP function 0x%04x\n",func); reg_ax = 0x82;/* FUNCTION_NOT_SUPPORTED */ break; } return 0; badBiosSelector: /* return an error. remind the user (possible developer) how lucky he is, a real * BIOS implementation would CRASH when misused like this */ LOG_MSG("ISA PnP function 0x%04x called with incorrect BiosSelector parameter 0x%04x\n",(int)func,(int)BiosSelector); LOG_MSG(" > STACK %04X %04X %04X %04X %04X %04X %04X %04X\n", mem_readw(arg), mem_readw(arg+2), mem_readw(arg+4), mem_readw(arg+6), mem_readw(arg+8), mem_readw(arg+10), mem_readw(arg+12), mem_readw(arg+14)); reg_ax = 0x84;/* BAD_PARAMETER */ return 0; } static Bitu ISAPNP_Handler_PM(void) { return ISAPNP_Handler(true); } static Bitu ISAPNP_Handler_RM(void) { return ISAPNP_Handler(false); } static Bitu INT70_Handler(void) { /* Acknowledge irq with cmos */ IO_Write(0x70,0xc); IO_Read(0x71); if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) { uint32_t count=mem_readd(BIOS_WAIT_FLAG_COUNT); if (count>997) { mem_writed(BIOS_WAIT_FLAG_COUNT,count-997); } else { mem_writed(BIOS_WAIT_FLAG_COUNT,0); PhysPt where=Real2Phys(mem_readd(BIOS_WAIT_FLAG_POINTER)); mem_writeb(where,mem_readb(where)|0x80); mem_writeb(BIOS_WAIT_FLAG_ACTIVE,0); mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(0,BIOS_WAIT_FLAG_TEMP)); IO_Write(0x70,0xb); IO_Write(0x71,IO_Read(0x71)&~0x40); } } /* Signal EOI to both pics */ IO_Write(0xa0,0x20); IO_Write(0x20,0x20); return 0; } CALLBACK_HandlerObject* tandy_DAC_callback[2]; static struct { uint16_t port; uint8_t irq; uint8_t dma; } tandy_sb; static struct { uint16_t port; uint8_t irq; uint8_t dma; } tandy_dac; static bool Tandy_InitializeSB() { /* see if soundblaster module available and at what port/IRQ/DMA */ Bitu sbport, sbirq, sbdma; if (SB_Get_Address(sbport, sbirq, sbdma)) { tandy_sb.port=(uint16_t)(sbport&0xffff); tandy_sb.irq =(uint8_t)(sbirq&0xff); tandy_sb.dma =(uint8_t)(sbdma&0xff); return true; } else { /* no soundblaster accessible, disable Tandy DAC */ tandy_sb.port=0; return false; } } static bool Tandy_InitializeTS() { /* see if Tandy DAC module available and at what port/IRQ/DMA */ Bitu tsport, tsirq, tsdma; if (TS_Get_Address(tsport, tsirq, tsdma)) { tandy_dac.port=(uint16_t)(tsport&0xffff); tandy_dac.irq =(uint8_t)(tsirq&0xff); tandy_dac.dma =(uint8_t)(tsdma&0xff); return true; } else { /* no Tandy DAC accessible */ tandy_dac.port=0; return false; } } /* check if Tandy DAC is still playing */ static bool Tandy_TransferInProgress(void) { if (real_readw(0x40,0xd0)) return true; /* not yet done */ if (real_readb(0x40,0xd4)==0xff) return false; /* still in init-state */ uint8_t tandy_dma = 1; if (tandy_sb.port) tandy_dma = tandy_sb.dma; else if (tandy_dac.port) tandy_dma = tandy_dac.dma; IO_Write(0x0c,0x00); uint16_t datalen = (IO_ReadB(tandy_dma * 2 + 1)) + (IO_ReadB(tandy_dma * 2 + 1) << 8); if (datalen==0xffff) return false; /* no DMA transfer */ else if ((datalen<0x10) && (real_readb(0x40,0xd4)==0x0f) && (real_readw(0x40,0xd2)==0x1c)) { /* stop already requested */ return false; } return true; } static void Tandy_SetupTransfer(PhysPt bufpt,bool isplayback) { Bitu length=real_readw(0x40,0xd0); if (length==0) return; /* nothing to do... */ if ((tandy_sb.port==0) && (tandy_dac.port==0)) return; uint8_t tandy_irq = 7; if (tandy_sb.port) tandy_irq = tandy_sb.irq; else if (tandy_dac.port) tandy_irq = tandy_dac.irq; uint8_t tandy_irq_vector = tandy_irq; if (tandy_irq_vector<8) tandy_irq_vector += 8; else tandy_irq_vector += (0x70-8); /* revector IRQ-handler if necessary */ RealPt current_irq=RealGetVec(tandy_irq_vector); if (current_irq!=tandy_DAC_callback[0]->Get_RealPointer()) { real_writed(0x40,0xd6,current_irq); RealSetVec(tandy_irq_vector,tandy_DAC_callback[0]->Get_RealPointer()); } uint8_t tandy_dma = 1; if (tandy_sb.port) tandy_dma = tandy_sb.dma; else if (tandy_dac.port) tandy_dma = tandy_dac.dma; if (tandy_sb.port) { IO_Write(tandy_sb.port+0xcu,0xd0); /* stop DMA transfer */ IO_Write(0x21,IO_Read(0x21)&(~(1u<<tandy_irq))); /* unmask IRQ */ IO_Write(tandy_sb.port+0xcu,0xd1); /* turn speaker on */ } else { IO_Write(tandy_dac.port,IO_Read(tandy_dac.port)&0x60); /* disable DAC */ IO_Write(0x21,IO_Read(0x21)&(~(1u<<tandy_irq))); /* unmask IRQ */ } IO_Write(0x0a,0x04|tandy_dma); /* mask DMA channel */ IO_Write(0x0c,0x00); /* clear DMA flipflop */ if (isplayback) IO_Write(0x0b,0x48|tandy_dma); else IO_Write(0x0b,0x44|tandy_dma); /* set physical address of buffer */ uint8_t bufpage=(uint8_t)((bufpt>>16u)&0xff); IO_Write(tandy_dma*2u,(uint8_t)(bufpt&0xff)); IO_Write(tandy_dma*2u,(uint8_t)((bufpt>>8u)&0xff)); switch (tandy_dma) { case 0: IO_Write(0x87,bufpage); break; case 1: IO_Write(0x83,bufpage); break; case 2: IO_Write(0x81,bufpage); break; case 3: IO_Write(0x82,bufpage); break; } real_writeb(0x40,0xd4,bufpage); /* calculate transfer size (respects segment boundaries) */ uint32_t tlength=length; if (tlength+(bufpt&0xffff)>0x10000) tlength=0x10000-(bufpt&0xffff); real_writew(0x40,0xd0,(uint16_t)(length-tlength)); /* remaining buffer length */ tlength--; /* set transfer size */ IO_Write(tandy_dma*2u+1u,(uint8_t)(tlength&0xffu)); IO_Write(tandy_dma*2u+1u,(uint8_t)((tlength>>8u)&0xffu)); uint16_t delay=(uint16_t)(real_readw(0x40,0xd2)&0xfff); uint8_t amplitude=(uint8_t)(((unsigned int)real_readw(0x40,0xd2)>>13u)&0x7u); if (tandy_sb.port) { IO_Write(0x0a,tandy_dma); /* enable DMA channel */ /* set frequency */ IO_Write(tandy_sb.port+0xcu,0x40); IO_Write(tandy_sb.port+0xcu,256u - delay*100u/358u); /* set playback type to 8bit */ if (isplayback) IO_Write(tandy_sb.port+0xcu,0x14u); else IO_Write(tandy_sb.port+0xcu,0x24u); /* set transfer size */ IO_Write(tandy_sb.port+0xcu,(uint8_t)(tlength&0xffu)); IO_Write(tandy_sb.port+0xcu,(uint8_t)((tlength>>8)&0xffu)); } else { if (isplayback) IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7cu) | 0x03u); else IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7cu) | 0x02u); IO_Write(tandy_dac.port+2u,(uint8_t)(delay&0xffu)); IO_Write(tandy_dac.port+3u,(uint8_t)((((unsigned int)delay>>8u)&0xfu) | ((unsigned int)amplitude<<5u))); if (isplayback) IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7cu) | 0x1fu); else IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7c) | 0x1e); IO_Write(0x0a,tandy_dma); /* enable DMA channel */ } if (!isplayback) { /* mark transfer as recording operation */ real_writew(0x40,0xd2,(uint16_t)(delay|0x1000)); } } static Bitu IRQ_TandyDAC(void) { if (tandy_dac.port) { IO_Read(tandy_dac.port); } if (real_readw(0x40,0xd0)) { /* play/record next buffer */ /* acknowledge IRQ */ IO_Write(0x20,0x20); if (tandy_sb.port) { IO_Read(tandy_sb.port+0xeu); } /* buffer starts at the next page */ uint8_t npage=real_readb(0x40,0xd4)+1u; real_writeb(0x40,0xd4,npage); Bitu rb=real_readb(0x40,0xd3); if (rb&0x10) { /* start recording */ real_writeb(0x40,0xd3,rb&0xefu); Tandy_SetupTransfer((unsigned int)npage<<16u,false); } else { /* start playback */ Tandy_SetupTransfer((unsigned int)npage<<16u,true); } } else { /* playing/recording is finished */ uint8_t tandy_irq = 7u; if (tandy_sb.port) tandy_irq = tandy_sb.irq; else if (tandy_dac.port) tandy_irq = tandy_dac.irq; uint8_t tandy_irq_vector = tandy_irq; if (tandy_irq_vector<8u) tandy_irq_vector += 8u; else tandy_irq_vector += (0x70u-8u); RealSetVec(tandy_irq_vector,real_readd(0x40,0xd6)); /* turn off speaker and acknowledge soundblaster IRQ */ if (tandy_sb.port) { IO_Write(tandy_sb.port+0xcu,0xd3u); IO_Read(tandy_sb.port+0xeu); } /* issue BIOS tandy sound device busy callout */ SegSet16(cs, RealSeg(tandy_DAC_callback[1]->Get_RealPointer())); reg_ip = RealOff(tandy_DAC_callback[1]->Get_RealPointer()); } return CBRET_NONE; } static void TandyDAC_Handler(uint8_t tfunction) { if ((!tandy_sb.port) && (!tandy_dac.port)) return; switch (tfunction) { case 0x81: /* Tandy sound system check */ if (tandy_dac.port) { reg_ax=tandy_dac.port; } else { reg_ax=0xc4; } CALLBACK_SCF(Tandy_TransferInProgress()); break; case 0x82: /* Tandy sound system start recording */ case 0x83: /* Tandy sound system start playback */ if (Tandy_TransferInProgress()) { /* cannot play yet as the last transfer isn't finished yet */ reg_ah=0x00; CALLBACK_SCF(true); break; } /* store buffer length */ real_writew(0x40,0xd0,reg_cx); /* store delay and volume */ real_writew(0x40,0xd2,(reg_dx&0xfff)|((reg_al&7)<<13)); Tandy_SetupTransfer(PhysMake(SegValue(es),reg_bx),reg_ah==0x83); reg_ah=0x00; CALLBACK_SCF(false); break; case 0x84: /* Tandy sound system stop playing */ reg_ah=0x00; /* setup for a small buffer with silence */ real_writew(0x40,0xd0,0x0a); real_writew(0x40,0xd2,0x1c); Tandy_SetupTransfer(PhysMake(0xf000,0xa084),true); CALLBACK_SCF(false); break; case 0x85: /* Tandy sound system reset */ if (tandy_dac.port) { IO_Write(tandy_dac.port,(uint8_t)(IO_Read(tandy_dac.port)&0xe0)); } reg_ah=0x00; CALLBACK_SCF(false); break; } } extern bool date_host_forced; static uint8_t ReadCmosByte (Bitu index) { IO_Write(0x70, index); return IO_Read(0x71); } static void WriteCmosByte (Bitu index, Bitu val) { IO_Write(0x70, index); IO_Write(0x71, val); } static bool RtcUpdateDone () { while ((ReadCmosByte(0x0a) & 0x80) != 0) CALLBACK_Idle(); return true; // cannot fail in DOSbox } static void InitRtc () { WriteCmosByte(0x0a, 0x26); // default value (32768Hz, 1024Hz) // leave bits 6 (pirq), 5 (airq), 0 (dst) untouched // reset bits 7 (freeze), 4 (uirq), 3 (sqw), 2 (bcd) // set bit 1 (24h) WriteCmosByte(0x0b, (ReadCmosByte(0x0b) & 0x61u) | 0x02u); ReadCmosByte(0x0c); // clear any bits set } static Bitu INT1A_Handler(void) { CALLBACK_SIF(true); switch (reg_ah) { case 0x00: /* Get System time */ { uint32_t ticks=mem_readd(BIOS_TIMER); reg_al=mem_readb(BIOS_24_HOURS_FLAG); mem_writeb(BIOS_24_HOURS_FLAG,0); // reset the "flag" reg_cx=(uint16_t)(ticks >> 16u); reg_dx=(uint16_t)(ticks & 0xffff); break; } case 0x01: /* Set System time */ mem_writed(BIOS_TIMER,((unsigned int)reg_cx<<16u)|reg_dx); break; case 0x02: /* GET REAL-TIME CLOCK TIME (AT,XT286,PS) */ if(date_host_forced) { InitRtc(); // make sure BCD and no am/pm if (RtcUpdateDone()) { // make sure it's safe to read reg_ch = ReadCmosByte(0x04); // hours reg_cl = ReadCmosByte(0x02); // minutes reg_dh = ReadCmosByte(0x00); // seconds reg_dl = ReadCmosByte(0x0b) & 0x01; // daylight saving time } CALLBACK_SCF(false); break; } IO_Write(0x70,0x04); //Hours reg_ch=IO_Read(0x71); IO_Write(0x70,0x02); //Minutes reg_cl=IO_Read(0x71); IO_Write(0x70,0x00); //Seconds reg_dh=IO_Read(0x71); reg_dl=0; //Daylight saving disabled CALLBACK_SCF(false); break; case 0x03: // set RTC time if(date_host_forced) { InitRtc(); // make sure BCD and no am/pm WriteCmosByte(0x0b, ReadCmosByte(0x0b) | 0x80u); // prohibit updates WriteCmosByte(0x04, reg_ch); // hours WriteCmosByte(0x02, reg_cl); // minutes WriteCmosByte(0x00, reg_dh); // seconds WriteCmosByte(0x0b, (ReadCmosByte(0x0b) & 0x7eu) | (reg_dh & 0x01u)); // dst + implicitly allow updates } break; case 0x04: /* GET REAL-TIME ClOCK DATE (AT,XT286,PS) */ if(date_host_forced) { InitRtc(); // make sure BCD and no am/pm if (RtcUpdateDone()) { // make sure it's safe to read reg_ch = ReadCmosByte(0x32); // century reg_cl = ReadCmosByte(0x09); // year reg_dh = ReadCmosByte(0x08); // month reg_dl = ReadCmosByte(0x07); // day } CALLBACK_SCF(false); break; } IO_Write(0x70,0x32); //Centuries reg_ch=IO_Read(0x71); IO_Write(0x70,0x09); //Years reg_cl=IO_Read(0x71); IO_Write(0x70,0x08); //Months reg_dh=IO_Read(0x71); IO_Write(0x70,0x07); //Days reg_dl=IO_Read(0x71); CALLBACK_SCF(false); break; case 0x05: // set RTC date if(date_host_forced) { InitRtc(); // make sure BCD and no am/pm WriteCmosByte(0x0b, ReadCmosByte(0x0b) | 0x80); // prohibit updates WriteCmosByte(0x32, reg_ch); // century WriteCmosByte(0x09, reg_cl); // year WriteCmosByte(0x08, reg_dh); // month WriteCmosByte(0x07, reg_dl); // day WriteCmosByte(0x0b, (ReadCmosByte(0x0b) & 0x7f)); // allow updates } break; case 0x80: /* Pcjr Setup Sound Multiplexer */ LOG(LOG_BIOS,LOG_ERROR)("INT1A:80:Setup tandy sound multiplexer to %d",reg_al); break; case 0x81: /* Tandy sound system check */ case 0x82: /* Tandy sound system start recording */ case 0x83: /* Tandy sound system start playback */ case 0x84: /* Tandy sound system stop playing */ case 0x85: /* Tandy sound system reset */ TandyDAC_Handler(reg_ah); break; case 0xb1: /* PCI Bios Calls */ if (pcibus_enable) { LOG(LOG_BIOS,LOG_WARN)("INT1A:PCI bios call %2X",reg_al); switch (reg_al) { case 0x01: // installation check if (PCI_IsInitialized()) { reg_ah=0x00; reg_al=0x01; // cfg space mechanism 1 supported reg_bx=0x0210; // ver 2.10 reg_cx=0x0000; // only one PCI bus reg_edx=0x20494350; reg_edi=PCI_GetPModeInterface(); CALLBACK_SCF(false); } else { CALLBACK_SCF(true); } break; case 0x02: { // find device Bitu devnr=0u; Bitu count=0x100u; uint32_t devicetag=((unsigned int)reg_cx<<16u)|reg_dx; Bits found=-1; for (Bitu i=0; i<=count; i++) { IO_WriteD(0xcf8,0x80000000u|(i<<8u)); // query unique device/subdevice entries if (IO_ReadD(0xcfc)==devicetag) { if (devnr==reg_si) { found=(Bits)i; break; } else { // device found, but not the SIth device devnr++; } } } if (found>=0) { reg_ah=0x00; reg_bh=0x00; // bus 0 reg_bl=(uint8_t)(found&0xff); CALLBACK_SCF(false); } else { reg_ah=0x86; // device not found CALLBACK_SCF(true); } } break; case 0x03: { // find device by class code Bitu devnr=0; Bitu count=0x100u; uint32_t classtag=reg_ecx&0xffffffu; Bits found=-1; for (Bitu i=0; i<=count; i++) { IO_WriteD(0xcf8,0x80000000u|(i<<8u)); // query unique device/subdevice entries if (IO_ReadD(0xcfc)!=0xffffffffu) { IO_WriteD(0xcf8,0x80000000u|(i<<8u)|0x08u); if ((IO_ReadD(0xcfc)>>8u)==classtag) { if (devnr==reg_si) { found=(Bits)i; break; } else { // device found, but not the SIth device devnr++; } } } } if (found>=0) { reg_ah=0x00; reg_bh=0x00; // bus 0 reg_bl=(uint8_t)found & 0xffu; CALLBACK_SCF(false); } else { reg_ah=0x86; // device not found CALLBACK_SCF(true); } } break; case 0x08: // read configuration byte IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); reg_cl=IO_ReadB(0xcfc+(reg_di&3u)); CALLBACK_SCF(false); reg_ah=0x00; break; case 0x09: // read configuration word IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); reg_cx=IO_ReadW(0xcfc+(reg_di&2u)); CALLBACK_SCF(false); reg_ah=0x00; break; case 0x0a: // read configuration dword IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); reg_ecx=IO_ReadD(0xcfc+(reg_di&3u)); CALLBACK_SCF(false); reg_ah=0x00; break; case 0x0b: // write configuration byte IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); IO_WriteB(0xcfc+(reg_di&3u),reg_cl); CALLBACK_SCF(false); reg_ah=0x00; break; case 0x0c: // write configuration word IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); IO_WriteW(0xcfc+(reg_di&2u),reg_cx); CALLBACK_SCF(false); reg_ah=0x00; break; case 0x0d: // write configuration dword IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); IO_WriteD(0xcfc+((unsigned int)reg_di&3u),reg_ecx); CALLBACK_SCF(false); reg_ah=0x00; break; default: LOG(LOG_BIOS,LOG_ERROR)("INT1A:PCI BIOS: unknown function %x (%x %x %x)", reg_ax,reg_bx,reg_cx,reg_dx); CALLBACK_SCF(true); break; } } else { CALLBACK_SCF(true); } break; default: LOG(LOG_BIOS,LOG_ERROR)("INT1A:Undefined call %2X",reg_ah); } return CBRET_NONE; } bool INT16_get_key(uint16_t &code); bool INT16_peek_key(uint16_t &code); extern uint8_t GDC_display_plane; extern uint8_t GDC_display_plane_pending; extern bool GDC_vsync_interrupt; unsigned char prev_pc98_mode42 = 0; unsigned char pc98_function_row_mode = 0; const char *pc98_func_key_default[10] = { " C1 ", " CU ", " CA ", " S1 ", " SU ", "VOID ", "NWL ", "INS ", "REP ", " ^Z " }; const char pc98_func_key_escapes_default[10][3] = { {0x1B,0x53,0}, // F1 {0x1B,0x54,0}, // F2 {0x1B,0x55,0}, // F3 {0x1B,0x56,0}, // F4 {0x1B,0x57,0}, // F5 {0x1B,0x45,0}, // F6 {0x1B,0x4A,0}, // F7 {0x1B,0x50,0}, // F8 {0x1B,0x51,0}, // F9 {0x1B,0x5A,0} // F10 }; const char pc98_editor_key_escapes_default[11][3] = { {0}, // ROLL UP 0x36 {0}, // ROLL DOWN 0x37 {0x1B,0x50,0}, // INS 0x38 {0x1B,0x44,0}, // DEL 0x39 {0x0B,0}, // UP ARROW 0x3A {0x08,0}, // LEFT ARROW 0x3B {0x0C,0}, // RIGHT ARROW 0x3C {0x0A,0}, // DOWN ARROW 0x3D {0}, // HOME/CLR 0x3E {0}, // HELP 0x3F {0} // KEYPAD - 0x40 }; // shortcuts offered by SHIFT F1-F10. You can bring this onscreen using CTRL+F7. This row shows '*' in col 2. // The text displayed onscreen is obviously just the first 6 chars of the shortcut text. const char *pc98_shcut_key_defaults[10] = { "dir a:\x0D", "dir b:\x0D", "copy ", "del ", "ren ", "chkdsk a:\x0D", "chkdsk b:\x0D", "type ", "date\x0D", "time\x0D" }; #pragma pack(push,1) struct pc98_func_key_shortcut_def { unsigned char length; /* +0x00 length of text */ unsigned char shortcut[0x0F]; /* +0x01 Shortcut text to insert into CON device */ std::string getShortcutText(void) const { std::string ret; unsigned int i; /* Whether a shortcut or escape (0xFE or not) the first 6 chars are displayed always */ /* TODO: Strings for display are expected to display as Shift-JIS, convert to UTF-8 for display on host */ for (i=0;i < 0x0F;i++) { if (shortcut[i] == 0u) break; else if (shortcut[i] == 0x1B) { ret += "<ESC>"; } else if (shortcut[i] > 0x7Fu || shortcut[i] < 32u) /* 0xFE is invisible on real hardware */ ret += ' '; else ret += (char)shortcut[i]; } return ret; } std::string getDisplayText(void) const { unsigned int i; char tmp[8]; /* Whether a shortcut or escape (0xFE or not) the first 6 chars are displayed always */ /* TODO: Strings for display are expected to display as Shift-JIS, convert to UTF-8 for display on host */ for (i=0;i < 6;i++) { if (shortcut[i] == 0u) break; else if (shortcut[i] > 0x7Fu || shortcut[i] < 32u) /* 0xFE is invisible on real hardware */ tmp[i] = ' '; else tmp[i] = (char)shortcut[i]; } tmp[i] = 0; return tmp; } std::string debugToString(void) const { std::string ret; char tmp[512]; if (length == 0) return "(none)"; if (shortcut[0] == 0xFE) { sprintf(tmp,"disp=\"%s\" ",getDisplayText().c_str()); ret += tmp; ret += "dispraw={ "; for (unsigned int i=0;i < 6;i++) { sprintf(tmp,"%02x ",shortcut[i]); ret += tmp; } ret += "} "; ret += "esc={ "; for (unsigned int i=6;i < length;i++) { sprintf(tmp,"%02x ",shortcut[i]); ret += tmp; } ret += "}"; } else { sprintf(tmp,"text=\"%s\" ",getShortcutText().c_str()); ret += tmp; ret += "esc={ "; for (unsigned int i=0;i < length;i++) { sprintf(tmp,"%02x ",shortcut[i]); ret += tmp; } ret += "}"; } return ret; } // set shortcut. // usually a direct string to insert. void set_shortcut(const char *str) { unsigned int i=0; char c; while (i < 0x0F && (c = *str++) != 0) shortcut[i++] = (unsigned char)c; length = i; while (i < 0x0F) shortcut[i++] = 0; } // set text and escape code. text does NOT include the leading 0xFE char. void set_text_and_escape(const char *text,const char *escape) { unsigned int i=1; char c; // this is based on observed MS-DOS behavior on PC-98. // the length byte covers both the display text and escape code (sum of the two). // the first byte of the shortcut is 0xFE which apparently means the next 5 chars // are text to display. The 0xFE is copied as-is to the display when rendered. // 0xFE in the CG ROM is a blank space. shortcut[0] = 0xFE; while (i < 6 && (c = *text++) != 0) shortcut[i++] = (unsigned char)c; while (i < 6) shortcut[i++] = ' '; while (i < 0x0F && (c = *escape++) != 0) shortcut[i++] = (unsigned char)c; length = i; while (i < 0x0F) shortcut[i++] = 0; } }; /* =0x10 */ #pragma pack(pop) struct pc98_func_key_shortcut_def pc98_func_key[10]; /* F1-F10 */ struct pc98_func_key_shortcut_def pc98_vfunc_key[5]; /* VF1-VF5 */ struct pc98_func_key_shortcut_def pc98_func_key_shortcut[10]; /* Shift+F1 - Shift-F10 */ struct pc98_func_key_shortcut_def pc98_vfunc_key_shortcut[5]; /* Shift+VF1 - Shift-VF5 */ struct pc98_func_key_shortcut_def pc98_func_key_ctrl[10]; /* Control+F1 - Control-F10 */ struct pc98_func_key_shortcut_def pc98_vfunc_key_ctrl[5]; /* Control+VF1 - Control-VF5 */ struct pc98_func_key_shortcut_def pc98_editor_key_escapes[11]; /* Editor keys */ // FIXME: This is STUPID. Cleanup is needed in order to properly use std::min without causing grief. #ifdef _MSC_VER # define MIN(a,b) ((a) < (b) ? (a) : (b)) # define MAX(a,b) ((a) > (b) ? (a) : (b)) #else # define MIN(a,b) std::min(a,b) # define MAX(a,b) std::max(a,b) #endif void PC98_GetFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i,const struct pc98_func_key_shortcut_def *keylist) { if (i >= 1 && i <= 10) { const pc98_func_key_shortcut_def &def = keylist[i-1u]; unsigned int j=0,o=0; /* if the shortcut starts with 0xFE then the next 5 chars are intended for display only * and the shortcut starts after that. Else the entire string is stuffed into the CON * device. */ if (def.shortcut[0] == 0xFE) j = 6; while (j < MIN(0x0Fu,(unsigned int)def.length)) buf[o++] = def.shortcut[j++]; len = (size_t)o; buf[o] = 0; } else { len = 0; buf[0] = 0; } } void PC98_GetEditorKeyEscape(size_t &len,unsigned char buf[16],const unsigned int scan) { if (scan >= 0x36 && scan <= 0x40) { const pc98_func_key_shortcut_def &def = pc98_editor_key_escapes[scan-0x36]; unsigned int j=0,o=0; while (j < MIN(0x05u,(unsigned int)def.length)) buf[o++] = def.shortcut[j++]; len = (size_t)o; buf[o] = 0; } else { len = 0; buf[0] = 0; } } void PC98_GetVFKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i,const struct pc98_func_key_shortcut_def *keylist) { if (i >= 1 && i <= 5) { const pc98_func_key_shortcut_def &def = keylist[i-1]; unsigned int j=0,o=0; /* if the shortcut starts with 0xFE then the next 5 chars are intended for display only * and the shortcut starts after that. Else the entire string is stuffed into the CON * device. */ if (def.shortcut[0] == 0xFE) j = 6; while (j < MIN(0x0Fu,(unsigned int)def.length)) buf[o++] = def.shortcut[j++]; len = (size_t)o; buf[o] = 0; } else { len = 0; buf[0] = 0; } } void PC98_GetFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { PC98_GetFuncKeyEscape(len,buf,i,pc98_func_key); } void PC98_GetShiftFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { PC98_GetFuncKeyEscape(len,buf,i,pc98_func_key_shortcut); } void PC98_GetCtrlFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { PC98_GetFuncKeyEscape(len,buf,i,pc98_func_key_ctrl); } void PC98_GetVFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { PC98_GetVFKeyEscape(len,buf,i,pc98_vfunc_key); } void PC98_GetShiftVFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { PC98_GetVFKeyEscape(len,buf,i,pc98_vfunc_key_shortcut); } void PC98_GetCtrlVFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { PC98_GetVFKeyEscape(len,buf,i,pc98_vfunc_key_ctrl); } void PC98_InitDefFuncRow(void) { for (unsigned int i=0;i < 10;i++) { pc98_func_key_shortcut_def &def = pc98_func_key[i]; def.set_text_and_escape(pc98_func_key_default[i],pc98_func_key_escapes_default[i]); } for (unsigned int i=0;i < 10;i++) { pc98_func_key_shortcut_def &def = pc98_func_key_shortcut[i]; def.set_shortcut(pc98_shcut_key_defaults[i]); } for (unsigned int i=0;i < 11;i++) { pc98_func_key_shortcut_def &def = pc98_editor_key_escapes[i]; def.set_shortcut(pc98_editor_key_escapes_default[i]); } for (unsigned int i=0;i < 10;i++) { pc98_func_key_shortcut_def &def = pc98_func_key_ctrl[i]; def.set_shortcut(""); } /* MS-DOS by default does not assign the VFn keys anything */ for (unsigned int i=0;i < 5;i++) { pc98_func_key_shortcut_def &def = pc98_vfunc_key[i]; def.set_shortcut(""); } for (unsigned int i=0;i < 5;i++) { pc98_func_key_shortcut_def &def = pc98_vfunc_key_shortcut[i]; def.set_shortcut(""); } for (unsigned int i=0;i < 5;i++) { pc98_func_key_shortcut_def &def = pc98_vfunc_key_ctrl[i]; def.set_shortcut(""); } } #include "int10.h" void draw_pc98_function_row_elem(unsigned int o, unsigned int co, const struct pc98_func_key_shortcut_def& key) { const unsigned char *str = key.shortcut; unsigned int j = 0,i = 0; // NTS: Some shortcut strings start with 0xFE, which is rendered as an invisible space anyway. // NTS: Apparently the strings are Shift-JIS and expected to render to the function key row // the same way the console normally does it. ShiftJISDecoder sjis; while (j < 6u && str[i] != 0) { if (sjis.take(str[i++])) { if (sjis.doublewide) { /* JIS conversion to WORD value appropriate for text RAM */ if (sjis.b2 != 0) sjis.b1 -= 0x20; uint16_t w = (sjis.b2 << 8) + sjis.b1; mem_writew(0xA0000+((o+co+j)*2u),w); mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible j++; mem_writew(0xA0000+((o+co+j)*2u),w); mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible j++; } else { mem_writew(0xA0000+((o+co+j)*2u),str[j]); mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible j++; } } } while (j < 6u) { mem_writew(0xA0000+((o+co+j)*2u),(unsigned char)(' ')); mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible j++; } } void draw_pc98_function_row(unsigned int o, const struct pc98_func_key_shortcut_def* keylist) { mem_writew(0xA0000+((o+1)*2),real_readb(0x60,0x8B)); mem_writeb(0xA2000+((o+1)*2),0xE1); for (unsigned int i=0u;i < 5u;i++) draw_pc98_function_row_elem(o,4u + (i * 7u),keylist[i]); for (unsigned int i=5u;i < 10u;i++) draw_pc98_function_row_elem(o,42u + ((i - 5u) * 7u),keylist[i]); } unsigned int pc98_DOS_console_rows(void) { uint8_t b = real_readb(0x60,0x113); return (b & 0x01) ? 25 : 20; } void update_pc98_function_row(unsigned char setting,bool force_redraw) { if (!force_redraw && pc98_function_row_mode == setting) return; pc98_function_row_mode = setting; unsigned int total_rows = pc98_DOS_console_rows(); unsigned char c = real_readb(0x60,0x11C); unsigned char r = real_readb(0x60,0x110); unsigned int o = 80 * (total_rows - 1); if (pc98_function_row_mode != 0) { if (r > (total_rows - 2)) { r = (total_rows - 2); void INTDC_CL10h_AH04h(void); INTDC_CL10h_AH04h(); } } /* update mode 2 indicator */ real_writeb(0x60,0x8C,(pc98_function_row_mode == 2) ? '*' : ' '); real_writeb(0x60,0x112,total_rows - 1 - ((pc98_function_row_mode != 0) ? 1 : 0)); if (pc98_function_row_mode == 2) { /* draw the function row. * based on on real hardware: * * The function key is 72 chars wide. 4 blank chars on each side of the screen. * It is divided into two halves, 36 chars each. * Within each half, aligned to it's side, is 5 x 7 regions. * 6 of the 7 are inverted. centered in the white block is the function key. */ for (unsigned int i=0;i < 40;) { mem_writew(0xA0000+((o+i)*2),0x0000); mem_writeb(0xA2000+((o+i)*2),0xE1); mem_writew(0xA0000+((o+(79-i))*2),0x0000); mem_writeb(0xA2000+((o+(79-i))*2),0xE1); if (i >= 3 && i < 38) i += 7; else i++; } mem_writew(0xA0000+((o+2)*2),real_readb(0x60,0x8C)); mem_writeb(0xA2000+((o+2)*2),0xE1); draw_pc98_function_row(o,pc98_func_key_shortcut); } else if (pc98_function_row_mode == 1) { /* draw the function row. * based on on real hardware: * * The function key is 72 chars wide. 4 blank chars on each side of the screen. * It is divided into two halves, 36 chars each. * Within each half, aligned to it's side, is 5 x 7 regions. * 6 of the 7 are inverted. centered in the white block is the function key. */ for (unsigned int i=0;i < 40;) { mem_writew(0xA0000+((o+i)*2),0x0000); mem_writeb(0xA2000+((o+i)*2),0xE1); mem_writew(0xA0000+((o+(79-i))*2),0x0000); mem_writeb(0xA2000+((o+(79-i))*2),0xE1); if (i >= 3 && i < 38) i += 7; else i++; } draw_pc98_function_row(o,pc98_func_key); } else { /* erase the function row */ for (unsigned int i=0;i < 80;i++) { mem_writew(0xA0000+((o+i)*2),0x0000); mem_writeb(0xA2000+((o+i)*2),0xE1); } } real_writeb(0x60,0x11C,c); real_writeb(0x60,0x110,r); real_writeb(0x60,0x111,(pc98_function_row_mode != 0) ? 0x01 : 0x00);/* function key row display status */ void vga_pc98_direct_cursor_pos(uint16_t address); vga_pc98_direct_cursor_pos((r*80)+c); } void pc98_function_row_user_toggle(void) { if (pc98_function_row_mode >= 2) update_pc98_function_row(0,true); else update_pc98_function_row(pc98_function_row_mode+1,true); } void pc98_set_char_mode(bool mode) { real_writeb(0x60,0x8A,mode); real_writeb(0x60,0x8B,(mode == true) ? ' ' : 'g'); update_pc98_function_row(pc98_function_row_mode,true); } void pc98_toggle_char_mode(void) { pc98_set_char_mode(!real_readb(0x60,0x8A)); } void pc98_set_digpal_entry(unsigned char ent,unsigned char grb); void PC98_show_cursor(bool show); extern bool gdc_5mhz_mode; extern bool enable_pc98_egc; extern bool enable_pc98_grcg; extern bool enable_pc98_16color; extern bool enable_pc98_256color; extern bool enable_pc98_188usermod; extern bool pc98_31khz_mode; extern bool pc98_attr4_graphic; extern unsigned char pc98_text_first_row_scanline_start; /* port 70h */ extern unsigned char pc98_text_first_row_scanline_end; /* port 72h */ extern unsigned char pc98_text_row_scanline_blank_at; /* port 74h */ extern unsigned char pc98_text_row_scroll_lines; /* port 76h */ extern unsigned char pc98_text_row_scroll_count_start; /* port 78h */ extern unsigned char pc98_text_row_scroll_num_lines; /* port 7Ah */ void pc98_update_text_layer_lineheight_from_bda(void) { // unsigned char c = mem_readb(0x53C); unsigned char lineheight = mem_readb(0x53B) + 1; pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_MASTER].row_height = lineheight; if (lineheight > 20) { // usually 24 pc98_text_first_row_scanline_start = 0x1C; pc98_text_first_row_scanline_end = lineheight - 5; pc98_text_row_scanline_blank_at = 16; } else if (lineheight > 16) { // usually 20 pc98_text_first_row_scanline_start = 0x1E; pc98_text_first_row_scanline_end = lineheight - 3; pc98_text_row_scanline_blank_at = 16; } else { pc98_text_first_row_scanline_start = 0; pc98_text_first_row_scanline_end = lineheight - 1; pc98_text_row_scanline_blank_at = lineheight; } pc98_text_row_scroll_lines = 0; pc98_text_row_scroll_count_start = 0; pc98_text_row_scroll_num_lines = 0; vga.crtc.cursor_start = 0; vga.draw.cursor.sline = 0; vga.crtc.cursor_end = lineheight - 1; vga.draw.cursor.eline = lineheight - 1; } void pc98_update_text_lineheight_from_bda(void) { unsigned char b597 = mem_readb(0x597); unsigned char c = mem_readb(0x53C); unsigned char lineheight; if ((b597 & 0x3) == 0x3) {//WARNING: This could be wrong if (c & 0x10)/*30-line mode (30x16 = 640x480)*/ lineheight = 16; else if (c & 0x01)/*20-line mode (20x24 = 640x480)*/ lineheight = 24; else/*25-line mode (25x19 = 640x480)*/ lineheight = 19; } else { if (c & 0x10)/*30-line mode (30x13 = 640x400)*/ lineheight = 13;//?? else if (c & 0x01)/*20-line mode (20x20 = 640x400)*/ lineheight = 20; else/*25-line mode (25x16 = 640x400)*/ lineheight = 16; } mem_writeb(0x53B,lineheight - 1); } /* TODO: The text and graphics code that talks to the GDC will need to be converted * to CPU I/O read and write calls. I think the reason Windows 3.1's 16-color * driver is causing screen distortion when going fullscreen with COMMAND.COM, * and the reason COMMAND.COM windowed doesn't show anything, has to do with * the fact that Windows 3.1 expects this BIOS call to use I/O so it can trap * and virtualize the GDC and display state. * * Obviously for the same reason VGA INT 10h emulation in IBM PC mode needs to * do the same to prevent display and virtualization problems with the IBM PC * version of Windows 3.1. * * See also: [https://github.com/joncampbell123/dosbox-x/issues/1066] */ static Bitu INT18_PC98_Handler(void) { uint16_t temp16; #if 0 if (reg_ah >= 0x0A) { LOG_MSG("PC-98 INT 18h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); } #endif /* NTS: Based on information gleaned from Neko Project II source code including comments which * I've run through GNU iconv to convert from SHIFT-JIS to UTF-8 here in case Google Translate * got anything wrong. */ switch (reg_ah) { case 0x00: /* Reading of key data (キー・データの読みだし) */ /* FIXME: We use the IBM PC/AT keyboard buffer to fake this call. * This will be replaced with PROPER emulation once the PC-98 keyboard handler has been * updated to write the buffer the way PC-98 BIOSes do it. * * IBM PC/AT keyboard buffer at 40:1E-40:3D * * PC-98 keyboard buffer at 50:02-50:21 */ /* This call blocks until keyboard input */ if (INT16_get_key(temp16)) { reg_ax = temp16; } else { /* Keyboard checks. * If the interrupt got masked, unmask it. * If the keyboard has data waiting, make sure the interrupt signal is active in case the last interrupt handler * handled the keyboard interrupt and never read the keyboard (Quarth). * * TODO: Is this what real PC-98 BIOSes do? */ void check_keyboard_fire_IRQ1(void); check_keyboard_fire_IRQ1(); IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/1u))); // unmask IRQ1 reg_ip += 1; /* step over IRET, to NOPs which then JMP back to callback */ } break; case 0x01: /* Sense of key buffer state (キー・バッファ状態のセンス) */ /* This call returns whether or not there is input waiting. * The waiting data is read, but NOT discarded from the buffer. */ if (INT16_peek_key(temp16)) { reg_ax = temp16; reg_bh = 1; } else { /* Keyboard checks. * If the interrupt got masked, unmask it. * If the keyboard has data waiting, make sure the interrupt signal is active in case the last interrupt handler * handled the keyboard interrupt and never read the keyboard (Quarth). * * TODO: Is this what real PC-98 BIOSes do? */ void check_keyboard_fire_IRQ1(void); check_keyboard_fire_IRQ1(); IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/1u))); // unmask IRQ1 reg_bh = 0; } break; case 0x02: /* Sense of shift key state (シフト・キー状態のセンス) */ reg_al = mem_readb(0x53A); break; case 0x03: /* Initialization of keyboard interface (キーボード・インタフェイスの初期化) */ /* TODO */ break; case 0x04: /* Sense of key input state (キー入力状態のセンス) */ reg_ah = mem_readb(0x52A + (unsigned int)(reg_al & 0x0Fu)); /* Hack for "Shangrlia" by Elf: The game's regulation of animation speed seems to depend on * INT 18h AH=0x04 taking some amount of time. If we do not do this, animation will run way * too fast and everyone will be talking/moving at a million miles a second. * * This is based on comparing animation speed vs the same game on real Pentium-class PC-98 * hardware. * * Looking at the software loop involved during opening cutscenes, the game is constantly * polling INT 18h AH=04h (keyboard state) and INT 33h AH=03h (mouse button/position state) * while animating the characters on the screen. Without this delay, animation runs way too * fast. * * This guess is also loosely based on a report by the Touhou Community Reliant Automatic Patcher * that Touhou Project directly reads this byte but delays by 0.6ms to handle the fact that * the bit in question may toggle while the key is held down due to the scan codes returned by * the keyboard. * * This is a guess, but it seems to help animation speed match that of real hardware regardless * of cycle count in DOSBox-X. */ CPU_Cycles -= (cpu_cycles_count_t)(CPU_CycleMax * 0.006); break; case 0x05: /* Key input sense (キー入力センス) */ /* This appears to return a key from the buffer (and remove from * buffer) or return BH == 0 to signal no key was pending. */ if (INT16_get_key(temp16)) { reg_ax = temp16; reg_bh = 1; } else { /* Keyboard checks. * If the interrupt got masked, unmask it. * If the keyboard has data waiting, make sure the interrupt signal is active in case the last interrupt handler * handled the keyboard interrupt and never read the keyboard (Quarth). * * TODO: Is this what real PC-98 BIOSes do? */ void check_keyboard_fire_IRQ1(void); check_keyboard_fire_IRQ1(); IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/1u))); // unmask IRQ1 reg_bh = 0; } break; case 0x0A: /* set CRT mode */ /* bit off on 0 25lines 20lines 1 80cols 40cols 2 v.lines simp.graphics 3 K-CG access mode(not used in PC-98) */ //TODO: set 25/20 lines mode and 80/40 columns mode. //Attribute bit (bit 2) pc98_attr4_graphic = !!(reg_al & 0x04); pc98_40col_text = !!(reg_al & 0x02); mem_writeb(0x53C,(mem_readb(0x53C) & 0xF0u) | (reg_al & 0x0Fu)); if (reg_al & 8) LOG_MSG("INT 18H AH=0Ah warning: K-CG dot access mode not supported"); pc98_update_text_lineheight_from_bda(); pc98_update_text_layer_lineheight_from_bda(); /* Apparently, this BIOS call also hides the cursor */ PC98_show_cursor(0); break; case 0x0B: /* get CRT mode */ /* bit off on 0 25lines 20lines 1 80cols 40cols 2 v.lines simp.graphics 3 K-CG access mode(not used in PC-98) 7 std CRT hi-res CRT */ /* NTS: I assume that real hardware doesn't offer a way to read back the state of these bits, * so the BIOS's only option is to read the mode byte back from the data area. * Neko Project II agrees. */ reg_al = mem_readb(0x53C); break; // TODO: "Edge" is using INT 18h AH=06h, what is that? // (Something to do with the buffer [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf]) // Neko Project is also unaware of such a call. case 0x0C: /* text layer enable */ pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_MASTER].display_enable = true; #if defined(USE_TTF) ttf_switch_on(false); #endif break; case 0x0D: /* text layer disable */ #if defined(USE_TTF) ttf_switch_off(false); #endif pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_MASTER].display_enable = false; break; case 0x0E: /* set text display area (DX=byte offset) */ pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_MASTER].param_ram[0] = (reg_dx >> 1) & 0xFF; pc98_gdc[GDC_MASTER].param_ram[1] = (reg_dx >> 9) & 0xFF; pc98_gdc[GDC_MASTER].param_ram[2] = (400 << 4) & 0xFF; pc98_gdc[GDC_MASTER].param_ram[3] = (400 << 4) >> 8; break; case 0x11: /* show cursor */ PC98_show_cursor(true); break; case 0x12: /* hide cursor */ PC98_show_cursor(false); break; case 0x13: /* set cursor position (DX=byte position) */ void vga_pc98_direct_cursor_pos(uint16_t address); pc98_gdc[GDC_MASTER].force_fifo_complete(); vga_pc98_direct_cursor_pos(reg_dx >> 1); break; case 0x14: /* read FONT RAM */ { unsigned int i,o,r; /* DX = code (must be 0x76xx or 0x7700) * BX:CX = 34-byte region to write to */ if (reg_dh == 0x80u) { /* 8x16 ascii */ i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; mem_writew(i-2u,0x0102u); for (r=0;r < 16u;r++) { o = (reg_dl*16u)+r; assert((o+2u) <= sizeof(vga.draw.font)); mem_writeb(i+r,vga.draw.font[o]); } } else if ((reg_dh & 0xFC) == 0x28) { /* 8x16 kanji */ i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; mem_writew(i-2u,0x0102u); for (r=0;r < 16u;r++) { o = (((((reg_dl & 0x7Fu)*128u)+((reg_dh - 0x20u) & 0x7Fu))*16u)+r)*2u; assert((o+2u) <= sizeof(vga.draw.font)); mem_writeb(i+r+0u,vga.draw.font[o+0u]); } } else if (reg_dh != 0) { /* 16x16 kanji */ i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; mem_writew(i-2u,0x0202u); for (r=0;r < 16u;r++) { o = (((((reg_dl & 0x7Fu)*128u)+((reg_dh - 0x20u) & 0x7Fu))*16u)+r)*2u; assert((o+2u) <= sizeof(vga.draw.font)); mem_writeb(i+(r*2u)+0u,vga.draw.font[o+0u]); mem_writeb(i+(r*2u)+1u,vga.draw.font[o+1u]); } } else { LOG_MSG("PC-98 INT 18h AH=14h font RAM read ignored, code 0x%04x not supported",reg_dx); } } break; case 0x16: /* fill screen with chr + attr */ { /* DL = character * DH = attribute */ unsigned int i; for (i=0;i < 0x2000;i += 2) { vga.mem.linear[i+0] = reg_dl; vga.mem.linear[i+1] = 0x00; } for ( ;i < 0x3FE0;i += 2) { vga.mem.linear[i+0] = reg_dh; vga.mem.linear[i+1] = 0x00; } } break; case 0x17: /* BELL ON */ IO_WriteB(0x37,0x06); break; case 0x18: /* BELL OFF */ IO_WriteB(0x37,0x07); break; case 0x1A: /* load FONT RAM */ { /* DX = code (must be 0x76xx or 0x7700) * BX:CX = 34-byte region to read from */ if ((reg_dh & 0x7Eu) == 0x76u) { unsigned int i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; for (unsigned int r=0;r < 16u;r++) { unsigned int o = (((((reg_dl & 0x7Fu)*128u)+((reg_dh - 0x20u) & 0x7Fu))*16u)+r)*2u; assert((o+2u) <= sizeof(vga.draw.font)); vga.draw.font[o+0u] = mem_readb(i+(r*2u)+0u); vga.draw.font[o+1u] = mem_readb(i+(r*2u)+1u); } } else { LOG_MSG("PC-98 INT 18h AH=1Ah font RAM load ignored, code 0x%04x out of range",reg_dx); } } break; case 0x30: /* Set display mode */ /* FIXME: There is still a lot that is inaccurate about this call */ if (enable_pc98_egc) { unsigned char b597 = mem_readb(0x597); unsigned char tstat = mem_readb(0x53C); unsigned char b54C = mem_readb(0x54C); unsigned char ret = 0x05; // according to NP2 // assume the same as AH=42h while (!(IO_ReadB(0x60) & 0x20/*vertical retrace*/)) { void CALLBACK_Idle(void); CALLBACK_Idle(); } LOG_MSG("PC-98 INT 18 AH=30h AL=%02Xh BH=%02Xh",reg_al,reg_bh); if ((reg_bh & 0x30) == 0x30) { // 640x480 if ((reg_al & 0xC) == 0x0C) { // 31KHz sync void PC98_Set31KHz_480line(void); pc98_31khz_mode = true; PC98_Set31KHz_480line(); void pc98_port6A_command_write(unsigned char b); pc98_port6A_command_write(0x69); // disable 128KB wrap b54C = (b54C & (~0x20)) + ((reg_al & 0x04) ? 0x20 : 0x00); #if defined(USE_TTF) ttf_switch_off(false); #endif pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_SLAVE].force_fifo_complete(); // according to real hardware, this also hides the text layer for some reason pc98_gdc[GDC_MASTER].display_enable = false; /* clear PRAM, graphics */ for (unsigned int i=0;i < 16;i++) pc98_gdc[GDC_SLAVE].param_ram[i] = 0x00; /* reset scroll area of graphics */ pc98_gdc[GDC_SLAVE].param_ram[0] = 0; pc98_gdc[GDC_SLAVE].param_ram[1] = 0; pc98_gdc[GDC_SLAVE].param_ram[2] = 0xF0; pc98_gdc[GDC_SLAVE].param_ram[3] = 0x3F + (gdc_5mhz_according_to_bios()?0x40:0x00/*IM bit*/); pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_according_to_bios() ? 80u : 40u; pc98_gdc[GDC_SLAVE].doublescan = false; pc98_gdc[GDC_SLAVE].row_height = 1; b597 = (b597 & ~3u) + ((uint8_t)(reg_bh >> 4u) & 3u); pc98_gdc_vramop &= ~(1 << VOPBIT_ACCESS); pc98_update_cpu_page_ptr(); GDC_display_plane = GDC_display_plane_pending = 0; pc98_update_display_page_ptr(); /* based on real hardware behavior, this ALSO sets 256-color mode */ void pc98_port6A_command_write(unsigned char b); pc98_port6A_command_write(0x07); // enable EGC pc98_port6A_command_write(0x01); // enable 16-color pc98_port6A_command_write(0x21); // enable 256-color } else { // according to Neko Project II, this case is ignored. // this is confirmed on real hardware as well. LOG_MSG("PC-98 INT 18h AH=30h attempt to set 640x480 mode with 24KHz hsync which is not supported by the platform"); ret = 0; } } else { // 640x400 or 640x200 // TODO: A PC9821Lt2 laptop's BIOS refuses to allow 31khz except for 640x480 mode. // Perhaps it's just a technical restriction of the LCD display. // // Check on other PC-98 hardware to see what the policy is for 31khz in all modes. // That restriction would make no sense on another system I have that has a VGA // port and a default setting of 70Hz / 31KHz 640x400. if ((reg_al & 0x0C) < 0x08) { /* bits [3:2] == 0x */ LOG_MSG("PC-98 INT 18h AH=30h attempt to set 15KHz hsync which is not yet supported"); ret = 0; } else { if ((reg_al ^ (((b54C & 0x20) ? 3 : 2) << 2)) & 0x0C) { /* change in bits [3:2] */ LOG_MSG("PC-98 change in hsync frequency to %uHz",(reg_al & 0x04) ? 31 : 24); if (reg_al & 4) { void PC98_Set31KHz(void); pc98_31khz_mode = true; PC98_Set31KHz(); } else { void PC98_Set24KHz(void); pc98_31khz_mode = false; PC98_Set24KHz(); } b54C = (b54C & (~0x20)) + ((reg_al & 0x04) ? 0x20 : 0x00); } } void pc98_port6A_command_write(unsigned char b); pc98_port6A_command_write(0x68); // restore 128KB wrap #if defined(USE_TTF) ttf_switch_off(false); #endif pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_SLAVE].force_fifo_complete(); // 640x480 forces 256-color mode. // the 400 line modes (this case) do not clear 256-color mode. // according to real hardware, this also hides the text layer for some reason pc98_gdc[GDC_MASTER].display_enable = false; /* clear PRAM, graphics */ for (unsigned int i=0;i < 16;i++) pc98_gdc[GDC_SLAVE].param_ram[i] = 0x00; /* reset scroll area of graphics */ if ((reg_bh & 0x30) == 0x10) { /* 640x200 upper half bits [5:4] == 1 */ pc98_gdc[GDC_SLAVE].param_ram[0] = (200*40) & 0xFF; pc98_gdc[GDC_SLAVE].param_ram[1] = (200*40) >> 8; } else { pc98_gdc[GDC_SLAVE].param_ram[0] = 0; pc98_gdc[GDC_SLAVE].param_ram[1] = 0; } pc98_gdc[GDC_SLAVE].param_ram[2] = 0xF0; pc98_gdc[GDC_SLAVE].param_ram[3] = 0x3F + (gdc_5mhz_according_to_bios()?0x40:0x00/*IM bit*/); pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_according_to_bios() ? 80u : 40u; if ((reg_bh & 0x20) == 0x00) { /* 640x200 */ pc98_gdc[GDC_SLAVE].doublescan = true; pc98_gdc[GDC_SLAVE].row_height = pc98_gdc[GDC_SLAVE].doublescan ? 2 : 1; } else { pc98_gdc[GDC_SLAVE].doublescan = false; pc98_gdc[GDC_SLAVE].row_height = 1; } b597 = (b597 & ~3u) + ((uint8_t)(reg_bh >> 4u) & 3u); pc98_gdc_vramop &= ~(1 << VOPBIT_ACCESS); pc98_update_cpu_page_ptr(); GDC_display_plane = GDC_display_plane_pending = 0; pc98_update_display_page_ptr(); } tstat &= ~(0x10 | 0x01); if (reg_bh & 2) tstat |= 0x10; else if ((reg_bh & 1) == 0) tstat |= 0x01; mem_writeb(0x597,b597); mem_writeb(0x53C,tstat); mem_writeb(0x54C,b54C); pc98_update_text_lineheight_from_bda(); pc98_update_text_layer_lineheight_from_bda(); // according to real hardware (PC-9821Lt2), AH=5 on success (same as NP2) // or AH is unchanged on failure and AL=1 and BH=1 (NOT the same as NP2) if (ret == 0x05) reg_ah = ret; reg_al = (ret == 0x05) ? 0x00 : 0x01; // according to NP2 reg_bh = (ret == 0x05) ? 0x00 : 0x01; // according to NP2 } break; case 0x31: /* Return display mode and status */ /* NTS: According to NP II this call shouldn't even work unless you first call AH=30h to set 640x480 mode. * It seems that is wrong. Real hardware will still return the current mode regardless. */ if (enable_pc98_egc) { /* FIXME: INT 18h AH=31/30h availability is tied to EGC enable */ unsigned char b597 = mem_readb(0x597); unsigned char tstat = mem_readb(0x53C); unsigned char b54C = mem_readb(0x54C); /* 54Ch: * bit[5:5] = Horizontal sync rate 1=31.47KHz 0=24.83KHz */ /* Return values: * * AL = * bit [7:7] = ? * bit [6:6] = ? * bit [5:5] = ? * bit [4:4] = ? * bit [3:2] = horizontal sync * 00 = 15.98KHz * 01 = ? * 10 = 24.83KHz * 11 = 31.47KHz * bit [1:1] = ? * bit [0:0] = interlaced (1=yes 0=no) * BH = * bit [7:7] = ? * bit [6:6] = ? * bit [5:4] = graphics video mode * 00 = 640x200 (upper half) * 01 = 640x200 (lower half) * 10 = 640x400 * 11 = 640x480 * bit [3:3] = ? * bit [2:2] = ? * bit [1:0] = number of text rows * 00 = 20 rows * 01 = 25 rows * 10 = 30 rows * 11 = ? */ reg_al = (((b54C & 0x20) ? 3 : 2) << 2)/*hsync*/; reg_bh = ((b597 & 3) << 4)/*graphics video mode*/; if (tstat & 0x10) reg_bh |= 2;/*30 rows*/ else if ((tstat & 0x01) == 0) reg_bh |= 1;/*25 rows*/ } break; /* From this point on the INT 18h call list appears to wander off from the keyboard into CRT/GDC/display management. */ case 0x40: /* Start displaying the graphics screen (グラフィック画面の表示開始) */ pc98_gdc[GDC_SLAVE].force_fifo_complete(); pc98_gdc[GDC_SLAVE].display_enable = true; { unsigned char b = mem_readb(0x54C/*MEMB_PRXCRT*/); mem_writeb(0x54C/*MEMB_PRXCRT*/,b | 0x80); } break; case 0x41: /* Stop displaying the graphics screen (グラフィック画面の表示終了) */ pc98_gdc[GDC_SLAVE].force_fifo_complete(); pc98_gdc[GDC_SLAVE].display_enable = false; { unsigned char b = mem_readb(0x54C/*MEMB_PRXCRT*/); mem_writeb(0x54C/*MEMB_PRXCRT*/,b & (~0x80)); } break; case 0x42: /* Display area setup (表示領域の設定) */ // HACK for Quarth: If the game has triggered vsync interrupt, wait for it. // Quarth's vsync interrupt will reprogram the display partitions back to what // it would have set for gameplay after this modeset and cause display problems // with the main menu. Waiting one vertical retrace period before mode setting // gives Quarth one last frame to reprogram partitions before realizing that // it's time to stop it. // // If the BIOS on real hardware has any check like this, it's probably a loop // to wait for vsync. // // The interrupt does NOT cancel the vertical retrace interrupt. Some games // (Rusty) will not work properly if this call cancels the vertical retrace // interrupt. while (!(IO_ReadB(0x60) & 0x20/*vertical retrace*/)) { void CALLBACK_Idle(void); CALLBACK_Idle(); } pc98_gdc[GDC_MASTER].force_fifo_complete(); pc98_gdc[GDC_SLAVE].force_fifo_complete(); /* clear PRAM, graphics */ for (unsigned int i=0;i < 16;i++) pc98_gdc[GDC_SLAVE].param_ram[i] = 0x00; /* reset scroll area of graphics */ if ((reg_ch & 0xC0) == 0x40) { /* 640x200 G-RAM upper half */ pc98_gdc[GDC_SLAVE].param_ram[0] = (200*40) & 0xFF; pc98_gdc[GDC_SLAVE].param_ram[1] = (200*40) >> 8; } else { pc98_gdc[GDC_SLAVE].param_ram[0] = 0; pc98_gdc[GDC_SLAVE].param_ram[1] = 0; } pc98_gdc[GDC_SLAVE].param_ram[2] = 0xF0; pc98_gdc[GDC_SLAVE].param_ram[3] = 0x3F + (gdc_5mhz_according_to_bios()?0x40:0x00/*IM bit*/); pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_according_to_bios() ? 80u : 40u; // CH // [7:6] = G-RAM setup // 00 = no graphics (?) // 01 = 640x200 upper half // 10 = 640x200 lower half // 11 = 640x400 // [5:5] = CRT // 0 = color // 1 = monochrome // [4:4] = Display bank // FIXME: This is a guess. I have no idea as to actual behavior, yet. // This seems to help with clearing the text layer when games start the graphics. // This is ALSO how we will detect games that switch on the 200-line double-scan mode vs 400-line mode. if ((reg_ch & 0xC0) != 0) { pc98_gdc[GDC_SLAVE].doublescan = ((reg_ch & 0xC0) == 0x40) || ((reg_ch & 0xC0) == 0x80); pc98_gdc[GDC_SLAVE].row_height = pc98_gdc[GDC_SLAVE].doublescan ? 2 : 1; /* update graphics mode bits */ { unsigned char b = mem_readb(0x597); b &= ~3; b |= ((reg_ch >> 6) - 1) & 3; mem_writeb(0x597,b); } } else { pc98_gdc[GDC_SLAVE].doublescan = false; pc98_gdc[GDC_SLAVE].row_height = 1; } { unsigned char b = mem_readb(0x54C/*MEMB_PRXCRT*/); // Real hardware behavior: graphics selection updated by BIOS to reflect MEMB_PRXCRT state pc98_gdc[GDC_SLAVE].display_enable = !!(b & 0x80); #if defined(USE_TTF) pc98_gdc[GDC_SLAVE].display_enable?ttf_switch_off(false):ttf_switch_on(false); #endif } pc98_gdc_vramop &= ~(1 << VOPBIT_ACCESS); pc98_update_cpu_page_ptr(); GDC_display_plane = GDC_display_plane_pending = (reg_ch & 0x10) ? 1 : 0; pc98_update_display_page_ptr(); prev_pc98_mode42 = reg_ch; LOG_MSG("PC-98 INT 18 AH=42h CH=0x%02X",reg_ch); break; case 0x43: // Palette register settings? Only works in digital mode? --leonier // // This is said to fix Thexder's GAME ARTS logo. --Jonathan C. // // TODO: Validate this against real PC-98 hardware and BIOS { unsigned int gbcpc = SegValue(ds)*0x10u + reg_bx; for(unsigned int i=0;i<4;i++) { unsigned char p=mem_readb(gbcpc+4u+i); pc98_set_digpal_entry(7u-2u*i, p&0xFu); pc98_set_digpal_entry(6u-2u*i, p>>4u); } LOG_MSG("PC-98 INT 18 AH=43h CX=0x%04X DS=0x%04X", reg_cx, SegValue(ds)); break; } case 0x4D: // 256-color enable if (reg_ch == 1) { void pc98_port6A_command_write(unsigned char b); pc98_port6A_command_write(0x07); // enable EGC pc98_port6A_command_write(0x01); // enable 16-color pc98_port6A_command_write(0x21); // enable 256-color PC98_show_cursor(false); // apparently hides the cursor? } else if (reg_ch == 0) { void pc98_port6A_command_write(unsigned char b); pc98_port6A_command_write(0x20); // disable 256-color PC98_show_cursor(false); // apparently hides the cursor? } else { LOG_MSG("PC-98 INT 18h AH=4Dh unknown CH=%02xh",reg_ch); } break; default: LOG_MSG("PC-98 INT 18h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); break; } /* FIXME: What do actual BIOSes do when faced with an unknown INT 18h call? */ return CBRET_NONE; } #define PC98_FLOPPY_HIGHDENSITY 0x01 #define PC98_FLOPPY_2HEAD 0x02 #define PC98_FLOPPY_RPM_3MODE 0x04 #define PC98_FLOPPY_RPM_IBMPC 0x08 unsigned char PC98_BIOS_FLOPPY_BUFFER[32768]; /* 128 << 8 */ static unsigned int PC98_FDC_SZ_TO_BYTES(unsigned int sz) { return 128U << sz; } int PC98_BIOS_SCSI_POS(imageDisk *floppy,uint32_t &sector) { if (reg_al & 0x80) { uint32_t img_heads=0,img_cyl=0,img_sect=0,img_ssz=0; floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); /* DL = sector * DH = head * CX = track */ if (reg_dl >= img_sect || reg_dh >= img_heads || reg_cx >= img_cyl) { return (reg_ah=0x60); } sector = reg_cx; sector *= img_heads; sector += reg_dh; sector *= img_sect; sector += reg_dl; // LOG_MSG("Sector CHS %u/%u/%u -> %u (geo %u/%u/%u)",reg_cx,reg_dh,reg_dl,sector,img_cyl,img_heads,img_sect); } else { /* Linear LBA addressing */ sector = ((unsigned int)reg_dl << 16UL) + reg_cx; /* TODO: SASI caps at 0x1FFFFF according to NP2 */ } return 0; } void PC98_BIOS_SCSI_CALL(void) { uint32_t img_heads=0,img_cyl=0,img_sect=0,img_ssz=0; uint32_t memaddr,size,ssize; imageDisk *floppy; unsigned int i; uint32_t sector; int idx; #if 0 LOG_MSG("PC-98 INT 1Bh SCSI BIOS call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); #endif idx = (reg_al & 0xF) + 2; if (idx < 0 || idx >= MAX_DISK_IMAGES) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } floppy = imageDiskList[idx]; if (floppy == NULL) { CALLBACK_SCF(true); reg_ah = 0x60; return; } /* FIXME: According to NPKai, command is reg_ah & 0x1F not reg_ah & 0x0F. Right? */ /* what to do is in the lower 4 bits of AH */ switch (reg_ah & 0x0F) { case 0x05: /* write */ if (PC98_BIOS_SCSI_POS(floppy,/*&*/sector) == 0) { floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); assert(img_ssz != 0); size = reg_bx; if (size == 0) size = 0x10000U; memaddr = ((unsigned int)SegValue(es) << 4u) + reg_bp; reg_ah = 0; CALLBACK_SCF(false); // LOG_MSG("WRITE memaddr=0x%lx size=0x%x sector=0x%lx ES:BP=%04x:%04X", // (unsigned long)memaddr,(unsigned int)size,(unsigned long)sector,SegValue(es),reg_bp); while (size != 0) { ssize = size; if (ssize > img_ssz) ssize = img_ssz; // LOG_MSG(" ... memaddr=0x%lx ssize=0x%x sector=0x%lx", // (unsigned long)memaddr,(unsigned int)ssize,(unsigned long)sector); for (i=0;i < ssize;i++) PC98_BIOS_FLOPPY_BUFFER[i] = mem_readb(memaddr+i); if (floppy->Write_AbsoluteSector(sector,PC98_BIOS_FLOPPY_BUFFER) != 0) { reg_ah = 0xD0; CALLBACK_SCF(true); break; } sector++; size -= ssize; memaddr += ssize; } } else { CALLBACK_SCF(true); } break; case 0x06: /* read */ if (PC98_BIOS_SCSI_POS(floppy,/*&*/sector) == 0) { floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); assert(img_ssz != 0); size = reg_bx; if (size == 0) size = 0x10000U; memaddr = ((unsigned int)SegValue(es) << 4u) + reg_bp; reg_ah = 0; CALLBACK_SCF(false); // LOG_MSG("READ memaddr=0x%lx size=0x%x sector=0x%lx ES:BP=%04x:%04X", // (unsigned long)memaddr,(unsigned int)size,(unsigned long)sector,SegValue(es),reg_bp); while (size != 0) { ssize = size; if (ssize > img_ssz) ssize = img_ssz; // LOG_MSG(" ... memaddr=0x%lx ssize=0x%x sector=0x%lx", // (unsigned long)memaddr,(unsigned int)ssize,(unsigned long)sector); if (floppy->Read_AbsoluteSector(sector,PC98_BIOS_FLOPPY_BUFFER) == 0) { for (i=0;i < ssize;i++) mem_writeb(memaddr+i,PC98_BIOS_FLOPPY_BUFFER[i]); } else { reg_ah = 0xD0; CALLBACK_SCF(true); break; } sector++; size -= ssize; memaddr += ssize; } } else { CALLBACK_SCF(true); } break; case 0x03: /* according to NPKai source code: "negate ack" (cbus/scsicmd.c line 211, and 61) */ reg_ah = 0x35; /* according to scsicmd_negate() line 61, as translated by stat2ret[] by code line 228 */ CALLBACK_SCF(false); // NTS: This is needed for an HDI image to boot that apparently contains FreeDOS98 break; case 0x07: /* unknown, always succeeds */ reg_ah = 0x00; CALLBACK_SCF(false); break; case 0x0E: /* unknown, always fails */ reg_ah = 0x40; CALLBACK_SCF(true); break; case 0x04: /* drive status */ if (reg_ah == 0x84) { floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); reg_dl = img_sect; reg_dh = img_heads; /* Max 16 */ reg_cx = img_cyl; /* Max 4096 */ reg_bx = img_ssz; reg_ah = 0x00; CALLBACK_SCF(false); break; } else if (reg_ah == 0x04 || reg_ah == 0x14) { reg_ah = 0x00; CALLBACK_SCF(false); } else { goto default_goto; } default: default_goto: LOG_MSG("PC-98 INT 1Bh unknown SCSI BIOS call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); CALLBACK_SCF(true); break; } } void PC98_BIOS_FDC_CALL_GEO_UNPACK(unsigned int &fdc_cyl,unsigned int &fdc_head,unsigned int &fdc_sect,unsigned int &fdc_sz) { fdc_cyl = reg_cl; fdc_head = reg_dh; fdc_sect = reg_dl; fdc_sz = reg_ch; if (fdc_sz > 8) fdc_sz = 8; } /* NTS: FDC calls reset IRQ 0 timer to a specific fixed interval, * because the real BIOS likely does the same in the act of * controlling the floppy drive. * * Resetting the interval is required to prevent Ys II from * crashing after disk swap (divide by zero/overflow) because * Ys II reads the timer after INT 1Bh for whatever reason * and the upper half of the timer byte later affects a divide * by 3 in the code. */ void PC98_Interval_Timer_Continue(void); bool enable_fdc_timer_hack = false; void FDC_WAIT_TIMER_HACK(void) { unsigned int v; unsigned int c=0; // Explanation: // // Originally the FDC code here changed the timer interval back to the stock 100hz // normally used in PC-98, to fix Ys II. However that seems to break other booter // games that hook IRQ 0 directly and set the timer ONCE, then access the disk. // // For example, "Angelus" ran WAY too slow with the timer hack because it programs // the timer to a 600hz interval and expects it to stay that way. // // So the new method to satisfy both games is to loop here until the timer // count is below the maximum that would occur if the 100hz tick count were // still in effect, even if the timer interval was reprogrammed. // // NTS: Writing port 0x77 to relatch the timer also seems to break games // // TODO: As a safety against getting stuck, perhaps PIC_FullIndex() should be used // to break out of the loop if this runs for more than 1 second, since that // is a sign the timer is in an odd state that will never terminate this loop. v = ~0U; c = 10; do { void CALLBACK_Idle(void); CALLBACK_Idle(); unsigned int pv = v; v = (unsigned int)IO_ReadB(0x71); v |= (unsigned int)IO_ReadB(0x71) << 8u; if (v > pv) { /* if the timer rolled around, we might have missed the narrow window we're watching for */ if (--c == 0) break; } } while (v >= 0x60); } void PC98_BIOS_FDC_CALL(unsigned int flags) { static unsigned int fdc_cyl[2]={0,0},fdc_head[2]={0,0},fdc_sect[2]={0,0},fdc_sz[2]={0,0}; // FIXME: Rename and move out. Making "static" is a hack here. uint32_t img_heads=0,img_cyl=0,img_sect=0,img_ssz=0; unsigned int drive; unsigned int status; unsigned int size,accsize,unitsize; unsigned long memaddr; imageDisk *floppy; /* AL bits[1:0] = which floppy drive */ if ((reg_al & 3) >= 2) { /* This emulation only supports up to 2 floppy drives */ CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } floppy = GetINT13FloppyDrive(drive=(reg_al & 3)); /* what to do is in the lower 4 bits of AH */ switch (reg_ah & 0x0F) { /* TODO: 0x00 = seek to track (in CL) */ /* TODO: 0x01 = test read? */ /* TODO: 0x03 = equipment flags? */ /* TODO: 0x04 = format detect? */ /* TODO: 0x05 = write disk */ /* TODO: 0x07 = recalibrate (seek to track 0) */ /* TODO: 0x0A = Read ID */ /* TODO: 0x0D = Format track */ /* TODO: 0x0E = ?? */ case 0x03: /* equipment flags update (?) */ // TODO: Update the disk equipment flags in BDA. // For now, make Alantia happy by returning success. reg_ah = 0x00; CALLBACK_SCF(false); break; case 0x00: /* seek */ /* CL = track */ if (floppy == NULL) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } if (enable_fdc_timer_hack) { // Hack for Ys II FDC_WAIT_TIMER_HACK(); } fdc_cyl[drive] = reg_cl; reg_ah = 0x00; CALLBACK_SCF(false); break; case 0x01: /* test read */ /* AH bits[4:4] = If set, seek to track specified */ /* CL = cylinder (track) */ /* CH = sector size (0=128 1=256 2=512 3=1024 etc) */ /* DL = sector number (1-based) */ /* DH = head */ /* BX = size (in bytes) of data to read */ /* ES:BP = buffer to read data into */ if (floppy == NULL) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); if (enable_fdc_timer_hack) { // Hack for Ys II FDC_WAIT_TIMER_HACK(); } /* Prevent reading 1.44MB floppyies using 1.2MB read commands and vice versa. * FIXME: It seems MS-DOS 5.0 booted from a HDI image has trouble understanding * when Drive A: (the first floppy) is a 1.44MB drive or not and fails * because it only attempts it using 1.2MB format read commands. */ if (flags & PC98_FLOPPY_RPM_IBMPC) { if (img_ssz == 1024) { /* reject 1.2MB 3-mode format */ CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } } else { if (img_ssz == 512) { /* reject IBM PC 1.44MB format */ CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } } PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); if (0/*unitsize != img_ssz || img_heads == 0 || img_cyl == 0 || img_sect == 0*/) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } size = reg_bx; while (size > 0) { accsize = size > unitsize ? unitsize : size; if (floppy->Read_Sector(fdc_head[drive],fdc_cyl[drive],fdc_sect[drive],PC98_BIOS_FLOPPY_BUFFER,unitsize) != 0) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } size -= accsize; if (size == 0) break; if ((++fdc_sect[drive]) > img_sect && img_sect != 0) { fdc_sect[drive] = 1; if ((++fdc_head[drive]) >= img_heads && img_heads != 0) { fdc_head[drive] = 0; fdc_cyl[drive]++; } } } reg_ah = 0x00; CALLBACK_SCF(false); break; case 0x02: /* read sectors */ case 0x06: /* read sectors (what's the difference from 0x02?) */ /* AH bits[4:4] = If set, seek to track specified */ /* CL = cylinder (track) */ /* CH = sector size (0=128 1=256 2=512 3=1024 etc) */ /* DL = sector number (1-based) */ /* DH = head */ /* BX = size (in bytes) of data to read */ /* ES:BP = buffer to read data into */ if (floppy == NULL) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); if (enable_fdc_timer_hack) { // Hack for Ys II FDC_WAIT_TIMER_HACK(); } /* Prevent reading 1.44MB floppyies using 1.2MB read commands and vice versa. * FIXME: It seems MS-DOS 5.0 booted from a HDI image has trouble understanding * when Drive A: (the first floppy) is a 1.44MB drive or not and fails * because it only attempts it using 1.2MB format read commands. */ if (flags & PC98_FLOPPY_RPM_IBMPC) { if (img_ssz == 1024) { /* reject 1.2MB 3-mode format */ CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } } else { if (img_ssz == 512) { /* reject IBM PC 1.44MB format */ CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } } PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); if (0/*unitsize != img_ssz || img_heads == 0 || img_cyl == 0 || img_sect == 0*/) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } size = reg_bx; memaddr = ((unsigned int)SegValue(es) << 4U) + reg_bp; while (size > 0) { accsize = size > unitsize ? unitsize : size; if (floppy->Read_Sector(fdc_head[drive],fdc_cyl[drive],fdc_sect[drive],PC98_BIOS_FLOPPY_BUFFER,unitsize) != 0) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } for (unsigned int i=0;i < accsize;i++) mem_writeb(memaddr+i,PC98_BIOS_FLOPPY_BUFFER[i]); memaddr += accsize; size -= accsize; if (size == 0) break; if ((++fdc_sect[drive]) > img_sect && img_sect != 0) { fdc_sect[drive] = 1; if ((++fdc_head[drive]) >= img_heads && img_heads != 0) { fdc_head[drive] = 0; fdc_cyl[drive]++; } } } /* need to clear DMA terminal count after read as BIOS would, I assume (Arsys Star Cruiser) */ { DmaChannel *dma = GetDMAChannel(2); if (dma) dma->tcount = false; } reg_ah = 0x00; CALLBACK_SCF(false); break; case 0x04: /* drive status */ status = 0; /* TODO: bit 4 is set if write protected */ if (reg_al & 0x80) { /* high density */ status |= 0x01; } else { /* double density */ /* TODO: */ status |= 0x01; } if ((reg_ax & 0x8F40) == 0x8400) { status |= 8; /* 1MB/640KB format, spindle speed for 3-mode */ if (reg_ah & 0x40) /* DOSBox-X always supports 1.44MB */ status |= 4; /* 1.44MB format, spindle speed for IBM PC format */ } if (floppy == NULL) status |= 0xC0; reg_ah = status; CALLBACK_SCF(false); break; /* TODO: 0x00 = seek to track (in CL) */ /* TODO: 0x01 = test read? */ /* TODO: 0x03 = equipment flags? */ /* TODO: 0x04 = format detect? */ /* TODO: 0x05 = write disk */ /* TODO: 0x07 = recalibrate (seek to track 0) */ /* TODO: 0x0A = Read ID */ /* TODO: 0x0D = Format track */ /* TODO: 0x0E = ?? */ case 0x05: /* write sectors */ /* AH bits[4:4] = If set, seek to track specified */ /* CL = cylinder (track) */ /* CH = sector size (0=128 1=256 2=512 3=1024 etc) */ /* DL = sector number (1-based) */ /* DH = head */ /* BX = size (in bytes) of data to read */ /* ES:BP = buffer to write data from */ if (floppy == NULL) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); if (enable_fdc_timer_hack) { // Hack for Ys II FDC_WAIT_TIMER_HACK(); } /* TODO: Error if write protected */ PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); if (0/*unitsize != img_ssz || img_heads == 0 || img_cyl == 0 || img_sect == 0*/) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } size = reg_bx; memaddr = ((unsigned int)SegValue(es) << 4U) + reg_bp; while (size > 0) { accsize = size > unitsize ? unitsize : size; for (unsigned int i=0;i < accsize;i++) PC98_BIOS_FLOPPY_BUFFER[i] = mem_readb(memaddr+i); if (floppy->Write_Sector(fdc_head[drive],fdc_cyl[drive],fdc_sect[drive],PC98_BIOS_FLOPPY_BUFFER,unitsize) != 0) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } memaddr += accsize; size -= accsize; if (size == 0) break; if ((++fdc_sect[drive]) > img_sect && img_sect != 0) { fdc_sect[drive] = 1; if ((++fdc_head[drive]) >= img_heads && img_heads != 0) { fdc_head[drive] = 0; fdc_cyl[drive]++; } } } reg_ah = 0x00; CALLBACK_SCF(false); break; case 0x07: /* recalibrate (seek to track 0) */ if (floppy == NULL) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } if (enable_fdc_timer_hack) { // Hack for Ys II FDC_WAIT_TIMER_HACK(); } fdc_cyl[drive] = 0; reg_ah = 0x00; CALLBACK_SCF(false); break; case 0x0D: /* format track */ if (floppy == NULL) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); if (enable_fdc_timer_hack) { // Hack for Ys II FDC_WAIT_TIMER_HACK(); } LOG_MSG("WARNING: INT 1Bh FDC format track command not implemented. Formatting is faked, for now on C/H/S/sz %u/%u/%u/%u drive %c.", (unsigned int)fdc_cyl[drive], (unsigned int)fdc_head[drive], (unsigned int)fdc_sect[drive], (unsigned int)unitsize, drive + 'A'); reg_ah = 0x00; CALLBACK_SCF(false); break; case 0x0A: /* read ID */ /* NTS: PC-98 "MEGDOS" used by some games seems to rely heavily on this call to * verify the floppy head is where it thinks it should be! */ if (floppy == NULL) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); if (enable_fdc_timer_hack) { // Hack for Ys II FDC_WAIT_TIMER_HACK(); } if (reg_ah & 0x10) { // seek to track number in CL if (img_cyl != 0 && reg_cl >= img_cyl) { CALLBACK_SCF(true); reg_ah = 0x00; /* TODO? Error code? */ return; } fdc_cyl[drive] = reg_cl; } if (fdc_sect[drive] == 0) fdc_sect[drive] = 1; if (img_ssz >= 1024) fdc_sz[drive] = 3; else if (img_ssz >= 512) fdc_sz[drive] = 2; else if (img_ssz >= 256) fdc_sz[drive] = 1; else fdc_sz[drive] = 0; reg_cl = fdc_cyl[drive]; reg_dh = fdc_head[drive]; reg_dl = fdc_sect[drive]; /* ^ FIXME: A more realistic emulation would return a random number from 1 to N * where N=sectors/track because the floppy motor is running and tracks * are moving past the head. */ reg_ch = fdc_sz[drive]; /* per read ID call, increment the sector through the range on disk. * This is REQUIRED or else MEGDOS will not attempt to read this disk. */ if (img_sect != 0) { if ((++fdc_sect[drive]) > img_sect) fdc_sect[drive] = 1; } reg_ah = 0x00; CALLBACK_SCF(false); break; default: LOG_MSG("PC-98 INT 1Bh unknown FDC BIOS call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); CALLBACK_SCF(true); break; } } static Bitu INT19_PC98_Handler(void) { LOG_MSG("PC-98 INT 19h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); return CBRET_NONE; } static Bitu INT1A_PC98_Handler(void) { /* HACK: This makes the "test" program in DOSLIB work. * We'll remove this when we implement INT 1Ah */ if (reg_ax == 0x1000) { CALLBACK_SCF(false); reg_ax = 0; } LOG_MSG("PC-98 INT 1Ah unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); return CBRET_NONE; } static Bitu INT1B_PC98_Handler(void) { /* As BIOS interfaces for disk I/O go, this is fairly unusual */ switch (reg_al & 0xF0) { /* floppy disk access */ /* AL bits[1:0] = floppy drive number */ /* Uses INT42 if high density, INT41 if double density */ /* AH bits[3:0] = command */ case 0x90: /* 1.2MB HD */ PC98_BIOS_FDC_CALL(PC98_FLOPPY_HIGHDENSITY|PC98_FLOPPY_2HEAD|PC98_FLOPPY_RPM_3MODE); break; case 0x30: /* 1.44MB HD (NTS: not supported until the early 1990s) */ case 0xB0: PC98_BIOS_FDC_CALL(PC98_FLOPPY_HIGHDENSITY|PC98_FLOPPY_2HEAD|PC98_FLOPPY_RPM_IBMPC); break; case 0x70: /* 720KB DD (??) */ case 0xF0: PC98_BIOS_FDC_CALL(PC98_FLOPPY_2HEAD|PC98_FLOPPY_RPM_3MODE); // FIXME, correct?? break; case 0x20: /* SCSI hard disk BIOS */ case 0xA0: /* SCSI hard disk BIOS */ case 0x00: /* SASI hard disk BIOS */ case 0x80: /* SASI hard disk BIOS */ PC98_BIOS_SCSI_CALL(); break; /* TODO: Other disk formats */ /* TODO: Future SASI/SCSI BIOS emulation for hard disk images */ default: LOG_MSG("PC-98 INT 1Bh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); CALLBACK_SCF(true); break; } return CBRET_NONE; } void PC98_Interval_Timer_Continue(void) { /* assume: interrupts are disabled */ IO_WriteB(0x71,0x00); // TODO: What time interval is this supposed to be? if (PIT_TICK_RATE == PIT_TICK_RATE_PC98_8MHZ) IO_WriteB(0x71,0x4E); else IO_WriteB(0x71,0x60); IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/0u))); // unmask IRQ0 } unsigned char pc98_dec2bcd(unsigned char c) { return ((c / 10u) << 4u) + (c % 10u); } static Bitu INT1C_PC98_Handler(void) { if (reg_ah == 0x00) { /* get time and date */ time_t curtime; const struct tm *loctime; curtime = time (NULL); loctime = localtime (&curtime); unsigned char tmp[6]; tmp[0] = pc98_dec2bcd((unsigned int)loctime->tm_year % 100u); tmp[1] = (((unsigned int)loctime->tm_mon + 1u) << 4u) + (unsigned int)loctime->tm_wday; tmp[2] = pc98_dec2bcd(loctime->tm_mday); tmp[3] = pc98_dec2bcd(loctime->tm_hour); tmp[4] = pc98_dec2bcd(loctime->tm_min); tmp[5] = pc98_dec2bcd(loctime->tm_sec); unsigned long mem = ((unsigned int)SegValue(es) << 4u) + reg_bx; for (unsigned int i=0;i < 6;i++) mem_writeb(mem+i,tmp[i]); } else if (reg_ah == 0x02) { /* set interval timer (single event) */ /* es:bx = interrupt handler to execute * cx = timer interval in ticks (FIXME: what units of time?) */ mem_writew(0x1C,reg_bx); mem_writew(0x1E,SegValue(es)); mem_writew(0x58A,reg_cx); IO_WriteB(0x77,0x36); /* mode 3, binary, low-byte high-byte 16-bit counter */ PC98_Interval_Timer_Continue(); } else if (reg_ah == 0x03) { /* continue interval timer */ PC98_Interval_Timer_Continue(); } /* TODO: According to the PDF at * * http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20NEC%20PC%2d98/Collections/PC%2d9801%20Bible%20%e6%9d%b1%e4%ba%ac%e7%90%86%e7%a7%91%e5%a4%a7%e5%ad%a6EIC%20%281994%29%2epdf * * There are additional functions * * AH = 04h * ES:BX = ? * * --- * * AH = 05h * ES:BX = ? * * --- * * AH = 06h * CX = ? (1-FFFFh) * DX = ? (20h-8000h Hz) * * If any PC-98 games or applications rely on this, let me know. Adding a case for them is easy enough if anyone is interested. --J.C. */ else { LOG_MSG("PC-98 INT 1Ch unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); } return CBRET_NONE; } // NTS: According to this PDF, chapter 5, INT 1Dh has additional functions on "High Resolution" PC-98 systems. // [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf] static Bitu INT1D_PC98_Handler(void) { LOG_MSG("PC-98 INT 1Dh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); return CBRET_NONE; } static Bitu INT1E_PC98_Handler(void) { LOG_MSG("PC-98 INT 1Eh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); return CBRET_NONE; } void PC98_EXTMEMCPY(void) { bool enabled = MEM_A20_Enabled(); MEM_A20_Enable(true); Bitu bytes = ((reg_cx - 1u) & 0xFFFFu) + 1u; // bytes, except that 0 == 64KB PhysPt data = SegPhys(es)+reg_bx; PhysPt source = (mem_readd(data+0x12u) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data+0x17u)<<24u); PhysPt dest = (mem_readd(data+0x1Au) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data+0x1Fu)<<24u); LOG_MSG("PC-98 memcpy: src=0x%x dst=0x%x data=0x%x count=0x%x", (unsigned int)source,(unsigned int)dest,(unsigned int)data,(unsigned int)bytes); MEM_BlockCopy(dest,source,bytes); MEM_A20_Enable(enabled); Segs.limit[cs] = 0xFFFF; Segs.limit[ds] = 0xFFFF; Segs.limit[es] = 0xFFFF; Segs.limit[ss] = 0xFFFF; CALLBACK_SCF(false); } static Bitu INT1F_PC98_Handler(void) { switch (reg_ah) { case 0x90: /* Copy extended memory */ PC98_EXTMEMCPY(); break; default: LOG_MSG("PC-98 INT 1Fh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); CALLBACK_SCF(true); break; } return CBRET_NONE; } static Bitu INTGEN_PC98_Handler(void) { LOG_MSG("PC-98 INT stub unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); return CBRET_NONE; } /* This interrupt should only exist while the DOS kernel is active. * On actual PC-98 MS-DOS this is a direct interface to MS-DOS's built-in ANSI CON driver. * * CL = major function call number * AH = minor function call number * DX = data?? */ extern bool dos_kernel_disabled; void PC98_INTDC_WriteChar(unsigned char b); void INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut_def &def,const Bitu ofs) { unsigned int i; for (i=0;i < 0x0F;i++) def.shortcut[i] = mem_readb(ofs+0x0+i); for (i=0;i < 0x0F && def.shortcut[i] != 0;) i++; def.length = i; } void INTDC_STORE_FUNCDEC(const Bitu ofs,const pc98_func_key_shortcut_def &def) { for (unsigned int i=0;i < 0x0F;i++) mem_writeb(ofs+0x0+i,def.shortcut[i]); mem_writeb(ofs+0xF,0); } void INTDC_LOAD_EDITDEC(pc98_func_key_shortcut_def &def,const Bitu ofs) { unsigned int i; for (i=0;i < 0x05;i++) def.shortcut[i] = mem_readb(ofs+0x0+i); for (i=0;i < 0x05 && def.shortcut[i] != 0;) i++; def.length = i; } void INTDC_STORE_EDITDEC(const Bitu ofs,const pc98_func_key_shortcut_def &def) { for (unsigned int i=0;i < 0x05;i++) mem_writeb(ofs+0x0+i,def.shortcut[i]); mem_writeb(ofs+0x5,0); } bool inhibited_ControlFn(void) { return real_readb(0x60,0x10C) & 0x01; } extern bool dos_kernel_disabled; static const char *fneditkeys[11] = { "ROLLUP", "ROLLDOWN", "INS", "DEL", "UPARROW", "LEFTARROW", "RIGHTARROW", "DOWNARROW", "HOMECLR", "HELP", "KEYPAD-" }; void DEBUG_INTDC_FnKeyMapInfo(void) { if (!IS_PC98_ARCH) { DEBUG_ShowMsg("INT DCh has no meaning except in PC-98 mode"); } else if (dos_kernel_disabled) { DEBUG_ShowMsg("INT DCh FnKey mapping has no meaning outside the DOS environment"); } else { DEBUG_ShowMsg("INT DCh FnKey mapping. Ctrl+Fn builtin inhibited=%s",inhibited_ControlFn()?"yes":"no"); for (unsigned int i=0;i < 10;i++) DEBUG_ShowMsg(" F%u: %s",i+1,pc98_func_key[i].debugToString().c_str()); for (unsigned int i=0;i < 5;i++) DEBUG_ShowMsg(" VF%u: %s",i+1,pc98_vfunc_key[i].debugToString().c_str()); for (unsigned int i=0;i < 10;i++) DEBUG_ShowMsg(" Shift+F%u: %s",i+1,pc98_func_key_shortcut[i].debugToString().c_str()); for (unsigned int i=0;i < 5;i++) DEBUG_ShowMsg(" Shift+VF%u: %s",i+1,pc98_vfunc_key_shortcut[i].debugToString().c_str()); for (unsigned int i=0;i < 10;i++) DEBUG_ShowMsg(" Control+F%u: %s",i+1,pc98_func_key_ctrl[i].debugToString().c_str()); for (unsigned int i=0;i < 5;i++) DEBUG_ShowMsg(" Control+VF%u: %s",i+1,pc98_vfunc_key_ctrl[i].debugToString().c_str()); for (unsigned int i=0;i < 11;i++) DEBUG_ShowMsg(" %s: %s",fneditkeys[i],pc98_editor_key_escapes[i].debugToString().c_str()); } } /* PC-98 application notes, that are NOT DOSBox-X bugs because they occur on real MS-DOS as well: * * VZ.COM - If the function key row was hidden when VZ.COM is started, VZ.COM will not restore the * function key row. VZ.COM's function key shortcuts affect Fn and Shift+Fn keys and the * text they display even if VZ.COM also disables the Ctrl+F7 shortcut that lets you * toggle the function key row, which makes displaying the Shift+Fn key shortcuts impossible * unless the function key row was left showing that at startup. */ static Bitu INTDC_PC98_Handler(void) { if (dos_kernel_disabled) goto unknown; switch (reg_cl) { case 0x0C: /* CL=0x0C General entry point to read function key state */ if (reg_ax == 0xFF) { /* Extended version of the API when AX == 0, DS:DX = data to store to */ /* DS:DX contains * 16*10 bytes, 16 bytes per entry for function keys F1-F10 * 16*5 bytes, 16 bytes per entry for VF1-VF5 * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 * 16*5 bytes, 16 bytes per entry for shift VF1-VF5 * 6*11 bytes, 6 bytes per entry for editor keys * 16*10 bytes, 16 bytes per entry for function key shortcuts Control+F1 to Control+F10 * 16*5 bytes, 16 bytes per entry for control VF1-VF5 * * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; /* function keys F1-F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_STORE_FUNCDEC(ofs,pc98_func_key[f]); /* VF1-VF5 */ for (unsigned int f=0;f < 5;f++,ofs += 16) INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key[f]); /* function keys Shift+F1 - Shift+F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_STORE_FUNCDEC(ofs,pc98_func_key_shortcut[f]); /* VF1-VF5 */ for (unsigned int f=0;f < 5;f++,ofs += 16) INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_shortcut[f]); /* editor keys */ for (unsigned int f=0;f < 11;f++,ofs += 6) INTDC_STORE_EDITDEC(ofs,pc98_editor_key_escapes[f]); /* function keys Control+F1 - Control+F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_STORE_FUNCDEC(ofs,pc98_func_key_ctrl[f]); /* VF1-VF5 */ for (unsigned int f=0;f < 5;f++,ofs += 16) INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_ctrl[f]); goto done; } /* NTS: According to a translation table in the MS-DOS kernel, where * AX=1h to AX=29h inclusive look up from this 0x29-element table: * * Table starts with AX=1h, ends with AX=29h * * 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 * | | | | | | | | | | | | | | | | * 0ADC:00003DE0 01 02 03 04 05 06 07 08 09 0A 10 11 12 13 14 15 ................ * 0ADC:00003DF0 16 17 18 19 1F 20 21 22 23 24 25 26 27 28 29 0B ..... !"#$%&'(). * 0ADC:00003E00 0C 0D 0E 0F 1A 1B 1C 1D 1E| * * The table is read, then the byte is decremented by one. * * If the result of that is less than 0x1E, it's an index into * the 16 byte/entry Fn key table. * * If the result is 0x1E or larger, then (result - 0x1E) is an * index into the editor table, 8 bytes/entry. * * Meanings: * * 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 * | | | | | | | | | | | | | | | | * 0ADC:00003DE0 01 02 03 04 05 06 07 08 09 0A 10 11 12 13 14 15 ................ * | --- Function keys F1-F10 ---| Fn shift F1-F6 - * 0ADC:00003DF0 16 17 18 19 1F 20 21 22 23 24 25 26 27 28 29 0B ..... !"#$%&'(). * | Sh F7-F10 | ------- EDITOR KEYS -----------| - * 0ADC:00003E00 0C 0D 0E 0F 1A 1B 1C 1D 1E| * | --------- | ------------ | */ else if (reg_ax >= 0x01 && reg_ax <= 0x0A) { /* Read individual function keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_STORE_FUNCDEC(ofs,pc98_func_key[reg_ax - 0x01]); goto done; } else if (reg_ax >= 0x0B && reg_ax <= 0x14) { /* Read individual shift + function keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_STORE_FUNCDEC(ofs,pc98_func_key_shortcut[reg_ax - 0x0B]); goto done; } else if (reg_ax >= 0x15 && reg_ax <= 0x1F) { /* Read individual editor keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_STORE_EDITDEC(ofs,pc98_editor_key_escapes[reg_ax - 0x15]); goto done; } else if (reg_ax >= 0x20 && reg_ax <= 0x24) { /* Read VF1-VF5 keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key[reg_ax - 0x20]); goto done; } else if (reg_ax >= 0x25 && reg_ax <= 0x29) { /* Read shift VF1-VF5 keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_shortcut[reg_ax - 0x25]); goto done; } else if (reg_ax >= 0x2A && reg_ax <= 0x33) { /* Read individual function keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_STORE_FUNCDEC(ofs,pc98_func_key_ctrl[reg_ax - 0x2A]); goto done; } else if (reg_ax >= 0x34 && reg_ax <= 0x38) { /* Read control VF1-VF5 keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_ctrl[reg_ax - 0x34]); goto done; } else if (reg_ax == 0x00) { /* Read all state, DS:DX = data to store to */ /* DS:DX contains * 16*10 bytes, 16 bytes per entry for function keys F1-F10 * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 * 6*11 bytes, 6 bytes per entry of unknown relevence (GUESS: Escapes for other keys like INS, DEL?) * * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; /* function keys F1-F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_STORE_FUNCDEC(ofs,pc98_func_key[f]); /* function keys Shift+F1 - Shift+F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_STORE_FUNCDEC(ofs,pc98_func_key_shortcut[f]); /* editor keys */ for (unsigned int f=0;f < 11;f++,ofs += 6) INTDC_STORE_EDITDEC(ofs,pc98_editor_key_escapes[f]); goto done; } goto unknown; case 0x0D: /* CL=0x0D General entry point to set function key state */ if (reg_ax == 0xFF) { /* Extended version of the API when AX == 0, DS:DX = data to set */ /* DS:DX contains * 16*10 bytes, 16 bytes per entry for function keys F1-F10 * 16*5 bytes, 16 bytes per entry for VF1-VF5 * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 * 16*5 bytes, 16 bytes per entry for shift VF1-VF5 * 6*11 bytes, 6 bytes per entry for editor keys * 16*10 bytes, 16 bytes per entry for function key shortcuts Control+F1 to Control+F10 * 16*5 bytes, 16 bytes per entry for control VF1-VF5 * * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; /* function keys F1-F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_LOAD_FUNCDEC(pc98_func_key[f],ofs); /* VF1-VF5 */ for (unsigned int f=0;f < 5;f++,ofs += 16) INTDC_LOAD_FUNCDEC(pc98_vfunc_key[f],ofs); /* function keys Shift+F1 - Shift+F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut[f],ofs); /* Shift+VF1 - Shift+VF5 */ for (unsigned int f=0;f < 5;f++,ofs += 16) INTDC_LOAD_FUNCDEC(pc98_vfunc_key_shortcut[f],ofs); /* editor keys */ for (unsigned int f=0;f < 11;f++,ofs += 6) INTDC_LOAD_EDITDEC(pc98_editor_key_escapes[f],ofs); /* function keys Control+F1 - Control+F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_LOAD_FUNCDEC(pc98_func_key_ctrl[f],ofs); /* Shift+VF1 - Shift+VF5 */ for (unsigned int f=0;f < 5;f++,ofs += 16) INTDC_LOAD_FUNCDEC(pc98_vfunc_key_ctrl[f],ofs); update_pc98_function_row(pc98_function_row_mode,true); goto done; } else if (reg_ax >= 0x01 && reg_ax <= 0x0A) { /* Read individual function keys, DS:DX = data to set */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_LOAD_FUNCDEC(pc98_func_key[reg_ax - 0x01],ofs); goto done; } else if (reg_ax >= 0x0B && reg_ax <= 0x14) { /* Read individual shift + function keys, DS:DX = data to set */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut[reg_ax - 0x0B],ofs); goto done; } else if (reg_ax >= 0x15 && reg_ax <= 0x1F) { /* Read individual editor keys, DS:DX = data to set */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_LOAD_EDITDEC(pc98_editor_key_escapes[reg_ax - 0x15],ofs); goto done; } else if (reg_ax >= 0x20 && reg_ax <= 0x24) { /* Read VF1-VF5 keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_LOAD_FUNCDEC(pc98_vfunc_key[reg_ax - 0x20],ofs); goto done; } else if (reg_ax >= 0x25 && reg_ax <= 0x29) { /* Read shift VF1-VF5 keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_LOAD_FUNCDEC(pc98_vfunc_key_shortcut[reg_ax - 0x25],ofs); goto done; } else if (reg_ax >= 0x2A && reg_ax <= 0x33) { /* Read individual function keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_LOAD_FUNCDEC(pc98_func_key_ctrl[reg_ax - 0x2A],ofs); goto done; } else if (reg_ax >= 0x34 && reg_ax <= 0x38) { /* Read control VF1-VF5 keys, DS:DX = data to store to */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; INTDC_LOAD_FUNCDEC(pc98_vfunc_key_ctrl[reg_ax - 0x34],ofs); goto done; } else if (reg_ax == 0x00) { /* Read all state, DS:DX = data to set */ /* DS:DX contains * 16*10 bytes, 16 bytes per entry for function keys F1-F10 * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 * 6*11 bytes, 6 bytes per entry of editor keys (INS, DEL, etc) that match a specific scan code range * * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; /* function keys F1-F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_LOAD_FUNCDEC(pc98_func_key[f],ofs); /* function keys Shift+F1 - Shift+F10 */ for (unsigned int f=0;f < 10;f++,ofs += 16) INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut[f],ofs); /* editor keys */ for (unsigned int f=0;f < 11;f++,ofs += 6) INTDC_LOAD_EDITDEC(pc98_editor_key_escapes[f],ofs); update_pc98_function_row(pc98_function_row_mode,true); goto done; } goto unknown; case 0x0F: if (reg_ax == 0) { /* inhibit Control+Fn shortcuts */ real_writeb(0x60,0x10C,real_readb(0x60,0x10C) | 0x01); goto done; } else if (reg_ax == 1) { /* enable Control+Fn shortcuts */ real_writeb(0x60,0x10C,real_readb(0x60,0x10C) & (~0x01)); goto done; } goto unknown; case 0x10: if (reg_ah == 0x00) { /* CL=0x10 AH=0x00 DL=char write char to CON */ PC98_INTDC_WriteChar(reg_dl); goto done; } else if (reg_ah == 0x01) { /* CL=0x10 AH=0x01 DS:DX write string to CON */ /* According to the example at http://tepe.tec.fukuoka-u.ac.jp/HP98/studfile/grth/gt10.pdf * the string ends in '$' just like the main DOS string output function. */ uint16_t ofs = reg_dx; do { unsigned char c = real_readb(SegValue(ds),ofs++); if (c == '$') break; PC98_INTDC_WriteChar(c); } while (1); goto done; } else if (reg_ah == 0x02) { /* CL=0x10 AH=0x02 DL=attribute set console output attribute */ /* Ref: https://nas.jmc/jmcs/docs/browse/Computer/Platform/PC%2c%20NEC%20PC%2d98/Collections/Undocumented%209801%2c%209821%20Volume%202%20%28webtech.co.jp%29%20English%20translation/memdos%2eenglish%2dgoogle%2dtranslate%2etxt * * DL is the attribute byte (in the format written directly to video RAM, not the ANSI code) * * NTS: Reverse engineering INT DCh shows it sets both 71Dh and 73Ch as below */ real_writeb(0x60,0x11D,reg_dl); real_writeb(0x60,0x13C,reg_dx); goto done; } else if (reg_ah == 0x03) { /* CL=0x10 AH=0x03 DL=X-coord DH=Y-coord set cursor position */ void INTDC_CL10h_AH03h(uint16_t raw); INTDC_CL10h_AH03h(reg_dx); goto done; } else if (reg_ah == 0x04) { /* CL=0x10 AH=0x04 Move cursor down one line */ void INTDC_CL10h_AH04h(void); INTDC_CL10h_AH04h(); goto done; } else if (reg_ah == 0x05) { /* CL=0x10 AH=0x05 Move cursor up one line */ void INTDC_CL10h_AH05h(void); INTDC_CL10h_AH05h(); goto done; } else if (reg_ah == 0x06) { /* CL=0x10 AH=0x06 DX=count Move cursor up multiple lines */ void INTDC_CL10h_AH06h(uint16_t count); INTDC_CL10h_AH06h(reg_dx); goto done; } else if (reg_ah == 0x07) { /* CL=0x10 AH=0x07 DX=count Move cursor down multiple lines */ void INTDC_CL10h_AH07h(uint16_t count); INTDC_CL10h_AH07h(reg_dx); goto done; } else if (reg_ah == 0x08) { /* CL=0x10 AH=0x08 DX=count Move cursor right multiple lines */ void INTDC_CL10h_AH08h(uint16_t count); INTDC_CL10h_AH08h(reg_dx); goto done; } else if (reg_ah == 0x09) { /* CL=0x10 AH=0x09 DX=count Move cursor left multiple lines */ void INTDC_CL10h_AH09h(uint16_t count); INTDC_CL10h_AH09h(reg_dx); goto done; } goto unknown; default: /* some compilers don't like not having a default case */ goto unknown; } done: return CBRET_NONE; unknown: LOG_MSG("PC-98 INT DCh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); return CBRET_NONE; } static Bitu INTF2_PC98_Handler(void) { LOG_MSG("PC-98 INT F2h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); return CBRET_NONE; } // for more information see [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf] static Bitu PC98_BIOS_LIO(void) { const char *call_name = "?"; switch (reg_al) { case 0xA0: // GINIT call_name = "GINIT"; goto unknown; case 0xA1: // GSCREEN call_name = "GSCREEN"; goto unknown; case 0xA2: // GVIEW call_name = "GVIEW"; goto unknown; case 0xA3: // GCOLOR1 call_name = "GCOLOR1"; goto unknown; case 0xA4: // GCOLOR2 call_name = "GCOLOR2"; goto unknown; case 0xA5: // GCLS call_name = "GCLS"; goto unknown; case 0xA6: // GPSET call_name = "GPSET"; goto unknown; case 0xA7: // GLINE call_name = "GLINE"; goto unknown; case 0xA8: // GCIRCLE call_name = "GCIRCLE"; goto unknown; case 0xA9: // GPAINT1 call_name = "GPAINT1"; goto unknown; case 0xAA: // GPAINT2 call_name = "GPAINT2"; goto unknown; case 0xAB: // GGET call_name = "GGET"; goto unknown; case 0xAC: // GPUT1 call_name = "GPUT1"; goto unknown; case 0xAD: // GPUT2 call_name = "GPUT2"; goto unknown; case 0xAE: // GROLL call_name = "GROLL"; goto unknown; case 0xAF: // GPOINT2 call_name = "GPOINT2"; goto unknown; case 0xCE: // GCOPY call_name = "GCOPY"; goto unknown; case 0x00: // GRAPH BIO call_name = "GRAPH BIO"; goto unknown; default: unknown: /* on entry, AL (from our BIOS code) is set to the call number that lead here */ LOG_MSG("PC-98 BIOS LIO graphics call 0x%02x '%s' with AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", reg_al, call_name, reg_ax, reg_bx, reg_cx, reg_dx, reg_si, reg_di, SegValue(ds), SegValue(es)); break; }; // from Yksoft1's patch reg_ah = 0; return CBRET_NONE; } static Bitu INT11_Handler(void) { reg_ax=mem_readw(BIOS_CONFIGURATION); return CBRET_NONE; } /* * Define the following define to 1 if you want dosbox-x to check * the system time every 5 seconds and adjust 1/2 a second to sync them. */ #ifndef DOSBOX_CLOCKSYNC #define DOSBOX_CLOCKSYNC 0 #endif uint32_t BIOS_HostTimeSync(uint32_t ticks) { uint32_t milli = 0; #if defined(DB_HAVE_CLOCK_GETTIME) && ! defined(WIN32) struct timespec tp; clock_gettime(CLOCK_REALTIME,&tp); struct tm *loctime; loctime = localtime(&tp.tv_sec); milli = (uint32_t) (tp.tv_nsec / 1000000); #else /* Setup time and date */ struct timeb timebuffer; ftime(&timebuffer); const struct tm *loctime; loctime = localtime (&timebuffer.time); milli = (uint32_t) timebuffer.millitm; #endif /* loctime->tm_hour = 23; loctime->tm_min = 59; loctime->tm_sec = 45; loctime->tm_mday = 28; loctime->tm_mon = 2-1; loctime->tm_year = 2007 - 1900; */ dos.date.day=(uint8_t)loctime->tm_mday; dos.date.month=(uint8_t)loctime->tm_mon+1; dos.date.year=(uint16_t)loctime->tm_year+1900; uint32_t nticks=(uint32_t)(((double)( (unsigned int)loctime->tm_hour*3600u*1000u+ (unsigned int)loctime->tm_min*60u*1000u+ (unsigned int)loctime->tm_sec*1000u+ milli))*(((double)PIT_TICK_RATE/65536.0)/1000.0)); /* avoid stepping back from off by one errors */ if (nticks == (ticks - 1u)) nticks = ticks; return nticks; } // TODO: make option bool enable_bios_timer_synchronize_keyboard_leds = true; void KEYBOARD_SetLEDs(uint8_t bits); void BIOS_KEYBOARD_SetLEDs(Bitu state) { Bitu x = mem_readb(BIOS_KEYBOARD_LEDS); x &= ~7u; x |= (state & 7u); mem_writeb(BIOS_KEYBOARD_LEDS,x); KEYBOARD_SetLEDs(state); } /* PC-98 IRQ 0 system timer */ static Bitu INT8_PC98_Handler(void) { uint16_t counter = mem_readw(0x58A) - 1; mem_writew(0x58A,counter); /* NTS 2018/02/23: I just confirmed from the ROM BIOS of an actual * PC-98 system that this implementation and Neko Project II * are 100% accurate to what the BIOS actually does. * INT 07h really is the "timer tick" interrupt called * from INT 08h / IRQ 0, and the BIOS really does call * INT 1Ch AH=3 from INT 08h if the tick count has not * yet reached zero. * * I'm guessing NEC's BIOS developers invented this prior * to the Intel 80286 and it's INT 07h * "Coprocessor not present" exception. */ if (counter == 0) { /* mask IRQ 0 */ IO_WriteB(0x02,IO_ReadB(0x02) | 0x01); /* ack IRQ 0 */ IO_WriteB(0x00,0x20); /* INT 07h */ CPU_Interrupt(7,CPU_INT_SOFTWARE,reg_eip); } else { /* ack IRQ 0 */ IO_WriteB(0x00,0x20); /* make sure it continues ticking */ PC98_Interval_Timer_Continue(); } return CBRET_NONE; } extern bool sync_time, manualtime; bool sync_time_timerrate_warning = false; uint32_t PIT0_GetAssignedCounter(void); static Bitu INT8_Handler(void) { /* Increase the bios tick counter */ uint32_t value = mem_readd(BIOS_TIMER) + 1; if(value >= 0x1800B0) { // time wrap at midnight mem_writeb(BIOS_24_HOURS_FLAG,mem_readb(BIOS_24_HOURS_FLAG)+1); value=0; } /* Legacy BIOS behavior: This isn't documented at all but most BIOSes check the BIOS data area for LED keyboard status. If it sees that value change, then it sends it to the keyboard. This is why on older DOS machines you could change LEDs by writing to 40:17. We have to emulate this also because Windows 3.1/9x seems to rely on it when handling the keyboard from it's own driver. Their driver does hook the keyboard and handles keyboard I/O by itself, but it still allows the BIOS to do the keyboard magic from IRQ 0 (INT 8h). Yech. */ if (enable_bios_timer_synchronize_keyboard_leds) { Bitu should_be = (mem_readb(BIOS_KEYBOARD_STATE) >> 4) & 7; Bitu led_state = (mem_readb(BIOS_KEYBOARD_LEDS) & 7); if (should_be != led_state) BIOS_KEYBOARD_SetLEDs(should_be); } if (sync_time&&!manualtime) { #if DOSBOX_CLOCKSYNC static bool check = false; if((value %50)==0) { if(((value %100)==0) && check) { check = false; time_t curtime;struct tm *loctime; curtime = time (NULL);loctime = localtime (&curtime); uint32_t ticksnu = (uint32_t)((loctime->tm_hour*3600+loctime->tm_min*60+loctime->tm_sec)*(float)PIT_TICK_RATE/65536.0); int32_t bios = value;int32_t tn = ticksnu; int32_t diff = tn - bios; if(diff>0) { if(diff < 18) { diff = 0; } else diff = 9; } else { if(diff > -18) { diff = 0; } else diff = -9; } value += diff; } else if((value%100)==50) check = true; } #endif /* synchronize time=true is based around the assumption * that the timer is left ticking at the standard 18.2Hz * rate. If that is not true, and this IRQ0 handler is * being called faster, then synchronization will not * work properly. * * Two 1996 demoscene entries sl_fokus.zip and sl_haloo.zip * are known to program the timer to run faster (58Hz and * 150Hz) yet use BIOS_TIMER from the BIOS data area to * track the passage of time. Synchronizing time that way * will only lead to BIOS_TIMER values that repeat or go * backwards and will break the demo. */ if (PIT0_GetAssignedCounter() >= 0xFFFF/*Should be 0x10000 but we'll accept some programs might write 0xFFFF*/) { uint32_t BIOS_HostTimeSync(uint32_t ticks); value = BIOS_HostTimeSync(value); if (sync_time_timerrate_warning) { sync_time_timerrate_warning = false; LOG(LOG_MISC,LOG_WARN)("IRQ0 timer rate restored to 18.2Hz and synchronize time=true, resuming synchronization. BIOS_TIMER may jump backwards suddenly."); } } else { if (!sync_time_timerrate_warning) { /* Okay, you changed the tick rate. That affects BIOS_TIMER * and therefore counts as manual time. Sorry. */ sync_time_timerrate_warning = true; LOG(LOG_MISC,LOG_WARN)("IRQ0 timer rate is not 18.2Hz and synchronize time=true, disabling synchronization until normal rate restored."); } } } mem_writed(BIOS_TIMER,value); if(bootdrive>=0) { #if (defined(WIN32) && !defined(HX_DOS) || defined(LINUX) && C_X11) && (defined(C_SDL2) || defined(SDL_DOSBOX_X_SPECIAL)) SetIMPosition(); #endif } else if (IS_DOSV && DOSV_CheckCJKVideoMode()) { INT8_DOSV(); } else if(J3_IsJapanese()) { INT8_J3(); } else if (IS_DOS_CJK) { #if (defined(WIN32) && !defined(HX_DOS) || defined(LINUX) && C_X11) && (defined(C_SDL2) || defined(SDL_DOSBOX_X_SPECIAL)) SetIMPosition(); #endif } /* decrement FDD motor timeout counter; roll over on earlier PC, stop at zero on later PC */ uint8_t val = mem_readb(BIOS_DISK_MOTOR_TIMEOUT); if (val || !IS_EGAVGA_ARCH) mem_writeb(BIOS_DISK_MOTOR_TIMEOUT,val-1); /* clear FDD motor bits when counter reaches zero */ if (val == 1) mem_writeb(BIOS_DRIVE_RUNNING,mem_readb(BIOS_DRIVE_RUNNING) & 0xF0); return CBRET_NONE; } #undef DOSBOX_CLOCKSYNC static Bitu INT1C_Handler(void) { return CBRET_NONE; } static Bitu INT12_Handler(void) { reg_ax=mem_readw(BIOS_MEMORY_SIZE); return CBRET_NONE; } static Bitu INT17_Handler(void) { if (reg_ah > 0x2 || reg_dx > 0x2) { // 0-2 printer port functions // and no more than 3 parallel ports LOG_MSG("BIOS INT17: Unhandled call AH=%2X DX=%4x",reg_ah,reg_dx); return CBRET_NONE; } switch(reg_ah) { case 0x00: // PRINTER: Write Character if(parallelPortObjects[reg_dx]!=0) { if(parallelPortObjects[reg_dx]->Putchar(reg_al)) reg_ah=parallelPortObjects[reg_dx]->getPrinterStatus(); else reg_ah=1; } break; case 0x01: // PRINTER: Initialize port if(parallelPortObjects[reg_dx]!= 0) { parallelPortObjects[reg_dx]->initialize(); reg_ah=parallelPortObjects[reg_dx]->getPrinterStatus(); } break; case 0x02: // PRINTER: Get Status if(parallelPortObjects[reg_dx] != 0) reg_ah=parallelPortObjects[reg_dx]->getPrinterStatus(); //LOG_MSG("printer status: %x",reg_ah); break; case 0x20: /* Some sort of printerdriver install check*/ break; case 0x50: // Printer BIOS for AX if (!IS_JEGA_ARCH) break; switch (reg_al) { case 0x00:// Set JP/US mode in PRT BIOS LOG(LOG_BIOS, LOG_NORMAL)("AX PRT BIOS 5000h is called. (not implemented)"); reg_al = 0x01; // Return error (not implemented) break; case 0x01:// Get JP/US mode in PRT BIOS reg_al = 0x01; // Return US mode (not implemented) break; default: LOG(LOG_BIOS, LOG_ERROR)("Unhandled AX Function 50%2X", reg_al); break; } break; } return CBRET_NONE; } static bool INT14_Wait(uint16_t port, uint8_t mask, uint8_t timeout, uint8_t* retval) { double starttime = PIC_FullIndex(); double timeout_f = timeout * 1000.0; while (((*retval = IO_ReadB(port)) & mask) != mask) { if (starttime < (PIC_FullIndex() - timeout_f)) { return false; } CALLBACK_Idle(); } return true; } static Bitu INT4B_Handler(void) { /* TODO: This is where the Virtual DMA specification is accessed on modern systems. * When we implement that, move this to EMM386 emulation code. */ if (reg_ax >= 0x8102 && reg_ax <= 0x810D) { LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted Virtual DMA specification call (INT 4Bh AX=%04x BX=%04x CX=%04x DX=%04x", reg_ax,reg_bx,reg_cx,reg_dx); } else if (reg_ah == 0x80) { LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted IBM SCSI interface call"); } else if (reg_ah <= 0x02) { LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted TI Professional PC parallel port function AH=%02x",reg_ah); } else { LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted unknown INT 4Bh call AX=%04x",reg_ax); } /* Oh, I'm just a BIOS that doesn't know what the hell you're doing. CF=1 */ CALLBACK_SCF(true); return CBRET_NONE; } static Bitu INT14_Handler(void) { if (reg_ah > 0x3 || reg_dx > 0x3) { // 0-3 serial port functions // and no more than 4 serial ports LOG_MSG("BIOS INT14: Unhandled call AH=%2X DX=%4x",reg_ah,reg_dx); return CBRET_NONE; } uint16_t port = real_readw(0x40,reg_dx * 2u); // DX is always port number uint8_t timeout = mem_readb((PhysPt)((unsigned int)BIOS_COM1_TIMEOUT + (unsigned int)reg_dx)); if (port==0) { LOG(LOG_BIOS,LOG_NORMAL)("BIOS INT14: port %d does not exist.",reg_dx); return CBRET_NONE; } switch (reg_ah) { case 0x00: { // Initialize port // Parameters: Return: // AL: port parameters AL: modem status // AH: line status // set baud rate Bitu baudrate = 9600u; uint16_t baudresult; Bitu rawbaud=(Bitu)reg_al>>5u; if (rawbaud==0){ baudrate=110u;} else if (rawbaud==1){ baudrate=150u;} else if (rawbaud==2){ baudrate=300u;} else if (rawbaud==3){ baudrate=600u;} else if (rawbaud==4){ baudrate=1200u;} else if (rawbaud==5){ baudrate=2400u;} else if (rawbaud==6){ baudrate=4800u;} else if (rawbaud==7){ baudrate=9600u;} baudresult = (uint16_t)(115200u / baudrate); IO_WriteB(port+3u, 0x80u); // enable divider access IO_WriteB(port, (uint8_t)baudresult&0xffu); IO_WriteB(port+1u, (uint8_t)(baudresult>>8u)); // set line parameters, disable divider access IO_WriteB(port+3u, reg_al&0x1Fu); // LCR // disable interrupts IO_WriteB(port+1u, 0u); // IER // get result reg_ah=IO_ReadB(port+5u)&0xffu; reg_al=IO_ReadB(port+6u)&0xffu; CALLBACK_SCF(false); break; } case 0x01: // Transmit character // Parameters: Return: // AL: character AL: unchanged // AH: 0x01 AH: line status from just before the char was sent // (0x80 | unpredicted) in case of timeout // [undoc] (0x80 | line status) in case of tx timeout // [undoc] (0x80 | modem status) in case of dsr/cts timeout // set DTR & RTS on IO_WriteB(port+4u,0x3u); // wait for DSR & CTS if (INT14_Wait(port+6u, 0x30u, timeout, &reg_ah)) { // wait for TX buffer empty if (INT14_Wait(port+5u, 0x20u, timeout, &reg_ah)) { // fianlly send the character IO_WriteB(port,reg_al); } else reg_ah |= 0x80u; } else // timed out reg_ah |= 0x80u; CALLBACK_SCF(false); break; case 0x02: // Read character // Parameters: Return: // AH: 0x02 AL: received character // [undoc] will be trashed in case of timeout // AH: (line status & 0x1E) in case of success // (0x80 | unpredicted) in case of timeout // [undoc] (0x80 | line status) in case of rx timeout // [undoc] (0x80 | modem status) in case of dsr timeout // set DTR on IO_WriteB(port+4u,0x1u); // wait for DSR if (INT14_Wait(port+6, 0x20, timeout, &reg_ah)) { // wait for character to arrive if (INT14_Wait(port+5, 0x01, timeout, &reg_ah)) { reg_ah &= 0x1E; reg_al = IO_ReadB(port); } else reg_ah |= 0x80; } else reg_ah |= 0x80; CALLBACK_SCF(false); break; case 0x03: // get status reg_ah=IO_ReadB(port+5u)&0xffu; reg_al=IO_ReadB(port+6u)&0xffu; CALLBACK_SCF(false); break; } return CBRET_NONE; } Bits HLT_Decode(void); void KEYBOARD_AUX_Write(Bitu val); unsigned char KEYBOARD_AUX_GetType(); unsigned char KEYBOARD_AUX_DevStatus(); unsigned char KEYBOARD_AUX_Resolution(); unsigned char KEYBOARD_AUX_SampleRate(); void KEYBOARD_ClrBuffer(void); void KEYBOARD_AUX_LowerIRQ(); static Bitu INT15_Handler(void) { if( ( machine==MCH_AMSTRAD ) && ( reg_ah<0x07 ) ) { switch(reg_ah) { case 0x00: // Read/Reset Mouse X/Y Counts. // CX = Signed X Count. // DX = Signed Y Count. // CC. case 0x01: // Write NVR Location. // AL = NVR Address to be written (0-63). // BL = NVR Data to be written. // AH = Return Code. // 00 = NVR Written Successfully. // 01 = NVR Address out of range. // 02 = NVR Data write error. // CC. case 0x02: // Read NVR Location. // AL = NVR Address to be read (0-63). // AH = Return Code. // 00 = NVR read successfully. // 01 = NVR Address out of range. // 02 = NVR checksum error. // AL = Byte read from NVR. // CC. default: LOG(LOG_BIOS,LOG_NORMAL)("INT15 Unsupported PC1512 Call %02X",reg_ah); return CBRET_NONE; case 0x03: // Write VDU Colour Plane Write Register. vga.amstrad.write_plane = reg_al & 0x0F; CALLBACK_SCF(false); break; case 0x04: // Write VDU Colour Plane Read Register. vga.amstrad.read_plane = reg_al & 0x03; CALLBACK_SCF(false); break; case 0x05: // Write VDU Graphics Border Register. vga.amstrad.border_color = reg_al & 0x0F; CALLBACK_SCF(false); break; case 0x06: // Return ROS Version Number. reg_bx = 0x0001; CALLBACK_SCF(false); break; } } switch (reg_ah) { case 0x06: LOG(LOG_BIOS,LOG_NORMAL)("INT15 Unknown Function 6 (Amstrad?)"); break; case 0x24: //A20 stuff switch (reg_al) { case 0: //Disable a20 MEM_A20_Enable(false); reg_ah = 0; //call successful CALLBACK_SCF(false); //clear on success break; case 1: //Enable a20 MEM_A20_Enable( true ); reg_ah = 0; //call successful CALLBACK_SCF(false); //clear on success break; case 2: //Query a20 reg_al = MEM_A20_Enabled() ? 0x1 : 0x0; reg_ah = 0; //call successful CALLBACK_SCF(false); break; case 3: //Get a20 support reg_bx = 0x3; //Bitmask, keyboard and 0x92 reg_ah = 0; //call successful CALLBACK_SCF(false); break; default: goto unhandled; } break; case 0xC0: /* Get Configuration*/ CPU_SetSegGeneral(es,biosConfigSeg); reg_bx = 0; reg_ah = 0; CALLBACK_SCF(false); break; case 0x4f: /* BIOS - Keyboard intercept */ /* Carry should be set but let's just set it just in case */ CALLBACK_SCF(true); break; case 0x83: /* BIOS - SET EVENT WAIT INTERVAL */ { if(reg_al == 0x01) { /* Cancel it */ mem_writeb(BIOS_WAIT_FLAG_ACTIVE,0); IO_Write(0x70,0xb); IO_Write(0x71,IO_Read(0x71)&~0x40); CALLBACK_SCF(false); break; } if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) { reg_ah=0x80; CALLBACK_SCF(true); break; } uint32_t count=((uint32_t)reg_cx<<16u)|reg_dx; mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(SegValue(es),reg_bx)); mem_writed(BIOS_WAIT_FLAG_COUNT,count); mem_writeb(BIOS_WAIT_FLAG_ACTIVE,1); /* Reprogram RTC to start */ IO_Write(0x70,0xb); IO_Write(0x71,IO_Read(0x71)|0x40); CALLBACK_SCF(false); } break; case 0x84: /* BIOS - JOYSTICK SUPPORT (XT after 11/8/82,AT,XT286,PS) */ if (reg_dx == 0x0000) { // Get Joystick button status if (JOYSTICK_IsEnabled(0) || JOYSTICK_IsEnabled(1)) { reg_al = IO_ReadB(0x201)&0xf0; CALLBACK_SCF(false); } else { // dos values reg_ax = 0x00f0; reg_dx = 0x0201; CALLBACK_SCF(true); } } else if (reg_dx == 0x0001) { if (JOYSTICK_IsEnabled(0)) { reg_ax = (uint16_t)(JOYSTICK_GetMove_X(0)*127+128); reg_bx = (uint16_t)(JOYSTICK_GetMove_Y(0)*127+128); if(JOYSTICK_IsEnabled(1)) { reg_cx = (uint16_t)(JOYSTICK_GetMove_X(1)*127+128); reg_dx = (uint16_t)(JOYSTICK_GetMove_Y(1)*127+128); } else { reg_cx = reg_dx = 0; } CALLBACK_SCF(false); } else if (JOYSTICK_IsEnabled(1)) { reg_ax = reg_bx = 0; reg_cx = (uint16_t)(JOYSTICK_GetMove_X(1)*127+128); reg_dx = (uint16_t)(JOYSTICK_GetMove_Y(1)*127+128); CALLBACK_SCF(false); } else { reg_ax = reg_bx = reg_cx = reg_dx = 0; CALLBACK_SCF(true); } } else { LOG(LOG_BIOS,LOG_ERROR)("INT15:84:Unknown Bios Joystick functionality."); } break; case 0x86: /* BIOS - WAIT (AT,PS) */ { if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) { reg_ah=0x83; CALLBACK_SCF(true); break; } uint8_t t; uint32_t count=((uint32_t)reg_cx<<16u)|reg_dx; mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(0,BIOS_WAIT_FLAG_TEMP)); mem_writed(BIOS_WAIT_FLAG_COUNT,count); mem_writeb(BIOS_WAIT_FLAG_ACTIVE,1); /* if the user has not set the option, warn if IRQs are masked */ if (!int15_wait_force_unmask_irq) { /* make sure our wait function works by unmasking IRQ 2, and IRQ 8. * (bugfix for 1993 demo Yodel "Mayday" demo. this demo keeps masking IRQ 2 for some stupid reason.) */ if ((t=IO_Read(0x21)) & (1 << 2)) { LOG(LOG_BIOS,LOG_ERROR)("INT15:86:Wait: IRQ 2 masked during wait. " "Consider adding 'int15 wait force unmask irq=true' to your dosbox-x.conf"); } if ((t=IO_Read(0xA1)) & (1 << 0)) { LOG(LOG_BIOS,LOG_ERROR)("INT15:86:Wait: IRQ 8 masked during wait. " "Consider adding 'int15 wait force unmask irq=true' to your dosbox-x.conf"); } } /* Reprogram RTC to start */ IO_Write(0x70,0xb); IO_Write(0x71,IO_Read(0x71)|0x40); while (mem_readd(BIOS_WAIT_FLAG_COUNT)) { if (int15_wait_force_unmask_irq) { /* make sure our wait function works by unmasking IRQ 2, and IRQ 8. * (bugfix for 1993 demo Yodel "Mayday" demo. this demo keeps masking IRQ 2 for some stupid reason.) */ if ((t=IO_Read(0x21)) & (1 << 2)) { LOG(LOG_BIOS,LOG_WARN)("INT15:86:Wait: IRQ 2 masked during wait. " "This condition might result in an infinite wait on " "some BIOSes. Unmasking IRQ to keep things moving along."); IO_Write(0x21,t & ~(1 << 2)); } if ((t=IO_Read(0xA1)) & (1 << 0)) { LOG(LOG_BIOS,LOG_WARN)("INT15:86:Wait: IRQ 8 masked during wait. " "This condition might result in an infinite wait on some " "BIOSes. Unmasking IRQ to keep things moving along."); IO_Write(0xA1,t & ~(1 << 0)); } } CALLBACK_Idle(); } CALLBACK_SCF(false); break; } case 0x87: /* Copy extended memory */ { bool enabled = MEM_A20_Enabled(); MEM_A20_Enable(true); Bitu bytes = reg_cx * 2u; PhysPt data = SegPhys(es)+reg_si; PhysPt source = (mem_readd(data+0x12u) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data+0x17u)<<24u); PhysPt dest = (mem_readd(data+0x1Au) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data+0x1Fu)<<24u); MEM_BlockCopy(dest,source,bytes); reg_ax = 0x00; MEM_A20_Enable(enabled); Segs.limit[cs] = 0xFFFF; Segs.limit[ds] = 0xFFFF; Segs.limit[es] = 0xFFFF; Segs.limit[ss] = 0xFFFF; CALLBACK_SCF(false); break; } case 0x88: /* SYSTEM - GET EXTENDED MEMORY SIZE (286+) */ /* This uses the 16-bit value read back from CMOS which is capped at 64MB */ reg_ax=other_memsystems?0:size_extended; LOG(LOG_BIOS,LOG_NORMAL)("INT15:Function 0x88 Remaining %04X kb",reg_ax); CALLBACK_SCF(false); break; case 0x89: /* SYSTEM - SWITCH TO PROTECTED MODE */ { IO_Write(0x20,0x10);IO_Write(0x21,reg_bh);IO_Write(0x21,0);IO_Write(0x21,0xFF); IO_Write(0xA0,0x10);IO_Write(0xA1,reg_bl);IO_Write(0xA1,0);IO_Write(0xA1,0xFF); MEM_A20_Enable(true); PhysPt table=SegPhys(es)+reg_si; CPU_LGDT(mem_readw(table+0x8),mem_readd(table+0x8+0x2) & 0xFFFFFF); CPU_LIDT(mem_readw(table+0x10),mem_readd(table+0x10+0x2) & 0xFFFFFF); CPU_SET_CRX(0,CPU_GET_CRX(0)|1); CPU_SetSegGeneral(ds,0x18); CPU_SetSegGeneral(es,0x20); CPU_SetSegGeneral(ss,0x28); Bitu ret = mem_readw(SegPhys(ss)+reg_sp); reg_sp+=6; //Clear stack of interrupt frame CPU_SetFlags(0,FMASK_ALL); reg_ax=0; CPU_JMP(false,0x30,ret,0); } break; case 0x8A: /* EXTENDED MEMORY SIZE */ { Bitu sz = MEM_TotalPages()*4; if (sz >= 1024) sz -= 1024; else sz = 0; reg_ax = sz & 0xFFFF; reg_dx = sz >> 16; CALLBACK_SCF(false); } break; case 0x90: /* OS HOOK - DEVICE BUSY */ CALLBACK_SCF(false); reg_ah=0; break; case 0x91: /* OS HOOK - DEVICE POST */ CALLBACK_SCF(false); reg_ah=0; break; case 0xc2: /* BIOS PS2 Pointing Device Support */ /* TODO: Our reliance on AUX emulation means that at some point, AUX emulation * must always be enabled if BIOS PS/2 emulation is enabled. Future planned change: * * If biosps2=true and aux=true, carry on what we're already doing now: emulate INT 15h by * directly writing to the AUX port of the keyboard controller. * * If biosps2=false, the aux= setting enables/disables AUX emulation as it already does now. * biosps2=false implies that we're emulating a keyboard controller with AUX but no BIOS * support for it (however rare that might be). This gives the user of DOSBox-X the means * to test that scenario especially in case he/she is developing a homebrew OS and needs * to ensure their code can handle cases like that gracefully. * * If biosps2=true and aux=false, AUX emulation is enabled anyway, but the keyboard emulation * must act as if the AUX port is not there so the guest OS cannot control it. Again, not * likely on real hardware, but a useful test case for homebrew OS developers. * * If you the user set aux=false, then you obviously want to test a system configuration * where the keyboard controller has no AUX port. If you set biosps2=true, then you want to * test an OS that uses BIOS functions to setup the "pointing device" but you do not want the * guest OS to talk directly to the AUX port on the keyboard controller. * * Logically that's not likely to happen on real hardware, but we like giving the end-user * options to play with, so instead, if aux=false and biosps2=true, DOSBox-X should print * a warning stating that INT 15h mouse emulation with a PS/2 port is nonstandard and may * cause problems with OSes that need to talk directly to hardware. * * It is noteworthy that PS/2 mouse support in MS-DOS mouse drivers as well as Windows 3.x, * Windows 95, and Windows 98, is carried out NOT by talking directly to the AUX port but * instead by relying on the BIOS INT 15h functions here to do the dirty work. For those * scenarios, biosps2=true and aux=false is perfectly safe and does not cause issues. * * OSes that communicate directly with the AUX port however (Linux, Windows NT) will not work * unless aux=true. */ if (en_bios_ps2mouse) { // LOG_MSG("INT 15h AX=%04x BX=%04x\n",reg_ax,reg_bx); switch (reg_al) { case 0x00: // enable/disable if (reg_bh==0) { // disable KEYBOARD_AUX_Write(0xF5); Mouse_SetPS2State(false); reg_ah=0; CALLBACK_SCF(false); KEYBOARD_ClrBuffer(); } else if (reg_bh==0x01) { //enable if (!Mouse_SetPS2State(true)) { reg_ah=5; CALLBACK_SCF(true); break; } KEYBOARD_AUX_Write(0xF4); KEYBOARD_ClrBuffer(); reg_ah=0; CALLBACK_SCF(false); } else { CALLBACK_SCF(true); reg_ah=1; } break; case 0x01: // reset KEYBOARD_AUX_Write(0xFF); Mouse_SetPS2State(false); KEYBOARD_ClrBuffer(); reg_bx=0x00aa; // mouse (BH=device ID BL=value returned by attached device after reset) [http://www.ctyme.com/intr/rb-1597.htm] LOG_MSG("INT 15h mouse reset\n"); KEYBOARD_AUX_Write(0xF6); /* set defaults */ Mouse_SetPS2State(false); KEYBOARD_ClrBuffer(); KEYBOARD_AUX_LowerIRQ(); /* HACK: Lower IRQ or else it will persist, which can cause problems with Windows 3.1 stock PS/2 mouse drivers */ CALLBACK_SCF(false); reg_ah=0; // must return success. Fall through was well intended but, no, causes an error code that confuses mouse drivers break; case 0x05: // initialize if (reg_bh >= 3 && reg_bh <= 4) { /* TODO: BIOSes remember this value as the number of bytes to store before * calling the device callback. Setting this value to "1" is perfectly * valid if you want a byte-stream like mode (at the cost of one * interrupt per byte!). Most OSes will call this with BH=3 for standard * PS/2 mouse protocol. You can also call this with BH=4 for Intellimouse * protocol support, though testing (so far with VirtualBox) shows the * device callback still only gets the first three bytes on the stack. * Contrary to what you might think, the BIOS does not interpret the * bytes at all. * * The source code of CuteMouse 1.9 seems to suggest some BIOSes take * pains to repack the 4th byte in the upper 8 bits of one of the WORDs * on the stack in Intellimouse mode at the cost of shifting the W and X * fields around. I can't seem to find any source on who does that or * if it's even true, so I disregard the example at this time. * * Anyway, you need to store off this value somewhere and make use of * it in src/ints/mouse.cpp device callback emulation to reframe the * PS/2 mouse bytes coming from AUX (if aux=true) or emulate the * re-framing if aux=false to emulate this protocol fully. */ LOG_MSG("INT 15h mouse initialized to %u-byte protocol\n",reg_bh); KEYBOARD_AUX_Write(0xF6); /* set defaults */ Mouse_SetPS2State(false); KEYBOARD_ClrBuffer(); CALLBACK_SCF(false); reg_ah=0; } else { CALLBACK_SCF(false); reg_ah=0x02; /* invalid input */ } break; case 0x02: { // set sampling rate static const unsigned char tbl[7] = {10,20,40,60,80,100,200}; KEYBOARD_AUX_Write(0xF3); if (reg_bh > 6) reg_bh = 6; KEYBOARD_AUX_Write(tbl[reg_bh]); KEYBOARD_ClrBuffer(); CALLBACK_SCF(false); reg_ah=0; } break; case 0x03: // set resolution KEYBOARD_AUX_Write(0xE8); KEYBOARD_AUX_Write(reg_bh&3); KEYBOARD_ClrBuffer(); CALLBACK_SCF(false); reg_ah=0; break; case 0x04: // get type reg_bh=KEYBOARD_AUX_GetType(); // ID KEYBOARD_AUX_LowerIRQ(); /* HACK: Lower IRQ or else it will persist, which can cause problems with Windows 3.1 stock PS/2 mouse drivers */ LOG_MSG("INT 15h reporting mouse device ID 0x%02x\n",reg_bh); KEYBOARD_ClrBuffer(); CALLBACK_SCF(false); reg_ah=0; break; case 0x06: // extended commands if (reg_bh == 0x00) { /* Read device status and info. * Windows 9x does not appear to use this, but Windows NT 3.1 does (prior to entering * full 32-bit protected mode) */ CALLBACK_SCF(false); reg_bx=KEYBOARD_AUX_DevStatus(); reg_cx=KEYBOARD_AUX_Resolution(); reg_dx=KEYBOARD_AUX_SampleRate(); KEYBOARD_AUX_LowerIRQ(); /* HACK: Lower IRQ or else it will persist, which can cause problems with Windows 3.1 stock PS/2 mouse drivers */ KEYBOARD_ClrBuffer(); reg_ah=0; } else if ((reg_bh==0x01) || (reg_bh==0x02)) { /* set scaling */ KEYBOARD_AUX_Write(0xE6u+reg_bh-1u); /* 0xE6 1:1 or 0xE7 2:1 */ KEYBOARD_ClrBuffer(); CALLBACK_SCF(false); reg_ah=0; } else { CALLBACK_SCF(true); reg_ah=1; } break; case 0x07: // set callback Mouse_ChangePS2Callback(SegValue(es),reg_bx); CALLBACK_SCF(false); reg_ah=0; break; default: LOG_MSG("INT 15h unknown mouse call AX=%04x\n",reg_ax); CALLBACK_SCF(true); reg_ah=1; break; } } else { reg_ah=0x86; CALLBACK_SCF(true); if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA)) { /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ CALLBACK_SZF(false); } } break; case 0xc3: /* set carry flag so BorlandRTM doesn't assume a VECTRA/PS2 */ reg_ah=0x86; CALLBACK_SCF(true); break; case 0xc4: /* BIOS POS Programm option Select */ LOG(LOG_BIOS,LOG_NORMAL)("INT15:Function %X called, bios mouse not supported",reg_ah); CALLBACK_SCF(true); break; case 0x53: // APM BIOS if (APMBIOS) { LOG(LOG_BIOS,LOG_DEBUG)("APM BIOS call AX=%04x BX=0x%04x CX=0x%04x\n",reg_ax,reg_bx,reg_cx); switch(reg_al) { case 0x00: // installation check reg_ah = 1; // major reg_al = APM_BIOS_minor_version; // minor reg_bx = 0x504d; // 'PM' reg_cx = (APMBIOS_allow_prot16?0x01:0x00) + (APMBIOS_allow_prot32?0x02:0x00); // 32-bit interface seems to be needed for standby in win95 CALLBACK_SCF(false); break; case 0x01: // connect real mode interface if(!APMBIOS_allow_realmode) { LOG_MSG("APM BIOS: OS attemped real-mode connection, which is disabled in your dosbox-x.conf\n"); reg_ah = 0x86; // APM not present CALLBACK_SCF(true); break; } if(reg_bx != 0x0) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } if(!apm_realmode_connected) { // not yet connected LOG_MSG("APM BIOS: Connected to real-mode interface\n"); CALLBACK_SCF(false); APMBIOS_connect_mode = APMBIOS_CONNECT_REAL; apm_realmode_connected=true; } else { LOG_MSG("APM BIOS: OS attempted to connect to real-mode interface when already connected\n"); reg_ah = APMBIOS_connected_already_err(); // interface connection already in effect CALLBACK_SCF(true); } APM_BIOS_connected_minor_version = 0; break; case 0x02: // connect 16-bit protected mode interface if(!APMBIOS_allow_prot16) { LOG_MSG("APM BIOS: OS attemped 16-bit protected mode connection, which is disabled in your dosbox-x.conf\n"); reg_ah = 0x06; // not supported CALLBACK_SCF(true); break; } if(reg_bx != 0x0) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } if(!apm_realmode_connected) { // not yet connected /* NTS: We use the same callback address for both 16-bit and 32-bit * because only the DOS callback and RETF instructions are involved, * which can be executed as either 16-bit or 32-bit code without problems. */ LOG_MSG("APM BIOS: Connected to 16-bit protected mode interface\n"); CALLBACK_SCF(false); reg_ax = INT15_apm_pmentry >> 16; // AX = 16-bit code segment (real mode base) reg_bx = INT15_apm_pmentry & 0xFFFF; // BX = offset of entry point reg_cx = INT15_apm_pmentry >> 16; // CX = 16-bit data segment (NTS: doesn't really matter) reg_si = 0xFFFF; // SI = code segment length reg_di = 0xFFFF; // DI = data segment length APMBIOS_connect_mode = APMBIOS_CONNECT_PROT16; apm_realmode_connected=true; } else { LOG_MSG("APM BIOS: OS attempted to connect to 16-bit protected mode interface when already connected\n"); reg_ah = APMBIOS_connected_already_err(); // interface connection already in effect CALLBACK_SCF(true); } APM_BIOS_connected_minor_version = 0; break; case 0x03: // connect 32-bit protected mode interface // Note that Windows 98 will NOT talk to the APM BIOS unless the 32-bit protected mode connection is available. // And if you lie about it in function 0x00 and then fail, Windows 98 will fail with a "Windows protection error". if(!APMBIOS_allow_prot32) { LOG_MSG("APM BIOS: OS attemped 32-bit protected mode connection, which is disabled in your dosbox-x.conf\n"); reg_ah = 0x08; // not supported CALLBACK_SCF(true); break; } if(reg_bx != 0x0) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } if(!apm_realmode_connected) { // not yet connected LOG_MSG("APM BIOS: Connected to 32-bit protected mode interface\n"); CALLBACK_SCF(false); /* NTS: We use the same callback address for both 16-bit and 32-bit * because only the DOS callback and RETF instructions are involved, * which can be executed as either 16-bit or 32-bit code without problems. */ reg_ax = INT15_apm_pmentry >> 16; // AX = 32-bit code segment (real mode base) reg_ebx = INT15_apm_pmentry & 0xFFFF; // EBX = offset of entry point reg_cx = INT15_apm_pmentry >> 16; // CX = 16-bit code segment (real mode base) reg_dx = INT15_apm_pmentry >> 16; // DX = data segment (real mode base) (?? what size?) reg_esi = 0xFFFFFFFF; // ESI = upper word: 16-bit code segment len lower word: 32-bit code segment length reg_di = 0xFFFF; // DI = data segment length APMBIOS_connect_mode = APMBIOS_CONNECT_PROT32; apm_realmode_connected=true; } else { LOG_MSG("APM BIOS: OS attempted to connect to 32-bit protected mode interface when already connected\n"); reg_ah = APMBIOS_connected_already_err(); // interface connection already in effect CALLBACK_SCF(true); } APM_BIOS_connected_minor_version = 0; break; case 0x04: // DISCONNECT INTERFACE if(reg_bx != 0x0) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } if(apm_realmode_connected) { LOG_MSG("APM BIOS: OS disconnected\n"); CALLBACK_SCF(false); apm_realmode_connected=false; } else { reg_ah = 0x03; // interface not connected CALLBACK_SCF(true); } APM_BIOS_connected_minor_version = 0; break; case 0x05: // CPU IDLE if(!apm_realmode_connected) { reg_ah = 0x03; CALLBACK_SCF(true); break; } // Trigger CPU HLT instruction. // NTS: For whatever weird reason, NOT emulating HLT makes Windows 95 // crashy when the APM driver is active! There's something within // the Win95 kernel that apparently screws up really badly if // the APM IDLE call returns immediately. The best case scenario // seems to be that Win95's APM driver has some sort of timing // logic to it that if it detects an immediate return, immediately // shuts down and powers off the machine. Windows 98 also seems // to require a HLT, and will act erratically without it. // // Also need to note that the choice of "HLT" is not arbitrary // at all. The APM BIOS standard mentions CPU IDLE either stopping // the CPU clock temporarily or issuing HLT as a valid method. // // TODO: Make this a dosbox-x.conf configuration option: what do we do // on APM idle calls? Allow selection between "nothing" "hlt" // and "software delay". if (!(reg_flags&0x200)) { LOG(LOG_BIOS,LOG_WARN)("APM BIOS warning: CPU IDLE called with IF=0, not HLTing\n"); } else if (cpudecoder == &HLT_Decode) { /* do not re-execute HLT, it makes DOSBox-X hang */ LOG_MSG("APM BIOS warning: CPU IDLE HLT within HLT (DOSBox-X core failure)\n"); } else { CPU_HLT(reg_eip); } break; case 0x06: // CPU BUSY if(!apm_realmode_connected) { reg_ah = 0x03; CALLBACK_SCF(true); break; } /* OK. whatever. system no longer idle */ CALLBACK_SCF(false); break; case 0x07: if(reg_bx != 0x1) { reg_ah = 0x09; // wrong device ID CALLBACK_SCF(true); break; } if(!apm_realmode_connected) { reg_ah = 0x03; CALLBACK_SCF(true); break; } switch(reg_cx) { case 0x3: // power off throw(0); default: reg_ah = 0x0A; // invalid parameter value in CX CALLBACK_SCF(true); break; } break; case 0x08: // ENABLE/DISABLE POWER MANAGEMENT if(reg_bx != 0x0 && reg_bx != 0x1) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } else if(!apm_realmode_connected) { reg_ah = 0x03; CALLBACK_SCF(true); break; } if(reg_cx==0x0) LOG_MSG("disable APM for device %4x",reg_bx); else if(reg_cx==0x1) LOG_MSG("enable APM for device %4x",reg_bx); else { reg_ah = 0x0A; // invalid parameter value in CX CALLBACK_SCF(true); } break; case 0x0a: // GET POWER STATUS if (!apm_realmode_connected) { reg_ah = 0x03; // interface not connected CALLBACK_SCF(true); break; } if (reg_bx != 0x0001 && reg_bx != 0x8001) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } /* FIXME: Allow configuration and shell commands to dictate whether or * not we emulate a laptop with a battery */ reg_bh = 0x01; // AC line status (1=on-line) reg_bl = 0xFF; // Battery status (unknown) reg_ch = 0x80; // Battery flag (no system battery) reg_cl = 0xFF; // Remaining battery charge (unknown) reg_dx = 0xFFFF; // Remaining battery life (unknown) reg_si = 0; // Number of battery units (if called with reg_bx == 0x8001) CALLBACK_SCF(false); break; case 0x0b: // GET PM EVENT if (!apm_realmode_connected) { reg_ah = 0x03; // interface not connected CALLBACK_SCF(true); break; } reg_ah = 0x80; // no power management events pending CALLBACK_SCF(true); break; case 0x0d: // NTS: NOT implementing this call can cause Windows 98's APM driver to crash on startup if(reg_bx != 0x0 && reg_bx != 0x1) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } else if(!apm_realmode_connected) { reg_ah = 0x03; CALLBACK_SCF(true); break; } if(reg_cx==0x0) { LOG_MSG("disable APM for device %4x",reg_bx); CALLBACK_SCF(false); } else if(reg_cx==0x1) { LOG_MSG("enable APM for device %4x",reg_bx); CALLBACK_SCF(false); } else { reg_ah = 0x0A; // invalid parameter value in CX CALLBACK_SCF(true); } break; case 0x0e: if (APM_BIOS_minor_version != 0) { // APM 1.1 or higher only if(reg_bx != 0x0) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } else if(!apm_realmode_connected) { reg_ah = 0x03; // interface not connected CALLBACK_SCF(true); break; } reg_ah = reg_ch; /* we are called with desired version in CH,CL, return actual version in AH,AL */ reg_al = reg_cl; if(reg_ah != 1) reg_ah = 1; // major if(reg_al > APM_BIOS_minor_version) reg_al = APM_BIOS_minor_version; // minor APM_BIOS_connected_minor_version = reg_al; // what we decided becomes the interface we emulate LOG_MSG("APM BIOS negotiated to v1.%u",APM_BIOS_connected_minor_version); CALLBACK_SCF(false); } else { // APM 1.0 does not recognize this call reg_ah = 0x0C; // function not supported CALLBACK_SCF(true); } break; case 0x0f: if(reg_bx != 0x0 && reg_bx != 0x1) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } else if(!apm_realmode_connected) { reg_ah = 0x03; CALLBACK_SCF(true); break; } if(reg_cx==0x0) { LOG_MSG("disengage APM for device %4x",reg_bx); CALLBACK_SCF(false); } else if(reg_cx==0x1) { LOG_MSG("engage APM for device %4x",reg_bx); CALLBACK_SCF(false); } else { reg_ah = 0x0A; // invalid parameter value in CX CALLBACK_SCF(true); } break; case 0x10: if (!apm_realmode_connected) { reg_ah = 0x03; // interface not connected CALLBACK_SCF(true); break; } if (reg_bx != 0) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } reg_ah = 0; reg_bl = 0; // number of battery units reg_cx = 0x03; // can enter suspend/standby and will post standby/resume events CALLBACK_SCF(false); break; case 0x13://enable/disable/query timer based requests // NTS: NOT implementing this call can cause Windows 98's APM driver to crash on startup if (!apm_realmode_connected) { reg_ah = 0x03; // interface not connected CALLBACK_SCF(true); break; } if (reg_bx != 0) { reg_ah = 0x09; // unrecognized device ID CALLBACK_SCF(true); break; } if (reg_cx == 0) { // disable APM_inactivity_timer = false; reg_cx = 0; CALLBACK_SCF(false); } else if (reg_cx == 1) { // enable APM_inactivity_timer = true; reg_cx = 1; CALLBACK_SCF(false); } else if (reg_cx == 2) { // get enabled status reg_cx = APM_inactivity_timer ? 1 : 0; CALLBACK_SCF(false); } else { reg_ah = 0x0A; // invalid parameter value in CX CALLBACK_SCF(true); } break; default: LOG_MSG("Unknown APM BIOS call AX=%04x\n",reg_ax); if (!apm_realmode_connected) { reg_ah = 0x03; // interface not connected CALLBACK_SCF(true); break; } reg_ah = 0x0C; // function not supported CALLBACK_SCF(true); break; } } else { reg_ah=0x86; CALLBACK_SCF(true); LOG_MSG("APM BIOS call attempted. set apmbios=1 if you want power management\n"); if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA) || (machine==MCH_AMSTRAD)) { /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ CALLBACK_SZF(false); } } break; case 0xe8: switch (reg_al) { case 0x01: { /* E801: memory size */ Bitu sz = MEM_TotalPages()*4; if (sz >= 1024) sz -= 1024; else sz = 0; reg_ax = reg_cx = (sz > 0x3C00) ? 0x3C00 : sz; /* extended memory between 1MB and 16MB in KBs */ sz -= reg_ax; sz /= 64; /* extended memory size from 16MB in 64KB blocks */ if (sz > 65535) sz = 65535; reg_bx = reg_dx = sz; CALLBACK_SCF(false); } break; case 0x20: { /* E820: MEMORY LISTING */ if (reg_edx == 0x534D4150 && reg_ecx >= 20 && (MEM_TotalPages()*4) >= 24000) { /* return a minimalist list: * * 0) 0x000000-0x09EFFF Free memory * 1) 0x0C0000-0x0FFFFF Reserved * 2) 0x100000-... Free memory (no ACPI tables) */ if (reg_ebx < 3) { uint32_t base = 0,len = 0,type = 0; Bitu seg = SegValue(es); assert((MEM_TotalPages()*4096) >= 0x100000); switch (reg_ebx) { case 0: base=0x000000; len=0x09F000; type=1; break; case 1: base=0x0C0000; len=0x040000; type=2; break; case 2: base=0x100000; len=(MEM_TotalPages()*4096)-0x100000; type=1; break; default: E_Exit("Despite checks EBX is wrong value"); /* BUG! */ } /* write to ES:DI */ real_writed(seg,reg_di+0x00,base); real_writed(seg,reg_di+0x04,0); real_writed(seg,reg_di+0x08,len); real_writed(seg,reg_di+0x0C,0); real_writed(seg,reg_di+0x10,type); reg_ecx = 20; /* return EBX pointing to next entry. wrap around, as most BIOSes do. * the program is supposed to stop on CF=1 or when we return EBX == 0 */ if (++reg_ebx >= 3) reg_ebx = 0; } else { CALLBACK_SCF(true); } reg_eax = 0x534D4150; } else { reg_eax = 0x8600; CALLBACK_SCF(true); } } break; default: unhandled: LOG(LOG_BIOS,LOG_ERROR)("INT15:Unknown call ah=E8, al=%2X",reg_al); reg_ah=0x86; CALLBACK_SCF(true); if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA) || (machine==MCH_AMSTRAD)) { /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ CALLBACK_SZF(false); } } break; case 0x50: if(isDBCSCP()) { if(reg_al == 0x00) { if(reg_bl == 0x00 && reg_bp == 0x00) { enum DOSV_FONT font = DOSV_FONT_MAX; if(reg_bh & 0x01) { if(reg_dh == 16 && reg_dl == 16) { font = DOSV_FONT_16X16; } else if(reg_dh == 24 && reg_dl == 24) { font = DOSV_FONT_24X24; } } else { if(reg_dh == 8) { if(reg_dl == 16) { font = DOSV_FONT_8X16; } else if(reg_dl == 19) { font = DOSV_FONT_8X19; } } else if(reg_dh == 12 && reg_dl == 24) { font = DOSV_FONT_12X24; } } if(font != DOSV_FONT_MAX) { reg_ah = 0x00; SegSet16(es, CB_SEG); reg_bx = DOSV_GetFontHandlerOffset(font); CALLBACK_SCF(false); break; } } } else if(reg_al == 0x01) { if(reg_dh == 16 && reg_dl == 16) { reg_ah = 0x00; SegSet16(es, CB_SEG); reg_bx = DOSV_GetFontHandlerOffset(DOSV_FONT_16X16_WRITE); CALLBACK_SCF(false); break; } else if(reg_dh == 24 && reg_dl == 24) { reg_ah = 0x00; SegSet16(es, CB_SEG); reg_bx = DOSV_GetFontHandlerOffset(DOSV_FONT_24X24_WRITE); CALLBACK_SCF(false); break; } else { reg_ah = 0x06; // read only } } CALLBACK_SCF(true); } break; case 0x49: if(isDBCSCP()) { reg_ah = 0x00; reg_bl = 0x00; CALLBACK_SCF(false); } else { CALLBACK_SCF(true); } break; default: LOG(LOG_BIOS,LOG_ERROR)("INT15:Unknown call ax=%4X",reg_ax); reg_ah=0x86; CALLBACK_SCF(true); if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA) || (machine==MCH_AMSTRAD)) { /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ CALLBACK_SZF(false); } } return CBRET_NONE; } void BIOS_UnsetupKeyboard(void); void BIOS_SetupKeyboard(void); void BIOS_UnsetupDisks(void); void BIOS_SetupDisks(void); void CPU_Snap_Back_To_Real_Mode(); void CPU_Snap_Back_Restore(); static Bitu Default_IRQ_Handler(void) { IO_WriteB(0x20, 0x0b); uint8_t master_isr = IO_ReadB(0x20); if (master_isr) { IO_WriteB(0xa0, 0x0b); uint8_t slave_isr = IO_ReadB(0xa0); if (slave_isr) { IO_WriteB(0xa1, IO_ReadB(0xa1) | slave_isr); IO_WriteB(0xa0, 0x20); } else IO_WriteB(0x21, IO_ReadB(0x21) | (master_isr & ~4)); IO_WriteB(0x20, 0x20); #if C_DEBUG uint16_t irq = 0; uint16_t isr = master_isr; if (slave_isr) isr = slave_isr << 8; while (isr >>= 1) irq++; LOG(LOG_BIOS, LOG_WARN)("Unexpected IRQ %u", irq); #endif } else master_isr = 0xff; mem_writeb(BIOS_LAST_UNEXPECTED_IRQ, master_isr); return CBRET_NONE; } static Bitu IRQ14_Dummy(void) { /* FIXME: That's it? Don't I EOI the PIC? */ return CBRET_NONE; } static Bitu IRQ15_Dummy(void) { /* FIXME: That's it? Don't I EOI the PIC? */ return CBRET_NONE; } void On_Software_CPU_Reset(); static Bitu INT18_Handler(void) { if (ibm_rom_basic_size != 0) { /* jump to BASIC (usually F600:0000 for IBM 5150 ROM BASIC) */ SegSet16(cs, ibm_rom_basic_base >> 4); reg_eip = 0; } else { LOG_MSG("Restart by INT 18h requested\n"); On_Software_CPU_Reset(); /* does not return */ } return CBRET_NONE; } static Bitu INT19_Handler(void) { LOG_MSG("Restart by INT 19h requested\n"); /* FIXME: INT 19h is sort of a BIOS boot BIOS reset-ish thing, not really a CPU reset at all. */ On_Software_CPU_Reset(); /* does not return */ return CBRET_NONE; } void bios_enable_ps2() { mem_writew(BIOS_CONFIGURATION, mem_readw(BIOS_CONFIGURATION)|0x04); /* PS/2 mouse */ } void BIOS_ZeroExtendedSize(bool in) { if(in) other_memsystems++; else other_memsystems--; if(other_memsystems < 0) other_memsystems=0; if (IS_PC98_ARCH) { Bitu mempages = MEM_TotalPages(); /* in 4KB pages */ /* What applies to IBM PC/AT (zeroing out the extended memory size) * also applies to PC-98, when HIMEM.SYS is loaded */ if (in) mempages = 0; /* extended memory size (286 systems, below 16MB) */ if (mempages > (1024UL/4UL)) { unsigned int ext = ((mempages - (1024UL/4UL)) * 4096UL) / (128UL * 1024UL); /* convert to 128KB units */ /* extended memory, up to 16MB capacity (for 286 systems?) * * MS-DOS drivers will "allocate" for themselves by taking from the top of * extended memory then subtracting from this value. * * capacity does not include conventional memory below 1MB, nor any memory * above 16MB. * * PC-98 systems may reserve the top 1MB, limiting the top to 15MB instead. * * 0x70 = 128KB * 0x70 = 14MB * 0x78 = 128KB * 0x70 = 15MB */ if (ext > 0x78) ext = 0x78; mem_writeb(0x401,ext); } else { mem_writeb(0x401,0x00); } /* extended memory size (386 systems, at or above 16MB) */ if (mempages > ((1024UL*16UL)/4UL)) { unsigned int ext = ((mempages - ((1024UL*16UL)/4UL)) * 4096UL) / (1024UL * 1024UL); /* convert to MB */ /* extended memory, at or above 16MB capacity (for 386+ systems?) * * MS-DOS drivers will "allocate" for themselves by taking from the top of * extended memory then subtracting from this value. * * capacity does not include conventional memory below 1MB, nor any memory * below 16MB. */ if (ext > 0xFFFE) ext = 0xFFFE; mem_writew(0x594,ext); } else { mem_writew(0x594,0x00); } } } unsigned char do_isapnp_chksum(const unsigned char* d, int i) { unsigned char sum = 0; while (i-- > 0) sum += *d++; return (0x100 - sum) & 0xFF; } void MEM_ResetPageHandler_Unmapped(Bitu phys_page, Bitu pages); unsigned int dos_conventional_limit = 0; bool AdapterROM_Read(Bitu address,unsigned long *size) { unsigned char c[3]; unsigned int i; if ((address & 0x1FF) != 0) { LOG(LOG_MISC,LOG_DEBUG)("AdapterROM_Read: Caller attempted ROM scan not aligned to 512-byte boundary"); return false; } for (i=0;i < 3;i++) c[i] = mem_readb(address+i); if (c[0] == 0x55 && c[1] == 0xAA) { unsigned char chksum=0; *size = (unsigned long)c[2] * 512UL; for (i=0;i < (unsigned int)(*size);i++) chksum += mem_readb(address+i); if (chksum != 0) { LOG(LOG_MISC,LOG_WARN)("AdapterROM_Read: Found ROM at 0x%lx but checksum failed (got %02xh expect %02xh)\n",(unsigned long)address,chksum,0); return false; } return true; } return false; } #include "src/gui/dosbox.vga16.bmp.h" #include "src/gui/dosbox.cga640.bmp.h" void DrawDOSBoxLogoCGA6(unsigned int x,unsigned int y) { const unsigned char *s = dosbox_cga640_bmp; const unsigned char *sf = s + sizeof(dosbox_cga640_bmp); uint32_t width,height; unsigned int dx,dy; uint32_t off; uint32_t sz; if (memcmp(s,"BM",2)) return; sz = host_readd(s+2); // size of total bitmap off = host_readd(s+10); // offset of bitmap if ((s+sz) > sf) return; if ((s+14+40) > sf) return; sz = host_readd(s+34); // biSize if ((s+off+sz) > sf) return; if (host_readw(s+26) != 1) return; // biBitPlanes if (host_readw(s+28) != 1) return; // biBitCount width = host_readd(s+18); height = host_readd(s+22); if (width > (640-x) || height > (200-y)) return; LOG(LOG_MISC,LOG_DEBUG)("Drawing CGA logo (%u x %u)",(int)width,(int)height); for (dy=0;dy < height;dy++) { uint32_t vram = ((y+dy) >> 1) * 80; vram += ((y+dy) & 1) * 0x2000; vram += (x / 8); s = dosbox_cga640_bmp + off + ((height-(dy+1))*((width+7)/8)); for (dx=0;dx < width;dx += 8) { mem_writeb(0xB8000+vram,*s); vram++; s++; } } } /* HACK: Re-use the VGA logo */ void DrawDOSBoxLogoPC98(unsigned int x,unsigned int y) { const unsigned char *s = dosbox_vga16_bmp; const unsigned char *sf = s + sizeof(dosbox_vga16_bmp); unsigned int bit,dx,dy; uint32_t width,height; unsigned char p[4]; unsigned char c; uint32_t off; uint32_t sz; if (memcmp(s,"BM",2)) return; sz = host_readd(s+2); // size of total bitmap off = host_readd(s+10); // offset of bitmap if ((s+sz) > sf) return; if ((s+14+40) > sf) return; sz = host_readd(s+34); // biSize if ((s+off+sz) > sf) return; if (host_readw(s+26) != 1) return; // biBitPlanes if (host_readw(s+28) != 4) return; // biBitCount width = host_readd(s+18); height = host_readd(s+22); if (width > (640-x) || height > (350-y)) return; // EGA/VGA Write Mode 2 LOG(LOG_MISC,LOG_DEBUG)("Drawing VGA logo as PC-98 (%u x %u)",(int)width,(int)height); for (dy=0;dy < height;dy++) { uint32_t vram = ((y+dy) * 80) + (x / 8); s = dosbox_vga16_bmp + off + ((height-(dy+1))*((width+1)/2)); for (dx=0;dx < width;dx += 8) { p[0] = p[1] = p[2] = p[3] = 0; for (bit=0;bit < 8;) { c = (*s >> 4); p[0] |= ((c >> 0) & 1) << (7 - bit); p[1] |= ((c >> 1) & 1) << (7 - bit); p[2] |= ((c >> 2) & 1) << (7 - bit); p[3] |= ((c >> 3) & 1) << (7 - bit); bit++; c = (*s++) & 0xF; p[0] |= ((c >> 0) & 1) << (7 - bit); p[1] |= ((c >> 1) & 1) << (7 - bit); p[2] |= ((c >> 2) & 1) << (7 - bit); p[3] |= ((c >> 3) & 1) << (7 - bit); bit++; } mem_writeb(0xA8000+vram,p[0]); mem_writeb(0xB0000+vram,p[1]); mem_writeb(0xB8000+vram,p[2]); mem_writeb(0xE0000+vram,p[3]); vram++; } } } void DrawDOSBoxLogoVGA(unsigned int x,unsigned int y) { const unsigned char *s = dosbox_vga16_bmp; const unsigned char *sf = s + sizeof(dosbox_vga16_bmp); unsigned int bit,dx,dy; uint32_t width,height; uint32_t vram; uint32_t off; uint32_t sz; if (memcmp(s,"BM",2)) return; sz = host_readd(s+2); // size of total bitmap off = host_readd(s+10); // offset of bitmap if ((s+sz) > sf) return; if ((s+14+40) > sf) return; sz = host_readd(s+34); // biSize if ((s+off+sz) > sf) return; if (host_readw(s+26) != 1) return; // biBitPlanes if (host_readw(s+28) != 4) return; // biBitCount width = host_readd(s+18); height = host_readd(s+22); if (width > (640-x) || height > (350-y)) return; // EGA/VGA Write Mode 2 LOG(LOG_MISC,LOG_DEBUG)("Drawing VGA logo (%u x %u)",(int)width,(int)height); IO_Write(0x3CE,0x05); // graphics mode IO_Write(0x3CF,0x02); // read=0 write=2 odd/even=0 shift=0 shift256=0 IO_Write(0x3CE,0x03); // data rotate IO_Write(0x3CE,0x00); // no rotate, no XOP for (bit=0;bit < 8;bit++) { const unsigned char shf = ((bit & 1) ^ 1) * 4; IO_Write(0x3CE,0x08); // bit mask IO_Write(0x3CF,0x80 >> bit); for (dy=0;dy < height;dy++) { vram = ((y+dy) * 80) + (x / 8); s = dosbox_vga16_bmp + off + (bit/2) + ((height-(dy+1))*((width+1)/2)); for (dx=bit;dx < width;dx += 8) { mem_readb(0xA0000+vram); // load VGA latches mem_writeb(0xA0000+vram,(*s >> shf) & 0xF); vram++; s += 4; } } } // restore write mode 0 IO_Write(0x3CE,0x05); // graphics mode IO_Write(0x3CF,0x00); // read=0 write=0 odd/even=0 shift=0 shift256=0 IO_Write(0x3CE,0x08); // bit mask IO_Write(0x3CF,0xFF); } static int bios_pc98_posx = 0; extern bool tooutttf; static void BIOS_Int10RightJustifiedPrint(const int x,int &y,const char *msg, bool boxdraw = false, bool tobold = false) { if (tooutttf) { tooutttf = false; change_output(10); } if (control->opt_fastlaunch) return; const char *s = msg; if (machine != MCH_PC98) { unsigned int bold = 0; while (*s != 0) { if (*s == '\n') { y++; reg_eax = 0x0200u; // set cursor pos reg_ebx = 0; // page zero reg_dh = y; // row 4 reg_dl = x; // column 20 CALLBACK_RunRealInt(0x10); s++; } else { if (tobold&&!bold) { if ((strlen(s)>3&&!strncmp(s, "DEL", 3))||!strncmp(s, "ESC", 3)) bold = 3; else if (strlen(s)>5&&!strncmp(s, "ENTER", 5)) bold = 5; else if (strlen(s)>8&&!strncmp(s, "SPACEBAR", 8)) bold = 8; } if (bold>0) { bold--; reg_eax = 0x0900u | ((unsigned char)(*s++)); reg_ebx = 0x000fu; reg_ecx = 0x0001u; CALLBACK_RunRealInt(0x10); reg_eax = 0x0300u; reg_ebx = 0x0000u; CALLBACK_RunRealInt(0x10); reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx++; CALLBACK_RunRealInt(0x10); } else { reg_eax = 0x0E00u | ((unsigned char)(*s++)); reg_ebx = 0x07u; } CALLBACK_RunRealInt(0x10); } } } else { unsigned int bo; while (*s != 0) { if (*s == '\n') { y++; s++; bios_pc98_posx = x; bo = (((unsigned int)y * 80u) + (unsigned int)bios_pc98_posx) * 2u; } else if (*s == '\r') { s++; /* ignore */ continue; } else { bo = (((unsigned int)y * 80u) + (unsigned int)(bios_pc98_posx++)) * 2u; /* NTS: note the post increment */ if (boxdraw) { unsigned int ch = (unsigned char)*s; if (ch==0xcd) ch = 0x250B; else if (ch==0xba) ch = 0x270B; else if (ch==0xc9) ch = 0x330B; else if (ch==0xbb) ch = 0x370B; else if (ch==0xc8) ch = 0x3B0B; else if (ch==0xbc) ch = 0x3F0B; mem_writew(0xA0000+bo,ch); } else mem_writew(0xA0000+bo,(unsigned char)*s); mem_writeb(0xA2000+bo,0xE1); s++; bo += 2; /* and keep the cursor following the text */ } reg_eax = 0x1300; // set cursor pos (PC-98) reg_edx = bo; // byte position CALLBACK_RunRealInt(0x18); } } } char *getSetupLine(const char *capt, const char *cont) { unsigned int pad1=(unsigned int)(25-strlen(capt)), pad2=(unsigned int)(41-strlen(cont)); static char line[90]; sprintf(line, "\x0ba%*c%s%*c%s%*c\x0ba", 12, ' ', capt, pad1, ' ', cont, pad2, ' '); return line; } const char *GetCPUType(); void updateDateTime(int x, int y, int pos) { (void)x;//UNUSED (void)y;//UNUSED char str[50]; time_t curtime = time(NULL); struct tm *loctime = localtime (&curtime); Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * mem_readd(BIOS_TIMER))/100; unsigned int sec=(uint8_t)((Bitu)time % 60); time/=60; unsigned int min=(uint8_t)((Bitu)time % 60); time/=60; unsigned int hour=(uint8_t)((Bitu)time % 24); int val=0; unsigned int bo; Bitu edx=0, pdx=0x0500u; for (int i=1; i<7; i++) { switch (i) { case 1: val = machine==MCH_PC98?loctime->tm_year+1900:dos.date.year; reg_edx = 0x0326u; if (i==pos) pdx = reg_edx; break; case 2: val = machine==MCH_PC98?loctime->tm_mon+1:dos.date.month; reg_edx = 0x032bu; if (i==pos) pdx = reg_edx; break; case 3: val = machine==MCH_PC98?loctime->tm_mday:dos.date.day; reg_edx = 0x032eu; if (i==pos) pdx = reg_edx; break; case 4: val = machine==MCH_PC98?loctime->tm_hour:hour; reg_edx = 0x0426u; if (i==pos) pdx = reg_edx; break; case 5: val = machine==MCH_PC98?loctime->tm_min:min; reg_edx = 0x0429u; if (i==pos) pdx = reg_edx; break; case 6: val = machine==MCH_PC98?loctime->tm_sec:sec; reg_edx = 0x042cu; if (i==pos) pdx = reg_edx; break; } edx = reg_edx; sprintf(str, i==1?"%04u":"%02u",val); for (unsigned int j=0; j<strlen(str); j++) { if (machine == MCH_PC98) { bo = (((unsigned int)(edx/0x100) * 80u) + (unsigned int)(edx%0x100) + j) * 2u; mem_writew(0xA0000+bo,str[j]); mem_writeb(0xA2000+bo,0xE1); } else { reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx = edx + j; CALLBACK_RunRealInt(0x10); reg_eax = 0x0900u+str[j]; reg_ebx = i==pos?0x001fu:0x001eu; reg_ecx = 0x0001u; CALLBACK_RunRealInt(0x10); } } } if (pos) { sprintf(str, "%-30s", GetCPUType()); for (unsigned int j=0; j<strlen(str); j++) { if (machine == MCH_PC98) { bo = ((0x0F * 80u) + (unsigned int)(0x26 + j)) * 2u; mem_writew(0xA0000+bo,str[j]); mem_writeb(0xA2000+bo,0xE1); } else { reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx = 0x0F26u + j; CALLBACK_RunRealInt(0x10); reg_eax = 0x0900u+str[j]; reg_ebx = 0x001eu; reg_ecx = 0x0001u; CALLBACK_RunRealInt(0x10); } } sprintf(str, "%-30s", (std::to_string(CPU_CycleAutoAdjust?CPU_CyclePercUsed:CPU_CycleMax)+(CPU_CycleAutoAdjust?"%":" cycles/ms")).c_str()); for (unsigned int j=0; j<strlen(str); j++) { if (machine == MCH_PC98) { bo = ((0x10 * 80u) + (unsigned int)(0x26 + j)) * 2u; mem_writew(0xA0000+bo,str[j]); mem_writeb(0xA2000+bo,0xE1); } else { reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx = 0x1026u + j; CALLBACK_RunRealInt(0x10); reg_eax = 0x0900u+str[j]; reg_ebx = 0x001eu; reg_ecx = 0x0001u; CALLBACK_RunRealInt(0x10); } } } if (machine == MCH_PC98) { reg_eax = 0x1300; reg_edx = 0x1826; CALLBACK_RunRealInt(0x18); } else { reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx = pdx; CALLBACK_RunRealInt(0x10); } } int oldcols = 0, oldlins = 0; void showBIOSSetup(const char* card, int x, int y) { reg_eax = 3; // 80x25 text CALLBACK_RunRealInt(0x10); if (machine == MCH_PC98) { for (unsigned int i=0;i < (80*400);i++) { mem_writeb(0xA8000+i,0); // B mem_writeb(0xB0000+i,0); // G mem_writeb(0xB8000+i,0); // R mem_writeb(0xE0000+i,0); // E } reg_eax = 0x1600; reg_edx = 0xE100; CALLBACK_RunRealInt(0x18); reg_eax = 0x1300; reg_edx = 0x0000; CALLBACK_RunRealInt(0x18); x = 0; y = 0; } else { reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx = 0x0000u; CALLBACK_RunRealInt(0x10); reg_eax = 0x0600u; reg_ebx = 0x1e00u; reg_ecx = 0x0000u; reg_edx = #if defined(USE_TTF) TTF_using()?(ttf.lins-1)*0x100+(ttf.cols-1): #endif 0x184Fu; CALLBACK_RunRealInt(0x10); } #if defined(USE_TTF) if (TTF_using() && (ttf.cols != 80 || ttf.lins != 25)) ttf_setlines(80, 25); #endif char title[]=" BIOS Setup Utility "; char *p=machine == MCH_PC98?title+2:title; BIOS_Int10RightJustifiedPrint(x,y,p); BIOS_Int10RightJustifiedPrint(x,y,"\x0c9\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0bb", true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("System date:", "0000-00-00"), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("System time:", "00:00:00"), true); updateDateTime(x,y,0); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Installed OS:", "DOS"), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); #define DOSNAMEBUF 256 char pcname[DOSNAMEBUF]; if (control->opt_securemode || control->SecureMode()) strcpy(pcname, "N/A"); else { #if defined(WIN32) DWORD size = DOSNAMEBUF; GetComputerName(pcname, &size); if (!size) #else int result = gethostname(pcname, DOSNAMEBUF); if (result) #endif strcpy(pcname, "N/A"); } BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Computer name:", pcname), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Product name:", ("DOSBox-X "+std::string(VERSION)).c_str()), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Product updated:", UPDATED_STR), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS description:", bios_type_string), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS version:", bios_version_string), true); uint32_t year,month,day; if (sscanf(bios_date_string,"%u/%u/%u",&month,&day,&year)==3) { char datestr[30]; sprintf(datestr, "%04u-%02u-%02u",year<80?2000+year:(year<100?1900+year:year),month,day); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS date:", datestr), true); } else BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS date:", bios_date_string), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Processor type:", GetCPUType()), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Processor speed:", (std::to_string(CPU_CycleAutoAdjust?CPU_CyclePercUsed:CPU_CycleMax)+(CPU_CycleAutoAdjust?"%":" cycles/ms")).c_str()), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Coprocessor:", enable_fpu?"Yes":"No"), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Video card:", card), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Video memory:", (std::to_string(vga.mem.memsize/1024)+"K").c_str()), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Total memory:", (std::to_string(MEM_TotalPages()*4096/1024)+"K").c_str()), true); BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); BIOS_Int10RightJustifiedPrint(x,y,"\x0c8\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0bc", true); if (machine == MCH_PC98) BIOS_Int10RightJustifiedPrint(x,y," ESC = Exit "); else BIOS_Int10RightJustifiedPrint(x,y," ESC: Exit Arrows: Select Item +/-: Change Values "); } static Bitu ulimit = 0; static Bitu t_conv = 0; static Bitu t_conv_real = 0; static bool bios_first_init=true; static bool bios_has_exec_vga_bios=false; static Bitu adapter_scan_start; /* FIXME: At global scope their destructors are called after the rest of DOSBox-X has shut down. Move back into BIOS scope. */ static CALLBACK_HandlerObject int4b_callback; static const size_t callback_count = 20; static CALLBACK_HandlerObject callback[callback_count]; /* <- fixme: this is stupid. just declare one per interrupt. */ static CALLBACK_HandlerObject cb_bios_post; static CALLBACK_HandlerObject callback_pc98_lio; Bitu call_pnp_r = ~0UL; Bitu call_pnp_rp = 0; Bitu call_pnp_p = ~0UL; Bitu call_pnp_pp = 0; Bitu isapnp_biosstruct_base = 0; Bitu BIOS_boot_code_offset = 0; Bitu BIOS_bootfail_code_offset = 0; bool bios_user_reset_vector_blob_run = false; Bitu bios_user_reset_vector_blob = 0; Bitu bios_user_boot_hook = 0; void CALLBACK_DeAllocate(Bitu in); void BIOS_OnResetComplete(Section *x); Bitu call_irq0 = 0; Bitu call_irq07default = 0; Bitu call_irq815default = 0; void write_FFFF_PC98_signature() { /* this may overwrite the existing signature. * PC-98 systems DO NOT have an ASCII date at F000:FFF5 * and the WORD value at F000:FFFE is said to be a checksum of the BIOS */ // The farjump at the processor reset entry point (jumps to POST routine) phys_writeb(0xffff0,0xEA); // FARJMP phys_writew(0xffff1,RealOff(BIOS_DEFAULT_RESET_LOCATION)); // offset phys_writew(0xffff3,RealSeg(BIOS_DEFAULT_RESET_LOCATION)); // segment // write nothing (not used) for(Bitu i = 0; i < 9; i++) phys_writeb(0xffff5+i,0); // fake BIOS checksum phys_writew(0xffffe,0xABCD); } void gdc_egc_enable_update_vars(void) { unsigned char b; b = mem_readb(0x54D); b &= ~0x40; if (enable_pc98_egc) b |= 0x40; mem_writeb(0x54D,b); b = mem_readb(0x597); b &= ~0x04; if (enable_pc98_egc) b |= 0x04; mem_writeb(0x597,b); if (!enable_pc98_egc) pc98_gdc_vramop &= ~(1 << VOPBIT_EGC); } void gdc_grcg_enable_update_vars(void) { unsigned char b; b = mem_readb(0x54C); b &= ~0x02; if (enable_pc98_grcg) b |= 0x02; mem_writeb(0x54C,b); //TODO: How to reset GRCG? } void gdc_16color_enable_update_vars(void) { unsigned char b; b = mem_readb(0x54C); b &= ~0x04; if (enable_pc98_16color) b |= 0x04; mem_writeb(0x54C,b); if(!enable_pc98_256color) {//force switch to 16-colors mode void pc98_port6A_command_write(unsigned char b); pc98_port6A_command_write(0x20); } if(!enable_pc98_16color) {//force switch to 8-colors mode void pc98_port6A_command_write(unsigned char b); pc98_port6A_command_write(0x00); } } uint32_t BIOS_get_PC98_INT_STUB(void) { return callback[18].Get_RealPointer(); } Bitu call_pc98_default_stop; extern bool DOS_BreakFlag; extern bool DOS_BreakConioFlag; static Bitu pc98_default_stop_handler(void) { // INT 06h, which means someone pressed the STOP key... or the CPU is signalling an invalid opcode. // The overlap makes it extremely unclear. LOG_MSG("Invalid opcode or unhandled PC-98 STOP key interrupt 06h"); // try to make it work as CTRL+BREAK in the built-in DOS environment. if (!dos_kernel_disabled) DOS_BreakFlag = DOS_BreakConioFlag = true; return CBRET_NONE; } /* NTS: Remember the 8259 is non-sentient, and the term "slave" is used in a computer programming context */ static Bitu Default_IRQ_Handler_Cooperative_Slave_Pic(void) { /* PC-98 style IRQ 8-15 handling. * * This mimics the recommended procedure [https://www.webtech.co.jp/company/doc/undocumented_mem/io_pic.txt] * * mov al,20h ;Send EOI to SLAVE * out 0008h,al * jmp $+2 ;I/O WAIT * mov al,0Bh ;ISR read mode set(slave) * out 0008h,al * jmp $+2 ;I/O WAIT * in al,0008h ;ISR read(slave) * cmp al,00h ;slave pic in-service ? * jne EoiEnd * mov al,20h ;Send EOI to MASTER * out 0000h,al */ IO_WriteB(IS_PC98_ARCH ? 0x08 : 0xA0,0x20); // send EOI to slave IO_WriteB(IS_PC98_ARCH ? 0x08 : 0xA0,0x0B); // ISR read mode set if (IO_ReadB(IS_PC98_ARCH ? 0x08 : 0xA0) == 0) // if slave pic in service.. IO_WriteB(IS_PC98_ARCH ? 0x00 : 0x20,0x20); // then EOI the master return CBRET_NONE; } extern uint32_t tandy_128kbase; static int bios_post_counter = 0; class BIOS:public Module_base{ private: static Bitu cb_bios_post__func(void) { void TIMER_BIOS_INIT_Configure(); #if C_DEBUG void DEBUG_CheckCSIP(); # if C_HEAVY_DEBUG /* the game/app obviously crashed, which is way more important * to log than what we do here in the BIOS at POST */ void DEBUG_StopLog(void); DEBUG_StopLog(); # endif #endif { Section_prop * section=static_cast<Section_prop *>(control->GetSection("dosbox")); int val = section->Get_int("reboot delay"); if (val < 0) val = IS_PC98_ARCH ? 1000 : 500; reset_post_delay = (unsigned int)val; } if (bios_post_counter != 0 && reset_post_delay != 0) { /* reboot delay, in case the guest OS/application had something to day before hitting the "reset" signal */ uint32_t lasttick=GetTicks(); while ((GetTicks()-lasttick) < reset_post_delay) { void CALLBACK_IdleNoInts(void); CALLBACK_IdleNoInts(); } } if (bios_post_counter != 0) { /* turn off the PC speaker if the guest left it on at reset */ if (IS_PC98_ARCH) { IO_Write(0x37,0x07); } else { IO_Write(0x61,IO_Read(0x61) & (~3u)); } } bios_post_counter++; if (bios_first_init) { /* clear the first 1KB-32KB */ for (uint16_t i=0x400;i<0x8000;i++) real_writeb(0x0,i,0); } if (IS_PC98_ARCH) { for (unsigned int i=0;i < callback_count;i++) callback[i].Uninstall(); /* clear out 0x50 segment (TODO: 0x40 too?) */ for (unsigned int i=0;i < 0x100;i++) phys_writeb(0x500+i,0); write_FFFF_PC98_signature(); BIOS_ZeroExtendedSize(false); if (call_pc98_default_stop == 0) call_pc98_default_stop = CALLBACK_Allocate(); CALLBACK_Setup(call_pc98_default_stop,&pc98_default_stop_handler,CB_IRET,"INT 6h invalid opcode or STOP interrupt"); unsigned char memsize_real_code = 0; Bitu mempages = MEM_TotalPages(); /* in 4KB pages */ /* NTS: Fill in the 3-bit code in FLAGS1 that represents * how much lower conventional memory is in the system. * * Note that MEM.EXE requires this value, or else it * will complain about broken UMB linkage and fail * to show anything else. */ /* TODO: In the event we eventually support "high resolution mode" * we can indicate 768KB here, code == 5, meaning that * the RAM extends up to 0xBFFFF instead of 0x9FFFF */ if (mempages >= (640UL/4UL)) /* 640KB */ memsize_real_code = 4; else if (mempages >= (512UL/4UL)) /* 512KB */ memsize_real_code = 3; else if (mempages >= (384UL/4UL)) /* 384KB */ memsize_real_code = 2; else if (mempages >= (256UL/4UL)) /* 256KB */ memsize_real_code = 1; else /* 128KB */ memsize_real_code = 0; void pc98_msw3_set_ramsize(const unsigned char b); pc98_msw3_set_ramsize(memsize_real_code); /* CRT status */ /* bit[7:6] = 00=conventional compatible 01=extended attr JEH 10=extended attr EGH * bit[5:5] = Single event timer in use flag 1=busy 0=not used * bit[4:4] = ? * bit[3:3] = raster scan 1=non-interlaced 0=interlaced * bit[2:2] = Content ruled line color 1=I/O set value 0=attributes of VRAM * bit[1:1] = ? * bit[0:0] = 480-line mode 1=640x480 0=640x400 or 640x200 */ mem_writeb(0x459,0x08/*non-interlaced*/); /* CPU/Display */ /* bit[7:7] = 486SX equivalent (?) 1=yes * bit[6:6] = PC-9821 Extended Graph Architecture supported (FIXME: Is this the same as having EGC?) 1=yes * bit[5:5] = LCD display is color 1=yes 0=no * bit[4:4] = ? * bit[3:3] = ROM drive allow writing * bit[2:2] = 98 NOTE PC-9801N-08 expansion I/O box connected * bit[1:1] = 98 NOTE prohibit transition to power saving mode * bit[0:0] = 98 NOTE coprocessor function available */ mem_writeb(0x45C,(enable_pc98_egc ? 0x40/*Extended Graphics*/ : 0x00)); /* Keyboard type */ /* bit[7:7] = ? * bit[6:6] = keyboard type bit 1 * bit[5:5] = EMS page frame at B0000h 1=present 0=none * bit[4:4] = EMS page frame at B0000h 1=page frame 0=G-VRAM * bit[3:3] = keyboard type bit 0 * bit[2:2] = High resolution memory window available * bit[1:1] = ? * bit[0:0] = ? * * keyboard bits[1:0] from bit 6 as bit 1 and bit 3 as bit 0 combined: * 11 = new keyboard (NUM key, DIP switch 2-7 OFF) * 10 = new keyboard (without NUM key) * 01 = new keyboard (NUM key, DIP switch 2-7 ON) * 00 = old keyboard * * The old keyboard is documented not to support software control of CAPS and KANA states */ /* TODO: Make this a dosbox-x.conf option. Default is new keyboard without NUM key because that is * what keyboard emulation currently acts like anyway. */ mem_writeb(0x481,0x40/*bit 6=1 bit 3=0 new keyboard without NUM key*/); /* BIOS flags */ /* bit[7:7] = Startup 1=hot start 0=cold start * bit[6:6] = BASIC type ?? * bit[5:5] = Keyboard beep 1=don't beep 0=beep ... when buffer full * bit[4:4] = Expansion conv RAM 1=present 0=absent * bit[3:3] = ?? * bit[2:2] = ?? * bit[1:1] = HD mode 1=1MB mode 0=640KB mode ... of the floppy drive * bit[0:0] = Model 1=other 0=PC-9801 original */ /* NTS: MS-DOS 5.0 appears to reduce it's BIOS calls and render the whole * console as green IF bit 0 is clear. * * If bit 0 is set, INT 1Ah will be hooked by MS-DOS and, for some odd reason, * MS-DOS's hook proc will call to our INT 1Ah + 0x19 bytes. */ mem_writeb(0x500,0x01 | 0x02/*high density drive*/); /* BIOS flags */ /* timer setup will set/clear bit 7 */ /* bit[7:7] = system clock freq 1=8MHz 0=5/10Mhz * = timer clock freq 1=1.9968MHz 0=2.4576MHz * bit[6:6] = CPU 1=V30 0=Intel (8086 through Pentium) * bit[5:5] = Model info 1=Other model 0=PC-9801 Muji, PC-98XA * bit[4:4] = Model info ... * bit[3:3] = Model info 1=High res 0=normal * bit[2:0] = Realmode memsize * 000=128KB 001=256KB * 010=384KB 011=512KB * 100=640KB 101=768KB * * Ref: http://hackipedia.org/browse/Computer/Platform/PC,%20NEC%20PC-98/Collections/Undocumented%209801,%209821%20Volume%202%20(webtech.co.jp)/memsys.txt */ /* NTS: High resolution means 640x400, not the 1120x750 mode known as super high resolution mode. * DOSBox-X does not yet emulate super high resolution nor does it emulate the 15khz 200-line "standard" mode. * ref: https://github.com/joncampbell123/dosbox-x/issues/906#issuecomment-434513930 * ref: https://jisho.org/search?utf8=%E2%9C%93&keyword=%E8%B6%85 */ mem_writeb(0x501,0x20 | memsize_real_code); /* keyboard buffer */ mem_writew(0x524/*tail*/,0x502); mem_writew(0x526/*tail*/,0x502); /* number of scanlines per text row - 1 */ mem_writeb(0x53B,0x0F); // CRT_RASTER, 640x400 24.83KHz-hsync 56.42Hz-vsync /* Text screen status. * Note that most of the bits are used verbatim in INT 18h AH=0Ah/AH=0Bh */ /* bit[7:7] = High resolution display 1=yes 0=no (standard) NOT super high res * bit[6:6] = vsync 1=VSYNC wait 0=end of vsync handling * bit[5:5] = unused * bit[4:4] = Number of lines 1=30 lines 0=20/25 lines * bit[3:3] = K-CG access mode 1=dot access 0=code access * bit[2:2] = Attribute mode (how to handle bit 4) 1=Simp. graphic 0=Vertical line * bit[1:1] = Number of columns 1=40 cols 0=80 cols * bit[0:0] = Number of lines 1=20/30 lines 0=25 lines */ mem_writeb(0x53C,(true/*TODO*/ ? 0x80/*high res*/ : 0x00/*standard*/)); /* BIOS raster location */ mem_writew(0x54A,0x1900); /* BIOS flags */ /* bit[7:7] = Graphics display state 1=Visible 0=Blanked (hidden) * bit[6:6] = CRT type 1=high res 0=standard NOT super high res * bit[5:5] = Horizontal sync rate 1=31.47KHz 0=24.83KHz * bit[4:4] = CRT line mode 1=480-line 0=400-line * bit[3:3] = Number of user-defined characters 1=188+ 0=63 * bit[2:2] = Extended graphics RAM (for 16-color) 1=present 0=absent * bit[1:1] = Graphics Charger is present 1=present 0=absent * bit[0:0] = DIP switch 1-8 at startup 1=ON 0=OFF (?) */ mem_writeb(0x54C,(true/*TODO*/ ? 0x40/*high res*/ : 0x00/*standard*/) | (enable_pc98_grcg ? 0x02 : 0x00) | (enable_pc98_16color ? 0x04 : 0x00) | (pc98_31khz_mode ? 0x20/*31khz*/ : 0x00/*24khz*/) | (enable_pc98_188usermod ? 0x08 : 0x00)); // PRXCRT, 16-color G-VRAM, GRCG /* BIOS flags */ /* bit[7:7] = 256-color board present (PC-H98) * bit[6:6] = Enhanced Graphics Charger (EGC) is present * bit[5:5] = GDC at 5.0MHz at boot up (copy of DIP switch 2-8 at startup) 1=yes 0=no * bit[4:4] = Always "flickerless" drawing mode * bit[3:3] = Drawing mode with flicker * bit[2:2] = GDC clock 1=5MHz 0=2.5MHz * bit[1:0] = Drawing mode of the GDC * 00 = REPLACE * 01 = COMPLEMENT * 10 = CLEAR * 11 = SET */ mem_writeb(0x54D, (enable_pc98_256color ? 0x80 : 0x00) | (enable_pc98_egc ? 0x40 : 0x00) | (gdc_5mhz_mode ? 0x20 : 0x00) | (gdc_5mhz_mode ? 0x04 : 0x00)); // EGC /* BIOS flags */ /* bit[7:7] = INT 18h AH=30h/31h support enabled * bit[6:3] = 0 (unused) * bit[2:2] = Enhanced Graphics Mode (EGC) supported * bit[1:0] = Graphic resolution * 00 = 640x200 upper half (2/8/16-color mode) * 01 = 640x200 lower half (2/8/16-color mode) * 10 = 640x400 (2/8/16/256-color mode) * 11 = 640x480 256-color mode */ mem_writeb(0x597,(enable_pc98_egc ? 0x04 : 0x00)/*EGC*/ | (enable_pc98_egc ? 0x80 : 0x00)/*supports INT 18h AH=30h and AH=31h*/ | 2/*640x400*/); /* TODO: I would like to eventually add a dosbox-x.conf option that controls whether INT 18h AH=30h and 31h * are enabled, so that retro-development can test code to see how it acts on a newer PC-9821 * that supports it vs an older PC-9821 that doesn't. * * If the user doesn't set the option, then it is "auto" and determined by machine= PC-98 model and * by another option in dosbox-x.conf that determines whether 31khz support is enabled. * * NOTED: Neko Project II determines INT 18h AH=30h availability by whether or not it was compiled * with 31khz hsync support (SUPPORT_CRT31KHZ) */ } if (bios_user_reset_vector_blob != 0 && !bios_user_reset_vector_blob_run) { LOG_MSG("BIOS POST: Running user reset vector blob at 0x%lx",(unsigned long)bios_user_reset_vector_blob); bios_user_reset_vector_blob_run = true; assert((bios_user_reset_vector_blob&0xF) == 0); /* must be page aligned */ SegSet16(cs,bios_user_reset_vector_blob>>4); reg_eip = 0; #if C_DEBUG /* help the debugger reflect the new instruction pointer */ DEBUG_CheckCSIP(); #endif return CBRET_NONE; } if (cpu.pmode) E_Exit("BIOS error: POST function called while in protected/vm86 mode"); CPU_CLI(); /* we need A20 enabled for BIOS boot-up */ void A20Gate_OverrideOn(Section *sec); void MEM_A20_Enable(bool enabled); A20Gate_OverrideOn(NULL); MEM_A20_Enable(true); BIOS_OnResetComplete(NULL); adapter_scan_start = 0xC0000; bios_has_exec_vga_bios = false; LOG(LOG_MISC,LOG_DEBUG)("BIOS: executing POST routine"); // TODO: Anything we can test in the CPU here? // initialize registers SegSet16(ds,0x0000); SegSet16(es,0x0000); SegSet16(fs,0x0000); SegSet16(gs,0x0000); SegSet16(ss,0x0000); { Bitu sz = MEM_TotalPages(); /* The standard BIOS is said to put it's stack (at least at OS boot time) 512 bytes past the end of the boot sector * meaning that the boot sector loads to 0000:7C00 and the stack is set grow downward from 0000:8000 */ if (sz > 8) sz = 8; /* 4KB * 8 = 32KB = 0x8000 */ sz *= 4096; reg_esp = sz - 4; reg_ebp = 0; LOG(LOG_MISC,LOG_DEBUG)("BIOS: POST stack set to 0000:%04x",reg_esp); } if (dosbox_int_iocallout != IO_Callout_t_none) { IO_FreeCallout(dosbox_int_iocallout); dosbox_int_iocallout = IO_Callout_t_none; } if (isapnp_biosstruct_base != 0) { ROMBIOS_FreeMemory(isapnp_biosstruct_base); isapnp_biosstruct_base = 0; } if (BOCHS_PORT_E9) { delete BOCHS_PORT_E9; BOCHS_PORT_E9=NULL; } if (ISAPNP_PNP_ADDRESS_PORT) { delete ISAPNP_PNP_ADDRESS_PORT; ISAPNP_PNP_ADDRESS_PORT=NULL; } if (ISAPNP_PNP_DATA_PORT) { delete ISAPNP_PNP_DATA_PORT; ISAPNP_PNP_DATA_PORT=NULL; } if (ISAPNP_PNP_READ_PORT) { delete ISAPNP_PNP_READ_PORT; ISAPNP_PNP_READ_PORT=NULL; } if (bochs_port_e9) { if (BOCHS_PORT_E9 == NULL) { BOCHS_PORT_E9 = new IO_WriteHandleObject; BOCHS_PORT_E9->Install(0xE9,bochs_port_e9_write,IO_MB); } LOG(LOG_MISC,LOG_DEBUG)("Bochs port E9h emulation is active"); } else { if (BOCHS_PORT_E9 != NULL) { delete BOCHS_PORT_E9; BOCHS_PORT_E9 = NULL; } } extern Bitu call_default; if (IS_PC98_ARCH) { /* INT 00h-FFh generic stub routine */ /* NTS: MS-DOS on PC-98 will fill all yet-unused interrupt vectors with a stub. * No vector is left at 0000:0000. On a related note, PC-98 games apparently * like to call INT 33h (mouse functions) without first checking that the * vector is non-null. */ callback[18].Uninstall(); callback[18].Install(&INTGEN_PC98_Handler,CB_IRET,"Int stub ???"); for (unsigned int i=0x00;i < 0x100;i++) RealSetVec(i,callback[18].Get_RealPointer()); for (unsigned int i=0x00;i < 0x08;i++) real_writed(0,i*4,CALLBACK_RealPointer(call_default)); // STOP interrupt or invalid opcode real_writed(0,0x06*4,CALLBACK_RealPointer(call_pc98_default_stop)); } else { /* Clear the vector table */ for (uint16_t i=0x70*4;i<0x400;i++) real_writeb(0x00,i,0); /* Only setup default handler for first part of interrupt table */ for (uint16_t ct=0;ct<0x60;ct++) { real_writed(0,ct*4,CALLBACK_RealPointer(call_default)); } for (uint16_t ct=0x68;ct<0x70;ct++) { if(!IS_J3100 || ct != 0x6f) real_writed(0,ct*4,CALLBACK_RealPointer(call_default)); } // default handler for IRQ 2-7 for (uint16_t ct=0x0A;ct <= 0x0F;ct++) RealSetVec(ct,BIOS_DEFAULT_IRQ07_DEF_LOCATION); } if (unhandled_irq_method == UNHANDLED_IRQ_COOPERATIVE_2ND) { // PC-98 style: Master PIC ack with 0x20 for IRQ 0-7. // For the slave PIC, ack with 0x20 on the slave, then only ack the master (cascade interrupt) // if the ISR register on the slave indicates none are in service. CALLBACK_Setup(call_irq07default,NULL,CB_IRET_EOI_PIC1,Real2Phys(BIOS_DEFAULT_IRQ07_DEF_LOCATION),"bios irq 0-7 default handler"); CALLBACK_Setup(call_irq815default,Default_IRQ_Handler_Cooperative_Slave_Pic,CB_IRET,Real2Phys(BIOS_DEFAULT_IRQ815_DEF_LOCATION),"bios irq 8-15 default handler"); } else { // IBM PC style: Master PIC ack with 0x20, slave PIC ack with 0x20, no checking CALLBACK_Setup(call_irq07default,NULL,CB_IRET_EOI_PIC1,Real2Phys(BIOS_DEFAULT_IRQ07_DEF_LOCATION),"bios irq 0-7 default handler"); CALLBACK_Setup(call_irq815default,NULL,CB_IRET_EOI_PIC2,Real2Phys(BIOS_DEFAULT_IRQ815_DEF_LOCATION),"bios irq 8-15 default handler"); } if (IS_PC98_ARCH) { BIOS_UnsetupKeyboard(); BIOS_UnsetupDisks(); /* no such INT 4Bh */ int4b_callback.Uninstall(); /* remove some IBM-style BIOS interrupts that don't exist on PC-98 */ /* IRQ to INT arrangement * * IBM PC-98 IRQ * -------------------------------- * 0x08 0x08 0 * 0x09 0x09 1 * 0x0A CASCADE 0x0A 2 * 0x0B 0x0B 3 * 0x0C 0x0C 4 * 0x0D 0x0D 5 * 0x0E 0x0E 6 * 0x0F 0x0F CASCADE 7 * 0x70 0x10 8 * 0x71 0x11 9 * 0x72 0x12 10 * 0x73 0x13 11 * 0x74 0x14 12 * 0x75 0x15 13 * 0x76 0x16 14 * 0x77 0x17 15 * * As part of the change the IRQ cascade emulation needs to change for PC-98 as well. * IBM uses IRQ 2 for cascade. * PC-98 uses IRQ 7 for cascade. */ void INT10_EnterPC98(Section *sec); INT10_EnterPC98(NULL); /* INT 10h */ callback_pc98_lio.Uninstall(); callback[1].Uninstall(); /* INT 11h */ callback[2].Uninstall(); /* INT 12h */ callback[3].Uninstall(); /* INT 14h */ callback[4].Uninstall(); /* INT 15h */ callback[5].Uninstall(); /* INT 17h */ callback[6].Uninstall(); /* INT 1Ah */ callback[7].Uninstall(); /* INT 1Ch */ callback[10].Uninstall(); /* INT 19h */ callback[11].Uninstall(); /* INT 76h: IDE IRQ 14 */ callback[12].Uninstall(); /* INT 77h: IDE IRQ 15 */ callback[15].Uninstall(); /* INT 18h: Enter BASIC */ callback[19].Uninstall(); /* INT 1Bh */ /* IRQ 6 is nothing special */ callback[13].Uninstall(); /* INT 0Eh: IDE IRQ 6 */ callback[13].Install(NULL,CB_IRET_EOI_PIC1,"irq 6"); /* IRQ 8 is nothing special */ callback[8].Uninstall(); callback[8].Install(NULL,CB_IRET_EOI_PIC2,"irq 8"); /* IRQ 9 is nothing special */ callback[9].Uninstall(); callback[9].Install(NULL,CB_IRET_EOI_PIC2,"irq 9"); /* INT 18h keyboard and video display functions */ callback[1].Install(&INT18_PC98_Handler,CB_INT16,"Int 18 keyboard and display"); callback[1].Set_RealVec(0x18,/*reinstall*/true); /* INT 19h *STUB* */ callback[2].Install(&INT19_PC98_Handler,CB_IRET,"Int 19 ???"); callback[2].Set_RealVec(0x19,/*reinstall*/true); /* INT 1Ah *STUB* */ callback[3].Install(&INT1A_PC98_Handler,CB_IRET,"Int 1A ???"); callback[3].Set_RealVec(0x1A,/*reinstall*/true); /* MS-DOS 5.0 FIXUP: * - For whatever reason, if we set bits in the BIOS data area that * indicate we're NOT the original model of the PC-98, MS-DOS will * hook our INT 1Ah and then call down to 0x19 bytes into our * INT 1Ah procedure. If anyone can explain this, I'd like to hear it. --J.C. * * NTS: On real hardware, the BIOS appears to have an INT 1Ah, a bunch of NOPs, * then at 0x19 bytes into the procedure, the actual handler. This is what * MS-DOS is pointing at. * * But wait, there's more. * * MS-DOS calldown pushes DS and DX onto the stack (after the IRET frame) * before JMPing into the BIOS. * * Apparently the function at INT 1Ah + 0x19 is expected to do this: * * <function code> * POP DX * POP DS * IRET * * I can only imaging what a headache this might have caused NEC when * maintaining the platform and compatibility! */ { Bitu addr = callback[3].Get_RealPointer(); addr = ((addr >> 16) << 4) + (addr & 0xFFFF); /* to make this work, we need to pop the two regs, then JMP to our * callback and proceed as normal. */ phys_writeb(addr + 0x19,0x5A); // POP DX phys_writeb(addr + 0x1A,0x1F); // POP DS phys_writeb(addr + 0x1B,0xEB); // jmp short ... phys_writeb(addr + 0x1C,0x100 - 0x1D); } /* INT 1Bh *STUB* */ callback[4].Install(&INT1B_PC98_Handler,CB_IRET,"Int 1B ???"); callback[4].Set_RealVec(0x1B,/*reinstall*/true); /* INT 1Ch *STUB* */ callback[5].Install(&INT1C_PC98_Handler,CB_IRET,"Int 1C ???"); callback[5].Set_RealVec(0x1C,/*reinstall*/true); /* INT 1Dh *STUB* */ /* Place it in the PC-98 int vector area at FD80:0000 to satisfy some DOS games * that detect PC-98 from the segment value of the vector (issue #927). * Note that on real hardware (PC-9821) INT 1Dh appears to be a stub that IRETs immediately. */ callback[6].Install(&INT1D_PC98_Handler,CB_IRET,"Int 1D ???"); // callback[6].Set_RealVec(0x1D,/*reinstall*/true); { Bitu ofs = 0xFD813; /* 0xFD80:0013 try not to look like a phony address */ unsigned int vec = 0x1D; uint32_t target = callback[6].Get_RealPointer(); phys_writeb(ofs+0,0xEA); // JMP FAR <callback> phys_writed(ofs+1,target); phys_writew((vec*4)+0,(ofs-0xFD800)); phys_writew((vec*4)+2,0xFD80); } /* INT 1Eh *STUB* */ callback[7].Install(&INT1E_PC98_Handler,CB_IRET,"Int 1E ???"); callback[7].Set_RealVec(0x1E,/*reinstall*/true); /* INT 1Fh *STUB* */ callback[10].Install(&INT1F_PC98_Handler,CB_IRET,"Int 1F ???"); callback[10].Set_RealVec(0x1F,/*reinstall*/true); /* INT DCh *STUB* */ callback[16].Install(&INTDC_PC98_Handler,CB_IRET,"Int DC ???"); callback[16].Set_RealVec(0xDC,/*reinstall*/true); /* INT F2h *STUB* */ callback[17].Install(&INTF2_PC98_Handler,CB_IRET,"Int F2 ???"); callback[17].Set_RealVec(0xF2,/*reinstall*/true); // default handler for IRQ 2-7 for (uint16_t ct=0x0A;ct <= 0x0F;ct++) RealSetVec(ct,BIOS_DEFAULT_IRQ07_DEF_LOCATION); // default handler for IRQ 8-15 for (uint16_t ct=0;ct < 8;ct++) RealSetVec(ct+(IS_PC98_ARCH ? 0x10 : 0x70),BIOS_DEFAULT_IRQ815_DEF_LOCATION); // LIO graphics interface (number of entry points, unknown WORD value and offset into the segment). // For more information see Chapter 6 of this PDF [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf] { callback_pc98_lio.Install(&PC98_BIOS_LIO,CB_IRET,"LIO graphics library"); Bitu ofs = 0xF990u << 4u; // F990:0000... unsigned int entrypoints = 0x11; Bitu final_addr = callback_pc98_lio.Get_RealPointer(); /* NTS: Based on GAME/MAZE 999 behavior, these numbers are interrupt vector numbers. * The entry point marked 0xA0 is copied by the game to interrupt vector A0 and * then called with INT A0h even though it blindly assumes the numbers are * sequential from 0xA0-0xAF. */ unsigned char entrypoint_indexes[0x11] = { 0xA0, 0xA1, 0xA2, 0xA3, // +0x00 0xA4, 0xA5, 0xA6, 0xA7, // +0x04 0xA8, 0xA9, 0xAA, 0xAB, // +0x08 0xAC, 0xAD, 0xAE, 0xAF, // +0x0C 0xCE // +0x10 }; assert(((entrypoints * 4) + 4) <= 0x50); assert((50 + (entrypoints * 7)) <= 0x100); // a 256-byte region is set aside for this! phys_writed(ofs+0,entrypoints); for (unsigned int ent=0;ent < entrypoints;ent++) { /* each entry point is "MOV AL,<entrypoint> ; JMP FAR <callback>" */ /* Yksoft1's patch suggests a segment offset of 0x50 which I'm OK with */ unsigned int ins_ofs = ofs + 0x50 + (ent * 7); phys_writew(ofs+4+(ent*4)+0,entrypoint_indexes[ent]); phys_writew(ofs+4+(ent*4)+2,ins_ofs - ofs); phys_writeb(ins_ofs+0,0xB0); // MOV AL,(entrypoint index) phys_writeb(ins_ofs+1,entrypoint_indexes[ent]); phys_writeb(ins_ofs+2,0xEA); // JMP FAR <callback> phys_writed(ins_ofs+3,final_addr); // total: ins_ofs+7 } } } if (IS_PC98_ARCH) { real_writew(0,0x58A,0x0000U); // countdown timer value PIC_SetIRQMask(0,true); /* PC-98 keeps the timer off unless INT 1Ch is called to set a timer interval */ } bool null_68h = false; { Section_prop * section=static_cast<Section_prop *>(control->GetSection("dos")); null_68h = section->Get_bool("zero unused int 68h"); } /* Default IRQ handler */ if (call_irq_default == 0) call_irq_default = CALLBACK_Allocate(); CALLBACK_Setup(call_irq_default, &Default_IRQ_Handler, CB_IRET, "irq default"); RealSetVec(0x0b, CALLBACK_RealPointer(call_irq_default)); // IRQ 3 RealSetVec(0x0c, CALLBACK_RealPointer(call_irq_default)); // IRQ 4 RealSetVec(0x0d, CALLBACK_RealPointer(call_irq_default)); // IRQ 5 RealSetVec(0x0f, CALLBACK_RealPointer(call_irq_default)); // IRQ 7 if (!IS_PC98_ARCH) { RealSetVec(0x72, CALLBACK_RealPointer(call_irq_default)); // IRQ 10 RealSetVec(0x73, CALLBACK_RealPointer(call_irq_default)); // IRQ 11 } // setup a few interrupt handlers that point to bios IRETs by default real_writed(0,0x66*4,CALLBACK_RealPointer(call_default)); //war2d real_writed(0,0x67*4,CALLBACK_RealPointer(call_default)); if (machine==MCH_CGA || null_68h) real_writed(0,0x68*4,0); //Popcorn real_writed(0,0x5c*4,CALLBACK_RealPointer(call_default)); //Network stuff //real_writed(0,0xf*4,0); some games don't like it bios_first_init = false; DispatchVMEvent(VM_EVENT_BIOS_INIT); TIMER_BIOS_INIT_Configure(); void INT10_Startup(Section *sec); INT10_Startup(NULL); if (!IS_PC98_ARCH) { extern uint8_t BIOS_tandy_D4_flag; real_writeb(0x40,0xd4,BIOS_tandy_D4_flag); } /* INT 13 Bios Disk Support */ BIOS_SetupDisks(); /* INT 16 Keyboard handled in another file */ BIOS_SetupKeyboard(); if (!IS_PC98_ARCH) { int4b_callback.Set_RealVec(0x4B,/*reinstall*/true); callback[1].Set_RealVec(0x11,/*reinstall*/true); callback[2].Set_RealVec(0x12,/*reinstall*/true); callback[3].Set_RealVec(0x14,/*reinstall*/true); callback[4].Set_RealVec(0x15,/*reinstall*/true); callback[5].Set_RealVec(0x17,/*reinstall*/true); callback[6].Set_RealVec(0x1A,/*reinstall*/true); callback[7].Set_RealVec(0x1C,/*reinstall*/true); callback[8].Set_RealVec(0x70,/*reinstall*/true); callback[9].Set_RealVec(0x71,/*reinstall*/true); callback[10].Set_RealVec(0x19,/*reinstall*/true); callback[11].Set_RealVec(0x76,/*reinstall*/true); callback[12].Set_RealVec(0x77,/*reinstall*/true); callback[13].Set_RealVec(0x0E,/*reinstall*/true); callback[15].Set_RealVec(0x18,/*reinstall*/true); callback[19].Set_RealVec(0x1B,/*reinstall*/true); } // FIXME: We're using IBM PC memory size storage even in PC-98 mode. // This cannot be removed, because the DOS kernel uses this variable even in PC-98 mode. mem_writew(BIOS_MEMORY_SIZE,t_conv); // According to Ripsaw, Tandy systems hold the real memory size in a normally reserved field [https://www.vogons.org/viewtopic.php?p=948898#p948898] // According to the PCjr hardware reference library that memory location means the same thing if (machine == MCH_PCJR || machine == MCH_TANDY) mem_writew(BIOS_MEMORY_SIZE+2,t_conv_real); RealSetVec(0x08,BIOS_DEFAULT_IRQ0_LOCATION); // pseudocode for CB_IRQ0: // sti // callback INT8_Handler // push ds,ax,dx // int 0x1c // cli // mov al, 0x20 // out 0x20, al // pop dx,ax,ds // iret if (!IS_PC98_ARCH) { mem_writed(BIOS_TIMER,0); //Calculate the correct time // INT 05h: Print Screen // IRQ1 handler calls it when PrtSc key is pressed; does nothing unless hooked phys_writeb(Real2Phys(BIOS_DEFAULT_INT5_LOCATION), 0xcf); RealSetVec(0x05, BIOS_DEFAULT_INT5_LOCATION); phys_writew(Real2Phys(RealGetVec(0x12))+0x12,0x20); //Hack for Jurresic } phys_writeb(Real2Phys(BIOS_DEFAULT_HANDLER_LOCATION),0xcf); /* bios default interrupt vector location -> IRET */ if (!IS_PC98_ARCH) { // tandy DAC setup bool use_tandyDAC=(real_readb(0x40,0xd4)==0xff); tandy_sb.port=0; tandy_dac.port=0; if (use_tandyDAC) { /* tandy DAC sound requested, see if soundblaster device is available */ Bitu tandy_dac_type = 0; if (Tandy_InitializeSB()) { tandy_dac_type = 1; } else if (Tandy_InitializeTS()) { tandy_dac_type = 2; } if (tandy_dac_type) { real_writew(0x40,0xd0,0x0000); real_writew(0x40,0xd2,0x0000); real_writeb(0x40,0xd4,0xff); /* tandy DAC init value */ real_writed(0x40,0xd6,0x00000000); /* install the DAC callback handler */ tandy_DAC_callback[0]=new CALLBACK_HandlerObject(); tandy_DAC_callback[1]=new CALLBACK_HandlerObject(); tandy_DAC_callback[0]->Install(&IRQ_TandyDAC,CB_IRET,"Tandy DAC IRQ"); tandy_DAC_callback[1]->Install(NULL,CB_TDE_IRET,"Tandy DAC end transfer"); // pseudocode for CB_TDE_IRET: // push ax // mov ax, 0x91fb // int 15 // cli // mov al, 0x20 // out 0x20, al // pop ax // iret uint8_t tandy_irq = 7; if (tandy_dac_type==1) tandy_irq = tandy_sb.irq; else if (tandy_dac_type==2) tandy_irq = tandy_dac.irq; uint8_t tandy_irq_vector = tandy_irq; if (tandy_irq_vector<8) tandy_irq_vector += 8; else tandy_irq_vector += (0x70-8); RealPt current_irq=RealGetVec(tandy_irq_vector); real_writed(0x40,0xd6,current_irq); for (uint16_t i=0; i<0x10; i++) phys_writeb(PhysMake(0xf000,0xa084+i),0x80); } else real_writeb(0x40,0xd4,0x00); } } if (!IS_PC98_ARCH) { /* Setup some stuff in 0x40 bios segment */ // Disney workaround // uint16_t disney_port = mem_readw(BIOS_ADDRESS_LPT1); // port timeouts // always 1 second even if the port does not exist // BIOS_SetLPTPort(0, disney_port); for(Bitu i = 1; i < 3; i++) BIOS_SetLPTPort(i, 0); mem_writeb(BIOS_COM1_TIMEOUT,1); mem_writeb(BIOS_COM2_TIMEOUT,1); mem_writeb(BIOS_COM3_TIMEOUT,1); mem_writeb(BIOS_COM4_TIMEOUT,1); void BIOS_Post_register_parports(); BIOS_Post_register_parports(); void BIOS_Post_register_comports(); BIOS_Post_register_comports(); } if (!IS_PC98_ARCH) { /* Setup equipment list */ // look http://www.bioscentral.com/misc/bda.htm //uint16_t config=0x4400; //1 Floppy, 2 serial and 1 parallel uint16_t config = 0x0; config |= bios_post_parport_count() << 14; config |= bios_post_comport_count() << 9; #if (C_FPU) //FPU if (enable_fpu) config|=0x2; #endif switch (machine) { case MCH_MDA: case MCH_HERC: //Startup monochrome config|=0x30; break; case EGAVGA_ARCH_CASE: case MCH_CGA: case MCH_MCGA: case TANDY_ARCH_CASE: case MCH_AMSTRAD: //Startup 80x25 color config|=0x20; break; default: //EGA VGA config|=0; break; } // PS2 mouse if (KEYBOARD_Report_BIOS_PS2Mouse()) config |= 0x04; // DMA *not* supported - Ancient Art of War CGA uses this to identify PCjr if (machine==MCH_PCJR) config |= 0x100; // Gameport config |= 0x1000; mem_writew(BIOS_CONFIGURATION,config); if (IS_EGAVGA_ARCH) config &= ~0x30; //EGA/VGA startup display mode differs in CMOS CMOS_SetRegister(0x14,(uint8_t)(config&0xff)); //Should be updated on changes } if (!IS_PC98_ARCH) { /* Setup extended memory size */ IO_Write(0x70,0x30); size_extended=IO_Read(0x71); IO_Write(0x70,0x31); size_extended|=(IO_Read(0x71) << 8); uint32_t value = 0; /* Read date/time from host at start */ value = BIOS_HostTimeSync(value); mem_writed(BIOS_TIMER,value); } else { /* Provide a valid memory size anyway */ size_extended=MEM_TotalPages()*4; if (size_extended >= 1024) size_extended -= 1024; else size_extended = 0; } if (!IS_PC98_ARCH) { /* PS/2 mouse */ void BIOS_PS2Mouse_Startup(Section *sec); BIOS_PS2Mouse_Startup(NULL); } if (!IS_PC98_ARCH) { /* this belongs HERE not on-demand from INT 15h! */ biosConfigSeg = ROMBIOS_GetMemory(16/*one paragraph*/,"BIOS configuration (INT 15h AH=0xC0)",/*paragraph align*/16)>>4; if (biosConfigSeg != 0) { PhysPt data = PhysMake(biosConfigSeg,0); phys_writew(data,8); // 8 Bytes following if (IS_TANDY_ARCH) { if (machine==MCH_TANDY) { // Model ID (Tandy) phys_writeb(data+2,0xFF); } else { // Model ID (PCJR) phys_writeb(data+2,0xFD); } phys_writeb(data+3,0x0A); // Submodel ID phys_writeb(data+4,0x10); // Bios Revision /* Tandy doesn't have a 2nd PIC, left as is for now */ phys_writeb(data+5,(1<<6)|(1<<5)|(1<<4)); // Feature Byte 1 } else { if (machine==MCH_MCGA) { /* PC/2 model 30 model */ phys_writeb(data+2,0xFA); phys_writeb(data+3,0x00); // Submodel ID (PS/2) model 30 } else if (PS1AudioCard) { /* FIXME: Won't work because BIOS_Init() comes before PS1SOUND_Init() */ phys_writeb(data+2,0xFC); // Model ID (PC) phys_writeb(data+3,0x0B); // Submodel ID (PS/1). } else { phys_writeb(data+2,0xFC); // Model ID (PC) phys_writeb(data+3,0x00); // Submodel ID } phys_writeb(data+4,0x01); // Bios Revision phys_writeb(data+5,(1<<6)|(1<<5)|(1<<4)); // Feature Byte 1 } phys_writeb(data+6,(1<<6)); // Feature Byte 2 phys_writeb(data+7,0); // Feature Byte 3 phys_writeb(data+8,0); // Feature Byte 4 phys_writeb(data+9,0); // Feature Byte 5 } } // ISA Plug & Play I/O ports if (!IS_PC98_ARCH) { ISAPNP_PNP_ADDRESS_PORT = new IO_WriteHandleObject; ISAPNP_PNP_ADDRESS_PORT->Install(0x279,isapnp_write_port,IO_MB); ISAPNP_PNP_DATA_PORT = new IO_WriteHandleObject; ISAPNP_PNP_DATA_PORT->Install(0xA79,isapnp_write_port,IO_MB); ISAPNP_PNP_READ_PORT = new IO_ReadHandleObject; ISAPNP_PNP_READ_PORT->Install(ISA_PNP_WPORT,isapnp_read_port,IO_MB); LOG(LOG_MISC,LOG_DEBUG)("Registered ISA PnP read port at 0x%03x",ISA_PNP_WPORT); } if (enable_integration_device) { /* integration device callout */ if (dosbox_int_iocallout == IO_Callout_t_none) dosbox_int_iocallout = IO_AllocateCallout(IO_TYPE_MB); if (dosbox_int_iocallout == IO_Callout_t_none) E_Exit("Failed to get dosbox-x integration IO callout handle"); { IO_CalloutObject *obj = IO_GetCallout(dosbox_int_iocallout); if (obj == NULL) E_Exit("Failed to get dosbox-x integration IO callout"); /* NTS: Ports 28h-2Bh conflict with extended DMA control registers in PC-98 mode. * TODO: Move again, if DB28h-DB2Bh are taken by something standard on PC-98. */ obj->Install(IS_PC98_ARCH ? 0xDB28 : 0x28, IOMASK_Combine(IOMASK_FULL,IOMASK_Range(4)),dosbox_integration_cb_port_r,dosbox_integration_cb_port_w); IO_PutCallout(obj); } /* DOSBox-X integration device */ if (!IS_PC98_ARCH && isapnpigdevice == NULL && enable_integration_device_pnp) { isapnpigdevice = new ISAPnPIntegrationDevice; ISA_PNP_devreg(isapnpigdevice); } } // ISA Plug & Play BIOS entrypoint // NTS: Apparently, Windows 95, 98, and ME will re-enumerate and re-install PnP devices if our entry point changes it's address. if (!IS_PC98_ARCH && ISAPNPBIOS) { Bitu base; unsigned int i; unsigned char c,tmp[256]; isapnp_biosstruct_base = base = ROMBIOS_GetMemory(0x21,"ISA Plug & Play BIOS struct",/*paragraph alignment*/0x10); if (base == 0) E_Exit("Unable to allocate ISA PnP struct"); LOG_MSG("ISA Plug & Play BIOS enabled"); call_pnp_r = CALLBACK_Allocate(); call_pnp_rp = PNPentry_real = CALLBACK_RealPointer(call_pnp_r); CALLBACK_Setup(call_pnp_r,ISAPNP_Handler_RM,CB_RETF,"ISA Plug & Play entry point (real)"); //LOG_MSG("real entry pt=%08lx\n",PNPentry_real); call_pnp_p = CALLBACK_Allocate(); call_pnp_pp = PNPentry_prot = CALLBACK_RealPointer(call_pnp_p); CALLBACK_Setup(call_pnp_p,ISAPNP_Handler_PM,CB_RETF,"ISA Plug & Play entry point (protected)"); //LOG_MSG("prot entry pt=%08lx\n",PNPentry_prot); phys_writeb(base+0,'$'); phys_writeb(base+1,'P'); phys_writeb(base+2,'n'); phys_writeb(base+3,'P'); phys_writeb(base+4,0x10); /* Version: 1.0 */ phys_writeb(base+5,0x21); /* Length: 0x21 bytes */ phys_writew(base+6,0x0000); /* Control field: Event notification not supported */ /* skip checksum atm */ phys_writed(base+9,0); /* Event notify flag addr: (none) */ phys_writed(base+0xD,call_pnp_rp); /* Real-mode entry point */ phys_writew(base+0x11,call_pnp_pp&0xFFFF); /* Protected mode offset */ phys_writed(base+0x13,(call_pnp_pp >> 12) & 0xFFFF0); /* Protected mode code segment base */ phys_writed(base+0x17,ISAPNP_ID('D','O','S',0,8,3,0)); /* OEM device identifier (DOSBox-X 0.83.x) */ phys_writew(base+0x1B,0xF000); /* real-mode data segment */ phys_writed(base+0x1D,0xF0000); /* protected mode data segment address */ /* run checksum */ c=0; for (i=0;i < 0x21;i++) { if (i != 8) c += phys_readb(base+i); } phys_writeb(base+8,0x100-c); /* checksum value: set so that summing bytes across the struct == 0 */ /* input device (keyboard) */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Keyboard,sizeof(ISAPNP_sysdev_Keyboard),true)) LOG_MSG("ISAPNP register failed\n"); /* input device (mouse) */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Mouse,sizeof(ISAPNP_sysdev_Mouse),true)) LOG_MSG("ISAPNP register failed\n"); /* DMA controller */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_DMA_Controller,sizeof(ISAPNP_sysdev_DMA_Controller),true)) LOG_MSG("ISAPNP register failed\n"); /* Interrupt controller */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_PIC,sizeof(ISAPNP_sysdev_PIC),true)) LOG_MSG("ISAPNP register failed\n"); /* Timer */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Timer,sizeof(ISAPNP_sysdev_Timer),true)) LOG_MSG("ISAPNP register failed\n"); /* Realtime clock */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_RTC,sizeof(ISAPNP_sysdev_RTC),true)) LOG_MSG("ISAPNP register failed\n"); /* PC speaker */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_PC_Speaker,sizeof(ISAPNP_sysdev_PC_Speaker),true)) LOG_MSG("ISAPNP register failed\n"); /* System board */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_System_Board,sizeof(ISAPNP_sysdev_System_Board),true)) LOG_MSG("ISAPNP register failed\n"); /* Motherboard PNP resources and general */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_General_ISAPNP,sizeof(ISAPNP_sysdev_General_ISAPNP),true)) LOG_MSG("ISAPNP register failed\n"); /* ISA bus, meaning, a computer with ISA slots. * The purpose of this device is to convince Windows 95 to automatically install it's * "ISA Plug and Play bus" so that PnP devices are recognized automatically */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_ISA_BUS,sizeof(ISAPNP_sysdev_ISA_BUS),true)) LOG_MSG("ISAPNP register failed\n"); if (pcibus_enable) { /* PCI bus, meaning, a computer with PCI slots. * The purpose of this device is to tell Windows 95 that a PCI bus is present. Without * this entry, PCI devices will not be recognized until you manually install the PCI driver. */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_PCI_BUS,sizeof(ISAPNP_sysdev_PCI_BUS),true)) LOG_MSG("ISAPNP register failed\n"); } /* APM BIOS device. To help Windows 95 see our APM BIOS. */ if (APMBIOS && APMBIOS_pnp) { LOG_MSG("Registering APM BIOS as ISA Plug & Play BIOS device node"); if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_APM_BIOS,sizeof(ISAPNP_sysdev_APM_BIOS),true)) LOG_MSG("ISAPNP register failed\n"); } #if (C_FPU) /* Numeric Coprocessor */ if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Numeric_Coprocessor,sizeof(ISAPNP_sysdev_Numeric_Coprocessor),true)) LOG_MSG("ISAPNP register failed\n"); #endif /* RAM resources. we have to construct it */ /* NTS: We don't do this here, but I have an old Toshiba laptop who's PnP BIOS uses * this device ID to report both RAM and ROM regions. */ { Bitu max = MEM_TotalPages() * 4096; const unsigned char h1[9] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x1), /* PNP0C01 System device, motherboard resources */ ISAPNP_TYPE(0x05,0x00,0x00), /* type: Memory, RAM, general */ 0x0001 | 0x0002) }; i = 0; memcpy(tmp+i,h1,9); i += 9; /* can't disable, can't configure */ /*----------allocated--------*/ tmp[i+0] = 0x80 | 6; /* 32-bit memory range */ tmp[i+1] = 9; /* length=9 */ tmp[i+2] = 0; tmp[i+3] = 0x01; /* writeable, no cache, 8-bit, not shadowable, not ROM */ host_writed(tmp+i+4,0x00000); /* base */ host_writed(tmp+i+8,max > 0xA0000 ? 0xA0000 : 0x00000); /* length */ i += 9+3; if (max > 0x100000) { tmp[i+0] = 0x80 | 6; /* 32-bit memory range */ tmp[i+1] = 9; /* length=9 */ tmp[i+2] = 0; tmp[i+3] = 0x01; host_writed(tmp+i+4,0x100000); /* base */ host_writed(tmp+i+8,max-0x100000); /* length */ i += 9+3; } tmp[i+0] = 0x79; /* END TAG */ tmp[i+1] = 0x00; i += 2; /*-------------possible-----------*/ tmp[i+0] = 0x79; /* END TAG */ tmp[i+1] = 0x00; i += 2; /*-------------compatible---------*/ tmp[i+0] = 0x79; /* END TAG */ tmp[i+1] = 0x00; i += 2; if (!ISAPNP_RegisterSysDev(tmp,i)) LOG_MSG("ISAPNP register failed\n"); } /* register parallel ports */ for (Bitu portn=0;portn < 3;portn++) { Bitu port = mem_readw(BIOS_ADDRESS_LPT1+(portn*2)); if (port != 0) { const unsigned char h1[9] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0x4,0x0,0x0), /* PNP0400 Standard LPT printer port */ ISAPNP_TYPE(0x07,0x01,0x00), /* type: General parallel port */ 0x0001 | 0x0002) }; i = 0; memcpy(tmp+i,h1,9); i += 9; /* can't disable, can't configure */ /*----------allocated--------*/ tmp[i+0] = (8 << 3) | 7; /* IO resource */ tmp[i+1] = 0x01; /* 16-bit decode */ host_writew(tmp+i+2,port); /* min */ host_writew(tmp+i+4,port); /* max */ tmp[i+6] = 0x10; /* align */ tmp[i+7] = 0x03; /* length */ i += 7+1; /* TODO: If/when LPT emulation handles the IRQ, add IRQ resource here */ tmp[i+0] = 0x79; /* END TAG */ tmp[i+1] = 0x00; i += 2; /*-------------possible-----------*/ tmp[i+0] = 0x79; /* END TAG */ tmp[i+1] = 0x00; i += 2; /*-------------compatible---------*/ tmp[i+0] = 0x79; /* END TAG */ tmp[i+1] = 0x00; i += 2; if (!ISAPNP_RegisterSysDev(tmp,i)) LOG_MSG("ISAPNP register failed\n"); } } void BIOS_Post_register_comports_PNP(); BIOS_Post_register_comports_PNP(); void BIOS_Post_register_IDE(); BIOS_Post_register_IDE(); void BIOS_Post_register_FDC(); BIOS_Post_register_FDC(); } if (IS_PC98_ARCH) { /* initialize IRQ0 timer to default tick interval. * PC-98 does not pre-initialize timer 0 of the PIT to 0xFFFF the way IBM PC/XT/AT do */ PC98_Interval_Timer_Continue(); PIC_SetIRQMask(0,true); /* PC-98 keeps the timer off unless INT 1Ch is called to set a timer interval */ } if (!IS_PC98_ARCH) { Section_prop * section=static_cast<Section_prop *>(control->GetSection("speaker")); bool bit0en = section->Get_bool("pcspeaker clock gate enable at startup"); if (bit0en) { uint8_t x = IO_Read(0x61); IO_Write(0x61,(x & (~3u)) | 1u); /* set bits[1:0] = 01 (clock gate enable but output gate disable) */ LOG_MSG("xxxx"); } } CPU_STI(); return CBRET_NONE; } CALLBACK_HandlerObject cb_bios_scan_video_bios; static Bitu cb_bios_scan_video_bios__func(void) { unsigned long size; /* NTS: As far as I can tell, video is integrated into the PC-98 BIOS and there is no separate BIOS */ if (IS_PC98_ARCH) return CBRET_NONE; if (cpu.pmode) E_Exit("BIOS error: VIDEO BIOS SCAN function called while in protected/vm86 mode"); if (!bios_has_exec_vga_bios) { bios_has_exec_vga_bios = true; if (IS_EGAVGA_ARCH) { /* make sure VGA BIOS is there at 0xC000:0x0000 */ if (AdapterROM_Read(0xC0000,&size)) { LOG(LOG_MISC,LOG_DEBUG)("BIOS VIDEO ROM SCAN found VGA BIOS (size=%lu)",size); adapter_scan_start = 0xC0000 + size; // step back into the callback instruction that triggered this call reg_eip -= 4; // FAR CALL into the VGA BIOS CPU_CALL(false,0xC000,0x0003,reg_eip); return CBRET_NONE; } else { LOG(LOG_MISC,LOG_WARN)("BIOS VIDEO ROM SCAN did not find VGA BIOS"); } } else { // CGA, MDA, Tandy, PCjr. No video BIOS to scan for } } return CBRET_NONE; } CALLBACK_HandlerObject cb_bios_adapter_rom_scan; static Bitu cb_bios_adapter_rom_scan__func(void) { unsigned long size; uint32_t c1; /* FIXME: I have no documentation on how PC-98 scans for adapter ROM or even if it supports it */ if (IS_PC98_ARCH) return CBRET_NONE; if (cpu.pmode) E_Exit("BIOS error: ADAPTER ROM function called while in protected/vm86 mode"); while (adapter_scan_start < 0xF0000) { if (AdapterROM_Read(adapter_scan_start,&size)) { uint16_t segm = (uint16_t)(adapter_scan_start >> 4); LOG(LOG_MISC,LOG_DEBUG)("BIOS ADAPTER ROM scan found ROM at 0x%lx (size=%lu)",(unsigned long)adapter_scan_start,size); c1 = mem_readd(adapter_scan_start+3); adapter_scan_start += size; if (c1 != 0UL) { LOG(LOG_MISC,LOG_DEBUG)("Running ADAPTER ROM entry point"); // step back into the callback instruction that triggered this call reg_eip -= 4; // FAR CALL into the VGA BIOS CPU_CALL(false,segm,0x0003,reg_eip); return CBRET_NONE; } else { LOG(LOG_MISC,LOG_DEBUG)("FIXME: ADAPTER ROM entry point does not exist"); } } else { if (IS_EGAVGA_ARCH) // supposedly newer systems only scan on 2KB boundaries by standard? right? adapter_scan_start = (adapter_scan_start | 2047UL) + 1UL; else // while older PC/XT systems scanned on 512-byte boundaries? right? adapter_scan_start = (adapter_scan_start | 511UL) + 1UL; } } LOG(LOG_MISC,LOG_DEBUG)("BIOS ADAPTER ROM scan complete"); return CBRET_NONE; } CALLBACK_HandlerObject cb_bios_startup_screen; static Bitu cb_bios_startup_screen__func(void) { const Section_prop* section = static_cast<Section_prop *>(control->GetSection("dosbox")); bool fastbioslogo=section->Get_bool("fastbioslogo")||control->opt_fastbioslogo||control->opt_fastlaunch; if (fastbioslogo && machine != MCH_PC98) { #if defined(USE_TTF) if (TTF_using()) { uint32_t lasttick=GetTicks(); while ((GetTicks()-lasttick)<500) { reg_eax = 0x0100; CALLBACK_RunRealInt(0x16); } reg_eax = 3; CALLBACK_RunRealInt(0x10); } #endif if (control->opt_fastlaunch) return CBRET_NONE; } extern const char* RunningProgram; extern void GFX_SetTitle(int32_t cycles, int frameskip, Bits timing, bool paused); RunningProgram = "DOSBOX-X"; GFX_SetTitle(-1,-1,-1,false); const char *msg = "DOSBox-X (C) 2011-" COPYRIGHT_END_YEAR " The DOSBox-X Team\nDOSBox-X project maintainer: joncampbell123\nDOSBox-X project homepage: https://dosbox-x.com\nDOSBox-X user guide: https://dosbox-x.com/wiki\n\n"; bool textsplash = section->Get_bool("disable graphical splash"); #if defined(USE_TTF) if (TTF_using()) { textsplash = true; if (ttf.cols != 80 || ttf.lins != 25) { oldcols = ttf.cols; oldlins = ttf.lins; } else oldcols = oldlins = 0; } #endif char logostr[8][30]; strcpy(logostr[0], "+-------------------+"); strcpy(logostr[1], "| Welcome To |"); strcpy(logostr[2], "| |"); strcpy(logostr[3], "| D O S B o x - X ! |"); strcpy(logostr[4], "| |"); sprintf(logostr[5], "| %d-bit %s |", #if defined(_M_X64) || defined (_M_AMD64) || defined (_M_ARM64) || defined (_M_IA64) || defined(__ia64__) || defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(__aarch64__) || defined(__powerpc64__)^M 64 #else 32 #endif , SDL_STRING); sprintf(logostr[6], "| Version %7s |", VERSION); strcpy(logostr[7], "+-------------------+"); startfunction: int logo_x,logo_y,x=2,y=2,rowheight=8; logo_y = 2; logo_x = 80 - 2 - (224/8); if (cpu.pmode) E_Exit("BIOS error: STARTUP function called while in protected/vm86 mode"); if (IS_VGA_ARCH && !textsplash) { rowheight = 16; reg_eax = 18; // 640x480 16-color CALLBACK_RunRealInt(0x10); DrawDOSBoxLogoVGA((unsigned int)logo_x*8u,(unsigned int)logo_y*(unsigned int)rowheight); } else if (machine == MCH_EGA && !textsplash) { rowheight = 14; reg_eax = 16; // 640x350 16-color CALLBACK_RunRealInt(0x10); // color correction: change Dark Puke Yellow to brown IO_Read(0x3DA); IO_Read(0x3BA); IO_Write(0x3C0,0x06); IO_Write(0x3C0,0x14); // red=1 green=1 blue=0 IO_Read(0x3DA); IO_Read(0x3BA); IO_Write(0x3C0,0x20); DrawDOSBoxLogoVGA((unsigned int)logo_x*8u,(unsigned int)logo_y*(unsigned int)rowheight); } else if ((machine == MCH_CGA || machine == MCH_MCGA || machine == MCH_PCJR || machine == MCH_AMSTRAD || machine == MCH_TANDY) && !textsplash) { rowheight = 8; reg_eax = 6; // 640x200 2-color CALLBACK_RunRealInt(0x10); DrawDOSBoxLogoCGA6((unsigned int)logo_x*8u,(unsigned int)logo_y*(unsigned int)rowheight); } else if (machine == MCH_PC98) { // clear the graphics layer for (unsigned int i=0;i < (80*400);i++) { mem_writeb(0xA8000+i,0); // B mem_writeb(0xB0000+i,0); // G mem_writeb(0xB8000+i,0); // R mem_writeb(0xE0000+i,0); // E } reg_eax = 0x0C00; // enable text layer (PC-98) CALLBACK_RunRealInt(0x18); reg_eax = 0x1100; // show cursor (PC-98) CALLBACK_RunRealInt(0x18); reg_eax = 0x1300; // set cursor pos (PC-98) reg_edx = 0x0000; // byte position CALLBACK_RunRealInt(0x18); bios_pc98_posx = x; reg_eax = 0x4200; // setup 640x400 graphics reg_ecx = 0xC000; CALLBACK_RunRealInt(0x18); // enable the 4th bitplane, for 16-color analog graphics mode. // TODO: When we allow the user to emulate only the 8-color BGR digital mode, // logo drawing should use an alternate drawing method. IO_Write(0x6A,0x01); // enable 16-color analog mode (this makes the 4th bitplane appear) IO_Write(0x6A,0x04); // but we don't need the EGC graphics // If we caught a game mid-page flip, set the display and VRAM pages back to zero IO_Write(0xA4,0x00); // display page 0 IO_Write(0xA6,0x00); // write to page 0 // program a VGA-like color palette so we can re-use the VGA logo for (unsigned int i=0;i < 16;i++) { unsigned int bias = (i & 8) ? 0x5 : 0x0; IO_Write(0xA8,i); // DAC index if (i != 6) { IO_Write(0xAA,((i & 2) ? 0xA : 0x0) + bias); // green IO_Write(0xAC,((i & 4) ? 0xA : 0x0) + bias); // red IO_Write(0xAE,((i & 1) ? 0xA : 0x0) + bias); // blue } else { // brown #6 instead of puke yellow IO_Write(0xAA, 0x5 + bias); // green IO_Write(0xAC, 0xA + bias); // red IO_Write(0xAE, 0x0 + bias); // blue } } if (textsplash) { unsigned int bo, lastline = 7; for (unsigned int i=0; i<=lastline; i++) { for (unsigned int j=0; j<strlen(logostr[i]); j++) { bo = (((unsigned int)(i+2) * 80u) + (unsigned int)(j+0x36)) * 2u; mem_writew(0xA0000+bo,i==0&&j==0?0x300B:(i==0&&j==strlen(logostr[0])-1?0x340B:(i==lastline&&j==0?0x380B:(i==lastline&&j==strlen(logostr[lastline])-1?0x3C0B:(logostr[i][j]=='-'&&(i==0||i==lastline)?0x240B:(logostr[i][j]=='|'?0x260B:logostr[i][j]%0xff)))))); mem_writeb(0xA2000+bo+1,0xE1); } } } else { if (!control->opt_fastlaunch) DrawDOSBoxLogoPC98((unsigned int)logo_x*8u,(unsigned int)logo_y*(unsigned int)rowheight); reg_eax = 0x4000; // show the graphics layer (PC-98) so we can render the DOSBox-X logo CALLBACK_RunRealInt(0x18); } } else { reg_eax = 3; // 80x25 text CALLBACK_RunRealInt(0x10); // TODO: For CGA, PCjr, and Tandy, we could render a 4-color CGA version of the same logo. // And for MDA/Hercules, we could render a monochromatic ASCII art version. } #if defined(USE_TTF) if (TTF_using() && (ttf.cols != 80 || ttf.lins != 25)) ttf_setlines(80, 25); #endif if (machine != MCH_PC98) { reg_eax = 0x0200; // set cursor pos reg_ebx = 0; // page zero reg_dh = y; // row 4 reg_dl = x; // column 20 CALLBACK_RunRealInt(0x10); } BIOS_Int10RightJustifiedPrint(x,y,msg); if (machine != MCH_PC98 && textsplash) { Bitu edx = reg_edx; //int oldx = x, oldy = y; UNUSED unsigned int lastline = 7; for (unsigned int i=0; i<=lastline; i++) { for (unsigned int j=0; j<strlen(logostr[i]); j++) { reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx = 0x0236u + i*0x100 + j; CALLBACK_RunRealInt(0x10); reg_eax = 0x0900u+(i==0&&j==0?0xDA:(i==0&&j==strlen(logostr[0])-1?0xBF:(i==lastline&&j==0?0xC0:(i==lastline&&j==strlen(logostr[lastline])-1?0xD9:(logostr[i][j]=='-'&&(i==0||i==lastline)?0xC4:(logostr[i][j]=='|'?0xB3:logostr[i][j]%0xff)))))); reg_ebx = i!=0&&i!=lastline&&logostr[i][j]!='|'?0x002eu:0x002fu; reg_ecx = 0x0001u; CALLBACK_RunRealInt(0x10); } } reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx = edx; CALLBACK_RunRealInt(0x10); } { uint64_t sz = (uint64_t)MEM_TotalPages() * (uint64_t)4096; char tmp[512]; if (sz >= ((uint64_t)128 << (uint64_t)20)) sprintf(tmp,"%uMB memory installed\r\n",(unsigned int)(sz >> (uint64_t)20)); else sprintf(tmp,"%uKB memory installed\r\n",(unsigned int)(sz >> (uint64_t)10)); BIOS_Int10RightJustifiedPrint(x,y,tmp); } const char *card = "Unknown Graphics Adapter"; switch (machine) { case MCH_CGA: card = "IBM Color Graphics Adapter"; break; case MCH_MCGA: card = "IBM Multi Color Graphics Adapter"; break; case MCH_MDA: card = "IBM Monochrome Display Adapter"; break; case MCH_HERC: card = "Hercules Monochrome Graphics Adapter"; break; case MCH_EGA: card = "IBM Enhanced Graphics Adapter"; break; case MCH_PCJR: card = "PCjr Graphics Adapter"; break; case MCH_TANDY: card = "Tandy Graphics Adapter"; break; case MCH_VGA: switch (svgaCard) { case SVGA_TsengET4K: card = "Tseng ET4000 SVGA"; break; case SVGA_TsengET3K: card = "Tseng ET3000 SVGA"; break; case SVGA_ParadisePVGA1A: card = "Paradise SVGA"; break; case SVGA_S3Trio: card = "S3 Trio SVGA"; switch (s3Card) { case S3_86C928: card = "S3 86C928"; break; case S3_Vision864: card = "S3 Vision864 SVGA"; break; case S3_Vision868: card = "S3 Vision868 SVGA"; break; case S3_Trio32: card = "S3 Trio32 SVGA"; break; case S3_Trio64: card = "S3 Trio64 SVGA"; break; case S3_Trio64V: card = "S3 Trio64V+ SVGA"; break; case S3_ViRGE: card = "S3 ViRGE SVGA"; break; case S3_ViRGEVX: card = "S3 ViRGE VX SVGA"; break; } break; default: card = "Standard VGA"; break; } break; case MCH_PC98: card = "PC98 graphics"; break; case MCH_AMSTRAD: card = "Amstrad graphics"; break; default: abort(); // should not happen } { char tmp[512]; sprintf(tmp,"Video card is %s\n",card); BIOS_Int10RightJustifiedPrint(x,y,tmp); } { char tmp[512]; const char *cpuType = "?"; switch (CPU_ArchitectureType) { case CPU_ARCHTYPE_8086: cpuType = "8086"; break; case CPU_ARCHTYPE_80186: cpuType = "80186"; break; case CPU_ARCHTYPE_286: cpuType = "286"; break; case CPU_ARCHTYPE_386: cpuType = "386"; break; case CPU_ARCHTYPE_486OLD: cpuType = "486 (older generation)"; break; case CPU_ARCHTYPE_486NEW: cpuType = "486 (later generation)"; break; case CPU_ARCHTYPE_PENTIUM: cpuType = "Pentium"; break; case CPU_ARCHTYPE_PMMXSLOW: cpuType = "Pentium MMX"; break; case CPU_ARCHTYPE_PPROSLOW: cpuType = "Pentium Pro"; break; case CPU_ARCHTYPE_PENTIUMII: cpuType = "Pentium II"; break; case CPU_ARCHTYPE_PENTIUMIII: cpuType = "Pentium III"; break; case CPU_ARCHTYPE_MIXED: cpuType = "Auto (mixed)"; break; case CPU_ARCHTYPE_EXPERIMENTAL: cpuType = "Experimental"; break; } sprintf(tmp,"%s CPU present",cpuType); BIOS_Int10RightJustifiedPrint(x,y,tmp); if (enable_fpu) BIOS_Int10RightJustifiedPrint(x,y," with FPU"); BIOS_Int10RightJustifiedPrint(x,y,"\n"); } if (APMBIOS) { BIOS_Int10RightJustifiedPrint(x,y,"Advanced Power Management interface active\n"); } if (ISAPNPBIOS) { BIOS_Int10RightJustifiedPrint(x,y,"ISA Plug & Play BIOS active\n"); } #if !defined(C_EMSCRIPTEN) BIOS_Int10RightJustifiedPrint(x,y,"\nHit SPACEBAR to pause at this screen\n", false, true); BIOS_Int10RightJustifiedPrint(x,y,"\nPress DEL to enter BIOS setup screen\n", false, true); y--; /* next message should overprint */ if (machine != MCH_PC98) { reg_eax = 0x0200; // set cursor pos reg_ebx = 0; // page zero reg_dh = y; // row 4 reg_dl = x; // column 20 CALLBACK_RunRealInt(0x10); } else { reg_eax = 0x1300u; // set cursor pos (PC-98) reg_edx = (((unsigned int)y * 80u) + (unsigned int)x) * 2u; // byte position CALLBACK_RunRealInt(0x18); } #endif // TODO: Then at this screen, we can print messages demonstrating the detection of // IDE devices, floppy, ISA PnP initialization, anything of importance. // I also envision adding the ability to hit DEL or F2 at this point to enter // a "BIOS setup" screen where all DOSBox-X configuration options can be // modified, with the same look and feel of an old BIOS. #if C_EMSCRIPTEN uint32_t lasttick=GetTicks(); while ((GetTicks()-lasttick)<1000) { void CALLBACK_Idle(void); CALLBACK_Idle(); emscripten_sleep(100); } #else if (!fastbioslogo&&!bootguest&&!bootfast&&(bootvm||!use_quick_reboot)) { bool wait_for_user = false, bios_setup = false; int pos=1; uint32_t lasttick=GetTicks(); while ((GetTicks()-lasttick)<1000) { if (machine == MCH_PC98) { reg_eax = 0x0100; // sense key CALLBACK_RunRealInt(0x18); SETFLAGBIT(ZF,reg_bh == 0); } else { reg_eax = 0x0100; CALLBACK_RunRealInt(0x16); } if (!GETFLAG(ZF)) { if (machine == MCH_PC98) { reg_eax = 0x0000; // read key CALLBACK_RunRealInt(0x18); } else { reg_eax = 0x0000; CALLBACK_RunRealInt(0x16); } if (reg_al == 32) { // user hit space BIOS_Int10RightJustifiedPrint(x,y,"Hit ENTER or ESC to continue \n", false, true); // overprint BIOS_Int10RightJustifiedPrint(x,y,"\nPress DEL to enter BIOS setup screen\n", false, true); wait_for_user = true; break; } if ((machine != MCH_PC98 && reg_ax == 0x5300) || (machine == MCH_PC98 && reg_ax == 0x3900)) { // user hit Del bios_setup = true; showBIOSSetup(card, x, y); break; } } } while (wait_for_user) { if (machine == MCH_PC98) { reg_eax = 0x0000; // read key CALLBACK_RunRealInt(0x18); } else { reg_eax = 0x0000; CALLBACK_RunRealInt(0x16); } if ((machine != MCH_PC98 && reg_ax == 0x5300/*DEL*/) || (machine == MCH_PC98 && reg_ax == 0x3900)) { bios_setup = true; showBIOSSetup(card, x, y); break; } if (reg_al == 27/*ESC*/ || reg_al == 13/*ENTER*/) break; } lasttick=GetTicks(); bool askexit = false, mod = false; while (bios_setup) { if (GetTicks()-lasttick>=500 && !askexit) { lasttick=GetTicks(); updateDateTime(x,y,pos); } if (machine == MCH_PC98) { reg_eax = 0x0100; // sense key CALLBACK_RunRealInt(0x18); SETFLAGBIT(ZF,reg_bh == 0); } else { reg_eax = 0x0100; CALLBACK_RunRealInt(0x16); } if (!GETFLAG(ZF)) { if (machine == MCH_PC98) { reg_eax = 0x0000; // read key CALLBACK_RunRealInt(0x18); } else { reg_eax = 0x0000; CALLBACK_RunRealInt(0x16); } if (askexit) { if (reg_al == 'Y' || reg_al == 'y') { if (machine == MCH_PC98) { reg_eax = 0x1600; reg_edx = 0xE100; CALLBACK_RunRealInt(0x18); } goto startfunction; } else if (machine == MCH_PC98) { const char *exitstr = "ESC = Exit"; unsigned int bo; for (unsigned int i=0; i<strlen(exitstr); i++) { bo = (((unsigned int)24 * 80u) + (unsigned int)0x22+i) * 2u; mem_writew(0xA0000+bo,(unsigned char)exitstr[i]); mem_writeb(0xA2000+bo,0xE1); } askexit = false; continue; } else { reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx = 0x1800u; CALLBACK_RunRealInt(0x10); BIOS_Int10RightJustifiedPrint(x,y," ESC: Exit Arrows: Select Item +/-: Change Values "); askexit = false; continue; } } if ((machine != MCH_PC98 && reg_ax == 0x4B00) || (machine == MCH_PC98 && reg_ax == 0x3B00)) { // Left key pos=pos>1?pos-1:6; lasttick-=500; } else if ((machine != MCH_PC98 && reg_ax == 0x4D00) || (machine == MCH_PC98 && reg_ax == 0x3C00)) { // Right key pos=pos<6?pos+1:1; lasttick-=500; } else if (((machine != MCH_PC98 && reg_ax == 0x4800) || (machine == MCH_PC98 && reg_ax == 0x3A00)) && pos>3) { // Up key if (pos==4||pos==5) pos=1; else if (pos==6) pos=2; lasttick-=500; } else if (((machine != MCH_PC98 && reg_ax == 0x5000) || (machine == MCH_PC98 && reg_ax == 0x3D00)) && pos<4) { // Down key if (pos==1) pos=4; else if (pos==2||pos==3) pos=6; lasttick-=500; } else if (machine != MCH_PC98 && reg_al == 43) { // '+' key if (pos==1&&dos.date.year<2100) dos.date.year++; else if (pos==2) dos.date.month=dos.date.month<12?dos.date.month+1:1; else if (pos==3) dos.date.day=dos.date.day<(dos.date.month==1||dos.date.month==3||dos.date.month==5||dos.date.month==7||dos.date.month==8||dos.date.month==10||dos.date.month==12?31:(dos.date.month==2?29:30))?dos.date.day+1:1; else if (pos==4||pos==5||pos==6) { Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * mem_readd(BIOS_TIMER))/100; unsigned int sec=(uint8_t)((Bitu)time % 60); time/=60; unsigned int min=(uint8_t)((Bitu)time % 60); time/=60; unsigned int hour=(uint8_t)((Bitu)time % 24); if (pos==4) hour=hour<23?hour+1:0; else if (pos==5) min=min<59?min+1:0; else if (pos==6) sec=sec<59?sec+1:0; mem_writed(BIOS_TIMER,(uint32_t)(((double)hour*3600+min*60+sec))*18.206481481); } mod = true; if (sync_time) {manualtime=true;mainMenu.get_item("sync_host_datetime").check(false).refresh_item(mainMenu);} lasttick-=500; } else if (machine != MCH_PC98 && reg_al == 45) { // '-' key if (pos==1&&dos.date.year>1900) dos.date.year--; else if (pos==2) dos.date.month=dos.date.month>1?dos.date.month-1:12; else if (pos==3) dos.date.day=dos.date.day>1?dos.date.day-1:(dos.date.month==1||dos.date.month==3||dos.date.month==5||dos.date.month==7||dos.date.month==8||dos.date.month==10||dos.date.month==12?31:(dos.date.month==2?29:30)); else if (pos==4||pos==5||pos==6) { Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * mem_readd(BIOS_TIMER))/100; unsigned int sec=(uint8_t)((Bitu)time % 60); time/=60; unsigned int min=(uint8_t)((Bitu)time % 60); time/=60; unsigned int hour=(uint8_t)((Bitu)time % 24); if (pos==4) hour=hour>0?hour-1:23; else if (pos==5) min=min>0?min-1:59; else if (pos==6) sec=sec>0?sec-1:59; mem_writed(BIOS_TIMER,(uint32_t)(((double)hour*3600+min*60+sec))*18.206481481); } mod = true; if (sync_time) {manualtime=true;mainMenu.get_item("sync_host_datetime").check(false).refresh_item(mainMenu);} lasttick-=500; } else if (reg_al == 27/*ESC*/) { if (machine == MCH_PC98) { const char *exitstr = "Exit[Y/N]?"; unsigned int bo; for (unsigned int i=0; i<strlen(exitstr); i++) { bo = (((unsigned int)24 * 80u) + (unsigned int)0x22+i) * 2u; mem_writew(0xA0000+bo,(unsigned char)exitstr[i]); mem_writeb(0xA2000+bo,0xE1); } } else { reg_eax = 0x0200u; reg_ebx = 0x0000u; reg_edx = 0x1800u; CALLBACK_RunRealInt(0x10); if (mod) BIOS_Int10RightJustifiedPrint(x,y," Save settings and exit the BIOS Setup Utility [Y/N]? "); else BIOS_Int10RightJustifiedPrint(x,y," Exit the BIOS Setup Utility and reboot system [Y/N]? "); } askexit = true; } } } } #endif if (machine == MCH_PC98) { reg_eax = 0x4100; // hide the graphics layer (PC-98) CALLBACK_RunRealInt(0x18); // clear the graphics layer for (unsigned int i=0;i < (80*400);i++) { mem_writeb(0xA8000+i,0); // B mem_writeb(0xB0000+i,0); // G mem_writeb(0xB8000+i,0); // R mem_writeb(0xE0000+i,0); // E } IO_Write(0x6A,0x00); // switch back to 8-color mode reg_eax = 0x4200; // setup 640x200 graphics reg_ecx = 0x8000; // lower CALLBACK_RunRealInt(0x18); if (textsplash) { reg_eax = 0x1600; reg_edx = 0xE100; CALLBACK_RunRealInt(0x18); } } else { // restore 80x25 text mode reg_eax = 3; CALLBACK_RunRealInt(0x10); } #if defined(USE_TTF) if (TTF_using() && oldcols>0 && oldlins>0) { ttf_setlines(oldcols, oldlins); oldcols = oldlins = 0; } #endif return CBRET_NONE; } CALLBACK_HandlerObject cb_bios_boot; CALLBACK_HandlerObject cb_bios_bootfail; CALLBACK_HandlerObject cb_pc98_rombasic; /* hardcoded entry point used by various PC-98 games that jump to N88 ROM BASIC */ CALLBACK_HandlerObject cb_ibm_basic; /* hardcoded entry point used by MS-DOS 1.x BASIC.COM and BASICA.COM to jump to IBM ROM BASIC (F600:4C79) */ static Bitu cb_pc98_entry__func(void) { /* the purpose of this function is to say "N88 ROM BASIC NOT FOUND" */ int x,y; x = y = 0; /* PC-98 MS-DOS boot sector may RETF back to the BIOS, and this is where execution ends up */ BIOS_Int10RightJustifiedPrint(x,y,"N88 ROM BASIC NOT IMPLEMENTED"); return CBRET_NONE; } static Bitu cb_ibm_basic_entry__func(void) { /* the purpose of this function is to say "IBM ROM BASIC NOT FOUND" */ int x,y; x = y = 0; /* PC-98 MS-DOS boot sector may RETF back to the BIOS, and this is where execution ends up */ BIOS_Int10RightJustifiedPrint(x,y,"IBM ROM BASIC NOT IMPLEMENTED"); return CBRET_NONE; } static Bitu cb_bios_bootfail__func(void) { int x,y; x = y = 0; /* PC-98 MS-DOS boot sector may RETF back to the BIOS, and this is where execution ends up */ BIOS_Int10RightJustifiedPrint(x,y,"Guest OS failed to boot, returned failure"); /* and then after this call, there is a JMP $ to loop endlessly */ return CBRET_NONE; } static Bitu cb_bios_boot__func(void) { /* Reset/power-on overrides the user's A20 gate preferences. * It's time to revert back to what the user wants. */ void A20Gate_TakeUserSetting(Section *sec); void MEM_A20_Enable(bool enabled); A20Gate_TakeUserSetting(NULL); MEM_A20_Enable(false); if (cpu.pmode) E_Exit("BIOS error: BOOT function called while in protected/vm86 mode"); DispatchVMEvent(VM_EVENT_BIOS_BOOT); // TODO: If instructed to, follow the INT 19h boot pattern, perhaps follow the BIOS Boot Specification, etc. // TODO: If instructed to boot a guest OS... /* wipe out the stack so it's not there to interfere with the system */ reg_esp = 0; reg_eip = 0; CPU_SetSegGeneral(cs, 0x60); CPU_SetSegGeneral(ss, 0x60); for (Bitu i=0;i < 0x400;i++) mem_writeb(0x7C00+i,0); if ((bootguest||(!bootvm&&use_quick_reboot))&&!bootfast&&bootdrive>=0&&imageDiskList[bootdrive]) { MOUSE_Startup(NULL); char drive[] = "-QQ A:"; drive[4]='A'+bootdrive; runBoot(drive); } if (!bootguest&&!bootvm&&!bootfast&&bootdrive>=0) { void IDE_CDROM_DetachAll(); IDE_CDROM_DetachAll(); } if ((use_quick_reboot||IS_DOSV)&&!bootvm&&!bootfast&&bootdrive<0&&first_shell != NULL) throw int(6); bootvm=false; bootfast=false; bootguest=false; bootdrive=-1; // Begin booting the DOSBox-X shell. NOTE: VM_Boot_DOSBox_Kernel will change CS:IP instruction pointer! if (!VM_Boot_DOSBox_Kernel()) E_Exit("BIOS error: BOOT function failed to boot DOSBox-X kernel"); return CBRET_NONE; } public: void write_FFFF_signature() { /* write the signature at 0xF000:0xFFF0 */ // The farjump at the processor reset entry point (jumps to POST routine) phys_writeb(0xffff0,0xEA); // FARJMP phys_writew(0xffff1,RealOff(BIOS_DEFAULT_RESET_LOCATION)); // offset phys_writew(0xffff3,RealSeg(BIOS_DEFAULT_RESET_LOCATION)); // segment // write system BIOS date for(Bitu i = 0; i < strlen(bios_date_string); i++) phys_writeb(0xffff5+i,(uint8_t)bios_date_string[i]); /* model byte */ if (machine==MCH_TANDY || machine==MCH_AMSTRAD) phys_writeb(0xffffe,0xff); /* Tandy model */ else if (machine==MCH_PCJR) phys_writeb(0xffffe,0xfd); /* PCJr model */ else if (machine==MCH_MCGA) phys_writeb(0xffffe,0xfa); /* PC/2 model 30 model */ else phys_writeb(0xffffe,0xfc); /* PC (FIXME: This is listed as model byte PS/2 model 60) */ // signature phys_writeb(0xfffff,0x55); } BIOS(Section* configuration):Module_base(configuration){ isapnp_biosstruct_base = 0; { // TODO: Eventually, move this to BIOS POST or init phase Section_prop * section=static_cast<Section_prop *>(control->GetSection("dosbox")); Section_prop * pc98_section=static_cast<Section_prop *>(control->GetSection("pc98")); enable_pc98_copyright_string = pc98_section->Get_bool("pc-98 BIOS copyright string"); // NTS: This setting is also valid in PC-98 mode. According to Undocumented PC-98 by Webtech, // there's nothing at I/O port E9h. I will move the I/O port in PC-98 mode if there is in // fact a conflict. --J.C. bochs_port_e9 = section->Get_bool("bochs debug port e9"); // TODO: motherboard init, especially when we get around to full Intel Triton/i440FX chipset emulation isa_memory_hole_512kb = section->Get_bool("isa memory hole at 512kb"); // FIXME: Erm, well this couldv'e been named better. It refers to the amount of conventional memory // made available to the operating system below 1MB, which is usually DOS. dos_conventional_limit = (unsigned int)section->Get_int("dos mem limit"); // for PC-98: When accessing the floppy through INT 1Bh, when enabled, run through a waiting loop to make sure // the timer count is not too high on exit (Ys II) enable_fdc_timer_hack = pc98_section->Get_bool("pc-98 int 1b fdc timer wait"); { std::string s = section->Get_string("unhandled irq handler"); if (s == "simple") unhandled_irq_method = UNHANDLED_IRQ_SIMPLE; else if (s == "cooperative_2nd") unhandled_irq_method = UNHANDLED_IRQ_COOPERATIVE_2ND; // pick default else if (IS_PC98_ARCH) unhandled_irq_method = UNHANDLED_IRQ_COOPERATIVE_2ND; else unhandled_irq_method = UNHANDLED_IRQ_SIMPLE; } } /* pick locations */ /* IBM PC mode: See [https://github.com/skiselev/8088_bios/blob/master/bios.asm]. Some values also provided by Allofich. * PCJr: The BIOS jumps to an address much lower in segment F000, low enough that the second byte of the offset is zero. * "Pitstop II" uses that as a method to test for PCjr [https://www.vogons.org/viewtopic.php?t=50417] */ if (machine == MCH_PCJR) BIOS_DEFAULT_RESET_LOCATION = PhysToReal416(ROMBIOS_GetMemory(3/*JMP NEAR*/,"BIOS default reset location (JMP, PCjr style)",/*align*/1,0xF0043)); else BIOS_DEFAULT_RESET_LOCATION = PhysToReal416(ROMBIOS_GetMemory(3/*JMP NEAR*/,"BIOS default reset location (JMP)",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE05B)); BIOS_DEFAULT_RESET_CODE_LOCATION = PhysToReal416(ROMBIOS_GetMemory(64/*several callbacks*/,"BIOS default reset location (CODE)",/*align*/1)); BIOS_DEFAULT_HANDLER_LOCATION = PhysToReal416(ROMBIOS_GetMemory(1/*IRET*/,"BIOS default handler location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFF53)); BIOS_DEFAULT_INT5_LOCATION = PhysToReal416(ROMBIOS_GetMemory(1/*IRET*/, "BIOS default INT5 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFF54)); BIOS_DEFAULT_IRQ0_LOCATION = PhysToReal416(ROMBIOS_GetMemory(0x13/*see callback.cpp for IRQ0*/,"BIOS default IRQ0 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFEA5)); BIOS_DEFAULT_IRQ1_LOCATION = PhysToReal416(ROMBIOS_GetMemory(0x20/*see callback.cpp for IRQ1*/,"BIOS default IRQ1 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE987)); BIOS_DEFAULT_IRQ07_DEF_LOCATION = PhysToReal416(ROMBIOS_GetMemory(7/*see callback.cpp for EOI_PIC1*/,"BIOS default IRQ2-7 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFF55)); BIOS_DEFAULT_IRQ815_DEF_LOCATION = PhysToReal416(ROMBIOS_GetMemory(9/*see callback.cpp for EOI_PIC1*/,"BIOS default IRQ8-15 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE880)); write_FFFF_signature(); /* Setup all the interrupt handlers the bios controls */ /* INT 8 Clock IRQ Handler */ call_irq0=CALLBACK_Allocate(); if (IS_PC98_ARCH) CALLBACK_Setup(call_irq0,INT8_PC98_Handler,CB_IRET,Real2Phys(BIOS_DEFAULT_IRQ0_LOCATION),"IRQ 0 Clock"); else CALLBACK_Setup(call_irq0,INT8_Handler,CB_IRQ0,Real2Phys(BIOS_DEFAULT_IRQ0_LOCATION),"IRQ 0 Clock"); /* INT 11 Get equipment list */ callback[1].Install(&INT11_Handler,CB_IRET,"Int 11 Equipment"); /* INT 12 Memory Size default at 640 kb */ callback[2].Install(&INT12_Handler,CB_IRET,"Int 12 Memory"); ulimit = 640; t_conv = MEM_TotalPages() << 2; /* convert 4096/byte pages -> 1024/byte KB units */ if (allow_more_than_640kb) { if (machine == MCH_CGA) ulimit = 736; /* 640KB + 64KB + 32KB 0x00000-0xB7FFF */ else if (machine == MCH_HERC || machine == MCH_MDA) ulimit = 704; /* 640KB + 64KB = 0x00000-0xAFFFF */ if (t_conv > ulimit) t_conv = ulimit; if (t_conv > 640) { /* because the memory emulation has already set things up */ bool MEM_map_RAM_physmem(Bitu start,Bitu end); MEM_map_RAM_physmem(0xA0000,(t_conv<<10)-1); memset(GetMemBase()+(640<<10),0,(t_conv-640)<<10); } } else { if (t_conv > 640) t_conv = 640; } /* allow user to further limit the available memory below 1MB */ if (dos_conventional_limit != 0 && t_conv > dos_conventional_limit) t_conv = dos_conventional_limit; // TODO: Allow dosbox-x.conf to specify an option to add an EBDA (Extended BIOS Data Area) // at the top of the DOS conventional limit, which we then reduce further to hold // it. Most BIOSes past 1992 or so allocate an EBDA. /* if requested to emulate an ISA memory hole at 512KB, further limit the memory */ if (isa_memory_hole_512kb && t_conv > 512) t_conv = 512; t_conv_real = t_conv; if (machine == MCH_TANDY) { /* Tandy models are said to have started with 256KB. We'll allow down to 64KB */ if (t_conv < 64) t_conv = 64; if (t_conv < 256) LOG(LOG_MISC,LOG_WARN)("Warning: Tandy with less than 256KB is unusual"); /* The shared video/system memory design, and the placement of video RAM at top * of conventional memory, means that if conventional memory is less than 640KB * and not a multiple of 32KB, things can break. */ if ((t_conv % 32) != 0) LOG(LOG_MISC,LOG_WARN)("Warning: Conventional memory size %uKB in Tandy mode is not a multiple of 32KB, games may not display graphics correctly",(unsigned int)t_conv); } else if (machine == MCH_PCJR) { if (t_conv < 64) t_conv = 64; /* PCjr also shares video/system memory, but the video memory can only exist * below 128KB because IBM intended it to only carry 64KB or 128KB on the * motherboard. Any memory past 128KB is likely provided by addons (sidecars) */ if (t_conv < 128 && (t_conv % 32) != 0) LOG(LOG_MISC,LOG_WARN)("Warning: Conventional memory size %uKB in PCjr mode is not a multiple of 32KB, games may not display graphics correctly",(unsigned int)t_conv); } /* and then unmap RAM between t_conv and ulimit */ if (t_conv < ulimit) { Bitu start = (t_conv+3)/4; /* start = 1KB to page round up */ Bitu end = ulimit/4; /* end = 1KB to page round down */ if (start < end) MEM_ResetPageHandler_Unmapped(start,end-start); } if (machine == MCH_TANDY) { /* Take 16KB off the top for video RAM. * This value never changes after boot, even if you then use the 16-color modes which then moves * the video RAM region down 16KB to make a 32KB region. Neither MS-DOS nor INT 10h change this * top of memory value. I hope your DOS game doesn't put any important structures or MCBs above * the 32KB below top of memory, because it WILL get overwritten with graphics! * * This is apparently correct behavior, and DOSBox SVN and other forks follow it too. * * See also: [https://www.vogons.org/viewtopic.php?p=948879#p948879] * Issue: [https://github.com/joncampbell123/dosbox-x/issues/2380] * * Mickeys Space Adventure assumes it can find video RAM by calling INT 12h, subtracting 16KB, and * converting KB to paragraphs. Note that it calls INT 12h while in CGA mode, and subtracts 16KB * knowing video memory will extend downward 16KB into a 32KB region when it switches into the * Tandy/PCjr 16-color mode. */ if (t_conv > 640) t_conv = 640; if (ulimit > 640) ulimit = 640; t_conv -= 16; ulimit -= 16; /* if 32KB would cross a 128KB boundary, then adjust again or else * things will horribly break between text and graphics modes */ if ((t_conv % 128) < 16) t_conv -= 16; /* Our choice also affects which 128KB bank within which the 16KB banks * select what system memory becomes video memory. * * FIXME: Is this controlled by the "extended ram page register?" How? */ tandy_128kbase = ((t_conv - 16u) << 10u) & 0xE0000; /* byte offset = (KB - 16) * 64, round down to multiple of 128KB */ LOG(LOG_MISC,LOG_DEBUG)("BIOS: setting tandy 128KB base region to %lxh",(unsigned long)tandy_128kbase); } else if (machine == MCH_PCJR) { /* PCjr reserves the top of it's internal 128KB of RAM for video RAM. * Sidecars can extend it past 128KB but it requires DOS drivers or TSRs * to modify the MCB chain so that it a) marks the video memory as reserved * and b) creates a new free region above the video RAM region. * * Therefore, only subtract 16KB if 128KB or less is configured for this machine. * * Note this is not speculation, it's there in the PCjr BIOS source code: * [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/Video/PCjr/IBM%20Personal%20Computer%20PCjr%20Hardware%20Reference%20Library%20Technical%20Reference%20%281983%2d11%29%20First%20Edition%20Revised%2epdf] ROM BIOS source code page A-16 */ if (t_conv <= (128+16)) { if (t_conv > 128) t_conv = 128; t_conv -= 16; } if (ulimit <= (128+16)) { if (ulimit > 128) ulimit = 128; ulimit -= 16; } } /* INT 4B. Now we can safely signal error instead of printing "Invalid interrupt 4B" * whenever we install Windows 95. Note that Windows 95 would call INT 4Bh because * that is where the Virtual DMA API lies in relation to EMM386.EXE */ int4b_callback.Install(&INT4B_Handler,CB_IRET,"INT 4B"); /* INT 14 Serial Ports */ callback[3].Install(&INT14_Handler,CB_IRET_STI,"Int 14 COM-port"); /* INT 15 Misc Calls */ callback[4].Install(&INT15_Handler,CB_IRET,"Int 15 Bios"); /* INT 17 Printer Routines */ callback[5].Install(&INT17_Handler,CB_IRET_STI,"Int 17 Printer"); /* INT 1A TIME and some other functions */ callback[6].Install(&INT1A_Handler,CB_IRET_STI,"Int 1a Time"); /* INT 1C System Timer tick called from INT 8 */ callback[7].Install(&INT1C_Handler,CB_IRET,"Int 1c Timer"); /* IRQ 8 RTC Handler */ callback[8].Install(&INT70_Handler,CB_IRET,"Int 70 RTC"); /* Irq 9 rerouted to irq 2 */ callback[9].Install(NULL,CB_IRQ9,"irq 9 bios"); // INT 19h: Boot function callback[10].Install(&INT19_Handler,CB_IRET,"int 19"); // INT 1Bh: IBM PC CTRL+Break callback[19].Install(&INT1B_Break_Handler,CB_IRET,"BIOS 1Bh stock CTRL+BREAK handler"); // INT 76h: IDE IRQ 14 // This is just a dummy IRQ handler to prevent crashes when // IDE emulation fires the IRQ and OS's like Win95 expect // the BIOS to handle the interrupt. // FIXME: Shouldn't the IRQ send an ACK to the PIC as well?!? callback[11].Install(&IRQ14_Dummy,CB_IRET_EOI_PIC2,"irq 14 ide"); // INT 77h: IDE IRQ 15 // This is just a dummy IRQ handler to prevent crashes when // IDE emulation fires the IRQ and OS's like Win95 expect // the BIOS to handle the interrupt. // FIXME: Shouldn't the IRQ send an ACK to the PIC as well?!? callback[12].Install(&IRQ15_Dummy,CB_IRET_EOI_PIC2,"irq 15 ide"); // INT 0Eh: IDE IRQ 6 callback[13].Install(&IRQ15_Dummy,CB_IRET_EOI_PIC1,"irq 6 floppy"); // INT 18h: Enter BASIC // Non-IBM BIOS would display "NO ROM BASIC" here callback[15].Install(&INT18_Handler,CB_IRET,"int 18"); if(IS_J3100) { callback[16].Install(&INT60_Handler,CB_IRET,"Int 60 Bios"); callback[16].Set_RealVec(0x60); callback[17].Install(&INT6F_Handler,CB_INT6F_ATOK,"Int 6F Bios"); callback[17].Set_RealVec(0x6f); } init_vm86_fake_io(); /* Irq 2-7 */ call_irq07default=CALLBACK_Allocate(); /* Irq 8-15 */ call_irq815default=CALLBACK_Allocate(); /* BIOS boot stages */ cb_bios_post.Install(&cb_bios_post__func,CB_RETF,"BIOS POST"); cb_bios_scan_video_bios.Install(&cb_bios_scan_video_bios__func,CB_RETF,"BIOS Scan Video BIOS"); cb_bios_adapter_rom_scan.Install(&cb_bios_adapter_rom_scan__func,CB_RETF,"BIOS Adapter ROM scan"); cb_bios_startup_screen.Install(&cb_bios_startup_screen__func,CB_RETF,"BIOS Startup screen"); cb_bios_boot.Install(&cb_bios_boot__func,CB_RETF,"BIOS BOOT"); cb_bios_bootfail.Install(&cb_bios_bootfail__func,CB_RETF,"BIOS BOOT FAIL"); if (IS_PC98_ARCH) { cb_pc98_rombasic.Install(&cb_pc98_entry__func,CB_RETF,"N88 ROM BASIC"); } else { /* IBM ROM BASIC resides at segment F600:0000 just below the 5150 ROM BIOS. * MS-DOS 1.x and 2.x BASIC(A).COM jump to specific addresses in the ROM BASIC to do their thing. * The purpose of these callbacks is to catch those programs and safely halt emulation to * state that ROM BASIC is not present */ cb_ibm_basic.Install(&cb_ibm_basic_entry__func,CB_RETF,"IBM ROM BASIC entry"); } // Compatible POST routine location: jump to the callback { Bitu wo_fence; { unsigned int delta = (Real2Phys(BIOS_DEFAULT_RESET_CODE_LOCATION) - (Real2Phys(BIOS_DEFAULT_RESET_LOCATION) + 3u)) & 0xFFFFu; Bitu wo = Real2Phys(BIOS_DEFAULT_RESET_LOCATION); phys_writeb(wo+0,0xE9);/*JMP near*/ phys_writew(wo+1,delta); } Bitu wo = Real2Phys(BIOS_DEFAULT_RESET_CODE_LOCATION); wo_fence = wo + 64; // POST phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction phys_writew(wo+0x02,(uint16_t)cb_bios_post.Get_callback()); //The immediate word wo += 4; // video bios scan phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction phys_writew(wo+0x02,(uint16_t)cb_bios_scan_video_bios.Get_callback()); //The immediate word wo += 4; // adapter ROM scan phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction phys_writew(wo+0x02,(uint16_t)cb_bios_adapter_rom_scan.Get_callback()); //The immediate word wo += 4; // startup screen phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction phys_writew(wo+0x02,(uint16_t)cb_bios_startup_screen.Get_callback()); //The immediate word wo += 4; // user boot hook if (bios_user_boot_hook != 0) { phys_writeb(wo+0x00,0x9C); //PUSHF phys_writeb(wo+0x01,0x9A); //CALL FAR phys_writew(wo+0x02,0x0000); //seg:0 phys_writew(wo+0x04,bios_user_boot_hook>>4); wo += 6; } // boot BIOS_boot_code_offset = wo; phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction phys_writew(wo+0x02,(uint16_t)cb_bios_boot.Get_callback()); //The immediate word wo += 4; // boot fail BIOS_bootfail_code_offset = wo; phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction phys_writew(wo+0x02,(uint16_t)cb_bios_bootfail.Get_callback()); //The immediate word wo += 4; /* fence */ phys_writeb(wo++,0xEB); // JMP $-2 phys_writeb(wo++,0xFE); if (wo > wo_fence) E_Exit("BIOS boot callback overrun"); if (IS_PC98_ARCH) { /* Boot disks that run N88 basic, stopgap */ PhysPt bo = 0xE8002; // E800:0002 ROMBIOS_GetMemory(6,"N88 ROM BASIC entry point",/*align*/1,bo); phys_writeb(bo+0x00,(uint8_t)0xFE); //GRP 4 phys_writeb(bo+0x01,(uint8_t)0x38); //Extra Callback instruction phys_writew(bo+0x02,(uint16_t)cb_pc98_rombasic.Get_callback()); //The immediate word phys_writeb(bo+0x04,0xEB); // JMP $-2 phys_writeb(bo+0x05,0xFE); } else { if (ibm_rom_basic_size == 0) { /* IBM MS-DOS 1.x/2.x BASIC and BASICA, stopgap */ PhysPt bo; bo = 0xF6000+0x2DB0; // F600:2DB0 ROMBIOS_GetMemory(6,"IBM ROM BASIC entry point",/*align*/1,bo); phys_writeb(bo+0x00,(uint8_t)0xFE); //GRP 4 phys_writeb(bo+0x01,(uint8_t)0x38); //Extra Callback instruction phys_writew(bo+0x02,(uint16_t)cb_ibm_basic.Get_callback()); //The immediate word phys_writeb(bo+0x04,0xEB); // JMP $-2 phys_writeb(bo+0x05,0xFE); bo = 0xF6000+0x4C79; // F600:4C79 ROMBIOS_GetMemory(6,"IBM ROM BASIC entry point",/*align*/1,bo); phys_writeb(bo+0x00,(uint8_t)0xFE); //GRP 4 phys_writeb(bo+0x01,(uint8_t)0x38); //Extra Callback instruction phys_writew(bo+0x02,(uint16_t)cb_ibm_basic.Get_callback()); //The immediate word phys_writeb(bo+0x04,0xEB); // JMP $-2 phys_writeb(bo+0x05,0xFE); } } if (IS_PC98_ARCH && enable_pc98_copyright_string) { size_t i=0; ROMBIOS_GetMemory(pc98_copyright_str.length()+1,"NEC PC-98 copyright string",/*align*/1,0xE8000 + 0x0DD8); for (;i < pc98_copyright_str.length();i++) phys_writeb(0xE8000 + 0x0DD8 + (PhysPt)i,(uint8_t)pc98_copyright_str[i]); phys_writeb(0xE8000 + 0x0DD8 + (PhysPt)i,0); ROMBIOS_GetMemory(sizeof(pc98_epson_check_2),"NEC PC-98 Epson check data #2",/*align*/1,0xF5200 + 0x018E); for (i=0;i < sizeof(pc98_epson_check_2);i++) phys_writeb(0xF5200 + 0x018E + (PhysPt)i,(uint8_t)pc98_epson_check_2[i]); } } } ~BIOS(){ /* snap the CPU back to real mode. this code thinks in terms of 16-bit real mode * and if allowed to do it's thing in a 32-bit guest OS like WinNT, will trigger * a page fault. */ CPU_Snap_Back_To_Real_Mode(); if (BOCHS_PORT_E9) { delete BOCHS_PORT_E9; BOCHS_PORT_E9=NULL; } if (ISAPNP_PNP_ADDRESS_PORT) { delete ISAPNP_PNP_ADDRESS_PORT; ISAPNP_PNP_ADDRESS_PORT=NULL; } if (ISAPNP_PNP_DATA_PORT) { delete ISAPNP_PNP_DATA_PORT; ISAPNP_PNP_DATA_PORT=NULL; } if (ISAPNP_PNP_READ_PORT) { delete ISAPNP_PNP_READ_PORT; ISAPNP_PNP_READ_PORT=NULL; } if (isapnpigdevice) { /* ISA PnP will auto-free it */ isapnpigdevice=NULL; } if (dosbox_int_iocallout != IO_Callout_t_none) { IO_FreeCallout(dosbox_int_iocallout); dosbox_int_iocallout = IO_Callout_t_none; } /* abort DAC playing */ if (tandy_sb.port) { IO_Write(tandy_sb.port+0xcu,0xd3u); IO_Write(tandy_sb.port+0xcu,0xd0u); } real_writeb(0x40,0xd4,0x00); if (tandy_DAC_callback[0]) { uint32_t orig_vector=real_readd(0x40,0xd6); if (orig_vector==tandy_DAC_callback[0]->Get_RealPointer()) { /* set IRQ vector to old value */ uint8_t tandy_irq = 7; if (tandy_sb.port) tandy_irq = tandy_sb.irq; else if (tandy_dac.port) tandy_irq = tandy_dac.irq; uint8_t tandy_irq_vector = tandy_irq; if (tandy_irq_vector<8) tandy_irq_vector += 8; else tandy_irq_vector += (0x70-8); RealSetVec(tandy_irq_vector,real_readd(0x40,0xd6)); real_writed(0x40,0xd6,0x00000000); } delete tandy_DAC_callback[0]; delete tandy_DAC_callback[1]; tandy_DAC_callback[0]=NULL; tandy_DAC_callback[1]=NULL; } /* encourage the callback objects to uninstall HERE while we're in real mode, NOT during the * destructor stage where we're back in protected mode */ for (unsigned int i=0;i < callback_count;i++) callback[i].Uninstall(); /* assume these were allocated */ CALLBACK_DeAllocate(call_irq0); CALLBACK_DeAllocate(call_irq07default); CALLBACK_DeAllocate(call_irq815default); /* done */ CPU_Snap_Back_Restore(); } }; void BIOS_Enter_Boot_Phase(void) { /* direct CS:IP right to the instruction that leads to the boot process */ /* note that since it's a callback instruction it doesn't really matter * what CS:IP is as long as it points to the instruction */ reg_eip = BIOS_boot_code_offset & 0xFUL; CPU_SetSegGeneral(cs, BIOS_boot_code_offset >> 4UL); } void BIOS_SetCOMPort(Bitu port, uint16_t baseaddr) { switch(port) { case 0: mem_writew(BIOS_BASE_ADDRESS_COM1,baseaddr); mem_writeb(BIOS_COM1_TIMEOUT, 10); // FIXME: Right?? break; case 1: mem_writew(BIOS_BASE_ADDRESS_COM2,baseaddr); mem_writeb(BIOS_COM2_TIMEOUT, 10); // FIXME: Right?? break; case 2: mem_writew(BIOS_BASE_ADDRESS_COM3,baseaddr); mem_writeb(BIOS_COM3_TIMEOUT, 10); // FIXME: Right?? break; case 3: mem_writew(BIOS_BASE_ADDRESS_COM4,baseaddr); mem_writeb(BIOS_COM4_TIMEOUT, 10); // FIXME: Right?? break; } } void BIOS_SetLPTPort(Bitu port, uint16_t baseaddr) { switch(port) { case 0: mem_writew(BIOS_ADDRESS_LPT1,baseaddr); mem_writeb(BIOS_LPT1_TIMEOUT, 10); break; case 1: mem_writew(BIOS_ADDRESS_LPT2,baseaddr); mem_writeb(BIOS_LPT2_TIMEOUT, 10); break; case 2: mem_writew(BIOS_ADDRESS_LPT3,baseaddr); mem_writeb(BIOS_LPT3_TIMEOUT, 10); break; } } void BIOS_PnP_ComPortRegister(Bitu port,Bitu irq) { /* add to PnP BIOS */ if (ISAPNPBIOS) { unsigned char tmp[256]; unsigned int i; /* register serial ports */ const unsigned char h1[9] = { ISAPNP_SYSDEV_HEADER( ISAPNP_ID('P','N','P',0x0,0x5,0x0,0x1), /* PNP0501 16550A-compatible COM port */ ISAPNP_TYPE(0x07,0x00,0x02), /* type: RS-232 communcations device, 16550-compatible */ 0x0001 | 0x0002) }; i = 0; memcpy(tmp+i,h1,9); i += 9; /* can't disable, can't configure */ /*----------allocated--------*/ tmp[i+0] = (8 << 3) | 7; /* IO resource */ tmp[i+1] = 0x01; /* 16-bit decode */ host_writew(tmp+i+2,port); /* min */ host_writew(tmp+i+4,port); /* max */ tmp[i+6] = 0x10; /* align */ tmp[i+7] = 0x08; /* length */ i += 7+1; if (irq > 0) { tmp[i+0] = (4 << 3) | 3; /* IRQ resource */ host_writew(tmp+i+1,1 << irq); tmp[i+3] = 0x09; /* HTL=1 LTL=1 */ i += 3+1; } tmp[i+0] = 0x79; /* END TAG */ tmp[i+1] = 0x00; i += 2; /*-------------possible-----------*/ tmp[i+0] = 0x79; /* END TAG */ tmp[i+1] = 0x00; i += 2; /*-------------compatible---------*/ tmp[i+0] = 0x79; /* END TAG */ tmp[i+1] = 0x00; i += 2; if (!ISAPNP_RegisterSysDev(tmp,i)) { //LOG_MSG("ISAPNP register failed\n"); } } } static BIOS* test = NULL; void BIOS_Destroy(Section* /*sec*/){ ROMBIOS_DumpMemory(); ISA_PNP_FreeAllDevs(); if (test != NULL) { delete test; test = NULL; } } void BIOS_OnPowerOn(Section* sec) { (void)sec;//UNUSED if (test) delete test; test = new BIOS(control->GetSection("joystick")); } void swapInNextDisk(bool pressed); void swapInNextCD(bool pressed); void INT10_OnResetComplete(); void CALLBACK_DeAllocate(Bitu in); void MOUSE_Unsetup_DOS(void); void MOUSE_Unsetup_BIOS(void); void BIOS_OnResetComplete(Section *x) { (void)x;//UNUSED INT10_OnResetComplete(); if (IS_PC98_ARCH) { void PC98_BIOS_Bank_Switch_Reset(void); PC98_BIOS_Bank_Switch_Reset(); } if (biosConfigSeg != 0u) { ROMBIOS_FreeMemory((Bitu)(biosConfigSeg << 4u)); /* remember it was alloc'd paragraph aligned, then saved >> 4 */ biosConfigSeg = 0u; } call_pnp_rp = 0; if (call_pnp_r != ~0UL) { CALLBACK_DeAllocate(call_pnp_r); call_pnp_r = ~0UL; } call_pnp_pp = 0; if (call_pnp_p != ~0UL) { CALLBACK_DeAllocate(call_pnp_p); call_pnp_p = ~0UL; } MOUSE_Unsetup_DOS(); MOUSE_Unsetup_BIOS(); ISA_PNP_FreeAllSysNodeDevs(); } void BIOS_Init() { DOSBoxMenu::item *item; LOG(LOG_MISC,LOG_DEBUG)("Initializing BIOS"); /* make sure the array is zeroed */ ISAPNP_SysDevNodeCount = 0; ISAPNP_SysDevNodeLargest = 0; for (int i=0;i < MAX_ISA_PNP_SYSDEVNODES;i++) ISAPNP_SysDevNodes[i] = NULL; /* make sure CD swap and floppy swap mapper events are available */ MAPPER_AddHandler(swapInNextDisk,MK_o,MMODHOST,"swapimg","Swap floppy drive",&item); /* Originally "Swap Image" but this version does not swap CDs */ item->set_text("Swap floppy drive"); MAPPER_AddHandler(swapInNextCD,MK_d,MMODHOST,"swapcd","Swap CD drive",&item); /* Variant of "Swap Image" for CDs */ item->set_text("Swap CD drive"); /* NTS: VM_EVENT_BIOS_INIT this callback must be first. */ AddExitFunction(AddExitFunctionFuncPair(BIOS_Destroy),false); AddVMEventFunction(VM_EVENT_POWERON,AddVMEventFunctionFuncPair(BIOS_OnPowerOn)); AddVMEventFunction(VM_EVENT_RESET_END,AddVMEventFunctionFuncPair(BIOS_OnResetComplete)); } void write_ID_version_string() { Bitu str_id_at,str_ver_at; size_t str_id_len,str_ver_len; /* NTS: We can't move the version and ID strings, it causes programs like MSD.EXE to lose * track of the "IBM compatible blahblahblah" string. Which means that apparently * programs looking for this information have the address hardcoded ALTHOUGH * experiments show you can move the version string around so long as it's * +1 from a paragraph boundary */ /* TODO: *DO* allow dynamic relocation however if the dosbox-x.conf indicates that the user * is not interested in IBM BIOS compatability. Also, it would be really cool if * dosbox-x.conf could override these strings and the user could enter custom BIOS * version and ID strings. Heh heh heh.. :) */ str_id_at = 0xFE00E; str_ver_at = 0xFE061; str_id_len = strlen(bios_type_string)+1; str_ver_len = strlen(bios_version_string)+1; if (!IS_PC98_ARCH) { /* need to mark these strings off-limits so dynamic allocation does not overwrite them */ ROMBIOS_GetMemory((Bitu)str_id_len+1,"BIOS ID string",1,str_id_at); ROMBIOS_GetMemory((Bitu)str_ver_len+1,"BIOS version string",1,str_ver_at); } if (str_id_at != 0) { for (size_t i=0;i < str_id_len;i++) phys_writeb(str_id_at+(PhysPt)i,(uint8_t)bios_type_string[i]); } if (str_ver_at != 0) { for (size_t i=0;i < str_ver_len;i++) phys_writeb(str_ver_at+(PhysPt)i,(uint8_t)bios_version_string[i]); } } extern uint8_t int10_font_08[256 * 8]; /* NTS: Do not use callbacks! This function is called before CALLBACK_Init() */ void ROMBIOS_Init() { Section_prop * section=static_cast<Section_prop *>(control->GetSection("dosbox")); Bitu oi; // log LOG(LOG_MISC,LOG_DEBUG)("Initializing ROM BIOS"); ibm_rom_basic.clear(); ibm_rom_basic_size = 0; oi = (Bitu)section->Get_int("rom bios minimum size"); /* in KB */ oi = (oi + 3u) & ~3u; /* round to 4KB page */ if (oi > 128u) oi = 128u; if (oi == 0u) { if (IS_PC98_ARCH) oi = 96u; // BIOS standard range is E8000-FFFFF else oi = 64u; } if (oi < 8) oi = 8; /* because of some of DOSBox's fixed ROM structures we can only go down to 8KB */ rombios_minimum_size = (oi << 10); /* convert to minimum, using size coming downward from 1MB */ oi = (Bitu)section->Get_int("rom bios allocation max"); /* in KB */ oi = (oi + 3u) & ~3u; /* round to 4KB page */ if (oi > 128u) oi = 128u; if (oi == 0u) { if (IS_PC98_ARCH) oi = 96u; else oi = 64u; } if (oi < 8u) oi = 8u; /* because of some of DOSBox's fixed ROM structures we can only go down to 8KB */ oi <<= 10u; if (oi < rombios_minimum_size) oi = rombios_minimum_size; rombios_minimum_location = 0x100000ul - oi; /* convert to minimum, using size coming downward from 1MB */ LOG(LOG_BIOS,LOG_DEBUG)("ROM BIOS range: 0x%05X-0xFFFFF",(int)rombios_minimum_location); LOG(LOG_BIOS,LOG_DEBUG)("ROM BIOS range according to minimum size: 0x%05X-0xFFFFF",(int)(0x100000 - rombios_minimum_size)); if (IS_PC98_ARCH && rombios_minimum_location > 0xE8000) LOG(LOG_BIOS,LOG_DEBUG)("Caution: Minimum ROM base higher than E8000 will prevent use of actual PC-98 BIOS image or N88 BASIC"); if (!MEM_map_ROM_physmem(rombios_minimum_location,0xFFFFF)) E_Exit("Unable to map ROM region as ROM"); /* and the BIOS alias at the top of memory (TODO: what about 486/Pentium emulation where the BIOS at the 4GB top is different * from the BIOS at the legacy 1MB boundary because of shadowing and/or decompressing from ROM at boot? */ { uint64_t top = (uint64_t)1UL << (uint64_t)MEM_get_address_bits(); if (top >= ((uint64_t)1UL << (uint64_t)21UL)) { /* 2MB or more */ unsigned long alias_base,alias_end; alias_base = (unsigned long)top + (unsigned long)rombios_minimum_location - (unsigned long)0x100000UL; alias_end = (unsigned long)top - (unsigned long)1UL; LOG(LOG_BIOS,LOG_DEBUG)("ROM BIOS also mapping alias to 0x%08lx-0x%08lx",alias_base,alias_end); if (!MEM_map_ROM_alias_physmem(alias_base,alias_end)) { void MEM_cut_RAM_up_to(Bitu addr); /* it's possible if memory aliasing is set that memsize is too large to make room. * let memory emulation know where the ROM BIOS starts so it can unmap the RAM pages, * reduce the memory reported to the OS, and try again... */ LOG(LOG_BIOS,LOG_DEBUG)("No room for ROM BIOS alias, reducing reported memory and unmapping RAM pages to make room"); MEM_cut_RAM_up_to(alias_base); if (!MEM_map_ROM_alias_physmem(alias_base,alias_end)) E_Exit("Unable to map ROM region as ROM alias"); } } } /* set up allocation */ rombios_alloc.name = "ROM BIOS"; rombios_alloc.topDownAlloc = true; rombios_alloc.initSetRange(rombios_minimum_location,0xFFFF0 - 1); if (IS_PC98_ARCH) { /* TODO: Is this needed? And where? */ } else { /* prevent dynamic allocation from taking reserved fixed addresses above F000:E000 in IBM PC mode. */ rombios_alloc.setMaxDynamicAllocationAddress(0xFE000 - 1); } if (!IS_PC98_ARCH) { ibm_rom_basic = section->Get_string("ibm rom basic"); if (!ibm_rom_basic.empty()) { void ResolvePath(std::string& in); ResolvePath(ibm_rom_basic); struct stat st; if (stat(ibm_rom_basic.c_str(),&st) == 0 && S_ISREG(st.st_mode) && st.st_size >= (off_t)(32u*1024u) && st.st_size <= (off_t)(64u*1024u) && (st.st_size % 4096) == 0) { ibm_rom_basic_size = (size_t)st.st_size; ibm_rom_basic_base = rombios_alloc._max_nonfixed + 1 - st.st_size; LOG_MSG("Will load IBM ROM BASIC to %05lx-%05lx",(unsigned long)ibm_rom_basic_base,(unsigned long)(ibm_rom_basic_base+ibm_rom_basic_size-1)); Bitu base = ROMBIOS_GetMemory(ibm_rom_basic_size,"IBM ROM BASIC",1u/*page align*/,ibm_rom_basic_base); rombios_alloc.setMaxDynamicAllocationAddress(ibm_rom_basic_base - 1); FILE *fp = fopen(ibm_rom_basic.c_str(),"rb"); if (fp != NULL) { fread(GetMemBase()+ibm_rom_basic_base,(size_t)ibm_rom_basic_size,1u,fp); fclose(fp); } } } } write_ID_version_string(); if (IS_PC98_ARCH && enable_pc98_copyright_string) { // PC-98 BIOSes have a copyright string at E800:0DD8 if (ROMBIOS_GetMemory(pc98_copyright_str.length()+1,"PC-98 copyright string",1,0xE8000 + 0x0DD8) == 0) LOG_MSG("WARNING: Was not able to mark off E800:0DD8 off-limits for PC-98 copyright string"); if (ROMBIOS_GetMemory(sizeof(pc98_epson_check_2),"PC-98 unknown data / Epson check",1,0xF5200 + 0x018E) == 0) LOG_MSG("WARNING: Was not able to mark off E800:0DD8 off-limits for PC-98 copyright string"); } /* some structures when enabled are fixed no matter what */ if (rom_bios_8x8_cga_font && !IS_PC98_ARCH) { /* line 139, int10_memory.cpp: the 8x8 font at 0xF000:FA6E, first 128 chars. * allocate this NOW before other things get in the way */ if (ROMBIOS_GetMemory(128*8,"BIOS 8x8 font (first 128 chars)",1,0xFFA6E) == 0) { LOG_MSG("WARNING: Was not able to mark off 0xFFA6E off-limits for 8x8 font"); } } /* PC-98 BIOS vectors appear to reside at segment 0xFD80. This is so common some games * use it (through INT 1Dh) to detect whether they are running on PC-98 or not (issue #927). * * Note that INT 1Dh is one of the few BIOS interrupts not intercepted by PC-98 MS-DOS */ if (IS_PC98_ARCH) { if (ROMBIOS_GetMemory(128,"PC-98 INT vector stub segment 0xFD80",1,0xFD800) == 0) { LOG_MSG("WARNING: Was not able to mark off 0xFD800 off-limits for PC-98 int vector stubs"); } } /* PC-98 BIOSes have a LIO interface at segment F990 with graphic subroutines for Microsoft BASIC */ if (IS_PC98_ARCH) { if (ROMBIOS_GetMemory(256,"PC-98 LIO graphic ROM BIOS library",1,0xF9900) == 0) { LOG_MSG("WARNING: Was not able to mark off 0xF9900 off-limits for PC-98 LIO graphics library"); } } /* install the font */ if (rom_bios_8x8_cga_font) { for (Bitu i=0;i<128*8;i++) { phys_writeb(PhysMake(0xf000,0xfa6e)+i,int10_font_08[i]); } } /* we allow dosbox-x.conf to specify a binary blob to load into ROM BIOS and execute after reset. * we allow this for both hacker curiosity and automated CPU testing. */ { std::string path = section->Get_string("call binary on reset"); struct stat st; if (!path.empty() && stat(path.c_str(),&st) == 0 && S_ISREG(st.st_mode) && st.st_size <= (off_t)(128u*1024u)) { Bitu base = ROMBIOS_GetMemory((Bitu)st.st_size,"User reset vector binary",16u/*page align*/,0u); if (base != 0) { FILE *fp = fopen(path.c_str(),"rb"); if (fp != NULL) { /* NTS: Make sure memory base != NULL, and that it fits within 1MB. * memory code allocates a minimum 1MB of memory even if * guest memory is less than 1MB because ROM BIOS emulation * depends on it. */ assert(GetMemBase() != NULL); assert((base+(Bitu)st.st_size) <= 0x100000ul); size_t readResult = fread(GetMemBase()+base,(size_t)st.st_size,1u,fp); fclose(fp); if (readResult != 1) { LOG(LOG_IO, LOG_ERROR) ("Reading error in ROMBIOS_Init\n"); return; } LOG_MSG("User reset vector binary '%s' loaded at 0x%lx",path.c_str(),(unsigned long)base); bios_user_reset_vector_blob = base; } else { LOG_MSG("WARNING: Unable to open file to load user reset vector binary '%s' into ROM BIOS memory",path.c_str()); } } else { LOG_MSG("WARNING: Unable to load user reset vector binary '%s' into ROM BIOS memory",path.c_str()); } } } /* we allow dosbox-x.conf to specify a binary blob to load into ROM BIOS and execute just before boot. * we allow this for both hacker curiosity and automated CPU testing. */ { std::string path = section->Get_string("call binary on boot"); struct stat st; if (!path.empty() && stat(path.c_str(),&st) == 0 && S_ISREG(st.st_mode) && st.st_size <= (off_t)(128u*1024u)) { Bitu base = ROMBIOS_GetMemory((Bitu)st.st_size,"User boot hook binary",16u/*page align*/,0u); if (base != 0) { FILE *fp = fopen(path.c_str(),"rb"); if (fp != NULL) { /* NTS: Make sure memory base != NULL, and that it fits within 1MB. * memory code allocates a minimum 1MB of memory even if * guest memory is less than 1MB because ROM BIOS emulation * depends on it. */ assert(GetMemBase() != NULL); assert((base+(Bitu)st.st_size) <= 0x100000ul); size_t readResult = fread(GetMemBase()+base,(size_t)st.st_size,1u,fp); fclose(fp); if (readResult != 1) { LOG(LOG_IO, LOG_ERROR) ("Reading error in ROMBIOS_Init\n"); return; } LOG_MSG("User boot hook binary '%s' loaded at 0x%lx",path.c_str(),(unsigned long)base); bios_user_boot_hook = base; } else { LOG_MSG("WARNING: Unable to open file to load user boot hook binary '%s' into ROM BIOS memory",path.c_str()); } } else { LOG_MSG("WARNING: Unable to load user boot hook binary '%s' into ROM BIOS memory",path.c_str()); } } } } //! \brief Updates the state of a lockable key. void UpdateKeyWithLed(int nVirtKey, int flagAct, int flagLed); void BIOS_SynchronizeNumLock() { #if defined(WIN32) UpdateKeyWithLed(VK_NUMLOCK, BIOS_KEYBOARD_FLAGS1_NUMLOCK_ACTIVE, BIOS_KEYBOARD_LEDS_NUM_LOCK); #endif } void BIOS_SynchronizeCapsLock() { #if defined(WIN32) UpdateKeyWithLed(VK_CAPITAL, BIOS_KEYBOARD_FLAGS1_CAPS_LOCK_ACTIVE, BIOS_KEYBOARD_LEDS_CAPS_LOCK); #endif } void BIOS_SynchronizeScrollLock() { #if defined(WIN32) UpdateKeyWithLed(VK_SCROLL, BIOS_KEYBOARD_FLAGS1_SCROLL_LOCK_ACTIVE, BIOS_KEYBOARD_LEDS_SCROLL_LOCK); #endif } void UpdateKeyWithLed(int nVirtKey, int flagAct, int flagLed) { #if defined(WIN32) const auto state = GetKeyState(nVirtKey); const auto flags1 = BIOS_KEYBOARD_FLAGS1; const auto flags2 = BIOS_KEYBOARD_LEDS; auto flag1 = mem_readb(flags1); auto flag2 = mem_readb(flags2); if (state & 1) { flag1 |= flagAct; flag2 |= flagLed; } else { flag1 &= ~flagAct; flag2 &= ~flagLed; } mem_writeb(flags1, flag1); mem_writeb(flags2, flag2); #else (void)nVirtKey; (void)flagAct; (void)flagLed; #endif }
41.079742
448
0.532506
mediaexplorer74
8885496f45395f9f445d05ab7a5c9ece4c225142
869
cpp
C++
3-1_aritmatika_nilai.cpp
ahfa92/cpp
bddd80ea5c6aca23c91bd6693bb32da06e67cbd2
[ "MIT" ]
null
null
null
3-1_aritmatika_nilai.cpp
ahfa92/cpp
bddd80ea5c6aca23c91bd6693bb32da06e67cbd2
[ "MIT" ]
null
null
null
3-1_aritmatika_nilai.cpp
ahfa92/cpp
bddd80ea5c6aca23c91bd6693bb32da06e67cbd2
[ "MIT" ]
null
null
null
#include <stdio.h> #include <conio.h> #include <iostream.h> main() { int a,b,c,d; float hsl1,hsl2,hsl3,hsl4,total; cout <<" Masukkan Nilai Absen :";cin>>a; cout <<" Masukkan Nilai Tugas :";cin>>b; cout <<" Masukkan Nilai UTS :";cin>>c; cout <<" Masukkan Nilai UAS :";cin>>d; hsl1 = a * 20 / 100; hsl2 = b * 25 / 100; hsl3 = c * 25 / 100; hsl4 = d * 30 / 100; total = hsl1 + hsl2 + hsl3 + hsl4; cout <<"==================================\n"; cout <<" Hasil Akhir \n"; cout <<"==================================\n"; cout <<"\n Hasil Akhir : "; cout <<"\nNilai Absen : "<<a<<" x 20% = "<<hsl1<<ends; cout <<"\nNilai Tugas : "<<b<<" x 25% = "<<hsl2<<ends; cout <<"\nNilai UTS : "<<c<<" x 25% = "<<hsl3<<ends; cout <<"\nNilai UAS : "<<d<<" x 30% = "<<hsl4<<ends; cout <<"\nTotal : "<<total<<ends; getch(); }
28.966667
55
0.469505
ahfa92
888fb1d76408eae26b970cbbbc21976252d06c8a
6,908
cc
C++
src/web_server/old/jobs.cc
varqox/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
12
2017-11-05T21:02:58.000Z
2022-03-28T23:11:51.000Z
src/web_server/old/jobs.cc
varqox/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
11
2017-01-05T18:11:41.000Z
2019-11-01T12:40:55.000Z
src/web_server/old/jobs.cc
krzyk240/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
6
2016-12-25T11:22:34.000Z
2020-10-20T16:03:51.000Z
#include "sim/contests/contest.hh" #include "sim/jobs/utils.hh" #include "sim/problems/permissions.hh" #include "src/web_server/old/sim.hh" using sim::jobs::Job; using sim::problems::Problem; using sim::submissions::Submission; using sim::users::User; using std::optional; using std::string; namespace web_server::old { Sim::JobPermissions Sim::jobs_get_overall_permissions() noexcept { STACK_UNWINDING_MARK; using PERM = JobPermissions; if (not session.has_value()) { return PERM::NONE; } switch (session->user_type) { case User::Type::ADMIN: return PERM::VIEW_ALL; case User::Type::TEACHER: case User::Type::NORMAL: return PERM::NONE; } return PERM::NONE; // Shouldn't happen } Sim::JobPermissions Sim::jobs_get_permissions( std::optional<StringView> creator_id, Job::Type job_type, Job::Status job_status) noexcept { STACK_UNWINDING_MARK; using PERM = JobPermissions; using JT = Job::Type; using JS = Job::Status; JobPermissions overall_perms = jobs_get_overall_permissions(); if (not session.has_value()) { return overall_perms; } static_assert(uint(PERM::NONE) == 0, "Needed below"); JobPermissions type_perm = [job_type] { switch (job_type) { case JT::ADD_PROBLEM: case JT::REUPLOAD_PROBLEM: case JT::ADD_PROBLEM__JUDGE_MODEL_SOLUTION: case JT::REUPLOAD_PROBLEM__JUDGE_MODEL_SOLUTION: return PERM::DOWNLOAD_LOG | PERM::DOWNLOAD_UPLOADED_PACKAGE; case JT::CHANGE_PROBLEM_STATEMENT: return PERM::DOWNLOAD_LOG | PERM::DOWNLOAD_UPLOADED_STATEMENT; case JT::JUDGE_SUBMISSION: case JT::REJUDGE_SUBMISSION: case JT::EDIT_PROBLEM: case JT::DELETE_PROBLEM: case JT::MERGE_PROBLEMS: case JT::RESELECT_FINAL_SUBMISSIONS_IN_CONTEST_PROBLEM: case JT::MERGE_USERS: case JT::DELETE_USER: case JT::DELETE_CONTEST: case JT::DELETE_CONTEST_ROUND: case JT::DELETE_CONTEST_PROBLEM: case JT::RESET_PROBLEM_TIME_LIMITS_USING_MODEL_SOLUTION: case JT::DELETE_FILE: return PERM::NONE; } return PERM::NONE; // Shouldn't happen }(); if (session->user_type == User::Type::ADMIN) { switch (job_status) { case JS::PENDING: case JS::NOTICED_PENDING: case JS::IN_PROGRESS: return overall_perms | type_perm | PERM::VIEW | PERM::DOWNLOAD_LOG | PERM::VIEW_ALL | PERM::CANCEL; case JS::FAILED: case JS::CANCELED: return overall_perms | type_perm | PERM::VIEW | PERM::DOWNLOAD_LOG | PERM::VIEW_ALL | PERM::RESTART; case JS::DONE: return overall_perms | type_perm | PERM::VIEW | PERM::DOWNLOAD_LOG | PERM::VIEW_ALL; } } if (creator_id.has_value() and session->user_id == str2num<decltype(session->user_id)>(creator_id.value())) { if (is_one_of(job_status, JS::PENDING, JS::NOTICED_PENDING, JS::IN_PROGRESS)) { return overall_perms | type_perm | PERM::VIEW | PERM::CANCEL; } return overall_perms | type_perm | PERM::VIEW; } return overall_perms; } Sim::JobPermissions Sim::jobs_granted_permissions_problem(StringView problem_id) { STACK_UNWINDING_MARK; using PERM = JobPermissions; using P_PERMS = sim::problems::Permissions; auto problem_perms = sim::problems::get_permissions( mysql, problem_id, (session.has_value() ? optional{session->user_id} : std::nullopt), (session.has_value() ? optional{session->user_type} : std::nullopt)) .value_or(P_PERMS::NONE); if (uint(problem_perms & P_PERMS::VIEW_RELATED_JOBS)) { return PERM::VIEW | PERM::DOWNLOAD_LOG | PERM::DOWNLOAD_UPLOADED_PACKAGE | PERM::DOWNLOAD_UPLOADED_STATEMENT; } return PERM::NONE; } Sim::JobPermissions Sim::jobs_granted_permissions_submission(StringView submission_id) { STACK_UNWINDING_MARK; using PERM = JobPermissions; if (not session.has_value()) { return PERM::NONE; } auto stmt = mysql.prepare("SELECT s.type, p.owner, p.type, cu.mode," " c.is_public " "FROM submissions s " "STRAIGHT_JOIN problems p ON p.id=s.problem_id " "LEFT JOIN contests c ON c.id=s.contest_id " "LEFT JOIN contest_users cu ON cu.user_id=?" " AND cu.contest_id=s.contest_id " "WHERE s.id=?"); stmt.bind_and_execute(session->user_id, submission_id); EnumVal<Submission::Type> stype{}; mysql::Optional<decltype(Problem::owner)::value_type> problem_owner; decltype(Problem::type) problem_type; mysql::Optional<decltype(sim::contest_users::ContestUser::mode)> cu_mode; mysql::Optional<decltype(sim::contests::Contest::is_public)> is_public; stmt.res_bind_all(stype, problem_owner, problem_type, cu_mode, is_public); if (stmt.next()) { if (is_public.has_value() and // <-- contest exists uint( sim::contests::get_permissions( (session.has_value() ? std::optional{session->user_type} : std::nullopt), is_public.value(), cu_mode) & sim::contests::Permissions::ADMIN)) { return PERM::VIEW | PERM::DOWNLOAD_LOG; } // The below check has to be done as the last one because it gives the // least permissions auto problem_perms = sim::problems::get_permissions( (session.has_value() ? optional{session->user_id} : std::nullopt), (session.has_value() ? optional{session->user_type} : std::nullopt), problem_owner, problem_type); // Give access to the problem's submissions' jobs to the problem's admin if (bool(uint(problem_perms & sim::problems::Permissions::EDIT))) { return PERM::VIEW | PERM::DOWNLOAD_LOG; } } return PERM::NONE; } void Sim::jobs_handle() { STACK_UNWINDING_MARK; StringView next_arg = url_args.extract_next_arg(); if (is_digit(next_arg)) { jobs_jid = next_arg; page_template(intentional_unsafe_string_view(concat("Job ", jobs_jid))); append("view_job(false, ", jobs_jid, ", window.location.hash);"); return; } InplaceBuff<32> query_suffix{}; if (next_arg == "my") { query_suffix.append("/u", session->user_id); } else if (!next_arg.empty()) { return error404(); } /* List jobs */ page_template("Job queue"); append("document.body.appendChild(elem_with_text('h1', 'Jobs'));" "tab_jobs_lister($('body'));"); } } // namespace web_server::old
33.697561
95
0.624204
varqox
889006ef3f26eaf8d41bc9814206a2a2cc9e7338
3,394
cc
C++
src/repl/executionengine.cc
k3v/dfx-and-more
df435f624e78ad3b9c86f8b689b76b726f7883b2
[ "MIT" ]
2
2017-06-08T18:20:03.000Z
2017-06-10T19:21:36.000Z
src/repl/executionengine.cc
furryfaust/dfx-and-more
df435f624e78ad3b9c86f8b689b76b726f7883b2
[ "MIT" ]
null
null
null
src/repl/executionengine.cc
furryfaust/dfx-and-more
df435f624e78ad3b9c86f8b689b76b726f7883b2
[ "MIT" ]
null
null
null
#include "dfxam.h" using namespace dfxam; repl::Function::Function(std::string name, ast::Expression* expr) : name(name), expr(expr) {} repl::Function::Function(ast::Assignment* a) { ast::Expression* ident = a->getDeclaration()->getExpression(); if (ast::Function* func = dynamic_cast<ast::Function*>(ident)) { name = func->getName(); } std::vector<ast::Expression*> ins = a->getDeclaration()->getArguments(); for (auto it = ins.begin(); it != ins.end(); it++) { ast::Function* func = dynamic_cast<ast::Function*>(*it); if (func) { this->inputs.push_back(func->getName()); } } expr = a->getExpression(); } ast::Expression* repl::Function::getExpression() const { return expr; } std::string repl::Function::getName() const { return name; } std::vector<std::string> repl::Function::getInputs() const { return inputs; } repl::Frame::Frame(std::vector<ast::Expression*> args) : arguments(args) {} bool repl::Frame::bindParameters(std::vector<std::string> params) { if (params.size() != arguments.size()) { return false; } for (int i = 0; i < params.size(); i++) { parameters[params[i]] = i; } return true; } ast::Expression* repl::Frame::getArg(std::string name) { auto find = parameters.find(name); return find == parameters.end() ? nullptr : arguments[find->second]; } void repl::ExecutionEngine::registerFunction(repl::Function* f) { functions[f->getName()] = f; } repl::Function* repl::ExecutionEngine::retrieveFunction(std::string name) { auto find = functions.find(name); return find == functions.end() ? nullptr : find->second; } void repl::ExecutionEngine::deregisterFunction(std::string name) { Function* f; if (!(f = retrieveFunction(name))) { delete f; } functions.erase(name); } ast::Expression* repl::ExecutionEngine::getFrameArg(std::string name) { if (callStack.empty()) { return nullptr; } Frame& f = callStack.top(); return f.getArg(name); } bool repl::ExecutionEngine::bindFrameParameters(std::vector<std::string> params) { if (callStack.empty()) { return false; } Frame& f = callStack.top(); return f.bindParameters(params); } void repl::ExecutionEngine::pushFrame(std::vector<ast::Expression*> args) { Frame f(args); callStack.push(f); } void repl::ExecutionEngine::popFrame() { callStack.pop(); } void repl::ExecutionEngine::operator <<(std::string& raw) { repl::Lexer lexer(raw); std::vector<repl::Token> tokens; try { tokens = lexer.lex(); } catch (std::string ex) { std::cout << ex; return; } repl::Parser parser(tokens); ast::Expression* expr; try { expr = parser.parse(); } catch (std::string ex) { std::cout << ex; } execute(expr); } void repl::ExecutionEngine::execute(ast::Expression* expr) { if (ast::Assignment* a = dynamic_cast<ast::Assignment*>(expr)) { repl::Function* f = new repl::Function(a); std::cout << "Registering function: " << f->getName() << std::endl; registerFunction(f); } else { std::cout << "Evaluating expression: " << expr << std::endl; auto eval = expr->simplify(this); std::cout << eval; delete eval; delete expr; } }
24.594203
82
0.605775
k3v
889ae23c9eaf7124a0cbc221bcbcc785a915a651
723
cpp
C++
cl_dll/in_camera.cpp
edgarbarney/halflife-planckepoch
630e7066d8bf260783eaea7341f3c84fb87d69dd
[ "Unlicense" ]
3
2021-08-08T14:22:11.000Z
2022-02-02T03:08:17.000Z
cl_dll/in_camera.cpp
edgarbarney/halflife-planckepoch
630e7066d8bf260783eaea7341f3c84fb87d69dd
[ "Unlicense" ]
7
2021-02-27T01:55:27.000Z
2021-09-06T17:32:43.000Z
cl_dll/in_camera.cpp
edgarbarney/halflife-planckepoch
630e7066d8bf260783eaea7341f3c84fb87d69dd
[ "Unlicense" ]
6
2021-03-14T15:35:17.000Z
2022-01-10T22:53:15.000Z
//========= Copyright (c) 1996-2002, Valve LLC, All rights reserved. ============ // New clipping style camera - original idea by Xwider // Purpose: // // $NoKeywords: $ //============================================================================= #include "hud.h" #include "cl_util.h" #include "camera.h" #include "in_defs.h" extern "C" { void DLLEXPORT CAM_Think( void ); int DLLEXPORT CL_IsThirdPerson( void ); void DLLEXPORT CL_CameraOffset( float *ofs ); } int iMouseInUse = 0; void DLLEXPORT CAM_Think( void ) { } void CAM_Init( ) { } int DLLEXPORT CL_IsThirdPerson( void ) { return (gHUD.m_iCameraMode ? 1 : 0); } void DLLEXPORT CL_CameraOffset( float *ofs ) { VectorCopy( vec3_origin, ofs ); }
18.075
81
0.591978
edgarbarney
88a468221244b97b14a732ac7772f388952e285a
182
cpp
C++
Codeforces/A_AB_Balance.cpp
anubhab-code/Competitive-Programming
de28cb7d44044b9e7d8bdb475da61e37c018ac35
[ "MIT" ]
null
null
null
Codeforces/A_AB_Balance.cpp
anubhab-code/Competitive-Programming
de28cb7d44044b9e7d8bdb475da61e37c018ac35
[ "MIT" ]
null
null
null
Codeforces/A_AB_Balance.cpp
anubhab-code/Competitive-Programming
de28cb7d44044b9e7d8bdb475da61e37c018ac35
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int t; cin>>t; for(int i=0;i<t;i++) { string a; cin>>a; a[a.length() - 1] = a[0]; cout<<a<<endl; } return 0; }
12.133333
27
0.527473
anubhab-code
88a765367d9f6123c8a4a6f28abc47623683b10a
2,145
cpp
C++
src/caffe/layers/moving_normalize_layer.cpp
Rashomon5487/caffe-windows
a136724edbd0f86bd66a5b0eb7043af33dbf1c8b
[ "BSD-2-Clause" ]
1,617
2015-04-25T14:02:45.000Z
2022-03-20T09:54:40.000Z
src/caffe/layers/moving_normalize_layer.cpp
he2016012996/caffe-windows
967eedf25009e334b7f6f933bb5e17aaaff5bef6
[ "BSD-2-Clause" ]
319
2015-02-25T08:40:47.000Z
2022-03-21T04:36:06.000Z
src/caffe/layers/moving_normalize_layer.cpp
he2016012996/caffe-windows
967eedf25009e334b7f6f933bb5e17aaaff5bef6
[ "BSD-2-Clause" ]
834
2015-04-25T14:02:23.000Z
2022-03-16T17:56:55.000Z
#include <algorithm> #include <vector> #include <cmath> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/layers/moving_normalize_layer.hpp" namespace caffe { #define sign(x) (Dtype(0) < (x)) - ((x) < Dtype(0)) template <typename Dtype> void MovingNormalizeLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { if (this->blobs_.size() > 0) { LOG(INFO) << "Skipping parameter initialization"; } else { this->blobs_.resize(1); this->blobs_[0].reset(new Blob<Dtype>({ 1 })); this->blobs_[0]->mutable_cpu_data()[0] = -1; } if (this->layer_param_.param_size() == 0) { ParamSpec* fixed_param_spec = this->layer_param_.add_param(); fixed_param_spec->set_lr_mult(0.f); fixed_param_spec->set_decay_mult(0.f); } else { CHECK_EQ(this->layer_param_.param(0).lr_mult(), 0.f) << "Cannot configure statistics as layer parameters."; } } template <typename Dtype> void MovingNormalizeLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { top[0]->ReshapeLike(*bottom[0]); squared_.ReshapeLike(*bottom[0]); if (top.size() == 2) { top[1]->Reshape({ 1 }); } norm_.Reshape(bottom[0]->num(), 1, bottom[0]->height(), bottom[0]->width()); sum_multiplier_.Reshape(bottom[0]->num(), 1, bottom[0]->height(), bottom[0]->width()); caffe_set(sum_multiplier_.count(), Dtype(1), sum_multiplier_.mutable_cpu_data()); } template <typename Dtype> void MovingNormalizeLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { NOT_IMPLEMENTED; } template <typename Dtype> void MovingNormalizeLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { NOT_IMPLEMENTED; } #ifdef CPU_ONLY STUB_GPU(MovingNormalizeLayer); #endif INSTANTIATE_CLASS(MovingNormalizeLayer); REGISTER_LAYER_CLASS(MovingNormalize); } // namespace caffe
30.642857
83
0.654545
Rashomon5487
88a85427d3aa1b26cb4b83be6141092807cb7d4a
375
cpp
C++
ITP1/q34.cpp
felixny/AizuOnline
8ff399d60077e08961845502d4a99244da580cd2
[ "MIT" ]
null
null
null
ITP1/q34.cpp
felixny/AizuOnline
8ff399d60077e08961845502d4a99244da580cd2
[ "MIT" ]
null
null
null
ITP1/q34.cpp
felixny/AizuOnline
8ff399d60077e08961845502d4a99244da580cd2
[ "MIT" ]
null
null
null
// ITP1_10_B #include <iostream> #include <cmath> #include <iomanip> using namespace std; int main(){ double a,b,th; double PI=3.1415926535; cin >> a >> b >> th; th *= PI/180; cout << fixed << setprecision(10); cout << 0.5*a*b*sin(th) << endl; cout << a +b +sqrt(a*a +b*b -2*a*b*cos(th)) << endl; cout << b*sin(th) << endl; return 0; }
18.75
56
0.544
felixny
88a8a1811d83bba97c635fc492dfc91a167ecc92
13,736
cpp
C++
src/mia_tests/Maths/Matrix.tests.cpp
alexlukeneumann/mia
d6288eede3cded6913600ac8c6451b2345835028
[ "MIT" ]
null
null
null
src/mia_tests/Maths/Matrix.tests.cpp
alexlukeneumann/mia
d6288eede3cded6913600ac8c6451b2345835028
[ "MIT" ]
null
null
null
src/mia_tests/Maths/Matrix.tests.cpp
alexlukeneumann/mia
d6288eede3cded6913600ac8c6451b2345835028
[ "MIT" ]
null
null
null
#include <CppUnitTest.h> #include <Maths/Matrix.h> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace mia { namespace tests { TEST_CLASS(MatrixTests) { static f32 constexpr c_Precision = 1e-3f; public: TEST_METHOD(CanConstruct_AZeroFilledMatrix) { u32 const width = 3; u32 const height = 2; Matrix m(width, height); for (u32 rIdx = 0; rIdx < height; ++rIdx) { for (u32 cIdx = 0; cIdx < width; ++cIdx) { Assert::AreEqual(0.0f, m.GetElement(rIdx, cIdx)); } } } TEST_METHOD(CanConstruct_AMatrixFromAnExisting1DArray) { u32 const width = 2; u32 const height = 3; f32 array[] = { 1.0f, 2.0f, 4.2f, 3.0f, 1.1f, 2.4f }; Matrix m(width, height, array); for (u32 rIdx = 0; rIdx < height; ++rIdx) { for (u32 cIdx = 0; cIdx < width; ++cIdx) { Assert::AreEqual(array[(width * rIdx) + cIdx], m.GetElement(rIdx, cIdx)); } } Assert::IsTrue(array != &m.GetElement(0, 0)); } TEST_METHOD(CanCopyConstruct) { u32 const width = 2; u32 const height = 2; f32 array[] = { 1.0f, 2.0f, 4.2f, 3.0f }; Matrix m(width, height, array); Matrix mCopy(m); Assert::AreEqual(m.GetWidth(), mCopy.GetWidth()); Assert::AreEqual(m.GetHeight(), mCopy.GetHeight()); for (u32 rIdx = 0; rIdx < height; ++rIdx) { for (u32 cIdx = 0; cIdx < width; ++cIdx) { Assert::AreEqual(array[(width * rIdx) + cIdx], mCopy.GetElement(rIdx, cIdx)); } } Assert::AreNotEqual(&mCopy.GetElement(0, 0), &m.GetElement(0, 0)); } TEST_METHOD(CanMoveConstruct) { u32 const width = 2; u32 const height = 2; f32 array[] = { 1.0f, 2.0f, 4.2f, 3.0f }; Matrix m(width, height, array); Matrix mMove(std::move(m)); Assert::AreEqual(width, mMove.GetWidth()); Assert::AreEqual(height, mMove.GetHeight()); Assert::AreEqual(static_cast<u32>(0), m.GetWidth()); Assert::AreEqual(static_cast<u32>(0), m.GetHeight()); for (u32 rIdx = 0; rIdx < height; ++rIdx) { for (u32 cIdx = 0; cIdx < width; ++cIdx) { Assert::AreEqual(array[(width * rIdx) + cIdx], mMove.GetElement(rIdx, cIdx)); } } } TEST_METHOD(CanAssignElementValues) { u32 const width = 3; u32 const height = 2; Matrix m(width, height); for (u32 rIdx = 0; rIdx < height; ++rIdx) { for (u32 cIdx = 0; cIdx < width; ++cIdx) { Assert::AreEqual(0.0f, m.GetElement(rIdx, cIdx)); } } f32 const val01 = 2.4f; f32 const val10 = 3.2f; m.GetElement(0, 1) = 2.4f; m.GetElement(1, 0) = 3.2f; Assert::AreEqual(val01, m.GetElement(0, 1)); Assert::AreEqual(val10, m.GetElement(1, 0)); } TEST_METHOD(CanCopyValuesIntoMatrix_DifferentDimensions) { u32 const width = 3; u32 const height = 2; Matrix m(width, height); f32 data[] = { 2.0f, 3.0f, 4.0f }; m.Copy(1, 0, data, width); f32 const expected[] = { 0.0f, 0.0f, 0.0f, // Matrix should be prefilled to zero on construction 2.0f, 3.0f, 4.0f }; for (u32 rIdx = 0; rIdx < height; ++rIdx) { for (u32 cIdx = 0; cIdx < width; ++cIdx) { Assert::AreEqual(expected[(width * rIdx) + cIdx], m.GetElement(rIdx, cIdx)); } } } TEST_METHOD(CanCopyValuesIntoMatrix_SameDimensions) { u32 const width = 3; u32 const height = 3; Matrix m(width, height); f32 data[] = { 2.0f, 3.0f, 4.0f }; m.Copy(2, 0, data, width); f32 const expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 3.0f, 4.0f }; for (u32 rIdx = 0; rIdx < height; ++rIdx) { for (u32 cIdx = 0; cIdx < width; ++cIdx) { Assert::AreEqual(expected[(width * rIdx) + cIdx], m.GetElement(rIdx, cIdx)); } } } TEST_METHOD(CanMultiply_TwoMatrices_SameDimensions) { u32 const width = 3; u32 const height = 3; f32 aValues[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f }; f32 bValues[] = { 3.0f, 4.0f, 5.0f, 1.0f, 2.0f, 3.0f, 1.5f, 2.5f, 4.5f }; f32 expected[] = { 9.5f, 15.5f, 24.5f, 26.0f, 41.0f, 62.0f, 42.5f, 66.5f, 99.5f }; Matrix a(width, height, aValues); Matrix b(width, height, bValues); Matrix result = Matrix::Multiply(a, b); for (u32 rIdx = 0; rIdx < height; ++rIdx) { for (u32 cIdx = 0; cIdx < width; ++cIdx) { f32 const & expectedValue = expected[(width * rIdx) + cIdx]; f32 const & calculatedValue = result.GetElement(rIdx, cIdx); Assert::IsTrue(abs(expectedValue - calculatedValue) < c_Precision); } } } TEST_METHOD(CanMultiply_TwoMatrices_DifferentDimensions) { u32 const aWidth = 3; u32 const aHeight = 3; u32 const bWidth = 2; u32 const bHeight = 3; f32 aValues[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f }; f32 bValues[] = { 3.0f, 4.0f, 1.0f, 2.0f, 1.5f, 2.5f, }; f32 expected[] = { 9.5f, 15.5f, 26.0f, 41.0f, 42.5f, 66.5f, }; Matrix a(aWidth, aHeight, aValues); Matrix b(bWidth, bHeight, bValues); Matrix result = Matrix::Multiply(a, b); u32 const resultWidth = 2; u32 const resultHeight = 3; Assert::AreEqual(resultWidth, result.GetWidth()); Assert::AreEqual(resultHeight, result.GetHeight()); for (u32 rIdx = 0; rIdx < resultHeight; ++rIdx) { for (u32 cIdx = 0; cIdx < resultWidth; ++cIdx) { f32 const & expectedValue = expected[(resultWidth * rIdx) + cIdx]; f32 const & calculatedValue = result.GetElement(rIdx, cIdx); Assert::IsTrue(abs(expectedValue - calculatedValue) < c_Precision); } } } TEST_METHOD(CanTranspose_1DimensionMatrix) { u32 const width = 1; u32 const height = 3; f32 values[] = { 3.0f, 4.0f, 5.0f }; f32 expected[] = { 3.0f, 4.0f, 5.0f }; Matrix m(width, height, values); Matrix mTransposed = Matrix::Transpose(m); Assert::AreEqual(width, mTransposed.GetHeight()); Assert::AreEqual(height, mTransposed.GetWidth()); for (u32 rIdx = 0; rIdx < mTransposed.GetWidth(); ++rIdx) { Assert::AreEqual(expected[rIdx], mTransposed.GetElement(0, rIdx)); } } TEST_METHOD(CanTranspose_SameWidthAndHeight) { u32 const width = 3; u32 const height = 3; f32 values[] = { 3.0f, 4.0f, 5.0f, 1.0f, 2.0f, 3.0f, 1.5f, 2.5f, 4.5f }; f32 expected[] = { 3.0f, 1.0f, 1.5f, 4.0f, 2.0f, 2.5f, 5.0f, 3.0f, 4.5f }; Matrix m(width, height, values); Matrix mTransposed = Matrix::Transpose(m); Assert::AreEqual(width, mTransposed.GetWidth()); Assert::AreEqual(height, mTransposed.GetHeight()); for (u32 rIdx = 0; rIdx < mTransposed.GetHeight(); ++rIdx) { for (u32 cIdx = 0; cIdx < mTransposed.GetWidth(); ++cIdx) { Assert::AreEqual(expected[(mTransposed.GetWidth() * rIdx) + cIdx], mTransposed.GetElement(rIdx, cIdx)); } } } TEST_METHOD(CanTranspose_DifferentWidthAndHeight) { u32 const width = 3; u32 const height = 4; f32 values[] = { 3.0f, 4.0f, 5.0f, 1.0f, 2.0f, 3.0f, 1.5f, 2.5f, 4.5f, 2.0f, 7.0f, 6.0f }; f32 expected[] = { 3.0f, 1.0f, 1.5f, 2.0f, 4.0f, 2.0f, 2.5f, 7.0f, 5.0f, 3.0f, 4.5f, 6.0f }; Matrix m(width, height, values); Matrix mTransposed = Matrix::Transpose(m); Assert::AreEqual(height, mTransposed.GetWidth()); Assert::AreEqual(width, mTransposed.GetHeight()); for (u32 rIdx = 0; rIdx < mTransposed.GetHeight(); ++rIdx) { for (u32 cIdx = 0; cIdx < mTransposed.GetWidth(); ++cIdx) { Assert::AreEqual(expected[(mTransposed.GetWidth() * rIdx) + cIdx], mTransposed.GetElement(rIdx, cIdx)); } } } TEST_METHOD(EqualsOperator_ReturnsTrueIfMatricesAreTheSame) { u32 const width = 3; u32 const height = 3; f32 values[] = { 3.0f, 4.0f, 5.0f, 1.0f, 2.0f, 3.0f, 1.5f, 2.5f, 4.5f }; Matrix a(width, height, values); Matrix b(width, height, values); Assert::IsTrue(a == b); Assert::IsFalse(a != b); } TEST_METHOD(EqualsOperator_ReturnsFalseIfMatricesAreTheDifferent) { u32 const width = 3; u32 const height = 3; f32 aValues[] = { 3.0f, 4.0f, 5.0f, 1.0f, 2.0f, 3.0f, 1.5f, 2.5f, 4.5f }; f32 bValues[] = { 3.0f, 4.0f, 5.0f, 1.0f, 2.5f, 3.0f, 1.5f, 2.5f, 4.5f }; Matrix a(width, height, aValues); Matrix b(width, height, bValues); Assert::IsFalse(a == b); Assert::IsTrue(a != b); } TEST_METHOD(CanAdd_SameDimensions) { u32 const width = 3; u32 const height = 2; f32 aValues[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f }; f32 bValues[] = { 9.0f, 8.0f, 7.0f, 6.0f, 5.0f, 4.0f }; Matrix a(width, height, aValues); Matrix b(width, height, bValues); Matrix result = Matrix::Add(a, b); Assert::AreEqual(width, result.GetWidth()); Assert::AreEqual(height, result.GetHeight()); for (u32 rIdx = 0; rIdx < height; ++rIdx) { for (u32 cIdx = 0; cIdx < width; ++cIdx) { Assert::AreEqual(10.0f, result.GetElement(rIdx, cIdx)); } } } }; } }
31.218182
127
0.386357
alexlukeneumann