text
stringlengths
54
60.6k
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "adaptivepixelrenderer.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/global/globaltypes.h" #include "renderer/kernel/aov/aovsettings.h" #include "renderer/kernel/aov/imagestack.h" #include "renderer/kernel/aov/tilestack.h" #include "renderer/kernel/rendering/final/variationtracker.h" #include "renderer/kernel/rendering/isamplerenderer.h" #include "renderer/kernel/rendering/pixelcontext.h" #include "renderer/kernel/rendering/pixelrendererbase.h" #include "renderer/kernel/rendering/shadingresultframebuffer.h" #include "renderer/kernel/shading/shadingfragment.h" #include "renderer/kernel/shading/shadingresult.h" #include "renderer/modeling/frame/frame.h" #include "renderer/utility/settingsparsing.h" // appleseed.foundation headers. #include "foundation/image/color.h" #include "foundation/image/image.h" #include "foundation/image/tile.h" #include "foundation/math/aabb.h" #include "foundation/math/hash.h" #include "foundation/math/minmax.h" #include "foundation/math/scalar.h" #include "foundation/math/vector.h" #include "foundation/platform/types.h" #include "foundation/utility/autoreleaseptr.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/statistics.h" // Standard headers. #include <algorithm> #include <cassert> #include <cmath> #include <memory> using namespace foundation; using namespace std; namespace renderer { namespace { // // Adaptive pixel renderer. // class AdaptivePixelRenderer : public PixelRendererBase { public: AdaptivePixelRenderer( const Frame& frame, ISampleRendererFactory* factory, const ParamArray& params, const size_t thread_index) : m_params(params) , m_sample_renderer(factory->create(thread_index)) { if (m_params.m_diagnostics) { ImageStack& images = frame.aov_images(); m_variation_aov_index = images.get_index("variation"); if (m_variation_aov_index == size_t(~0) && images.size() < MaxAOVCount) m_variation_aov_index = images.append("variation", ImageStack::IdentificationType, 4, PixelFormatFloat); m_samples_aov_index = images.get_index("samples"); if (m_samples_aov_index == size_t(~0) && images.size() < MaxAOVCount) m_samples_aov_index = images.append("samples", ImageStack::IdentificationType, 4, PixelFormatFloat); if ((thread_index == 0) && (m_variation_aov_index == size_t(~0) || m_samples_aov_index == size_t(~0))) { RENDERER_LOG_WARNING( "could not create some of the diagnostic AOVs, maximum number of AOVs (" FMT_SIZE_T ") reached.", MaxAOVCount); } } } virtual void release() APPLESEED_OVERRIDE { delete this; } virtual void on_tile_begin( const Frame& frame, Tile& tile, TileStack& aov_tiles) APPLESEED_OVERRIDE { m_scratch_fb_half_width = truncate<int>(ceil(frame.get_filter().get_xradius())); m_scratch_fb_half_height = truncate<int>(ceil(frame.get_filter().get_yradius())); m_scratch_fb.reset( new ShadingResultFrameBuffer( 2 * m_scratch_fb_half_width + 1, 2 * m_scratch_fb_half_height + 1, frame.aov_images().size(), frame.get_filter())); if (m_params.m_diagnostics) m_diagnostics.reset(new Tile(tile.get_width(), tile.get_height(), 2, PixelFormatFloat)); } virtual void on_tile_end( const Frame& frame, Tile& tile, TileStack& aov_tiles) APPLESEED_OVERRIDE { if (m_params.m_diagnostics) { const size_t width = tile.get_width(); const size_t height = tile.get_height(); for (size_t y = 0; y < height; ++y) { for (size_t x = 0; x < width; ++x) { Color<float, 2> values; m_diagnostics->get_pixel(x, y, values); if (m_variation_aov_index != size_t(~0)) aov_tiles.set_pixel(x, y, m_variation_aov_index, scalar_to_color(values[0])); if (m_samples_aov_index != size_t(~0)) aov_tiles.set_pixel(x, y, m_samples_aov_index, scalar_to_color(values[1])); } } } } virtual void render_pixel( const Frame& frame, Tile& tile, TileStack& aov_tiles, const AABB2i& tile_bbox, const size_t pass_hash, const Vector2i& pi, const Vector2i& pt, SamplingContext::RNGType& rng, ShadingResultFrameBuffer& framebuffer) APPLESEED_OVERRIDE { const size_t aov_count = frame.aov_images().size(); on_pixel_begin(); m_scratch_fb->clear(); // Create a sampling context. const size_t frame_width = frame.image().properties().m_canvas_width; const size_t instance = mix_uint32( static_cast<uint32>(pass_hash), static_cast<uint32>(pi.y * frame_width + pi.x)); SamplingContext sampling_context( rng, m_params.m_sampling_mode, 2, // number of dimensions 0, // number of samples -- unknown instance); // initial instance number VariationTracker trackers[3]; while (true) { trackers[0].reset_variation(); trackers[1].reset_variation(); trackers[2].reset_variation(); // Don't exceed 'max' samples in total. assert(trackers[0].get_size() <= m_params.m_max_samples); const size_t remaining_samples = m_params.m_max_samples - trackers[0].get_size(); if (remaining_samples == 0) break; // Each batch contains 'min' samples. const size_t batch_size = min(m_params.m_min_samples, remaining_samples); for (size_t i = 0; i < batch_size; ++i) { // Generate a uniform sample in [0,1)^2. const Vector2d s = sampling_context.next2<Vector2d>(); // Compute the sample position in NDC. const Vector2d sample_position = frame.get_sample_position(pi.x + s.x, pi.y + s.y); // Create a pixel context that identifies the pixel and sample currently being rendered. const PixelContext pixel_context(pi, sample_position); // Render the sample. ShadingResult shading_result(aov_count); SamplingContext child_sampling_context(sampling_context); m_sample_renderer->render_sample( child_sampling_context, pixel_context, sample_position, shading_result); // Ignore invalid samples. if (!shading_result.is_valid_linear_rgb()) { signal_invalid_sample(); continue; } // Merge the sample into the scratch framebuffer. m_scratch_fb->add( static_cast<float>(m_scratch_fb_half_width + s.x), static_cast<float>(m_scratch_fb_half_height + s.y), shading_result); // Update statistics for this pixel. // todo: variation should be computed in a user-selectable color space, typically the target color space. // todo: one tracker per AOV? trackers[0].insert(shading_result.m_main.m_color[0]); trackers[1].insert(shading_result.m_main.m_color[1]); trackers[2].insert(shading_result.m_main.m_color[2]); } // Stop if the variation criterion is met. if (trackers[0].get_variation() <= m_params.m_max_variation && trackers[1].get_variation() <= m_params.m_max_variation && trackers[2].get_variation() <= m_params.m_max_variation) break; } // Merge the scratch framebuffer into the output framebuffer. const float rcp_sample_count = 1.0f / trackers[0].get_size(); for (int y = -m_scratch_fb_half_height; y <= m_scratch_fb_half_height; ++y) { for (int x = -m_scratch_fb_half_width; x <= m_scratch_fb_half_width; ++x) { if (tile_bbox.contains(Vector2i(pt.x + x, pt.y + y))) { framebuffer.merge( // destination pt.x + x, // destination X pt.y + y, // destination Y *m_scratch_fb.get(), // source m_scratch_fb_half_width + x, // source X m_scratch_fb_half_height + y, // source Y rcp_sample_count); // scaling } } } // Store diagnostics values in the diagnostics tile. if (m_params.m_diagnostics && tile_bbox.contains(pt)) { Color<float, 2> values; values[0] = saturate( max( trackers[0].get_variation(), trackers[1].get_variation(), trackers[2].get_variation()) / m_params.m_max_variation); values[1] = m_params.m_min_samples == m_params.m_max_samples ? 1.0f : fit( static_cast<float>(trackers[0].get_size()), static_cast<float>(m_params.m_min_samples), static_cast<float>(m_params.m_max_samples), 0.0f, 1.0f); m_diagnostics->set_pixel(pt.x, pt.y, values); } on_pixel_end(pi); } virtual StatisticsVector get_statistics() const APPLESEED_OVERRIDE { return m_sample_renderer->get_statistics(); } private: struct Parameters { const SamplingContext::Mode m_sampling_mode; const size_t m_min_samples; const size_t m_max_samples; const float m_max_variation; const bool m_diagnostics; explicit Parameters(const ParamArray& params) : m_sampling_mode(get_sampling_context_mode(params)) , m_min_samples(params.get_required<size_t>("min_samples", 16)) , m_max_samples(params.get_required<size_t>("max_samples", 256)) , m_max_variation(pow(10.0f, -params.get_optional<float>("quality", 2.0f))) , m_diagnostics(params.get_optional<bool>("enable_diagnostics", false)) { } }; const Parameters m_params; auto_release_ptr<ISampleRenderer> m_sample_renderer; size_t m_variation_aov_index; size_t m_samples_aov_index; int m_scratch_fb_half_width; int m_scratch_fb_half_height; auto_ptr<ShadingResultFrameBuffer> m_scratch_fb; auto_ptr<Tile> m_diagnostics; static Color4f scalar_to_color(const float value) { static const Color4f Blue(0.0f, 0.0f, 1.0f, 1.0f); static const Color4f Red(1.0f, 0.0f, 0.0f, 1.0f); return lerp(Blue, Red, saturate(value)); } }; } // // AdaptivePixelRendererFactory class implementation. // AdaptivePixelRendererFactory::AdaptivePixelRendererFactory( const Frame& frame, ISampleRendererFactory* factory, const ParamArray& params) : m_frame(frame) , m_factory(factory) , m_params(params) { } void AdaptivePixelRendererFactory::release() { delete this; } IPixelRenderer* AdaptivePixelRendererFactory::create( const size_t thread_index) { return new AdaptivePixelRenderer( m_frame, m_factory, m_params, thread_index); } Dictionary AdaptivePixelRendererFactory::get_params_metadata() { Dictionary metadata; metadata.dictionaries().insert( "min_samples", Dictionary() .insert("type", "int") .insert("default", "16") .insert("label", "Min Samples") .insert("help", "Minimum number of anti-aliasing samples")); metadata.dictionaries().insert( "max_samples", Dictionary() .insert("type", "int") .insert("default", "256") .insert("label", "Max Samples") .insert("help", "Maximum number of anti-aliasing samples")); metadata.dictionaries().insert( "quality", Dictionary() .insert("type", "float") .insert("default", "2.0") .insert("label", "Quality") .insert("help", "Quality factor")); metadata.dictionaries().insert( "enable_diagnostics", Dictionary() .insert("type", "bool") .insert("default", "false") .insert("label", "Enable Diagnostics") .insert( "help", "Enable adaptive sampling diagnostics")); return metadata; } } // namespace renderer <commit_msg>Do not create aov images directly.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "adaptivepixelrenderer.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/global/globaltypes.h" #include "renderer/kernel/aov/aovsettings.h" #include "renderer/kernel/aov/imagestack.h" #include "renderer/kernel/aov/tilestack.h" #include "renderer/kernel/rendering/final/variationtracker.h" #include "renderer/kernel/rendering/isamplerenderer.h" #include "renderer/kernel/rendering/pixelcontext.h" #include "renderer/kernel/rendering/pixelrendererbase.h" #include "renderer/kernel/rendering/shadingresultframebuffer.h" #include "renderer/kernel/shading/shadingfragment.h" #include "renderer/kernel/shading/shadingresult.h" #include "renderer/modeling/frame/frame.h" #include "renderer/utility/settingsparsing.h" // appleseed.foundation headers. #include "foundation/image/color.h" #include "foundation/image/image.h" #include "foundation/image/tile.h" #include "foundation/math/aabb.h" #include "foundation/math/hash.h" #include "foundation/math/minmax.h" #include "foundation/math/scalar.h" #include "foundation/math/vector.h" #include "foundation/platform/types.h" #include "foundation/utility/autoreleaseptr.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/statistics.h" // Standard headers. #include <algorithm> #include <cassert> #include <cmath> #include <memory> using namespace foundation; using namespace std; namespace renderer { namespace { // // Adaptive pixel renderer. // class AdaptivePixelRenderer : public PixelRendererBase { public: AdaptivePixelRenderer( const Frame& frame, ISampleRendererFactory* factory, const ParamArray& params, const size_t thread_index) : m_params(params) , m_sample_renderer(factory->create(thread_index)) { if (m_params.m_diagnostics) { m_variation_aov_index = frame.create_extra_aov_image("variation"); m_samples_aov_index = frame.create_extra_aov_image("samples"); if ((thread_index == 0) && (m_variation_aov_index == size_t(~0) || m_samples_aov_index == size_t(~0))) { RENDERER_LOG_WARNING( "could not create some of the diagnostic AOVs, maximum number of AOVs (" FMT_SIZE_T ") reached.", MaxAOVCount); } } } virtual void release() APPLESEED_OVERRIDE { delete this; } virtual void on_tile_begin( const Frame& frame, Tile& tile, TileStack& aov_tiles) APPLESEED_OVERRIDE { m_scratch_fb_half_width = truncate<int>(ceil(frame.get_filter().get_xradius())); m_scratch_fb_half_height = truncate<int>(ceil(frame.get_filter().get_yradius())); m_scratch_fb.reset( new ShadingResultFrameBuffer( 2 * m_scratch_fb_half_width + 1, 2 * m_scratch_fb_half_height + 1, frame.aov_images().size(), frame.get_filter())); if (m_params.m_diagnostics) m_diagnostics.reset(new Tile(tile.get_width(), tile.get_height(), 2, PixelFormatFloat)); } virtual void on_tile_end( const Frame& frame, Tile& tile, TileStack& aov_tiles) APPLESEED_OVERRIDE { if (m_params.m_diagnostics) { const size_t width = tile.get_width(); const size_t height = tile.get_height(); for (size_t y = 0; y < height; ++y) { for (size_t x = 0; x < width; ++x) { Color<float, 2> values; m_diagnostics->get_pixel(x, y, values); if (m_variation_aov_index != size_t(~0)) aov_tiles.set_pixel(x, y, m_variation_aov_index, scalar_to_color(values[0])); if (m_samples_aov_index != size_t(~0)) aov_tiles.set_pixel(x, y, m_samples_aov_index, scalar_to_color(values[1])); } } } } virtual void render_pixel( const Frame& frame, Tile& tile, TileStack& aov_tiles, const AABB2i& tile_bbox, const size_t pass_hash, const Vector2i& pi, const Vector2i& pt, SamplingContext::RNGType& rng, ShadingResultFrameBuffer& framebuffer) APPLESEED_OVERRIDE { const size_t aov_count = frame.aov_images().size(); on_pixel_begin(); m_scratch_fb->clear(); // Create a sampling context. const size_t frame_width = frame.image().properties().m_canvas_width; const size_t instance = mix_uint32( static_cast<uint32>(pass_hash), static_cast<uint32>(pi.y * frame_width + pi.x)); SamplingContext sampling_context( rng, m_params.m_sampling_mode, 2, // number of dimensions 0, // number of samples -- unknown instance); // initial instance number VariationTracker trackers[3]; while (true) { trackers[0].reset_variation(); trackers[1].reset_variation(); trackers[2].reset_variation(); // Don't exceed 'max' samples in total. assert(trackers[0].get_size() <= m_params.m_max_samples); const size_t remaining_samples = m_params.m_max_samples - trackers[0].get_size(); if (remaining_samples == 0) break; // Each batch contains 'min' samples. const size_t batch_size = min(m_params.m_min_samples, remaining_samples); for (size_t i = 0; i < batch_size; ++i) { // Generate a uniform sample in [0,1)^2. const Vector2d s = sampling_context.next2<Vector2d>(); // Compute the sample position in NDC. const Vector2d sample_position = frame.get_sample_position(pi.x + s.x, pi.y + s.y); // Create a pixel context that identifies the pixel and sample currently being rendered. const PixelContext pixel_context(pi, sample_position); // Render the sample. ShadingResult shading_result(aov_count); SamplingContext child_sampling_context(sampling_context); m_sample_renderer->render_sample( child_sampling_context, pixel_context, sample_position, shading_result); // Ignore invalid samples. if (!shading_result.is_valid_linear_rgb()) { signal_invalid_sample(); continue; } // Merge the sample into the scratch framebuffer. m_scratch_fb->add( static_cast<float>(m_scratch_fb_half_width + s.x), static_cast<float>(m_scratch_fb_half_height + s.y), shading_result); // Update statistics for this pixel. // todo: variation should be computed in a user-selectable color space, typically the target color space. // todo: one tracker per AOV? trackers[0].insert(shading_result.m_main.m_color[0]); trackers[1].insert(shading_result.m_main.m_color[1]); trackers[2].insert(shading_result.m_main.m_color[2]); } // Stop if the variation criterion is met. if (trackers[0].get_variation() <= m_params.m_max_variation && trackers[1].get_variation() <= m_params.m_max_variation && trackers[2].get_variation() <= m_params.m_max_variation) break; } // Merge the scratch framebuffer into the output framebuffer. const float rcp_sample_count = 1.0f / trackers[0].get_size(); for (int y = -m_scratch_fb_half_height; y <= m_scratch_fb_half_height; ++y) { for (int x = -m_scratch_fb_half_width; x <= m_scratch_fb_half_width; ++x) { if (tile_bbox.contains(Vector2i(pt.x + x, pt.y + y))) { framebuffer.merge( // destination pt.x + x, // destination X pt.y + y, // destination Y *m_scratch_fb.get(), // source m_scratch_fb_half_width + x, // source X m_scratch_fb_half_height + y, // source Y rcp_sample_count); // scaling } } } // Store diagnostics values in the diagnostics tile. if (m_params.m_diagnostics && tile_bbox.contains(pt)) { Color<float, 2> values; values[0] = saturate( max( trackers[0].get_variation(), trackers[1].get_variation(), trackers[2].get_variation()) / m_params.m_max_variation); values[1] = m_params.m_min_samples == m_params.m_max_samples ? 1.0f : fit( static_cast<float>(trackers[0].get_size()), static_cast<float>(m_params.m_min_samples), static_cast<float>(m_params.m_max_samples), 0.0f, 1.0f); m_diagnostics->set_pixel(pt.x, pt.y, values); } on_pixel_end(pi); } virtual StatisticsVector get_statistics() const APPLESEED_OVERRIDE { return m_sample_renderer->get_statistics(); } private: struct Parameters { const SamplingContext::Mode m_sampling_mode; const size_t m_min_samples; const size_t m_max_samples; const float m_max_variation; const bool m_diagnostics; explicit Parameters(const ParamArray& params) : m_sampling_mode(get_sampling_context_mode(params)) , m_min_samples(params.get_required<size_t>("min_samples", 16)) , m_max_samples(params.get_required<size_t>("max_samples", 256)) , m_max_variation(pow(10.0f, -params.get_optional<float>("quality", 2.0f))) , m_diagnostics(params.get_optional<bool>("enable_diagnostics", false)) { } }; const Parameters m_params; auto_release_ptr<ISampleRenderer> m_sample_renderer; size_t m_variation_aov_index; size_t m_samples_aov_index; int m_scratch_fb_half_width; int m_scratch_fb_half_height; auto_ptr<ShadingResultFrameBuffer> m_scratch_fb; auto_ptr<Tile> m_diagnostics; static Color4f scalar_to_color(const float value) { static const Color4f Blue(0.0f, 0.0f, 1.0f, 1.0f); static const Color4f Red(1.0f, 0.0f, 0.0f, 1.0f); return lerp(Blue, Red, saturate(value)); } }; } // // AdaptivePixelRendererFactory class implementation. // AdaptivePixelRendererFactory::AdaptivePixelRendererFactory( const Frame& frame, ISampleRendererFactory* factory, const ParamArray& params) : m_frame(frame) , m_factory(factory) , m_params(params) { } void AdaptivePixelRendererFactory::release() { delete this; } IPixelRenderer* AdaptivePixelRendererFactory::create( const size_t thread_index) { return new AdaptivePixelRenderer( m_frame, m_factory, m_params, thread_index); } Dictionary AdaptivePixelRendererFactory::get_params_metadata() { Dictionary metadata; metadata.dictionaries().insert( "min_samples", Dictionary() .insert("type", "int") .insert("default", "16") .insert("label", "Min Samples") .insert("help", "Minimum number of anti-aliasing samples")); metadata.dictionaries().insert( "max_samples", Dictionary() .insert("type", "int") .insert("default", "256") .insert("label", "Max Samples") .insert("help", "Maximum number of anti-aliasing samples")); metadata.dictionaries().insert( "quality", Dictionary() .insert("type", "float") .insert("default", "2.0") .insert("label", "Quality") .insert("help", "Quality factor")); metadata.dictionaries().insert( "enable_diagnostics", Dictionary() .insert("type", "bool") .insert("default", "false") .insert("label", "Enable Diagnostics") .insert( "help", "Enable adaptive sampling diagnostics")); return metadata; } } // namespace renderer <|endoftext|>
<commit_before>/** * Copyright (C) 2015 Virgil Security Inc. * * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> * * 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 AUTHOR ''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 AUTHOR 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. */ #include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <map> #include <stdexcept> #include <string> #include <tclap/CmdLine.h> #include <virgil/crypto/VirgilByteArray.h> #include <virgil/crypto/foundation/VirgilKeyPairGenerator.h> #include <virgil/crypto/foundation/VirgilAsymmetricCipher.h> #include <cli/version.h> #include <cli/util.h> using virgil::crypto::VirgilByteArray; using virgil::crypto::foundation::VirgilKeyPairGenerator; using virgil::crypto::foundation::VirgilAsymmetricCipher; /** * @brief Convert string representation of the Elliptic Curve group to the appropriate constant. */ static VirgilKeyPairGenerator::ECKeyGroup ec_key_group_from_param(const std::string &param); #ifdef SPLIT_CLI #define MAIN main #else #define MAIN keygen_main #endif int MAIN(int argc, char **argv) { try { // Parse arguments. TCLAP::CmdLine cmd("Generate private key with given parameters.", ' ', virgil::cli_version()); std::vector<std::string> ec_key; ec_key.push_back(" bp256r1 "); ec_key.push_back(" bp384r1 "); ec_key.push_back(" bp512r1 "); ec_key.push_back(" secp192r1 "); ec_key.push_back(" secp224r1 "); ec_key.push_back(" secp256r1 "); ec_key.push_back(" secp384r1 "); ec_key.push_back(" secp521r1 "); ec_key.push_back(" secp192k1 "); ec_key.push_back(" secp224k1 "); ec_key.push_back(" secp256k1 "); TCLAP::ValuesConstraint<std::string> allowedEcKey(ec_key); TCLAP::ValueArg<std::string> ecArg("e", "ec", "Generate elliptic curve key with one of the following curves:\n" "\t* bp256r1 - 256-bits Brainpool curve;\n" "\t* bp384r1 - 384-bits Brainpool curve;\n" "\t* bp512r1 - 512-bits Brainpool curve (default);\n" "\t* secp192r1 - 192-bits NIST curve;\n" "\t* secp224r1 - 224-bits NIST curve;\n" "\t* secp256r1 - 256-bits NIST curve;\n" "\t* secp384r1 - 384-bits NIST curve;\n" "\t* secp521r1 - 521-bits NIST curve;\n" "\t* secp192k1 - 192-bits \"Koblitz\" curve;\n" "\t* secp224k1 - 224-bits \"Koblitz\" curve;\n" "\t* secp256k1 - 256-bits \"Koblitz\" curve.\n", false, "bp512r1", &allowedEcKey); TCLAP::ValueArg<unsigned int> rsaArg("r", "rsa", "Generate RSA key with a given number of bits.", false, 0, "nbits"); TCLAP::ValueArg<std::string> outArg("o", "out", "Private key. If omitted stdout is used.", false, "", "file"); TCLAP::ValueArg<std::string> pwdArg("p", "pwd", "Password to be used for private key encryption. " "If omitted private key is stored in the plain format.", false, "", "arg"); cmd.add(pwdArg); cmd.add(outArg); cmd.add(ecArg); cmd.add(rsaArg); cmd.parse(argc, argv); // Check parameters if (!ecArg.getValue().empty() && rsaArg.getValue() > 0) { throw std::invalid_argument("-e, --ec and -r, --rsa parameters are both specified"); } VirgilAsymmetricCipher cipher = VirgilAsymmetricCipher::none(); if (rsaArg.isSet()) { // Generate RSA key cipher = VirgilAsymmetricCipher::rsa(); cipher.genKeyPair(VirgilKeyPairGenerator::rsa(rsaArg.getValue())); } else { // Generate EC key VirgilKeyPairGenerator::ECKeyGroup ecKeyGroup = ec_key_group_from_param(ecArg.getValue()); if (ecKeyGroup == VirgilKeyPairGenerator::ECKeyGroup_DP_NONE) { if (ecArg.getValue().empty()) { ecKeyGroup = VirgilKeyPairGenerator::ECKeyGroup_DP_BP512R1; } else { throw std::invalid_argument(std::string("unknown elliptic curve: ") + ecArg.getValue()); } } cipher = VirgilAsymmetricCipher::ec(); cipher.genKeyPair(VirgilKeyPairGenerator::ec(ecKeyGroup)); } // Export private key VirgilByteArray privateKey = cipher.exportPrivateKeyToPEM(virgil::crypto::str2bytes(pwdArg.getValue())); // Write private key virgil::cli::write_bytes(outArg.getValue(), privateKey); } catch (TCLAP::ArgException& exception) { std::cerr << "Error: " << exception.error() << " for arg " << exception.argId() << std::endl; return EXIT_FAILURE; } catch (std::exception& exception) { std::cerr << "Error: " << exception.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } static VirgilKeyPairGenerator::ECKeyGroup ec_key_group_from_param(const std::string &param) { std::map<std::string, VirgilKeyPairGenerator::ECKeyGroup> ecKeyGroup; ecKeyGroup["secp192r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP192R1; ecKeyGroup["secp224r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP224R1; ecKeyGroup["secp256r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP256R1; ecKeyGroup["secp384r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP384R1; ecKeyGroup["secp521r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP521R1; ecKeyGroup["bp256r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP256R1; ecKeyGroup["bp384r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP384R1; ecKeyGroup["bp512r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP512R1; ecKeyGroup["secp192k1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP192K1; ecKeyGroup["secp224k1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP224K1; ecKeyGroup["secp256k1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP256K1; auto group = ecKeyGroup.find(param); if (group != ecKeyGroup.end()) { return group->second; } return VirgilKeyPairGenerator::ECKeyGroup_DP_NONE; } <commit_msg>[CLI-7] Fix RSA and EC keys generation.<commit_after>/** * Copyright (C) 2015 Virgil Security Inc. * * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> * * 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 AUTHOR ''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 AUTHOR 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. */ #include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <map> #include <stdexcept> #include <string> #include <tclap/CmdLine.h> #include <virgil/crypto/VirgilByteArray.h> #include <virgil/crypto/foundation/VirgilKeyPairGenerator.h> #include <virgil/crypto/foundation/VirgilAsymmetricCipher.h> #include <cli/version.h> #include <cli/util.h> using virgil::crypto::VirgilByteArray; using virgil::crypto::foundation::VirgilKeyPairGenerator; using virgil::crypto::foundation::VirgilAsymmetricCipher; /** * @brief Convert string representation of the Elliptic Curve group to the appropriate constant. */ static VirgilKeyPairGenerator::ECKeyGroup ec_key_group_from_param(const std::string &param); #ifdef SPLIT_CLI #define MAIN main #else #define MAIN keygen_main #endif int MAIN(int argc, char **argv) { try { // Parse arguments. TCLAP::CmdLine cmd("Generate private key with given parameters.", ' ', virgil::cli_version()); std::vector<std::string> ec_key; ec_key.push_back("bp256r1"); ec_key.push_back("bp384r1"); ec_key.push_back("bp512r1"); ec_key.push_back("secp192r1"); ec_key.push_back("secp224r1"); ec_key.push_back("secp256r1"); ec_key.push_back("secp384r1"); ec_key.push_back("secp521r1"); ec_key.push_back("secp192k1"); ec_key.push_back("secp224k1"); ec_key.push_back("secp256k1"); TCLAP::ValuesConstraint<std::string> allowedEcKey(ec_key); TCLAP::ValueArg<std::string> ecArg("e", "ec", "Generate elliptic curve key with one of the following curves:\n" "\t* bp256r1 - 256-bits Brainpool curve;\n" "\t* bp384r1 - 384-bits Brainpool curve;\n" "\t* bp512r1 - 512-bits Brainpool curve (default);\n" "\t* secp192r1 - 192-bits NIST curve;\n" "\t* secp224r1 - 224-bits NIST curve;\n" "\t* secp256r1 - 256-bits NIST curve;\n" "\t* secp384r1 - 384-bits NIST curve;\n" "\t* secp521r1 - 521-bits NIST curve;\n" "\t* secp192k1 - 192-bits \"Koblitz\" curve;\n" "\t* secp224k1 - 224-bits \"Koblitz\" curve;\n" "\t* secp256k1 - 256-bits \"Koblitz\" curve.\n", false, "", &allowedEcKey); TCLAP::ValueArg<unsigned int> rsaArg("r", "rsa", "Generate RSA key with a given number of bits.", false, 0, "nbits"); TCLAP::ValueArg<std::string> outArg("o", "out", "Private key. If omitted stdout is used.", false, "", "file"); TCLAP::ValueArg<std::string> pwdArg("p", "pwd", "Password to be used for private key encryption. " "If omitted private key is stored in the plain format.", false, "", "arg"); cmd.add(pwdArg); cmd.add(outArg); cmd.add(ecArg); cmd.add(rsaArg); cmd.parse(argc, argv); // Check parameters if (ecArg.isSet() && rsaArg.isSet()) { throw std::invalid_argument("-e, --ec and -r, --rsa parameters are both specified"); } VirgilAsymmetricCipher cipher = VirgilAsymmetricCipher::none(); if (rsaArg.isSet()) { // Generate RSA key cipher = VirgilAsymmetricCipher::rsa(); cipher.genKeyPair(VirgilKeyPairGenerator::rsa(rsaArg.getValue())); } else { // Generate EC key VirgilKeyPairGenerator::ECKeyGroup ecKeyGroup = ec_key_group_from_param(ecArg.getValue()); if (ecKeyGroup == VirgilKeyPairGenerator::ECKeyGroup_DP_NONE) { if (ecArg.getValue().empty()) { ecKeyGroup = VirgilKeyPairGenerator::ECKeyGroup_DP_BP512R1; } else { throw std::invalid_argument(std::string("unknown elliptic curve: ") + ecArg.getValue()); } } cipher = VirgilAsymmetricCipher::ec(); cipher.genKeyPair(VirgilKeyPairGenerator::ec(ecKeyGroup)); } // Export private key VirgilByteArray privateKey = cipher.exportPrivateKeyToPEM(virgil::crypto::str2bytes(pwdArg.getValue())); // Write private key virgil::cli::write_bytes(outArg.getValue(), privateKey); } catch (TCLAP::ArgException& exception) { std::cerr << "Error: " << exception.error() << " for arg " << exception.argId() << std::endl; return EXIT_FAILURE; } catch (std::exception& exception) { std::cerr << "Error: " << exception.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } static VirgilKeyPairGenerator::ECKeyGroup ec_key_group_from_param(const std::string &param) { std::map<std::string, VirgilKeyPairGenerator::ECKeyGroup> ecKeyGroup; ecKeyGroup["secp192r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP192R1; ecKeyGroup["secp224r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP224R1; ecKeyGroup["secp256r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP256R1; ecKeyGroup["secp384r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP384R1; ecKeyGroup["secp521r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP521R1; ecKeyGroup["bp256r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP256R1; ecKeyGroup["bp384r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP384R1; ecKeyGroup["bp512r1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP512R1; ecKeyGroup["secp192k1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP192K1; ecKeyGroup["secp224k1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP224K1; ecKeyGroup["secp256k1"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP256K1; auto group = ecKeyGroup.find(param); if (group != ecKeyGroup.end()) { return group->second; } return VirgilKeyPairGenerator::ECKeyGroup_DP_NONE; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2003 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // system headers #include <ctype.h> #include <stdio.h> // class-specific headers #include "CommandManager.h" #include "TextUtils.h" CommandManager::CommandManager() { // do nothing } CommandManager::~CommandManager() { // do nothing } void CommandManager::add(const std::string& name, CommandFunction func, const std::string& help) { commands.erase(name); CmdInfo info; info.func = func; info.help = help; commands.insert(std::make_pair(name, info)); } void CommandManager::remove(const std::string& name) { commands.erase(name); } std::string CommandManager::getHelp(const std::string& name) const { // look up command Commands::const_iterator index = commands.find(name); if (index == commands.end()) return ""; // return help string return index->second.help; } std::string CommandManager::run(const std::string& name, const ArgList& args) const { // look up command Commands::const_iterator index = commands.find(name); if (index == commands.end()) return string_util::format("Command %s not found", name.c_str()); // run it return (*index->second.func)(name, args); } std::string CommandManager::run(const std::string& cmd) const { std::string result; const char* scan = cmd.c_str(); scan = skipWhitespace(scan); while (scan != NULL && *scan != '\0') { std::string name; ArgList args; // parse command name scan = skipWhitespace(scan); scan = readValue(scan, &name); if (scan != NULL) scan = skipWhitespace(scan); // parse arguments while (scan != NULL && *scan != '\0' && *scan != ';') { std::string value; scan = readValue(scan, &value); if (scan != NULL) { scan = skipWhitespace(scan); args.push_back(value); } } // run it or report error if (scan == NULL) return std::string("Error parsing command"); else result = run(name, args); // discard ; and empty commands while (scan != NULL && *scan == ';') { ++scan; scan = skipWhitespace(scan); } } // return result of last command only return result; } void CommandManager::iterate(Callback callback, void* userData) const { assert(callback != NULL); for (Commands::const_iterator index = commands.begin(); index != commands.end(); ++index) (*callback)(index->first, userData); } const char* CommandManager::readValue(const char* string, std::string* value) { if (*string == '\"') return readQuoted(string + 1, value); else if (*string != '\0') return readUnquoted(string, value); else return string; } const char* CommandManager::readUnquoted(const char* string, std::string* value) { // read up to next whitespace. escapes are not interpreted. const char* start = string; while (*string != '\0' && !isspace(*string) && *string != ';') ++string; *value = std::string(start, string - start); return string; } const char* CommandManager::readQuoted(const char* string, std::string* value) { *value = ""; bool escaped = false; for (; *string != '\0'; ++string) { if (escaped) { switch (*string) { case 't': value->append("\t", 1); break; case 'n': value->append("\n", 1); break; case 'r': value->append("\r", 1); break; case '\\': value->append("\\", 1); break; case '\"': value->append("\"", 1); break; default: value->append(string, 1); break; } escaped = false; } else if (*string == '\\') { escaped = true; } else if (*string == '\"') { return string + 1; } else { value->append(string, 1); } } // closing quote is missing. if escaped is true the called may have // wanted to continue the line but we don't allow that. return NULL; } const char* CommandManager::skipWhitespace(const char* string) { while (*string != '\0' && isspace(*string)) ++string; return string; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>stop the sym-trunc warnings<commit_after>/* bzflag * Copyright (c) 1993 - 2003 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _WIN32 #pragma warning(4:4786) #endif // system headers #include <ctype.h> #include <stdio.h> // class-specific headers #include "CommandManager.h" #include "TextUtils.h" CommandManager::CommandManager() { // do nothing } CommandManager::~CommandManager() { // do nothing } void CommandManager::add(const std::string& name, CommandFunction func, const std::string& help) { commands.erase(name); CmdInfo info; info.func = func; info.help = help; commands.insert(std::make_pair(name, info)); } void CommandManager::remove(const std::string& name) { commands.erase(name); } std::string CommandManager::getHelp(const std::string& name) const { // look up command Commands::const_iterator index = commands.find(name); if (index == commands.end()) return ""; // return help string return index->second.help; } std::string CommandManager::run(const std::string& name, const ArgList& args) const { // look up command Commands::const_iterator index = commands.find(name); if (index == commands.end()) return string_util::format("Command %s not found", name.c_str()); // run it return (*index->second.func)(name, args); } std::string CommandManager::run(const std::string& cmd) const { std::string result; const char* scan = cmd.c_str(); scan = skipWhitespace(scan); while (scan != NULL && *scan != '\0') { std::string name; ArgList args; // parse command name scan = skipWhitespace(scan); scan = readValue(scan, &name); if (scan != NULL) scan = skipWhitespace(scan); // parse arguments while (scan != NULL && *scan != '\0' && *scan != ';') { std::string value; scan = readValue(scan, &value); if (scan != NULL) { scan = skipWhitespace(scan); args.push_back(value); } } // run it or report error if (scan == NULL) return std::string("Error parsing command"); else result = run(name, args); // discard ; and empty commands while (scan != NULL && *scan == ';') { ++scan; scan = skipWhitespace(scan); } } // return result of last command only return result; } void CommandManager::iterate(Callback callback, void* userData) const { assert(callback != NULL); for (Commands::const_iterator index = commands.begin(); index != commands.end(); ++index) (*callback)(index->first, userData); } const char* CommandManager::readValue(const char* string, std::string* value) { if (*string == '\"') return readQuoted(string + 1, value); else if (*string != '\0') return readUnquoted(string, value); else return string; } const char* CommandManager::readUnquoted(const char* string, std::string* value) { // read up to next whitespace. escapes are not interpreted. const char* start = string; while (*string != '\0' && !isspace(*string) && *string != ';') ++string; *value = std::string(start, string - start); return string; } const char* CommandManager::readQuoted(const char* string, std::string* value) { *value = ""; bool escaped = false; for (; *string != '\0'; ++string) { if (escaped) { switch (*string) { case 't': value->append("\t", 1); break; case 'n': value->append("\n", 1); break; case 'r': value->append("\r", 1); break; case '\\': value->append("\\", 1); break; case '\"': value->append("\"", 1); break; default: value->append(string, 1); break; } escaped = false; } else if (*string == '\\') { escaped = true; } else if (*string == '\"') { return string + 1; } else { value->append(string, 1); } } // closing quote is missing. if escaped is true the called may have // wanted to continue the line but we don't allow that. return NULL; } const char* CommandManager::skipWhitespace(const char* string) { while (*string != '\0' && isspace(*string)) ++string; return string; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "condor_common.h" #include <sys/socket.h> #include <netinet/in.h> #if !defined(LINUX) && !defined(HPUX9) #include <sys/select.h> #endif #include "condor_types.h" #include "condor_debug.h" #include "condor_expressions.h" #include "condor_mach_status.h" #include "condor_attributes.h" #include "sched.h" #include "event.h" #include "state.h" #include "resource.h" #include "resmgr.h" extern ClassAd* template_ClassAd; static char *_FileName_ = __FILE__; /* * Higher level routines to manage a collection of resources. * XXX - DON'T do this using lineair searches.. */ static resource_info_t *resources=NULL; static int nresources; static fd_set cur_fds; static int resmgr_vacateone(resource_info_t *); static int resmgr_addfd(resource_info_t *); static int resmgr_command(resource_info_t *); void update_central_mgr(void); extern "C" int resmgr_setsocks(fd_set* fds); extern "C" int resmgr_call(fd_set* fds); extern "C" void resmgr_changestate(resource_id_t rid, int new_state); // collect all resources that were listed in the config file // initialize(including the ClassAd in each resource) // and store them in the global resources array. The number // of such resources (just 1 if RESOURCE_LIST i snot specified // in the config \file is recorded by nresources. int resmgr_init() { int nres, i, index; resource_name_t *rnames; resource_id_t rid; resource_param_t param; // collect all resources that were listed in the config file // and their number resource_names(&rnames, &nres); dprintf(D_ALWAYS, "resmgr_init: %d resources.\n", nres); resources = (resource_info_t *)calloc(nres, (sizeof (resource_info_t))); for (i = index = 0; i < nres; i++) { dprintf(D_ALWAYS, "opening resource '%s'\n", rnames[i]); if (resource_open(rnames[i], &rid) < 0) continue; resources[index].r_rid = rid; dprintf(D_ALWAYS, "resource %d has id '%s'\n", index, resources[index].r_rid); resources[index].r_state = NO_JOB; if (resource_params(rid, NO_JID, NO_TID, &resources[index].r_param, NULL) < 0) continue; resources[index].r_name = rnames[i]; resources[index].r_pid = NO_PID; resources[index].r_claimed = FALSE; // C H A N G E -> N Anand resources[index].r_context = new ClassAd(*template_ClassAd); resources[index].r_jobcontext = NULL; resources[index].r_capab = NULL; resources[index].r_interval = 0; resources[index].r_receivetime = 0; resources[index].r_universe = STANDARD; dprintf(D_FULLDEBUG, "create_context returned %x\n", resources[index].r_context); resources[index].r_port = create_port(&resources[index].r_sock); // CHANGE -> N Anand resource_initAd(&resources[index]); /* XXX following must be last in this initialization */ resource_context(&resources[index]); index++; } nresources = index; dprintf(D_ALWAYS, "nresources set to %d\n", nresources); return 0; } int resmgr_setsocks(fd_set* fds) { FD_ZERO(&cur_fds); resmgr_walk(resmgr_addfd); *fds = cur_fds; return 0; } int resmgr_call(fd_set* fds) { cur_fds = *fds; return resmgr_walk(resmgr_command); } int resmgr_add(resource_id_t rid, resource_info_t* rinfop) { int i; for (i = 0; i < nresources; i++) { if (resource_isused(resources[i])) { resources[i] = *rinfop; break; } } return i == nresources ? -1 : 0; } int resmgr_del(resource_id_t rid) { int i; for (i = 0; i < nresources; i++) { if (!resource_isused(resources[i])) continue; if (!resource_ridcmp(resources[i].r_rid, rid)) { resource_markunused(resources[i]); break; } } return i == nresources ? -1 : 0; } resource_info_t * resmgr_getbyrid(resource_id_t rid) { int i; for (i = 0; i < nresources; i++) { if (!resource_ridcmp(resources[i].r_rid, rid)) return &resources[i]; } return (resource_info_t *)0; } resource_info_t * resmgr_getbyname(resource_name_t rname) { int i; for (i = 0; i < nresources; i++) { if (!resource_rnamecmp(resources[i].r_name, rname)) return &resources[i]; } return (resource_info_t *)0; } resource_info_t * resmgr_getbypid(int pid) { int i; for (i = 0; i < nresources; i++) { if (resources[i].r_pid == pid) return &resources[i]; } return (resource_info_t *)0; } int resmgr_walk(int (*func)(resource_info_t*)) { int i; for (i = 0; i < nresources; i++) func(&resources[i]); return 0; } int resmgr_vacateall(void) { return resmgr_walk(resmgr_vacateone); } bool resmgr_resourceinuse(void) { int i; for (i = 0; i < nresources; i++) if (resources[i].r_state != NO_JOB) return true; return false; } static int resmgr_vacateone(resource_info_t* rinfop) { resource_id_t rid; rid = rinfop->r_rid; return resource_event(rid, NO_JID, NO_TID, EV_VACATE); } static int resmgr_addfd(resource_info_t* rip) { FD_SET(rip->r_sock, &cur_fds); return 0; } static int resmgr_command(resource_info_t* rinfop) { if (FD_ISSET(rinfop->r_sock, &cur_fds)) { call_incoming(rinfop->r_sock, SOCK_STREAM, rinfop->r_rid); FD_CLR(rinfop->r_sock , &cur_fds); } return 0; } ClassAd* resmgr_context(resource_id_t rid) { resource_info_t *rip; if (!(rip = resmgr_getbyrid(rid))) return NULL; return rip->r_context; } char * state_to_string(int state) { switch (state) { case NO_JOB: return "NoJob"; case JOB_RUNNING: return "Running"; case KILLED: return "Killed"; case CHECKPOINTING: return "Checkpointing"; case SUSPENDED: return "Suspended"; case BLOCKED: return "Blocked"; case SYSTEM: return "System"; } return "Unknown"; } void resmgr_changestate(resource_id_t rid, int new_state) { ClassAd* cp; char *name; char tmp[80]; int start = FALSE; int claimed; resource_info_t *rip; if (!(rip = resmgr_getbyrid(rid))) return; cp = rip->r_context; claimed = rip->r_claimed; switch (new_state) { case NO_JOB: cp->EvalBool(ATTR_REQUIREMENTS, template_ClassAd, start); if(start && claimed == FALSE ) { set_machine_status(M_IDLE); } else { set_machine_status(USER_BUSY); } cp->Delete("ClientMachine"); cp->Delete("RemoteUser"); cp->Delete("JobId"); cp->Delete("JobStart"); case JOB_RUNNING: set_machine_status(JOB_RUNNING); break; case KILLED: set_machine_status(KILLED); break; case CHECKPOINTING: set_machine_status(CHECKPOINTING); break; case SUSPENDED: set_machine_status(SUSPENDED); break; case BLOCKED: set_machine_status(BLOCKED); break; case SYSTEM: set_machine_status(SYSTEM); break; default: EXCEPT("Change states, unknown state (%d)", new_state); } name = state_to_string(new_state); rip->r_state = new_state; sprintf(tmp,"State=\"%s\"",name); cp->InsertOrUpdate(tmp); sprintf(tmp,"EnteredCurrentState=%d",(int)time((time_t*)0)); cp->InsertOrUpdate(tmp); update_central_mgr(); } <commit_msg>Removed all mention of "context" from variable names, etc. Also, made changes for update vs. timeout stuff described in the log for event.C or main.C<commit_after>#include "condor_common.h" #include <sys/socket.h> #include <netinet/in.h> #if !defined(LINUX) && !defined(HPUX9) #include <sys/select.h> #endif #include "condor_types.h" #include "condor_debug.h" #include "condor_expressions.h" #include "condor_mach_status.h" #include "condor_attributes.h" #include "sched.h" #include "event.h" #include "state.h" #include "resource.h" #include "resmgr.h" extern ClassAd* template_ClassAd; static char *_FileName_ = __FILE__; /* * Higher level routines to manage a collection of resources. * XXX - DON'T do this using lineair searches.. */ static resource_info_t *resources=NULL; static int nresources; static fd_set cur_fds; static int resmgr_vacateone(resource_info_t *); static int resmgr_addfd(resource_info_t *); static int resmgr_command(resource_info_t *); void update_central_mgr(void); extern "C" int resmgr_setsocks(fd_set* fds); extern "C" int resmgr_call(fd_set* fds); extern "C" void resmgr_changestate(resource_id_t rid, int new_state); // collect all resources that were listed in the config file // initialize(including the ClassAd in each resource) // and store them in the global resources array. The number // of such resources (just 1 if RESOURCE_LIST i snot specified // in the config \file is recorded by nresources. int resmgr_init() { int nres, i, index; resource_name_t *rnames; resource_id_t rid; resource_param_t param; // collect all resources that were listed in the config file // and their number resource_names(&rnames, &nres); dprintf(D_ALWAYS, "resmgr_init: %d resources.\n", nres); resources = (resource_info_t *)calloc(nres, (sizeof (resource_info_t))); for (i = index = 0; i < nres; i++) { dprintf(D_ALWAYS, "opening resource '%s'\n", rnames[i]); if (resource_open(rnames[i], &rid) < 0) continue; resources[index].r_rid = rid; dprintf(D_ALWAYS, "resource %d has id '%s'\n", index, resources[index].r_rid); resources[index].r_state = NO_JOB; if (resource_timeout_params(rid, NO_JID, NO_TID, &resources[index].r_param, NULL) < 0) continue; if (resource_update_params(rid, NO_JID, NO_TID, &resources[index].r_param, NULL) < 0) continue; resources[index].r_name = rnames[i]; resources[index].r_pid = NO_PID; resources[index].r_claimed = FALSE; // C H A N G E -> N Anand resources[index].r_classad = new ClassAd(*template_ClassAd); resources[index].r_jobclassad = NULL; resources[index].r_capab = NULL; resources[index].r_interval = 0; resources[index].r_receivetime = 0; resources[index].r_universe = STANDARD; dprintf(D_FULLDEBUG, "create_classad returned %x\n", resources[index].r_classad); resources[index].r_port = create_port(&resources[index].r_sock); // CHANGE -> N Anand resource_initAd(&resources[index]); /* XXX following must be last in this initialization */ resource_timeout_classad(&resources[index]); resource_update_classad(&resources[index]); index++; } nresources = index; dprintf(D_ALWAYS, "nresources set to %d\n", nresources); return 0; } int resmgr_setsocks(fd_set* fds) { FD_ZERO(&cur_fds); resmgr_walk(resmgr_addfd); *fds = cur_fds; return 0; } int resmgr_call(fd_set* fds) { cur_fds = *fds; return resmgr_walk(resmgr_command); } int resmgr_add(resource_id_t rid, resource_info_t* rinfop) { int i; for (i = 0; i < nresources; i++) { if (resource_isused(resources[i])) { resources[i] = *rinfop; break; } } return i == nresources ? -1 : 0; } int resmgr_del(resource_id_t rid) { int i; for (i = 0; i < nresources; i++) { if (!resource_isused(resources[i])) continue; if (!resource_ridcmp(resources[i].r_rid, rid)) { resource_markunused(resources[i]); break; } } return i == nresources ? -1 : 0; } resource_info_t * resmgr_getbyrid(resource_id_t rid) { int i; for (i = 0; i < nresources; i++) { if (!resource_ridcmp(resources[i].r_rid, rid)) return &resources[i]; } return (resource_info_t *)0; } resource_info_t * resmgr_getbyname(resource_name_t rname) { int i; for (i = 0; i < nresources; i++) { if (!resource_rnamecmp(resources[i].r_name, rname)) return &resources[i]; } return (resource_info_t *)0; } resource_info_t * resmgr_getbypid(int pid) { int i; for (i = 0; i < nresources; i++) { if (resources[i].r_pid == pid) return &resources[i]; } return (resource_info_t *)0; } int resmgr_walk(int (*func)(resource_info_t*)) { int i; for (i = 0; i < nresources; i++) func(&resources[i]); return 0; } int resmgr_vacateall(void) { return resmgr_walk(resmgr_vacateone); } bool resmgr_resourceinuse(void) { int i; for (i = 0; i < nresources; i++) if (resources[i].r_state != NO_JOB) return true; return false; } static int resmgr_vacateone(resource_info_t* rinfop) { resource_id_t rid; rid = rinfop->r_rid; return resource_event(rid, NO_JID, NO_TID, EV_VACATE); } static int resmgr_addfd(resource_info_t* rip) { FD_SET(rip->r_sock, &cur_fds); return 0; } static int resmgr_command(resource_info_t* rinfop) { if (FD_ISSET(rinfop->r_sock, &cur_fds)) { call_incoming(rinfop->r_sock, SOCK_STREAM, rinfop->r_rid); FD_CLR(rinfop->r_sock , &cur_fds); } return 0; } ClassAd* resmgr_classad(resource_id_t rid) { resource_info_t *rip; if (!(rip = resmgr_getbyrid(rid))) return NULL; return rip->r_classad; } char * state_to_string(int state) { switch (state) { case NO_JOB: return "NoJob"; case JOB_RUNNING: return "Running"; case KILLED: return "Killed"; case CHECKPOINTING: return "Checkpointing"; case SUSPENDED: return "Suspended"; case BLOCKED: return "Blocked"; case SYSTEM: return "System"; } return "Unknown"; } void resmgr_changestate(resource_id_t rid, int new_state) { ClassAd* cp; char *name; char tmp[80]; int start = FALSE; int claimed; resource_info_t *rip; if (!(rip = resmgr_getbyrid(rid))) return; cp = rip->r_classad; claimed = rip->r_claimed; switch (new_state) { case NO_JOB: cp->EvalBool(ATTR_REQUIREMENTS, template_ClassAd, start); if(start && claimed == FALSE ) { set_machine_status(M_IDLE); } else { set_machine_status(USER_BUSY); } cp->Delete("ClientMachine"); cp->Delete("RemoteUser"); cp->Delete("JobId"); cp->Delete("JobStart"); case JOB_RUNNING: set_machine_status(JOB_RUNNING); break; case KILLED: set_machine_status(KILLED); break; case CHECKPOINTING: set_machine_status(CHECKPOINTING); break; case SUSPENDED: set_machine_status(SUSPENDED); break; case BLOCKED: set_machine_status(BLOCKED); break; case SYSTEM: set_machine_status(SYSTEM); break; default: EXCEPT("Change states, unknown state (%d)", new_state); } name = state_to_string(new_state); rip->r_state = new_state; sprintf(tmp,"State=\"%s\"",name); cp->InsertOrUpdate(tmp); sprintf(tmp,"EnteredCurrentState=%d",(int)time((time_t*)0)); cp->InsertOrUpdate(tmp); update_central_mgr(); } <|endoftext|>
<commit_before>/* Copyright (c) 2014, Madd Games. 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. 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. */ #include <Apoc/Video/StandardRenderHandler.h> #include <Apoc/Entity/World.h> #include <Apoc/Utils/Utils.h> // Texture units: // 0 = main (diffuse) texture // 1 = directional light array // 2 = point light array // 3 = shadow map // 4 = specular map // 5 = normal map extern "C" const char *stdVertexShader; extern "C" const char *stdFragmentShader; float lmatheight = -0.3; const float defImageTexData[] = { 0.3, 0.3, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.3, 0.3, 1.0, 1.0 }; const float defSpecularMapData[] = { 1.0, 1.0, 1.0, 1.0 }; const float defNormalMapData[] = { 0.5, 0.5, 1.0, 0.0 }; StandardRenderHandler::StandardRenderHandler(int screenWidth, int screenHeight) : numDirLights(0), numPointLights(0), screenWidth(screenWidth), screenHeight(screenHeight) { renderProgram = createProgram(stdVertexShader, stdFragmentShader); // set up the directional light array buffer. glActiveTexture(GL_TEXTURE1); glGenTextures(1, &dirLightTex); glBindTexture(GL_TEXTURE_BUFFER, dirLightTex); glGenBuffers(1, &dirLightBuffer); glBindBuffer(GL_TEXTURE_BUFFER, dirLightBuffer); glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, dirLightBuffer); // set up the point light array buffer. glActiveTexture(GL_TEXTURE2); glGenTextures(1, &pointLightTex); glBindTexture(GL_TEXTURE_BUFFER, pointLightTex); glGenBuffers(1, &pointLightBuffer); glBindBuffer(GL_TEXTURE_BUFFER, pointLightBuffer); glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, pointLightBuffer); // default image texture. glGenTextures(1, &defImageTex); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, defImageTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_FLOAT, defImageTexData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // default specular map. glGenTextures(1, &defSpecularMap); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, defSpecularMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, defSpecularMapData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // default normal map. glGenTextures(1, &defNormalMap); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, defNormalMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, defNormalMapData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // the shadowmap framebuffer glGenFramebuffers(1, &shadowFramebuffer); glGenTextures(1, &shadowTex); glBindTexture(GL_TEXTURE_2D, shadowTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, 1366, 768, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_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); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); glBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowTex, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { ApocFail("The shadowmap framebuffer is incomplete!"); }; Matrix view = Matrix::LookAt( Vector(0.0, -0.1, -1.0), Vector(0.0, 1.0, 0.0), Vector(0.0, 0.0, 0.0) ); lightMatrix = Matrix::Ortho(20, -20, 20, -20, -30, 20) * view; //cout << "Light matrix: " << endl << lightMatrix << endl; //Vector point(-11.000000, 0.000000, 10.999980, 1); //cout << "Test point: " << (lightMatrix * point) << endl; }; void StandardRenderHandler::render() { Matrix view = Matrix::LookAt( Vector(0.0, lmatheight, -1.0), Vector(0.0, 1.0, 0.0), Vector(0.0, 0.0, 0.0) ); lightMatrix = Matrix::Ortho(20, -20, 20, -20, -20, 10) * view; //glDepthFunc(GL_LESS); glUniform1i(getUniformLocation("uIsParticle"), 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer); glViewport(0, 0, 1366, 768); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_DEPTH_BUFFER_BIT); glUniform1i(getUniformLocation("uIsShadowMap"), 1); glDrawBuffer(GL_NONE); Matrix identity = Matrix::Identity(); glUniformMatrix4fv(getUniformLocation("uProjectionMatrix"), 1, GL_FALSE, &identity[0][0]); glUniformMatrix4fv(getUniformLocation("uViewMatrix"), 1, GL_FALSE, &lightMatrix[0][0]); World::render(false); //return; glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, screenWidth, screenHeight); //glUseProgram(renderProgram); glDrawBuffer(GL_BACK); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUniformMatrix4fv(getUniformLocation("uLightMatrix"), 1, GL_FALSE, &lightMatrix[0][0]); glUniform1i(getUniformLocation("uIsShadowMap"), 0); glUniform4f(getUniformLocation("uAmbientLight"), 0.1, 0.1, 0.1, 1.0); glUniform1i(getUniformLocation("uDirLightArray"), 1); glUniform1i(getUniformLocation("uPointLightArray"), 2); glUniform1i(getUniformLocation("uShadowMap"), 3); glUniform1i(getUniformLocation("uSpecularMap"), 4); glUniform1i(getUniformLocation("uNormalMap"), 5); glUniform1i(getUniformLocation("uNumDirLights"), numDirLights); glUniform1i(getUniformLocation("uNumPointLights"), numPointLights); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, shadowTex); glEnable(GL_CULL_FACE); World::render(); glUniformMatrix4fv(getUniformLocation("uModelMatrix"), 1, GL_FALSE, &identity[0][0]); glUniformMatrix4fv(getUniformLocation("uObjectMatrix"), 1, GL_FALSE, &identity[0][0]); glUniform1i(getUniformLocation("uIsParticle"), 1); World::renderParticles(); }; void StandardRenderHandler::getAttrLocations(GLint &attrVertex, GLint &attrTexCoords, GLint &attrNormal) { attrVertex = glGetAttribLocation(renderProgram, "inVertex"); attrTexCoords = glGetAttribLocation(renderProgram, "inTexCoords"); attrNormal = glGetAttribLocation(renderProgram, "inNormal"); }; GLint StandardRenderHandler::getUniformLocation(const char *name) { return glGetUniformLocation(renderProgram, name); }; GLint StandardRenderHandler::getAttrLocation(const char *name) { return glGetAttribLocation(renderProgram, name); }; void StandardRenderHandler::bindProgram() { glUseProgram(renderProgram); glUniform4f(getUniformLocation("uAmbientLight"), 0.1, 0.1, 0.1, 1.0); }; void StandardRenderHandler::setDirLights(RenderHandler::DirLight *array, int count) { glBindBuffer(GL_TEXTURE_BUFFER, dirLightBuffer); glBufferData(GL_TEXTURE_BUFFER, sizeof(RenderHandler::DirLight)*count, array, GL_DYNAMIC_COPY); numDirLights = count; }; void StandardRenderHandler::setPointLights(RenderHandler::PointLight *array, int count) { glBindBuffer(GL_TEXTURE_BUFFER, pointLightBuffer); glBufferData(GL_TEXTURE_BUFFER, sizeof(RenderHandler::PointLight)*count, array, GL_DYNAMIC_COPY); numPointLights = count; }; void StandardRenderHandler::bindDefaultTextures() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, defImageTex); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, defSpecularMap); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, defNormalMap); }; <commit_msg>Comment cleanup<commit_after>/* Copyright (c) 2014, Madd Games. 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. 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. */ #include <Apoc/Video/StandardRenderHandler.h> #include <Apoc/Entity/World.h> #include <Apoc/Utils/Utils.h> // Texture units: // 0 = main (diffuse) texture // 1 = directional light array // 2 = point light array // 3 = shadow map // 4 = specular map // 5 = normal map extern "C" const char *stdVertexShader; extern "C" const char *stdFragmentShader; float lmatheight = -0.3; const float defImageTexData[] = { 0.3, 0.3, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.3, 0.3, 1.0, 1.0 }; const float defSpecularMapData[] = { 1.0, 1.0, 1.0, 1.0 }; const float defNormalMapData[] = { 0.5, 0.5, 1.0, 0.0 }; StandardRenderHandler::StandardRenderHandler(int screenWidth, int screenHeight) : numDirLights(0), numPointLights(0), screenWidth(screenWidth), screenHeight(screenHeight) { renderProgram = createProgram(stdVertexShader, stdFragmentShader); // set up the directional light array buffer. glActiveTexture(GL_TEXTURE1); glGenTextures(1, &dirLightTex); glBindTexture(GL_TEXTURE_BUFFER, dirLightTex); glGenBuffers(1, &dirLightBuffer); glBindBuffer(GL_TEXTURE_BUFFER, dirLightBuffer); glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, dirLightBuffer); // set up the point light array buffer. glActiveTexture(GL_TEXTURE2); glGenTextures(1, &pointLightTex); glBindTexture(GL_TEXTURE_BUFFER, pointLightTex); glGenBuffers(1, &pointLightBuffer); glBindBuffer(GL_TEXTURE_BUFFER, pointLightBuffer); glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, pointLightBuffer); // default image texture. glGenTextures(1, &defImageTex); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, defImageTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_FLOAT, defImageTexData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // default specular map. glGenTextures(1, &defSpecularMap); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, defSpecularMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, defSpecularMapData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // default normal map. glGenTextures(1, &defNormalMap); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, defNormalMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, defNormalMapData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // the shadowmap framebuffer glGenFramebuffers(1, &shadowFramebuffer); glGenTextures(1, &shadowTex); glBindTexture(GL_TEXTURE_2D, shadowTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, 1366, 768, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_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); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); glBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowTex, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { ApocFail("The shadowmap framebuffer is incomplete!"); }; Matrix view = Matrix::LookAt( Vector(0.0, -0.1, -1.0), Vector(0.0, 1.0, 0.0), Vector(0.0, 0.0, 0.0) ); lightMatrix = Matrix::Ortho(20, -20, 20, -20, -30, 20) * view; //cout << "Light matrix: " << endl << lightMatrix << endl; //Vector point(-11.000000, 0.000000, 10.999980, 1); //cout << "Test point: " << (lightMatrix * point) << endl; }; void StandardRenderHandler::render() { Matrix view = Matrix::LookAt( Vector(0.0, lmatheight, -1.0), Vector(0.0, 1.0, 0.0), Vector(0.0, 0.0, 0.0) ); lightMatrix = Matrix::Ortho(20, -20, 20, -20, -20, 10) * view; glUniform1i(getUniformLocation("uIsParticle"), 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer); glViewport(0, 0, 1366, 768); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_DEPTH_BUFFER_BIT); glUniform1i(getUniformLocation("uIsShadowMap"), 1); glDrawBuffer(GL_NONE); Matrix identity = Matrix::Identity(); glUniformMatrix4fv(getUniformLocation("uProjectionMatrix"), 1, GL_FALSE, &identity[0][0]); glUniformMatrix4fv(getUniformLocation("uViewMatrix"), 1, GL_FALSE, &lightMatrix[0][0]); World::render(false); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, screenWidth, screenHeight); glDrawBuffer(GL_BACK); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUniformMatrix4fv(getUniformLocation("uLightMatrix"), 1, GL_FALSE, &lightMatrix[0][0]); glUniform1i(getUniformLocation("uIsShadowMap"), 0); glUniform4f(getUniformLocation("uAmbientLight"), 0.1, 0.1, 0.1, 1.0); glUniform1i(getUniformLocation("uDirLightArray"), 1); glUniform1i(getUniformLocation("uPointLightArray"), 2); glUniform1i(getUniformLocation("uShadowMap"), 3); glUniform1i(getUniformLocation("uSpecularMap"), 4); glUniform1i(getUniformLocation("uNormalMap"), 5); glUniform1i(getUniformLocation("uNumDirLights"), numDirLights); glUniform1i(getUniformLocation("uNumPointLights"), numPointLights); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, shadowTex); glEnable(GL_CULL_FACE); World::render(); glUniformMatrix4fv(getUniformLocation("uModelMatrix"), 1, GL_FALSE, &identity[0][0]); glUniformMatrix4fv(getUniformLocation("uObjectMatrix"), 1, GL_FALSE, &identity[0][0]); glUniform1i(getUniformLocation("uIsParticle"), 1); World::renderParticles(); }; void StandardRenderHandler::getAttrLocations(GLint &attrVertex, GLint &attrTexCoords, GLint &attrNormal) { attrVertex = glGetAttribLocation(renderProgram, "inVertex"); attrTexCoords = glGetAttribLocation(renderProgram, "inTexCoords"); attrNormal = glGetAttribLocation(renderProgram, "inNormal"); }; GLint StandardRenderHandler::getUniformLocation(const char *name) { return glGetUniformLocation(renderProgram, name); }; GLint StandardRenderHandler::getAttrLocation(const char *name) { return glGetAttribLocation(renderProgram, name); }; void StandardRenderHandler::bindProgram() { glUseProgram(renderProgram); glUniform4f(getUniformLocation("uAmbientLight"), 0.1, 0.1, 0.1, 1.0); }; void StandardRenderHandler::setDirLights(RenderHandler::DirLight *array, int count) { glBindBuffer(GL_TEXTURE_BUFFER, dirLightBuffer); glBufferData(GL_TEXTURE_BUFFER, sizeof(RenderHandler::DirLight)*count, array, GL_DYNAMIC_COPY); numDirLights = count; }; void StandardRenderHandler::setPointLights(RenderHandler::PointLight *array, int count) { glBindBuffer(GL_TEXTURE_BUFFER, pointLightBuffer); glBufferData(GL_TEXTURE_BUFFER, sizeof(RenderHandler::PointLight)*count, array, GL_DYNAMIC_COPY); numPointLights = count; }; void StandardRenderHandler::bindDefaultTextures() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, defImageTex); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, defSpecularMap); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, defNormalMap); }; <|endoftext|>
<commit_before>#include "../../../inc/slib/core/definition.h" #if defined(SLIB_PLATFORM_IS_ANDROID) #include "../../../inc/slib/ui/core.h" #include "../../../inc/slib/ui/screen.h" #include "../../../inc/slib/ui/platform.h" #include "../../../inc/slib/ui/mobile_app.h" #include "../../../inc/slib/core/map.h" #include "../../../inc/slib/core/io.h" #include "../../../inc/slib/core/log.h" #include "../../../inc/slib/core/safe_static.h" SLIB_UI_NAMESPACE_BEGIN SLIB_JNI_BEGIN_CLASS(_JAndroidPoint, "android/graphics/Point") SLIB_JNI_INT_FIELD(x); SLIB_JNI_INT_FIELD(y); SLIB_JNI_END_CLASS SLIB_JNI_BEGIN_CLASS(_AndroidUtil, "slib/platform/android/ui/Util") SLIB_JNI_STATIC_METHOD(getDefaultDisplay, "getDefaultDisplay", "(Lslib/platform/android/SlibActivity;)Landroid/view/Display;"); SLIB_JNI_STATIC_METHOD(getDisplaySize, "getDisplaySize", "(Landroid/view/Display;)Landroid/graphics/Point;"); SLIB_JNI_STATIC_METHOD(openURL, "openURL", "(Lslib/platform/android/SlibActivity;Landroid/view/View;[Ljava/lang/String;)V"); SLIB_JNI_END_CLASS void _AndroidUiThread_runDispatchCallback(JNIEnv* env, jobject _this); SLIB_JNI_BEGIN_CLASS(_AndroidUiThread, "slib/platform/android/ui/UiThread") SLIB_JNI_STATIC_METHOD(isUiThread, "isUiThread", "()Z"); SLIB_JNI_STATIC_METHOD(dispatch, "dispatch", "()V"); SLIB_JNI_STATIC_METHOD(runLoop, "runLoop", "()V"); SLIB_JNI_STATIC_METHOD(quitLoop, "quitLoop", "()V"); SLIB_JNI_NATIVE(nativeDispatchCallback, "nativeDispatchCallback", "()V", _AndroidUiThread_runDispatchCallback); SLIB_JNI_END_CLASS void _Android_onCreateActivity(JNIEnv* env, jobject _this, jobject activity); void _Android_onDestroyActivity(JNIEnv* env, jobject _this, jobject activity); void _Android_onResumeActivity(JNIEnv* env, jobject _this, jobject activity); void _Android_onPauseActivity(JNIEnv* env, jobject _this, jobject activity); jboolean _Android_onBack(JNIEnv* env, jobject _this, jobject activity); SLIB_JNI_BEGIN_CLASS(_Android, "slib/platform/android/Android") SLIB_JNI_NATIVE(onCreateActivity, "nativeOnCreateActivity", "(Landroid/app/Activity;)V", _Android_onCreateActivity); SLIB_JNI_NATIVE(onDestroyActivity, "nativeOnDestnativeOnResumeActivityroyActivity", "(Landroid/app/Activity;)V", _Android_onDestroyActivity); SLIB_JNI_NATIVE(onResumeActivity, "", "(Landroid/app/Activity;)V", _Android_onResumeActivity); SLIB_JNI_NATIVE(onPauseActivity, "nativeOnPauseActivity", "(Landroid/app/Activity;)V", _Android_onPauseActivity); SLIB_JNI_NATIVE(onBack, "nativeOnBack", "(Landroid/app/Activity;)Z", _Android_onBack); SLIB_JNI_END_CLASS class _Android_Screen : public Screen { public: JniGlobal<jobject> m_display; int m_width; int m_height; public: static Ref<_Android_Screen> create(jobject display) { Ref<_Android_Screen> ret; if (display) { JniLocal<jobject> size = _AndroidUtil::getDisplaySize.callObject(sl_null, display); if (size.isNotNull()) { ret = new _Android_Screen(); if (ret.isNotNull()) { ret->m_display = display; ret->m_width = _JAndroidPoint::x.get(size); ret->m_height = _JAndroidPoint::y.get(size); } } } return ret; } public: // override UIRect getRegion() { UIRect ret; ret.left = 0; ret.top = 0; ret.right = (sl_ui_pos)m_width; ret.bottom = (sl_ui_pos)m_height; return ret; } }; Ref<Screen> UI::getPrimaryScreen() { SLIB_STATIC_ZERO_INITIALIZED(SafeRef<Screen>, ret) if (SLIB_SAFE_STATIC_CHECK_FREED(ret)) { return Ref<Screen>::null(); } if (ret.isNull()) { jobject jactivity = Android::getCurrentActivity(); if (jactivity) { JniLocal<jobject> display = _AndroidUtil::getDefaultDisplay.callObject(sl_null, jactivity); ret = _Android_Screen::create(display); } } return ret; } Ref<Screen> UI::getFocusedScreen() { return UI::getPrimaryScreen(); } List< Ref<Screen> > UI::getScreens() { List< Ref<Screen> > ret; Ref<Screen> screen = UI::getPrimaryScreen(); if (screen.isNotNull()) { ret.add(screen); } return ret; } void UI::openURL(String url) { jobject jactivity = Android::getCurrentActivity(); if (jactivity) { JniLocal<jstring> jurl = Jni::getJniString(url); _AndroidUtil::openURL(jactivity, jurl); } } sl_bool UI::isUiThread() { return _AndroidUiThread::isUiThread.callBoolean(sl_null) != 0; } SLIB_SAFE_STATIC_GETTER(Queue<Callback>, _AndroidUi_getDispatchQueue); void UI::dispatchToUiThread(const Callback& callback) { if (callback.isNotNull()) { Queue<Callback>* queue = _AndroidUi_getDispatchQueue(); if (queue) { queue->push(callback); _AndroidUiThread::dispatch.call(sl_null); } } } void _AndroidUiThread_runDispatchCallback(JNIEnv* env, jobject _this) { Queue<Callback>* queue = _AndroidUi_getDispatchQueue(); if (queue) { Callback callback; while (queue->pop(&callback)) { callback(); } } } void UIPlatform::runLoop(sl_uint32 level) { _AndroidUiThread::runLoop.call(sl_null); } void UIPlatform::quitLoop() { _AndroidUiThread::quitLoop.call(sl_null); } static Ref<UIApp> _g_mobile_app; void UIPlatform::runApp() { _g_mobile_app = UIApp::getApp(); } void UIPlatform::quitApp() { } void _Android_onCreateActivity(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "Created"); Android::setCurrentActivity(activity); Ref<UIApp> app = UIApp::getApp(); if (app.isNotNull()) { static sl_bool flagStartApp = sl_false; if (! flagStartApp) { flagStartApp = sl_true; UIApp::dispatchStartToApp(); } MobileApp::dispatchCreateActivityToApp(); } } void _Android_onDestroyActivity(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "Destroyed"); MobileApp::dispatchDestroyActivityToApp(); } void _Android_onResumeActivity(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "Resumed"); Android::setCurrentActivity(activity); MobileApp::dispatchResumeToApp(); } void _Android_onPauseActivity(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "Paused"); MobileApp::dispatchPauseToApp(); } jboolean _Android_onBack(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "BackPressed"); return (jboolean)(MobileApp::dispatchBackToApp()); } SLIB_UI_NAMESPACE_END #endif <commit_msg>Minor fixes<commit_after>#include "../../../inc/slib/core/definition.h" #if defined(SLIB_PLATFORM_IS_ANDROID) #include "../../../inc/slib/ui/core.h" #include "../../../inc/slib/ui/screen.h" #include "../../../inc/slib/ui/platform.h" #include "../../../inc/slib/ui/mobile_app.h" #include "../../../inc/slib/core/map.h" #include "../../../inc/slib/core/io.h" #include "../../../inc/slib/core/log.h" #include "../../../inc/slib/core/safe_static.h" SLIB_UI_NAMESPACE_BEGIN SLIB_JNI_BEGIN_CLASS(_JAndroidPoint, "android/graphics/Point") SLIB_JNI_INT_FIELD(x); SLIB_JNI_INT_FIELD(y); SLIB_JNI_END_CLASS SLIB_JNI_BEGIN_CLASS(_AndroidUtil, "slib/platform/android/ui/Util") SLIB_JNI_STATIC_METHOD(getDefaultDisplay, "getDefaultDisplay", "(Lslib/platform/android/SlibActivity;)Landroid/view/Display;"); SLIB_JNI_STATIC_METHOD(getDisplaySize, "getDisplaySize", "(Landroid/view/Display;)Landroid/graphics/Point;"); SLIB_JNI_STATIC_METHOD(openURL, "openURL", "(Lslib/platform/android/SlibActivity;Landroid/view/View;Ljava/lang/String;)V"); SLIB_JNI_END_CLASS void _AndroidUiThread_runDispatchCallback(JNIEnv* env, jobject _this); SLIB_JNI_BEGIN_CLASS(_AndroidUiThread, "slib/platform/android/ui/UiThread") SLIB_JNI_STATIC_METHOD(isUiThread, "isUiThread", "()Z"); SLIB_JNI_STATIC_METHOD(dispatch, "dispatch", "()V"); SLIB_JNI_STATIC_METHOD(runLoop, "runLoop", "()V"); SLIB_JNI_STATIC_METHOD(quitLoop, "quitLoop", "()V"); SLIB_JNI_NATIVE(nativeDispatchCallback, "nativeDispatchCallback", "()V", _AndroidUiThread_runDispatchCallback); SLIB_JNI_END_CLASS void _Android_onCreateActivity(JNIEnv* env, jobject _this, jobject activity); void _Android_onDestroyActivity(JNIEnv* env, jobject _this, jobject activity); void _Android_onResumeActivity(JNIEnv* env, jobject _this, jobject activity); void _Android_onPauseActivity(JNIEnv* env, jobject _this, jobject activity); jboolean _Android_onBack(JNIEnv* env, jobject _this, jobject activity); SLIB_JNI_BEGIN_CLASS(_Android, "slib/platform/android/Android") SLIB_JNI_NATIVE(onCreateActivity, "nativeOnCreateActivity", "(Landroid/app/Activity;)V", _Android_onCreateActivity); SLIB_JNI_NATIVE(onDestroyActivity, "nativeOnDestnativeOnResumeActivityroyActivity", "(Landroid/app/Activity;)V", _Android_onDestroyActivity); SLIB_JNI_NATIVE(onResumeActivity, "", "(Landroid/app/Activity;)V", _Android_onResumeActivity); SLIB_JNI_NATIVE(onPauseActivity, "nativeOnPauseActivity", "(Landroid/app/Activity;)V", _Android_onPauseActivity); SLIB_JNI_NATIVE(onBack, "nativeOnBack", "(Landroid/app/Activity;)Z", _Android_onBack); SLIB_JNI_END_CLASS class _Android_Screen : public Screen { public: JniGlobal<jobject> m_display; int m_width; int m_height; public: static Ref<_Android_Screen> create(jobject display) { Ref<_Android_Screen> ret; if (display) { JniLocal<jobject> size = _AndroidUtil::getDisplaySize.callObject(sl_null, display); if (size.isNotNull()) { ret = new _Android_Screen(); if (ret.isNotNull()) { ret->m_display = display; ret->m_width = _JAndroidPoint::x.get(size); ret->m_height = _JAndroidPoint::y.get(size); } } } return ret; } public: // override UIRect getRegion() { UIRect ret; ret.left = 0; ret.top = 0; ret.right = (sl_ui_pos)m_width; ret.bottom = (sl_ui_pos)m_height; return ret; } }; Ref<Screen> UI::getPrimaryScreen() { SLIB_STATIC_ZERO_INITIALIZED(SafeRef<Screen>, ret) if (SLIB_SAFE_STATIC_CHECK_FREED(ret)) { return Ref<Screen>::null(); } if (ret.isNull()) { jobject jactivity = Android::getCurrentActivity(); if (jactivity) { JniLocal<jobject> display = _AndroidUtil::getDefaultDisplay.callObject(sl_null, jactivity); ret = _Android_Screen::create(display); } } return ret; } Ref<Screen> UI::getFocusedScreen() { return UI::getPrimaryScreen(); } List< Ref<Screen> > UI::getScreens() { List< Ref<Screen> > ret; Ref<Screen> screen = UI::getPrimaryScreen(); if (screen.isNotNull()) { ret.add(screen); } return ret; } void UI::openURL(String url) { jobject jactivity = Android::getCurrentActivity(); if (jactivity) { JniLocal<jstring> jurl = Jni::getJniString(url); _AndroidUtil::openURL(jactivity, jurl); } } sl_bool UI::isUiThread() { return _AndroidUiThread::isUiThread.callBoolean(sl_null) != 0; } SLIB_SAFE_STATIC_GETTER(Queue<Callback>, _AndroidUi_getDispatchQueue); void UI::dispatchToUiThread(const Callback& callback) { if (callback.isNotNull()) { Queue<Callback>* queue = _AndroidUi_getDispatchQueue(); if (queue) { queue->push(callback); _AndroidUiThread::dispatch.call(sl_null); } } } void _AndroidUiThread_runDispatchCallback(JNIEnv* env, jobject _this) { Queue<Callback>* queue = _AndroidUi_getDispatchQueue(); if (queue) { Callback callback; while (queue->pop(&callback)) { callback(); } } } void UIPlatform::runLoop(sl_uint32 level) { _AndroidUiThread::runLoop.call(sl_null); } void UIPlatform::quitLoop() { _AndroidUiThread::quitLoop.call(sl_null); } static Ref<UIApp> _g_mobile_app; void UIPlatform::runApp() { _g_mobile_app = UIApp::getApp(); } void UIPlatform::quitApp() { } void _Android_onCreateActivity(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "Created"); Android::setCurrentActivity(activity); Ref<UIApp> app = UIApp::getApp(); if (app.isNotNull()) { static sl_bool flagStartApp = sl_false; if (! flagStartApp) { flagStartApp = sl_true; UIApp::dispatchStartToApp(); } MobileApp::dispatchCreateActivityToApp(); } } void _Android_onDestroyActivity(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "Destroyed"); MobileApp::dispatchDestroyActivityToApp(); } void _Android_onResumeActivity(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "Resumed"); Android::setCurrentActivity(activity); MobileApp::dispatchResumeToApp(); } void _Android_onPauseActivity(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "Paused"); MobileApp::dispatchPauseToApp(); } jboolean _Android_onBack(JNIEnv* env, jobject _this, jobject activity) { SLIB_LOG("Activity", "BackPressed"); return (jboolean)(MobileApp::dispatchBackToApp()); } SLIB_UI_NAMESPACE_END #endif <|endoftext|>
<commit_before>// // EmiPacketHeader.cc // rock // // Created by Per Eckerdal on 2012-05-10. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "EmiPacketHeader.h" #include "EmiNetUtil.h" #include <cstring> #include <algorithm> inline static void extractFlagsAndSize(EmiPacketFlags flags, EmiPacketExtraFlags extraFlags, bool *hasSequenceNumber, bool *hasAck, bool *hasNak, bool *hasLinkCapacity, bool *hasArrivalRate, bool *hasRttRequest, bool *hasRttResponse, size_t *fillerSizePtr, // Can be NULL size_t *expectedSize) { size_t fillerSize = 0; *hasSequenceNumber = !!(flags & EMI_SEQUENCE_NUMBER_PACKET_FLAG); *hasAck = !!(flags & EMI_ACK_PACKET_FLAG); *hasNak = !!(flags & EMI_NAK_PACKET_FLAG); *hasLinkCapacity = !!(flags & EMI_LINK_CAPACITY_PACKET_FLAG); *hasArrivalRate = !!(flags & EMI_ARRIVAL_RATE_PACKET_FLAG); *hasRttRequest = !!(flags & EMI_RTT_REQUEST_PACKET_FLAG); *hasRttResponse = !!(flags & EMI_RTT_RESPONSE_PACKET_FLAG); bool hasExtraFlags = !!(flags & EMI_EXTRA_FLAGS_PACKET_FLAG); // 1 for the flags byte *expectedSize = sizeof(EmiPacketFlags); if (hasExtraFlags) { *expectedSize += sizeof(EmiPacketExtraFlags); if (flags & EMI_1_BYTE_FILLER_EXTRA_PACKET_FLAG) { fillerSize = 1; } else if (flags & EMI_2_BYTE_FILLER_EXTRA_PACKET_FLAG) { fillerSize = 2; } else { fillerSize = 0; } *expectedSize += fillerSize; } if (fillerSizePtr) { *fillerSizePtr = fillerSize; } *expectedSize += (*hasSequenceNumber ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0); *expectedSize += (*hasAck ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0); *expectedSize += (*hasNak ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0); *expectedSize += (*hasLinkCapacity ? sizeof(float) : 0); *expectedSize += (*hasArrivalRate ? sizeof(float) : 0); *expectedSize += (*hasRttResponse ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH+sizeof(uint8_t) : 0); } EmiPacketHeader::EmiPacketHeader() : flags(0), sequenceNumber(0), ack(0), nak(0), linkCapacity(0), arrivalRate(0), rttResponse(0), rttResponseDelay(0) {} EmiPacketHeader::~EmiPacketHeader() {} bool EmiPacketHeader::parse(const uint8_t *buf, size_t bufSize, EmiPacketHeader *header, size_t *headerLength) { if (0 >= bufSize) { return false; } EmiPacketFlags flags = buf[0]; EmiPacketExtraFlags extraFlags = (EmiPacketExtraFlags) 0; if (bufSize >= 1) { extraFlags = (EmiPacketExtraFlags) buf[1]; } bool hasSequenceNumber, hasAck, hasNak, hasLinkCapacity; bool hasArrivalRate, hasRttRequest, hasRttResponse; size_t expectedSize, fillerSize; extractFlagsAndSize(flags, extraFlags, &hasSequenceNumber, &hasAck, &hasNak, &hasLinkCapacity, &hasArrivalRate, &hasRttRequest, &hasRttResponse, &fillerSize, &expectedSize); if (2 == fillerSize) { // A 2 byte filler size means that the packet contains a 16 bit // unsigned integer which specifies padding if (4 > bufSize) { return false; } uint16_t twoByteFillerSize = ntohs(*((uint16_t *)(buf+2))); fillerSize += twoByteFillerSize; expectedSize += twoByteFillerSize; } if (bufSize < expectedSize) { return false; } header->flags = flags; header->sequenceNumber = 0; header->ack = 0; header->nak = 0; header->linkCapacity = 0.0f; header->arrivalRate = 0.0f; header->rttResponse = 0; header->rttResponseDelay = 0; const uint8_t *bufCur = buf+sizeof(header->flags); if (flags & EMI_EXTRA_FLAGS_PACKET_FLAG) { bufCur += sizeof(EmiPacketExtraFlags); bufCur += fillerSize; } if (hasSequenceNumber) { header->sequenceNumber = EmiNetUtil::read24(bufCur); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasAck) { header->ack = EmiNetUtil::read24(bufCur); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasNak) { header->nak = EmiNetUtil::read24(bufCur); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasLinkCapacity) { uint32_t linkCapacityInt = ntohl(*reinterpret_cast<const uint32_t *>(bufCur)); header->linkCapacity = *reinterpret_cast<float *>(&linkCapacityInt); bufCur += sizeof(header->linkCapacity); } if (hasArrivalRate) { uint32_t arrivalRateInt = ntohl(*reinterpret_cast<const uint32_t *>(bufCur)); header->arrivalRate = *reinterpret_cast<float *>(&arrivalRateInt); bufCur += sizeof(header->arrivalRate); } if (hasRttResponse) { header->rttResponse = EmiNetUtil::read24(bufCur); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; header->rttResponseDelay = *bufCur; bufCur += sizeof(header->rttResponseDelay); } if (headerLength) { *headerLength = expectedSize; } return true; } bool EmiPacketHeader::write(uint8_t *buf, size_t bufSize, const EmiPacketHeader& header, size_t *headerLength) { if (0 >= bufSize) { return false; } bool hasSequenceNumber, hasAck, hasNak, hasLinkCapacity; bool hasArrivalRate, hasRttRequest, hasRttResponse; size_t expectedSize; extractFlagsAndSize(header.flags, (EmiPacketExtraFlags)0, &hasSequenceNumber, &hasAck, &hasNak, &hasLinkCapacity, &hasArrivalRate, &hasRttRequest, &hasRttResponse, /*fillerSize:*/NULL, &expectedSize); if (bufSize < expectedSize) { return false; } memset(buf, 0, expectedSize); buf[0] = header.flags; uint8_t *bufCur = buf+sizeof(EmiPacketFlags); if (hasSequenceNumber) { EmiNetUtil::write24(bufCur, header.sequenceNumber); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasAck) { EmiNetUtil::write24(bufCur, header.ack); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasNak) { EmiNetUtil::write24(bufCur, header.nak); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasLinkCapacity) { *((int32_t *)bufCur) = htonl(*reinterpret_cast<const uint32_t *>(&header.linkCapacity)); bufCur += sizeof(header.linkCapacity); } if (hasArrivalRate) { *((int32_t *)bufCur) = htonl(*reinterpret_cast<const uint32_t *>(&header.arrivalRate)); bufCur += sizeof(header.arrivalRate); } if (hasRttResponse) { EmiNetUtil::write24(bufCur, header.rttResponse); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; *bufCur = header.rttResponseDelay; bufCur += sizeof(header.rttResponseDelay); } if (headerLength) { *headerLength = expectedSize; } return true; } bool EmiPacketHeader::writeEmpty(uint8_t *buf, size_t bufSize, size_t *headerLength) { if (0 >= bufSize) { return false; } *buf = 0; *headerLength = 1; return true; } void EmiPacketHeader::addFillerBytes(uint8_t *buf, size_t packetSize, uint16_t fillerSize) { ASSERT(1 <= packetSize); if (0 == fillerSize) { // We don't need to do anything return; } // Move the packet data std::copy_backward(buf+1, buf+packetSize, buf+packetSize+fillerSize); // Make sure we have the extra flags byte if (!(buf[0] & EMI_EXTRA_FLAGS_PACKET_FLAG)) { buf[0] |= EMI_EXTRA_FLAGS_PACKET_FLAG; buf[1] = 0; // Decrement the filler size here because by adding // the extra flags byte we have already increased // the size of the packet by one. fillerSize -= sizeof(EmiPacketExtraFlags); } if (0 == fillerSize) { // We're done. This happens when fillerSize was 1 and // the packet did not already contain the extra flags // byte } else if (1 == fillerSize) { buf[1] |= EMI_1_BYTE_FILLER_EXTRA_PACKET_FLAG; buf[2] = 0; } else { buf[1] |= EMI_2_BYTE_FILLER_EXTRA_PACKET_FLAG; *((uint16_t *)(buf+2)) = htons(fillerSize - 2); memset(buf+4, 0, fillerSize-2); } } <commit_msg>Fixed a fairly extreme memory corruption bug found with Valgrind. EmiPacketHeader::addFillerBytes would zero out almost 64kb when the fillerSize parameter was 1, 2 or 3.<commit_after>// // EmiPacketHeader.cc // rock // // Created by Per Eckerdal on 2012-05-10. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "EmiPacketHeader.h" #include "EmiNetUtil.h" #include <cstring> #include <algorithm> inline static void extractFlagsAndSize(EmiPacketFlags flags, EmiPacketExtraFlags extraFlags, bool *hasSequenceNumber, bool *hasAck, bool *hasNak, bool *hasLinkCapacity, bool *hasArrivalRate, bool *hasRttRequest, bool *hasRttResponse, size_t *fillerSizePtr, // Can be NULL size_t *expectedSize) { size_t fillerSize = 0; *hasSequenceNumber = !!(flags & EMI_SEQUENCE_NUMBER_PACKET_FLAG); *hasAck = !!(flags & EMI_ACK_PACKET_FLAG); *hasNak = !!(flags & EMI_NAK_PACKET_FLAG); *hasLinkCapacity = !!(flags & EMI_LINK_CAPACITY_PACKET_FLAG); *hasArrivalRate = !!(flags & EMI_ARRIVAL_RATE_PACKET_FLAG); *hasRttRequest = !!(flags & EMI_RTT_REQUEST_PACKET_FLAG); *hasRttResponse = !!(flags & EMI_RTT_RESPONSE_PACKET_FLAG); bool hasExtraFlags = !!(flags & EMI_EXTRA_FLAGS_PACKET_FLAG); // 1 for the flags byte *expectedSize = sizeof(EmiPacketFlags); if (hasExtraFlags) { *expectedSize += sizeof(EmiPacketExtraFlags); if (flags & EMI_1_BYTE_FILLER_EXTRA_PACKET_FLAG) { fillerSize = 1; } else if (flags & EMI_2_BYTE_FILLER_EXTRA_PACKET_FLAG) { fillerSize = 2; } else { fillerSize = 0; } *expectedSize += fillerSize; } if (fillerSizePtr) { *fillerSizePtr = fillerSize; } *expectedSize += (*hasSequenceNumber ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0); *expectedSize += (*hasAck ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0); *expectedSize += (*hasNak ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0); *expectedSize += (*hasLinkCapacity ? sizeof(float) : 0); *expectedSize += (*hasArrivalRate ? sizeof(float) : 0); *expectedSize += (*hasRttResponse ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH+sizeof(uint8_t) : 0); } EmiPacketHeader::EmiPacketHeader() : flags(0), sequenceNumber(0), ack(0), nak(0), linkCapacity(0), arrivalRate(0), rttResponse(0), rttResponseDelay(0) {} EmiPacketHeader::~EmiPacketHeader() {} bool EmiPacketHeader::parse(const uint8_t *buf, size_t bufSize, EmiPacketHeader *header, size_t *headerLength) { if (0 >= bufSize) { return false; } EmiPacketFlags flags = buf[0]; EmiPacketExtraFlags extraFlags = (EmiPacketExtraFlags) 0; if (bufSize >= 1) { extraFlags = (EmiPacketExtraFlags) buf[1]; } bool hasSequenceNumber, hasAck, hasNak, hasLinkCapacity; bool hasArrivalRate, hasRttRequest, hasRttResponse; size_t expectedSize, fillerSize; extractFlagsAndSize(flags, extraFlags, &hasSequenceNumber, &hasAck, &hasNak, &hasLinkCapacity, &hasArrivalRate, &hasRttRequest, &hasRttResponse, &fillerSize, &expectedSize); if (2 == fillerSize) { // A 2 byte filler size means that the packet contains a 16 bit // unsigned integer which specifies padding if (4 > bufSize) { return false; } uint16_t twoByteFillerSize = ntohs(*((uint16_t *)(buf+2))); fillerSize += twoByteFillerSize; expectedSize += twoByteFillerSize; } if (bufSize < expectedSize) { return false; } header->flags = flags; header->sequenceNumber = 0; header->ack = 0; header->nak = 0; header->linkCapacity = 0.0f; header->arrivalRate = 0.0f; header->rttResponse = 0; header->rttResponseDelay = 0; const uint8_t *bufCur = buf+sizeof(header->flags); if (flags & EMI_EXTRA_FLAGS_PACKET_FLAG) { bufCur += sizeof(EmiPacketExtraFlags); bufCur += fillerSize; } if (hasSequenceNumber) { header->sequenceNumber = EmiNetUtil::read24(bufCur); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasAck) { header->ack = EmiNetUtil::read24(bufCur); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasNak) { header->nak = EmiNetUtil::read24(bufCur); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasLinkCapacity) { uint32_t linkCapacityInt = ntohl(*reinterpret_cast<const uint32_t *>(bufCur)); header->linkCapacity = *reinterpret_cast<float *>(&linkCapacityInt); bufCur += sizeof(header->linkCapacity); } if (hasArrivalRate) { uint32_t arrivalRateInt = ntohl(*reinterpret_cast<const uint32_t *>(bufCur)); header->arrivalRate = *reinterpret_cast<float *>(&arrivalRateInt); bufCur += sizeof(header->arrivalRate); } if (hasRttResponse) { header->rttResponse = EmiNetUtil::read24(bufCur); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; header->rttResponseDelay = *bufCur; bufCur += sizeof(header->rttResponseDelay); } if (headerLength) { *headerLength = expectedSize; } return true; } bool EmiPacketHeader::write(uint8_t *buf, size_t bufSize, const EmiPacketHeader& header, size_t *headerLength) { if (0 >= bufSize) { return false; } bool hasSequenceNumber, hasAck, hasNak, hasLinkCapacity; bool hasArrivalRate, hasRttRequest, hasRttResponse; size_t expectedSize; extractFlagsAndSize(header.flags, (EmiPacketExtraFlags)0, &hasSequenceNumber, &hasAck, &hasNak, &hasLinkCapacity, &hasArrivalRate, &hasRttRequest, &hasRttResponse, /*fillerSize:*/NULL, &expectedSize); if (bufSize < expectedSize) { return false; } memset(buf, 0, expectedSize); buf[0] = header.flags; uint8_t *bufCur = buf+sizeof(EmiPacketFlags); if (hasSequenceNumber) { EmiNetUtil::write24(bufCur, header.sequenceNumber); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasAck) { EmiNetUtil::write24(bufCur, header.ack); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasNak) { EmiNetUtil::write24(bufCur, header.nak); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; } if (hasLinkCapacity) { *((int32_t *)bufCur) = htonl(*reinterpret_cast<const uint32_t *>(&header.linkCapacity)); bufCur += sizeof(header.linkCapacity); } if (hasArrivalRate) { *((int32_t *)bufCur) = htonl(*reinterpret_cast<const uint32_t *>(&header.arrivalRate)); bufCur += sizeof(header.arrivalRate); } if (hasRttResponse) { EmiNetUtil::write24(bufCur, header.rttResponse); bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH; *bufCur = header.rttResponseDelay; bufCur += sizeof(header.rttResponseDelay); } if (headerLength) { *headerLength = expectedSize; } return true; } bool EmiPacketHeader::writeEmpty(uint8_t *buf, size_t bufSize, size_t *headerLength) { if (0 >= bufSize) { return false; } *buf = 0; *headerLength = 1; return true; } void EmiPacketHeader::addFillerBytes(uint8_t *buf, size_t packetSize, uint16_t fillerSize) { ASSERT(1 <= packetSize); if (0 == fillerSize) { // We don't need to do anything return; } // Move the packet data std::copy_backward(buf+1, buf+packetSize, buf+packetSize+fillerSize); // Make sure we have the extra flags byte if (!(buf[0] & EMI_EXTRA_FLAGS_PACKET_FLAG)) { buf[0] |= EMI_EXTRA_FLAGS_PACKET_FLAG; buf[1] = 0; // Decrement the filler size here because by adding // the extra flags byte we have already increased // the size of the packet by one. fillerSize -= 1; } if (0 == fillerSize) { // We're done. This happens when fillerSize was 1 and // the packet did not already contain the extra flags // byte } else if (1 == fillerSize) { buf[1] |= EMI_1_BYTE_FILLER_EXTRA_PACKET_FLAG; buf[2] = 0; } else { buf[1] |= EMI_2_BYTE_FILLER_EXTRA_PACKET_FLAG; *((uint16_t *)(buf+2)) = htons(fillerSize - 2); memset(buf+4, 0, fillerSize-2); } } <|endoftext|>
<commit_before><commit_msg>GraphicManager: fix crash when swapping out graphics<commit_after><|endoftext|>
<commit_before><commit_msg>fdo#38635: sw: fix border corner gaps:<commit_after><|endoftext|>
<commit_before><commit_msg>During sensor search only check data of joining device for resource creation<commit_after><|endoftext|>
<commit_before><commit_msg>Filter REST API plugin network interfaces to not include virtual and loopback interface<commit_after><|endoftext|>
<commit_before>#include "SwiftExtractor.h" #include <filesystem> #include <fstream> #include <iostream> #include <sstream> #include <memory> #include <unistd.h> #include <unordered_set> #include <swift/AST/SourceFile.h> #include <swift/Basic/FileTypes.h> #include <llvm/ADT/SmallString.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/Path.h> #include "swift/extractor/trap/generated/TrapClasses.h" #include "swift/extractor/trap/TrapOutput.h" #include "swift/extractor/SwiftVisitor.h" using namespace codeql; static void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) { if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) { std::cerr << "Cannot create TRAP directory: " << ec.message() << "\n"; return; } if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) { std::cerr << "Cannot create source archive directory: " << ec.message() << "\n"; return; } llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename()); llvm::sys::fs::make_absolute(srcFilePath); llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir); llvm::sys::path::append(dstFilePath, srcFilePath); llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath); if (std::error_code ec = llvm::sys::fs::create_directories(parent)) { std::cerr << "Cannot create source archive destination directory '" << parent.str() << "': " << ec.message() << "\n"; return; } if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) { std::cerr << "Cannot archive source file '" << srcFilePath.str().str() << "' -> '" << dstFilePath.str().str() << "': " << ec.message() << "\n"; return; } } static void extractDeclarations(const SwiftExtractorConfiguration& config, llvm::ArrayRef<swift::Decl*> topLevelDecls, swift::CompilerInstance& compiler, swift::ModuleDecl& module, swift::SourceFile* primaryFile = nullptr) { // The extractor can be called several times from different processes with // the same input file(s) // We are using PID to avoid concurrent access // TODO: find a more robust approach to avoid collisions? llvm::StringRef filename = primaryFile ? primaryFile->getFilename() : module.getModuleFilename(); std::string tempTrapName = filename.str() + '.' + std::to_string(getpid()) + ".trap"; llvm::SmallString<PATH_MAX> tempTrapPath(config.trapDir); llvm::sys::path::append(tempTrapPath, tempTrapName); llvm::StringRef trapParent = llvm::sys::path::parent_path(tempTrapPath); if (std::error_code ec = llvm::sys::fs::create_directories(trapParent)) { std::cerr << "Cannot create trap directory '" << trapParent.str() << "': " << ec.message() << "\n"; return; } std::ofstream trapStream(tempTrapPath.str().str()); if (!trapStream) { std::error_code ec; ec.assign(errno, std::generic_category()); std::cerr << "Cannot create temp trap file '" << tempTrapPath.str().str() << "': " << ec.message() << "\n"; return; } trapStream << "// extractor-args: "; for (auto opt : config.frontendOptions) { trapStream << std::quoted(opt) << " "; } trapStream << "\n\n"; TrapOutput trap{trapStream}; TrapArena arena{}; // TODO: move default location emission elsewhere, possibly in a separate global trap file auto unknownFileLabel = arena.allocateLabel<FileTag>(); // the following cannot conflict with actual files as those have an absolute path starting with / trap.assignKey(unknownFileLabel, "unknown"); trap.emit(FilesTrap{unknownFileLabel}); auto unknownLocationLabel = arena.allocateLabel<LocationTag>(); trap.assignKey(unknownLocationLabel, "unknown"); trap.emit(LocationsTrap{unknownLocationLabel, unknownFileLabel}); SwiftVisitor visitor(compiler.getSourceMgr(), arena, trap, module, primaryFile); for (auto decl : topLevelDecls) { visitor.extract(decl); } if (topLevelDecls.empty()) { // In the case of empty files, the dispatcher is not called, but we still want to 'record' the // fact that the file was extracted llvm::SmallString<PATH_MAX> name(filename); llvm::sys::fs::make_absolute(name); auto fileLabel = arena.allocateLabel<FileTag>(); trap.assignKey(fileLabel, name.str().str()); trap.emit(FilesTrap{fileLabel, name.str().str()}); } // TODO: Pick a better name to avoid collisions std::string trapName = filename.str() + ".trap"; llvm::SmallString<PATH_MAX> trapPath(config.trapDir); llvm::sys::path::append(trapPath, trapName); // TODO: The last process wins. Should we do better than that? if (std::error_code ec = llvm::sys::fs::rename(tempTrapPath, trapPath)) { std::cerr << "Cannot rename temp trap file '" << tempTrapPath.str().str() << "' -> '" << trapPath.str().str() << "': " << ec.message() << "\n"; } } void codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config, swift::CompilerInstance& compiler) { // The frontend can be called in many different ways. // At each invocation we only extract system and builtin modules and any input source files that // have an output associated with them. std::unordered_set<std::string> sourceFiles; auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs(); for (auto& input : inputFiles) { if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) { sourceFiles.insert(input.getFileName()); } } for (auto& [_, module] : compiler.getASTContext().getLoadedModules()) { // We only extract system and builtin modules here as the other "user" modules can be built // during the build process and then re-used at a later stage. In this case, we extract the // user code twice: once during the module build in a form of a source file, and then as // a pre-built module during building of the dependent source files. if (module->isSystemModule() || module->isBuiltinModule()) { llvm::SmallVector<swift::Decl*> decls; module->getTopLevelDecls(decls); // TODO: pass ModuleDecl directly when we have module extraction in place? extractDeclarations(config, decls, compiler, *module); } else { for (auto file : module->getFiles()) { if (!llvm::isa<swift::SourceFile>(file)) { continue; } auto sourceFile = llvm::cast<swift::SourceFile>(file); if (sourceFiles.count(sourceFile->getFilename().str()) == 0) { continue; } archiveFile(config, *sourceFile); extractDeclarations(config, sourceFile->getTopLevelDecls(), compiler, *module, sourceFile); } } } } <commit_msg>Update swift/extractor/SwiftExtractor.cpp<commit_after>#include "SwiftExtractor.h" #include <filesystem> #include <fstream> #include <iostream> #include <sstream> #include <memory> #include <unistd.h> #include <unordered_set> #include <swift/AST/SourceFile.h> #include <swift/Basic/FileTypes.h> #include <llvm/ADT/SmallString.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/Path.h> #include "swift/extractor/trap/generated/TrapClasses.h" #include "swift/extractor/trap/TrapOutput.h" #include "swift/extractor/SwiftVisitor.h" using namespace codeql; static void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) { if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) { std::cerr << "Cannot create TRAP directory: " << ec.message() << "\n"; return; } if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) { std::cerr << "Cannot create source archive directory: " << ec.message() << "\n"; return; } llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename()); llvm::sys::fs::make_absolute(srcFilePath); llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir); llvm::sys::path::append(dstFilePath, srcFilePath); llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath); if (std::error_code ec = llvm::sys::fs::create_directories(parent)) { std::cerr << "Cannot create source archive destination directory '" << parent.str() << "': " << ec.message() << "\n"; return; } if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) { std::cerr << "Cannot archive source file '" << srcFilePath.str().str() << "' -> '" << dstFilePath.str().str() << "': " << ec.message() << "\n"; return; } } static void extractDeclarations(const SwiftExtractorConfiguration& config, llvm::ArrayRef<swift::Decl*> topLevelDecls, swift::CompilerInstance& compiler, swift::ModuleDecl& module, swift::SourceFile* primaryFile = nullptr) { // The extractor can be called several times from different processes with // the same input file(s) // We are using PID to avoid concurrent access // TODO: find a more robust approach to avoid collisions? llvm::StringRef filename = primaryFile ? primaryFile->getFilename() : module.getModuleFilename(); std::string tempTrapName = filename.str() + '.' + std::to_string(getpid()) + ".trap"; llvm::SmallString<PATH_MAX> tempTrapPath(config.trapDir); llvm::sys::path::append(tempTrapPath, tempTrapName); llvm::StringRef trapParent = llvm::sys::path::parent_path(tempTrapPath); if (std::error_code ec = llvm::sys::fs::create_directories(trapParent)) { std::cerr << "Cannot create trap directory '" << trapParent.str() << "': " << ec.message() << "\n"; return; } std::ofstream trapStream(tempTrapPath.str().str()); if (!trapStream) { std::error_code ec; ec.assign(errno, std::generic_category()); std::cerr << "Cannot create temp trap file '" << tempTrapPath.str().str() << "': " << ec.message() << "\n"; return; } trapStream << "// extractor-args: "; for (auto opt : config.frontendOptions) { trapStream << std::quoted(opt) << " "; } trapStream << "\n\n"; TrapOutput trap{trapStream}; TrapArena arena{}; // TODO: move default location emission elsewhere, possibly in a separate global trap file auto unknownFileLabel = arena.allocateLabel<FileTag>(); // the following cannot conflict with actual files as those have an absolute path starting with / trap.assignKey(unknownFileLabel, "unknown"); trap.emit(FilesTrap{unknownFileLabel}); auto unknownLocationLabel = arena.allocateLabel<LocationTag>(); trap.assignKey(unknownLocationLabel, "unknown"); trap.emit(LocationsTrap{unknownLocationLabel, unknownFileLabel}); SwiftVisitor visitor(compiler.getSourceMgr(), arena, trap, module, primaryFile); for (auto decl : topLevelDecls) { visitor.extract(decl); } if (topLevelDecls.empty()) { // In the case of empty files, the dispatcher is not called, but we still want to 'record' the // fact that the file was extracted llvm::SmallString<PATH_MAX> name(filename); llvm::sys::fs::make_absolute(name); auto fileLabel = arena.allocateLabel<FileTag>(); trap.assignKey(fileLabel, name.str().str()); trap.emit(FilesTrap{fileLabel, name.str().str()}); } // TODO: Pick a better name to avoid collisions std::string trapName = filename.str() + ".trap"; llvm::SmallString<PATH_MAX> trapPath(config.trapDir); llvm::sys::path::append(trapPath, trapName); // TODO: The last process wins. Should we do better than that? if (std::error_code ec = llvm::sys::fs::rename(tempTrapPath, trapPath)) { std::cerr << "Cannot rename temp trap file '" << tempTrapPath.str().str() << "' -> '" << trapPath.str().str() << "': " << ec.message() << "\n"; } } void codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config, swift::CompilerInstance& compiler) { // The frontend can be called in many different ways. // At each invocation we only extract system and builtin modules and any input source files that // have an output associated with them. std::unordered_set<std::string> sourceFiles; auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs(); for (auto& input : inputFiles) { if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) { sourceFiles.insert(input.getFileName()); } } for (auto& [_, module] : compiler.getASTContext().getLoadedModules()) { // We only extract system and builtin modules here as the other "user" modules can be built // during the build process and then re-used at a later stage. In this case, we extract the // user code twice: once during the module build in a form of a source file, and then as // a pre-built module during building of the dependent source files. if (module->isSystemModule() || module->isBuiltinModule()) { llvm::SmallVector<swift::Decl*> decls; module->getTopLevelDecls(decls); // TODO: pass ModuleDecl directly when we have module extraction in place? extractDeclarations(config, decls, compiler, *module); } else { for (auto file : module->getFiles()) { auto sourceFile = llvm::dyn_cast<swift::SourceFile>(file); if (!sourceFile || sourceFiles.count(sourceFile->getFilename().str()) == 0) { continue; } archiveFile(config, *sourceFile); extractDeclarations(config, sourceFile->getTopLevelDecls(), compiler, *module, sourceFile); } } } } <|endoftext|>
<commit_before><commit_msg>UPDATE moved reflection cubmap subresource init to be independent to static shadows<commit_after><|endoftext|>
<commit_before>/* Copyright 2015-2018 Egor Yusov * * 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 * * 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include <queue> #include "SampleApp.h" #include "AntTweakBar.h" using namespace Diligent; class SampleAppIOS final : public SampleApp { public: SampleAppIOS() { m_DeviceType = DeviceType::OpenGLES; } virtual void OnGLContextCreated(void *eaglLayer)override final { InitializeDiligentEngine(eaglLayer); m_TheSample->SetUIScale(2); InitializeSample(); } virtual void Render()override { /*m_pImmediateContext->SetRenderTargets(0, nullptr, nullptr); // Handle all TwBar events here as the event handlers call draw commands // and thus cannot be used in the UI thread while(!TwBarEvents.empty()) { const auto& event = TwBarEvents.front(); switch (event.type) { case TwEvent::LMB_PRESSED: case TwEvent::RMB_PRESSED: TwMouseButton(TW_MOUSE_PRESSED, event.type == TwEvent::LMB_PRESSED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT); break; case TwEvent::LMB_RELEASED: case TwEvent::RMB_RELEASED: TwMouseButton(TW_MOUSE_RELEASED, event.type == TwEvent::LMB_RELEASED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT); break; case TwEvent::MOUSE_MOVE: TwMouseMotion(event.mouseX, event.mouseY); break; case TwEvent::KEY_PRESSED: TwKeyPressed(event.key, 0); break; } TwBarEvents.pop(); }*/ SampleApp::Render(); } private: /* // Unfortunately TwBar library calls rendering // functions from event handlers, which does not work on MacOS // as UI events and rendering are handled by separate threads struct TwEvent { enum EVENT_TYPE { LMB_PRESSED, LMB_RELEASED, RMB_PRESSED, RMB_RELEASED, MOUSE_MOVE, KEY_PRESSED }type; int mouseX = 0; int mouseY = 0; int key = 0; TwEvent(EVENT_TYPE _type) : type(_type){} TwEvent(int x, int y) : type(MOUSE_MOVE), mouseX(x), mouseY(y){} TwEvent(int k) : type(KEY_PRESSED), key(k){} }; std::queue<TwEvent> TwBarEvents;*/ }; NativeAppBase* CreateApplication() { return new SampleAppIOS; } <commit_msg>Removed UI scale on iOS<commit_after>/* Copyright 2015-2018 Egor Yusov * * 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 * * 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include <queue> #include "SampleApp.h" #include "AntTweakBar.h" using namespace Diligent; class SampleAppIOS final : public SampleApp { public: SampleAppIOS() { m_DeviceType = DeviceType::OpenGLES; } virtual void OnGLContextCreated(void *eaglLayer)override final { InitializeDiligentEngine(eaglLayer); InitializeSample(); } virtual void Render()override { /*m_pImmediateContext->SetRenderTargets(0, nullptr, nullptr); // Handle all TwBar events here as the event handlers call draw commands // and thus cannot be used in the UI thread while(!TwBarEvents.empty()) { const auto& event = TwBarEvents.front(); switch (event.type) { case TwEvent::LMB_PRESSED: case TwEvent::RMB_PRESSED: TwMouseButton(TW_MOUSE_PRESSED, event.type == TwEvent::LMB_PRESSED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT); break; case TwEvent::LMB_RELEASED: case TwEvent::RMB_RELEASED: TwMouseButton(TW_MOUSE_RELEASED, event.type == TwEvent::LMB_RELEASED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT); break; case TwEvent::MOUSE_MOVE: TwMouseMotion(event.mouseX, event.mouseY); break; case TwEvent::KEY_PRESSED: TwKeyPressed(event.key, 0); break; } TwBarEvents.pop(); }*/ SampleApp::Render(); } private: /* // Unfortunately TwBar library calls rendering // functions from event handlers, which does not work on MacOS // as UI events and rendering are handled by separate threads struct TwEvent { enum EVENT_TYPE { LMB_PRESSED, LMB_RELEASED, RMB_PRESSED, RMB_RELEASED, MOUSE_MOVE, KEY_PRESSED }type; int mouseX = 0; int mouseY = 0; int key = 0; TwEvent(EVENT_TYPE _type) : type(_type){} TwEvent(int x, int y) : type(MOUSE_MOVE), mouseX(x), mouseY(y){} TwEvent(int k) : type(KEY_PRESSED), key(k){} }; std::queue<TwEvent> TwBarEvents;*/ }; NativeAppBase* CreateApplication() { return new SampleAppIOS; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * Simbody(tm): SimTKmath * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2006-14 Stanford University and the Authors. * * Authors: Chris Dembia * * Contributors: Michael Sherman * * * * 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 "CMAESOptimizer.h" #include <bitset> namespace SimTK { #define SimTK_CMAES_PRINT(diag, cmds) \ do { \ if (std::bitset<2>(diag).test(0)) { cmds; } \ } \ while(false) #define SimTK_CMAES_FILE(diag, cmds) \ do { \ if (std::bitset<2>(diag).test(1)) { cmds; } \ } \ while(false) CMAESOptimizer::CMAESOptimizer(const OptimizerSystem& sys) : OptimizerRep(sys) { SimTK_VALUECHECK_ALWAYS(2, sys.getNumParameters(), INT_MAX, "nParameters", "CMAESOptimizer"); } Optimizer::OptimizerRep* CMAESOptimizer::clone() const { return new CMAESOptimizer(*this); } Real CMAESOptimizer::optimize(SimTK::Vector& results) { const OptimizerSystem& sys = getOptimizerSystem(); int n = sys.getNumParameters(); // Initialize objective function value and cmaes data structure. // ============================================================= Real f; cmaes_t evo; // Check that the initial point is feasible. // ========================================= checkInitialPointIsFeasible(results); // Initialize cmaes. // ================= double* funvals = init(evo, results); SimTK_CMAES_PRINT(diagnosticsLevel, printf("%s\n", cmaes_SayHello(&evo))); // Optimize. // ========= while (!cmaes_TestForTermination(&evo)) { // Sample a population. // ==================== double*const* pop = cmaes_SamplePopulation(&evo); // Resample to keep population within limits. // ========================================== if( sys.getHasLimits() ) { Real *lowerLimits, *upperLimits; sys.getParameterLimits( &lowerLimits, &upperLimits ); for (int i = 0; i < cmaes_Get(&evo, "lambda"); i++) { bool feasible = false; while (!feasible) { feasible = true; for (int j = 0; j < n; j++) { if (pop[i][j] < lowerLimits[j] || pop[i][j] > upperLimits[j]) { feasible = false; pop = cmaes_ReSampleSingle(&evo, i); break; } } } } } // Evaluate the objective function on the samples. // =============================================== for (int i = 0; i < cmaes_Get(&evo, "lambda"); i++) { objectiveFuncWrapper(n, pop[i], true, &funvals[i], this); } // Update the distribution (mean, covariance, etc.). // ================================================= cmaes_UpdateDistribution(&evo, funvals); } // Wrap up. // ======== SimTK_CMAES_PRINT(diagnosticsLevel, printf("Stop:\n%s\n", cmaes_TestForTermination(&evo))); // Update best parameters and objective function value. const double* optx = cmaes_GetPtr(&evo, "xbestever"); for (int i = 0; i < n; i++) { results[i] = optx[i]; } f = cmaes_Get(&evo, "fbestever"); SimTK_CMAES_FILE(diagnosticsLevel, cmaes_WriteToFile(&evo, "all", "allcmaes.dat")); // Free memory. cmaes_exit(&evo); return f; } void CMAESOptimizer::checkInitialPointIsFeasible(const Vector& x) const { const OptimizerSystem& sys = getOptimizerSystem(); if( sys.getHasLimits() ) { Real *lowerLimits, *upperLimits; sys.getParameterLimits( &lowerLimits, &upperLimits ); for (int i = 0; i < sys.getNumParameters(); i++) { SimTK_APIARGCHECK4_ALWAYS( lowerLimits[i] <= x[i] && x[i] <= upperLimits[i], "CMAESOptimizer", "checkInitialPointIsFeasible", "Initial guess results[%d] = %f " "is not within limits [%f, %f].", i, x[i], lowerLimits[i], upperLimits[i]); } } } double* CMAESOptimizer::init(cmaes_t& evo, SimTK::Vector& results) const { const OptimizerSystem& sys = getOptimizerSystem(); int n = sys.getNumParameters(); // Prepare to call cmaes_init_para. // ================================ // lambda // ------ int lambda = 0; getAdvancedIntOption("lambda", lambda); // sigma // ----- double sigma = 0; double* stddev = NULL; Vector sigmaArray; if (getAdvancedRealOption("sigma", sigma)) { sigmaArray.resize(n); for (int i = 0; i < n; i++) { sigmaArray[i] = sigma; } stddev = &sigmaArray[0]; } // seed // ---- int seed = 0; if (getAdvancedIntOption("seed", seed)) { SimTK_VALUECHECK_NONNEG_ALWAYS(seed, "seed", "CMAESOptimizer::processSettingsBeforeCMAESInit"); } // input parameter filename // ------------------------ std::string input_parameter_filename = "none"; SimTK_CMAES_FILE(diagnosticsLevel, input_parameter_filename = "writeonly";); // Call cmaes_init_para. // ===================== // Here, we specify the subset of options that can be passed to // cmaes_init_para. cmaes_init_para(&evo, n, // dimension &results[0], // xstart stddev, // stddev seed, // seed lambda, // lambda input_parameter_filename.c_str() // input_parameter_filename ); // Set settings that are usually read in from cmaes_initials.par. // ============================================================== process_readpara_settings(evo); // Once we've updated settings in readpara_t, finalize the initialization. return cmaes_init_final(&evo); } void CMAESOptimizer::process_readpara_settings(cmaes_t& evo) const { // Termination criteria // ==================== // stopMaxIter // ----------- // maxIterations is a protected member variable of OptimizerRep. evo.sp.stopMaxIter = maxIterations; // stopTolFun // ---------- // convergenceTolerance is a protected member variable of OptimizerRep. evo.sp.stopTolFun = convergenceTolerance; // stopMaxFunEvals // --------------- int stopMaxFunEvals; if (getAdvancedIntOption("stopMaxFunEvals", stopMaxFunEvals)) { SimTK_VALUECHECK_NONNEG_ALWAYS(stopMaxFunEvals, "stopMaxFunEvals", "CMAESOptimizer::processSettingsAfterCMAESInit"); evo.sp.stopMaxFunEvals = stopMaxFunEvals; } // stopFitness // ----------- double stopFitness; if (getAdvancedRealOption("stopFitness", stopFitness)) { evo.sp.stStopFitness.flg = 1; evo.sp.stStopFitness.val = stopFitness; } // stopTolFunHist // -------------- double stopTolFunHist; if (getAdvancedRealOption("stopTolFunHist", stopTolFunHist)) { evo.sp.stopTolFunHist = stopTolFunHist; } // stopTolX // -------- double stopTolX; if (getAdvancedRealOption("stopTolX", stopTolX)) { evo.sp.stopTolX = stopTolX; } // stopTolXFactor // -------------- double stopTolUpXFactor; if (getAdvancedRealOption("stopTolUpXFactor", stopTolUpXFactor)) { evo.sp.stopTolUpXFactor = stopTolUpXFactor; } // maxtime // ======= double maxtime; if (getAdvancedRealOption("maxTimeFractionForEigendecomposition", maxtime)) { evo.sp.updateCmode.maxtime = maxtime; } } #undef SimTK_CMAES_PRINT #undef SimTK_CMAES_FILE } // namespace SimTK <commit_msg>Add Niko as contributor to CMAESOptimizer.<commit_after>/* -------------------------------------------------------------------------- * * Simbody(tm): SimTKmath * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2006-14 Stanford University and the Authors. * * Authors: Chris Dembia * * Contributors: Michael Sherman, Nikolaus Hansen * * * * 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 "CMAESOptimizer.h" #include <bitset> namespace SimTK { #define SimTK_CMAES_PRINT(diag, cmds) \ do { \ if (std::bitset<2>(diag).test(0)) { cmds; } \ } \ while(false) #define SimTK_CMAES_FILE(diag, cmds) \ do { \ if (std::bitset<2>(diag).test(1)) { cmds; } \ } \ while(false) CMAESOptimizer::CMAESOptimizer(const OptimizerSystem& sys) : OptimizerRep(sys) { SimTK_VALUECHECK_ALWAYS(2, sys.getNumParameters(), INT_MAX, "nParameters", "CMAESOptimizer"); } Optimizer::OptimizerRep* CMAESOptimizer::clone() const { return new CMAESOptimizer(*this); } Real CMAESOptimizer::optimize(SimTK::Vector& results) { const OptimizerSystem& sys = getOptimizerSystem(); int n = sys.getNumParameters(); // Initialize objective function value and cmaes data structure. // ============================================================= Real f; cmaes_t evo; // Check that the initial point is feasible. // ========================================= checkInitialPointIsFeasible(results); // Initialize cmaes. // ================= double* funvals = init(evo, results); SimTK_CMAES_PRINT(diagnosticsLevel, printf("%s\n", cmaes_SayHello(&evo))); // Optimize. // ========= while (!cmaes_TestForTermination(&evo)) { // Sample a population. // ==================== double*const* pop = cmaes_SamplePopulation(&evo); // Resample to keep population within limits. // ========================================== if( sys.getHasLimits() ) { Real *lowerLimits, *upperLimits; sys.getParameterLimits( &lowerLimits, &upperLimits ); for (int i = 0; i < cmaes_Get(&evo, "lambda"); i++) { bool feasible = false; while (!feasible) { feasible = true; for (int j = 0; j < n; j++) { if (pop[i][j] < lowerLimits[j] || pop[i][j] > upperLimits[j]) { feasible = false; pop = cmaes_ReSampleSingle(&evo, i); break; } } } } } // Evaluate the objective function on the samples. // =============================================== for (int i = 0; i < cmaes_Get(&evo, "lambda"); i++) { objectiveFuncWrapper(n, pop[i], true, &funvals[i], this); } // Update the distribution (mean, covariance, etc.). // ================================================= cmaes_UpdateDistribution(&evo, funvals); } // Wrap up. // ======== SimTK_CMAES_PRINT(diagnosticsLevel, printf("Stop:\n%s\n", cmaes_TestForTermination(&evo))); // Update best parameters and objective function value. const double* optx = cmaes_GetPtr(&evo, "xbestever"); for (int i = 0; i < n; i++) { results[i] = optx[i]; } f = cmaes_Get(&evo, "fbestever"); SimTK_CMAES_FILE(diagnosticsLevel, cmaes_WriteToFile(&evo, "all", "allcmaes.dat")); // Free memory. cmaes_exit(&evo); return f; } void CMAESOptimizer::checkInitialPointIsFeasible(const Vector& x) const { const OptimizerSystem& sys = getOptimizerSystem(); if( sys.getHasLimits() ) { Real *lowerLimits, *upperLimits; sys.getParameterLimits( &lowerLimits, &upperLimits ); for (int i = 0; i < sys.getNumParameters(); i++) { SimTK_APIARGCHECK4_ALWAYS( lowerLimits[i] <= x[i] && x[i] <= upperLimits[i], "CMAESOptimizer", "checkInitialPointIsFeasible", "Initial guess results[%d] = %f " "is not within limits [%f, %f].", i, x[i], lowerLimits[i], upperLimits[i]); } } } double* CMAESOptimizer::init(cmaes_t& evo, SimTK::Vector& results) const { const OptimizerSystem& sys = getOptimizerSystem(); int n = sys.getNumParameters(); // Prepare to call cmaes_init_para. // ================================ // lambda // ------ int lambda = 0; getAdvancedIntOption("lambda", lambda); // sigma // ----- double sigma = 0; double* stddev = NULL; Vector sigmaArray; if (getAdvancedRealOption("sigma", sigma)) { sigmaArray.resize(n); for (int i = 0; i < n; i++) { sigmaArray[i] = sigma; } stddev = &sigmaArray[0]; } // seed // ---- int seed = 0; if (getAdvancedIntOption("seed", seed)) { SimTK_VALUECHECK_NONNEG_ALWAYS(seed, "seed", "CMAESOptimizer::processSettingsBeforeCMAESInit"); } // input parameter filename // ------------------------ std::string input_parameter_filename = "none"; SimTK_CMAES_FILE(diagnosticsLevel, input_parameter_filename = "writeonly";); // Call cmaes_init_para. // ===================== // Here, we specify the subset of options that can be passed to // cmaes_init_para. cmaes_init_para(&evo, n, // dimension &results[0], // xstart stddev, // stddev seed, // seed lambda, // lambda input_parameter_filename.c_str() // input_parameter_filename ); // Set settings that are usually read in from cmaes_initials.par. // ============================================================== process_readpara_settings(evo); // Once we've updated settings in readpara_t, finalize the initialization. return cmaes_init_final(&evo); } void CMAESOptimizer::process_readpara_settings(cmaes_t& evo) const { // Termination criteria // ==================== // stopMaxIter // ----------- // maxIterations is a protected member variable of OptimizerRep. evo.sp.stopMaxIter = maxIterations; // stopTolFun // ---------- // convergenceTolerance is a protected member variable of OptimizerRep. evo.sp.stopTolFun = convergenceTolerance; // stopMaxFunEvals // --------------- int stopMaxFunEvals; if (getAdvancedIntOption("stopMaxFunEvals", stopMaxFunEvals)) { SimTK_VALUECHECK_NONNEG_ALWAYS(stopMaxFunEvals, "stopMaxFunEvals", "CMAESOptimizer::processSettingsAfterCMAESInit"); evo.sp.stopMaxFunEvals = stopMaxFunEvals; } // stopFitness // ----------- double stopFitness; if (getAdvancedRealOption("stopFitness", stopFitness)) { evo.sp.stStopFitness.flg = 1; evo.sp.stStopFitness.val = stopFitness; } // stopTolFunHist // -------------- double stopTolFunHist; if (getAdvancedRealOption("stopTolFunHist", stopTolFunHist)) { evo.sp.stopTolFunHist = stopTolFunHist; } // stopTolX // -------- double stopTolX; if (getAdvancedRealOption("stopTolX", stopTolX)) { evo.sp.stopTolX = stopTolX; } // stopTolXFactor // -------------- double stopTolUpXFactor; if (getAdvancedRealOption("stopTolUpXFactor", stopTolUpXFactor)) { evo.sp.stopTolUpXFactor = stopTolUpXFactor; } // maxtime // ======= double maxtime; if (getAdvancedRealOption("maxTimeFractionForEigendecomposition", maxtime)) { evo.sp.updateCmode.maxtime = maxtime; } } #undef SimTK_CMAES_PRINT #undef SimTK_CMAES_FILE } // namespace SimTK <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Bernhard Firner and Rutgers University * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * or visit http://www.gnu.org/licenses/gpl-2.0.html */ /******************************************************************************* * This file defines a class that simplifies connecting to the world model * as a solver. ******************************************************************************/ #include "solver_world_connection.hpp" #include <algorithm> #include <iostream> #include <string> #include <tuple> #include <vector> #include <sys/types.h> #include <sys/socket.h> //Send a handshake and a type declaration message. bool SolverWorldModel::reconnect() { //Reset connection status and set to true after the handshake. _connected = false; if (s) { std::cout<<"Connected to the GRAIL world model.\n"; } else { //Otherwise try to make a new connection ClientSocket s2(AF_INET, SOCK_STREAM, 0, port, ip); if (not s2) { std::cerr<<"Failed to connect to the GRAIL world model.\n"; return false; } else { s = std::move(s2); } } //Try to get the handshake message { std::vector<unsigned char> handshake = world_model::solver::makeHandshakeMsg(); //Send the handshake message s.send(handshake); std::vector<unsigned char> raw_message(handshake.size()); size_t length = s.receive(raw_message); //Check if the handshake message failed if (not (length == handshake.size() and std::equal(handshake.begin(), handshake.end(), raw_message.begin()) )) { std::cerr<<"Failure during solver handshake with world model.\n"; return false; } } //Send the type announcement message try { s.send(world_model::solver::makeTypeAnnounceMsg(types, origin)); } catch (std::runtime_error err) { std::cerr<<"Problem sending type announce message: "<<err.what()<<'\n'; return false; } //Clear the old thread if one was running if (running) { interrupted = true; on_demand_tracker.join(); } ss.previous_unfinished.clear(); running = true; interrupted = false; //Start the on_demand status tracking thread on_demand_tracker = std::thread(std::mem_fun(&SolverWorldModel::trackOnDemands), this); _connected = true; return true; } static std::string toString(const std::u16string& str) { return std::string(str.begin(), str.end()); } void SolverWorldModel::trackOnDemands() { using world_model::solver::MessageID; while (not interrupted) { std::vector<unsigned char> in_buff = ss.getNextMessage(interrupted); if (5 <= in_buff.size()) { MessageID message_type = (MessageID)in_buff[4]; if (message_type == MessageID::start_on_demand) { std::vector<std::tuple<uint32_t, std::vector<std::u16string>>> trans = world_model::solver::decodeStartOnDemand(in_buff); std::unique_lock<std::mutex> lck(trans_mutex); for (auto I = trans.begin(); I != trans.end(); ++I) { std::cerr<<"OnDemand "<<std::get<0>(*I)<<" has "<<std::get<1>(*I).size()<<" URI requests.\n"; std::vector<std::u16string>& requests = std::get<1>(*I); for (std::u16string& request : requests) { //Store the regex pattern sent by the world model. std::cerr<<"Enabling on_demand: "<<std::get<0>(*I)<<" with string "<<toString(request)<<'\n'; OnDemandArgs ta; ta.request = request; int err = regcomp(&ta.exp, toString(ta.request).c_str(), REG_EXTENDED); if (0 != err) { ta.valid = false; std::cerr<<"Error compiling regular expression "<<toString(ta.request)<<" in on_demand request to solver client.\n"; } else { ta.valid = true; } on_demand_on[std::get<0>(*I)].insert(ta); } } } else if (message_type == MessageID::stop_on_demand) { std::vector<std::tuple<uint32_t, std::vector<std::u16string>>> trans = world_model::solver::decodeStopOnDemand(in_buff); std::unique_lock<std::mutex> lck(trans_mutex); for (auto I = trans.begin(); I != trans.end(); ++I) { uint32_t attr_name = std::get<0>(*I); std::vector<std::u16string>& requests = std::get<1>(*I); for (std::u16string& request : requests) { //Remove the regex that was sent by the world model std::cerr<<"Disabling on_demand: "<<attr_name<<" with request "<<toString(request)<<'\n'; if (on_demand_on.end() != on_demand_on.find(attr_name)) { std::multiset<OnDemandArgs>& uri_set = on_demand_on[attr_name]; auto J = std::find_if(uri_set.begin(), uri_set.end(), [&](const OnDemandArgs& ta) { return ta.request == request;}); if (J != uri_set.end()) { OnDemandArgs ta = *J; if (ta.valid) { regfree(&ta.exp); } uri_set.erase(J); } } } } } else if (message_type == MessageID::keep_alive) { //Send a keep alive message in reply to a keep alive from //the server. This makes sure that we are replying at less //than the sever's timeout period. std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeKeepAlive()); } } else { std::cerr<<"Got an invalid sized message (size = "<<in_buff.size()<<'\n'; } } } SolverWorldModel::SolverWorldModel(std::string ip, uint16_t port, std::vector<std::pair<std::u16string, bool>>& types, std::u16string origin) : s(AF_INET, SOCK_STREAM, 0, port, ip), ss(s) { this->origin = origin; //Store the alias types that this solver will use for (auto I = types.begin(); I != types.end(); ++I) { world_model::solver::AliasType at{(uint32_t)(this->types.size()+1), I->first, I->second}; this->types.push_back(at); aliases[at.type] = at.alias; if (I->second) { if (on_demand_on.end() == on_demand_on.find(at.alias)) { on_demand_on[at.alias] = std::multiset<OnDemandArgs>(); } } } //Store these values so that we can reconnect later this->ip = ip; this->port = port; reconnect(); } SolverWorldModel::~SolverWorldModel() { if (running) { interrupted = true; on_demand_tracker.join(); } } void SolverWorldModel::addTypes(std::vector<std::pair<std::u16string, bool>>& new_types) { //Store the alias types that this solver will use std::vector<world_model::solver::AliasType> new_aliases; for (auto I = new_types.begin(); I != new_types.end(); ++I) { world_model::solver::AliasType at{(uint32_t)(this->types.size()+1), I->first, I->second}; this->types.push_back(at); aliases[at.type] = at.alias; if (I->second) { if (on_demand_on.end() == on_demand_on.find(at.alias)) { on_demand_on[at.alias] = std::multiset<OnDemandArgs>(); } } new_aliases.push_back(at); } //Update the world model with a new type announcement message try { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeTypeAnnounceMsg(new_aliases, origin)); } catch (std::runtime_error err) { std::cerr<<"Problem sending type announce message: "<<err.what()<<'\n'; } } bool SolverWorldModel::connected() { return _connected; } void SolverWorldModel::sendData(std::vector<AttrUpdate>& solution, bool create_uris) { using world_model::solver::SolutionData; std::vector<SolutionData> sds; for (auto I = solution.begin(); I != solution.end(); ++I) { std::unique_lock<std::mutex> lck(trans_mutex); if (aliases.end() != aliases.find(I->type)) { uint32_t alias = aliases[I->type]; //TODO Let the user check this themselves, it should be up to them //whether or not to send data //Send if this is not a on_demand or it is a on_demand but is requested if (on_demand_on.end() == on_demand_on.find(alias)) { SolutionData sd{alias, I->time, I->target, I->data}; sds.push_back(sd); } else { //Find if any patterns match this information if (std::any_of(on_demand_on[alias].begin(), on_demand_on[alias].end(), [&](const OnDemandArgs& ta) { if (not ta.valid) { return false;} regmatch_t pmatch; int match = regexec(&ta.exp, toString(I->target).c_str(), 1, &pmatch, 0); return (0 == match and 0 == pmatch.rm_so and I->target.size() == pmatch.rm_eo); })) { SolutionData sd{alias, I->time, I->target, I->data}; sds.push_back(sd); } } } } //Allow sending an empty message (if all of the solutions are unrequested //on_demand solutions) to serve as a keep alive. std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeSolutionMsg(create_uris, sds)); } void SolverWorldModel::createURI(world_model::URI uri, world_model::grail_time created) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeCreateURI(uri, created, origin)); } void SolverWorldModel::expireURI(world_model::URI uri, world_model::grail_time expires) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeExpireURI(uri, expires, origin)); } void SolverWorldModel::deleteURI(world_model::URI uri) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeDeleteURI(uri, origin)); } void SolverWorldModel::expireURIAttribute(world_model::URI uri, std::u16string name, world_model::grail_time expires) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeExpireAttribute(uri, name, origin, expires)); } void SolverWorldModel::deleteURIAttribute(world_model::URI uri, std::u16string name) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeDeleteAttribute(uri, name, origin)); } <commit_msg>Initialize @running variable to false (no listening thread).<commit_after>/* * Copyright (c) 2012 Bernhard Firner and Rutgers University * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * or visit http://www.gnu.org/licenses/gpl-2.0.html */ /******************************************************************************* * This file defines a class that simplifies connecting to the world model * as a solver. ******************************************************************************/ #include "solver_world_connection.hpp" #include <algorithm> #include <iostream> #include <string> #include <tuple> #include <vector> #include <sys/types.h> #include <sys/socket.h> //Send a handshake and a type declaration message. bool SolverWorldModel::reconnect() { //Reset connection status and set to true after the handshake. _connected = false; if (s) { std::cout<<"Connected to the GRAIL world model.\n"; } else { //Otherwise try to make a new connection ClientSocket s2(AF_INET, SOCK_STREAM, 0, port, ip); if (not s2) { std::cerr<<"Failed to connect to the GRAIL world model.\n"; return false; } else { s = std::move(s2); } } //Try to get the handshake message { std::vector<unsigned char> handshake = world_model::solver::makeHandshakeMsg(); //Send the handshake message s.send(handshake); std::vector<unsigned char> raw_message(handshake.size()); size_t length = s.receive(raw_message); //Check if the handshake message failed if (not (length == handshake.size() and std::equal(handshake.begin(), handshake.end(), raw_message.begin()) )) { std::cerr<<"Failure during solver handshake with world model.\n"; return false; } } //Send the type announcement message try { s.send(world_model::solver::makeTypeAnnounceMsg(types, origin)); } catch (std::runtime_error err) { std::cerr<<"Problem sending type announce message: "<<err.what()<<'\n'; return false; } //Clear the old thread if one was running if (running) { interrupted = true; on_demand_tracker.join(); } ss.previous_unfinished.clear(); running = true; interrupted = false; //Start the on_demand status tracking thread on_demand_tracker = std::thread(std::mem_fun(&SolverWorldModel::trackOnDemands), this); _connected = true; return true; } static std::string toString(const std::u16string& str) { return std::string(str.begin(), str.end()); } void SolverWorldModel::trackOnDemands() { using world_model::solver::MessageID; while (not interrupted) { std::vector<unsigned char> in_buff = ss.getNextMessage(interrupted); if (5 <= in_buff.size()) { MessageID message_type = (MessageID)in_buff[4]; if (message_type == MessageID::start_on_demand) { std::vector<std::tuple<uint32_t, std::vector<std::u16string>>> trans = world_model::solver::decodeStartOnDemand(in_buff); std::unique_lock<std::mutex> lck(trans_mutex); for (auto I = trans.begin(); I != trans.end(); ++I) { std::cerr<<"OnDemand "<<std::get<0>(*I)<<" has "<<std::get<1>(*I).size()<<" URI requests.\n"; std::vector<std::u16string>& requests = std::get<1>(*I); for (std::u16string& request : requests) { //Store the regex pattern sent by the world model. std::cerr<<"Enabling on_demand: "<<std::get<0>(*I)<<" with string "<<toString(request)<<'\n'; OnDemandArgs ta; ta.request = request; int err = regcomp(&ta.exp, toString(ta.request).c_str(), REG_EXTENDED); if (0 != err) { ta.valid = false; std::cerr<<"Error compiling regular expression "<<toString(ta.request)<<" in on_demand request to solver client.\n"; } else { ta.valid = true; } on_demand_on[std::get<0>(*I)].insert(ta); } } } else if (message_type == MessageID::stop_on_demand) { std::vector<std::tuple<uint32_t, std::vector<std::u16string>>> trans = world_model::solver::decodeStopOnDemand(in_buff); std::unique_lock<std::mutex> lck(trans_mutex); for (auto I = trans.begin(); I != trans.end(); ++I) { uint32_t attr_name = std::get<0>(*I); std::vector<std::u16string>& requests = std::get<1>(*I); for (std::u16string& request : requests) { //Remove the regex that was sent by the world model std::cerr<<"Disabling on_demand: "<<attr_name<<" with request "<<toString(request)<<'\n'; if (on_demand_on.end() != on_demand_on.find(attr_name)) { std::multiset<OnDemandArgs>& uri_set = on_demand_on[attr_name]; auto J = std::find_if(uri_set.begin(), uri_set.end(), [&](const OnDemandArgs& ta) { return ta.request == request;}); if (J != uri_set.end()) { OnDemandArgs ta = *J; if (ta.valid) { regfree(&ta.exp); } uri_set.erase(J); } } } } } else if (message_type == MessageID::keep_alive) { //Send a keep alive message in reply to a keep alive from //the server. This makes sure that we are replying at less //than the sever's timeout period. std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeKeepAlive()); } } else { std::cerr<<"Got an invalid sized message (size = "<<in_buff.size()<<'\n'; } } } SolverWorldModel::SolverWorldModel(std::string ip, uint16_t port, std::vector<std::pair<std::u16string, bool>>& types, std::u16string origin) : s(AF_INET, SOCK_STREAM, 0, port, ip), ss(s) { running = false; this->origin = origin; //Store the alias types that this solver will use for (auto I = types.begin(); I != types.end(); ++I) { world_model::solver::AliasType at{(uint32_t)(this->types.size()+1), I->first, I->second}; this->types.push_back(at); aliases[at.type] = at.alias; if (I->second) { if (on_demand_on.end() == on_demand_on.find(at.alias)) { on_demand_on[at.alias] = std::multiset<OnDemandArgs>(); } } } //Store these values so that we can reconnect later this->ip = ip; this->port = port; reconnect(); } SolverWorldModel::~SolverWorldModel() { if (running) { interrupted = true; on_demand_tracker.join(); } } void SolverWorldModel::addTypes(std::vector<std::pair<std::u16string, bool>>& new_types) { //Store the alias types that this solver will use std::vector<world_model::solver::AliasType> new_aliases; for (auto I = new_types.begin(); I != new_types.end(); ++I) { world_model::solver::AliasType at{(uint32_t)(this->types.size()+1), I->first, I->second}; this->types.push_back(at); aliases[at.type] = at.alias; if (I->second) { if (on_demand_on.end() == on_demand_on.find(at.alias)) { on_demand_on[at.alias] = std::multiset<OnDemandArgs>(); } } new_aliases.push_back(at); } //Update the world model with a new type announcement message try { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeTypeAnnounceMsg(new_aliases, origin)); } catch (std::runtime_error err) { std::cerr<<"Problem sending type announce message: "<<err.what()<<'\n'; } } bool SolverWorldModel::connected() { return _connected; } void SolverWorldModel::sendData(std::vector<AttrUpdate>& solution, bool create_uris) { using world_model::solver::SolutionData; std::vector<SolutionData> sds; for (auto I = solution.begin(); I != solution.end(); ++I) { std::unique_lock<std::mutex> lck(trans_mutex); if (aliases.end() != aliases.find(I->type)) { uint32_t alias = aliases[I->type]; //TODO Let the user check this themselves, it should be up to them //whether or not to send data //Send if this is not a on_demand or it is a on_demand but is requested if (on_demand_on.end() == on_demand_on.find(alias)) { SolutionData sd{alias, I->time, I->target, I->data}; sds.push_back(sd); } else { //Find if any patterns match this information if (std::any_of(on_demand_on[alias].begin(), on_demand_on[alias].end(), [&](const OnDemandArgs& ta) { if (not ta.valid) { return false;} regmatch_t pmatch; int match = regexec(&ta.exp, toString(I->target).c_str(), 1, &pmatch, 0); return (0 == match and 0 == pmatch.rm_so and I->target.size() == pmatch.rm_eo); })) { SolutionData sd{alias, I->time, I->target, I->data}; sds.push_back(sd); } } } } //Allow sending an empty message (if all of the solutions are unrequested //on_demand solutions) to serve as a keep alive. std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeSolutionMsg(create_uris, sds)); } void SolverWorldModel::createURI(world_model::URI uri, world_model::grail_time created) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeCreateURI(uri, created, origin)); } void SolverWorldModel::expireURI(world_model::URI uri, world_model::grail_time expires) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeExpireURI(uri, expires, origin)); } void SolverWorldModel::deleteURI(world_model::URI uri) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeDeleteURI(uri, origin)); } void SolverWorldModel::expireURIAttribute(world_model::URI uri, std::u16string name, world_model::grail_time expires) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeExpireAttribute(uri, name, origin, expires)); } void SolverWorldModel::deleteURIAttribute(world_model::URI uri, std::u16string name) { std::unique_lock<std::mutex> lck(send_mutex); s.send(world_model::solver::makeDeleteAttribute(uri, name, origin)); } <|endoftext|>
<commit_before> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include <boost/test/unit_test.hpp> #include "Grappa.hpp" #include "CompletionEvent.hpp" #include "ParallelLoop.hpp" #include "Collective.hpp" #include <string> DECLARE_uint64( num_starting_workers ); DEFINE_uint64( num_test_workers, 4, "Number of workers for the tests"); DEFINE_uint64( iters_per_task, 10000, "Iterations per task" ); DEFINE_string( test_type, "yields", "options: {yields,sequential_updates, sequential_updates16" ); DEFINE_uint64( private_array_size, 1, "Size of private array of 8-bytes for each task" ); using namespace Grappa; CompletionEvent * final; CompletionEvent * task_barrier; struct SixteenBytes { uint64_t val1; uint64_t val2; }; struct Cacheline { uint64_t val; char padding[56]; }; uint64_t * values8; SixteenBytes * values16; // core-shared counter for counting progress uint64_t numst; uint64_t waitCount; bool running; BOOST_AUTO_TEST_SUITE( ContextSwitchRate_tests ); void user_main( void * args ) { srand((unsigned int)Grappa_walltime()); // must have enough threads because they all join a barrier BOOST_CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers ); if (FLAGS_test_type.compare("yields")==0) { BOOST_MESSAGE( "Test yields" ); { struct runtimes_t { double runtime_avg, runtime_min, runtime_max; }; runtimes_t r; on_all_cores( [&r] { // per core timing double start, end; bool started = false; final = new CompletionEvent(FLAGS_num_test_workers); task_barrier = new CompletionEvent(FLAGS_num_test_workers); for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) { privateTask( [&started,&start] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // first task to exit the local barrier will start the timer if ( !started ) { start = Grappa_walltime(); started = true; } // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { Grappa_yield(); } final->complete(); }); } BOOST_MESSAGE( "waiting" ); final->wait(); end = Grappa_walltime(); double runtime = end-start; BOOST_MESSAGE( "took time " << runtime ); Grappa::barrier(); BOOST_MESSAGE( "all done" ); // sort out timing double r_sum = Grappa::allreduce<double, collective_add>( runtime ); double r_min = Grappa::allreduce<double, collective_min>( runtime ); double r_max = Grappa::allreduce<double, collective_max>( runtime ); if ( Grappa::mycore()==0 ) { r.runtime_avg = r_sum / Grappa::cores(); r.runtime_min = r_min; r.runtime_max = r_max; } }); BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg << ", cores_time_max = " << r.runtime_max << ", cores_time_min = " << r.runtime_min); } } else if (FLAGS_test_type.compare("cvwakes")==0) { BOOST_MESSAGE( "Test cv wakes" ); { struct runtimes_t { double runtime_avg, runtime_min, runtime_max; }; runtimes_t r; on_all_cores( [&r] { // per core timing double start, end; ConditionVariable cvs[FLAGS_num_test_workers]; bool asleep[FLAGS_num_test_workers]; for( int i=0; i<FLAGS_num_test_workers; i++) { asleep[i] = false; } final = new CompletionEvent(1); task_barrier = new CompletionEvent(FLAGS_num_test_workers); running = false; waitCount = 0; numst = 0; for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) { privateTask( [&asleep,&start,&cvs] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // first task to exit the local barrier will start the timer if ( !running ) { start = Grappa_walltime(); running = true; } uint64_t tid = numst++; uint64_t partner = (tid + FLAGS_num_test_workers/2)%FLAGS_num_test_workers; uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers; // do the work while( waitCount++ < total_iters ) { if ( asleep[partner] ) { // TODO also test just wake up case Grappa::signal( &cvs[partner] ); } asleep[tid] = true; Grappa::wait( &cvs[tid] ); asleep[tid] = false; } // only first if ( running ) { final->complete(); // signal to finish as soon as the parent task gets scheduled running = false; } }); } BOOST_MESSAGE( "waiting" ); final->wait(); end = Grappa_walltime(); double runtime = end-start; BOOST_MESSAGE( "took time " << runtime ); // wake all for (int i=0; i<FLAGS_num_test_workers; i++) { Grappa::signal(&cvs[i]); } BOOST_MESSAGE( "woke all" ); Grappa::barrier(); BOOST_MESSAGE( "all done" ); // sort out timing double r_sum = Grappa::allreduce<double, collective_add>( runtime ); double r_min = Grappa::allreduce<double, collective_min>( runtime ); double r_max = Grappa::allreduce<double, collective_max>( runtime ); if ( Grappa::mycore()==0 ) { r.runtime_avg = r_sum / Grappa::cores(); r.runtime_min = r_min; r.runtime_max = r_max; } BOOST_MESSAGE( "done reduce" ); }); BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg << ", cores_time_max = " << r.runtime_max << ", cores_time_min = " << r.runtime_min); } } else if (FLAGS_test_type.compare("sequential_updates")==0) { BOOST_MESSAGE( "Test sequential_updates" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { values8[t] += 1; Grappa_yield(); } final->complete(); }); } final->wait(); double end = Grappa_walltime(); double runtime = end-start; BOOST_MESSAGE( "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task) ); } } else if (FLAGS_test_type.compare("sequential_updates16")==0) { BOOST_MESSAGE( "Test sequential_updates16" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values16 = new SixteenBytes[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { values16[t].val1 += 1; values16[t].val2 += 1; Grappa_yield(); } final->complete(); }); } final->wait(); double end = Grappa_walltime(); double runtime = end-start; BOOST_MESSAGE( "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task) ); } } else if (FLAGS_test_type.compare("private_array")==0) { BOOST_MESSAGE( "Test private_array" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { uint64_t myarray[FLAGS_private_array_size]; // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { for (uint64_t j=0; j<FLAGS_private_array_size; j++) { myarray[j] += 1; } Grappa_yield(); } values8[t] = myarray[rand()%FLAGS_private_array_size]; final->complete(); }); } final->wait(); double end = Grappa_walltime(); BOOST_MESSAGE( "result = " << values8[rand()%FLAGS_num_starting_workers] ); double runtime = end-start; BOOST_MESSAGE( "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task) ); } } else if (FLAGS_test_type.compare("private_array_bycache")==0) { BOOST_MESSAGE( "Test private_array_bycache" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { Cacheline myarray[FLAGS_private_array_size]; // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { for (uint64_t j=0; j<FLAGS_private_array_size; j++) { myarray[j].val += 1; } Grappa_yield(); } values8[t] = myarray[rand()%FLAGS_private_array_size].val; final->complete(); }); } final->wait(); double end = Grappa_walltime(); BOOST_MESSAGE( "result = " << values8[rand()%FLAGS_num_starting_workers] ); double runtime = end-start; BOOST_MESSAGE( "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task) ); } } else { BOOST_CHECK( false ); // Unrecognized test_type } BOOST_MESSAGE( "user main is exiting" ); } BOOST_AUTO_TEST_CASE( test1 ) { Grappa_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); Grappa_activate(); DVLOG(1) << "Spawning user main Thread...."; Grappa_run_user_main( &user_main, (void*)NULL ); VLOG(5) << "run_user_main returned"; CHECK( Grappa_done() ); Grappa_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>context switch tests: allocate CVs on the heap, add statistics output<commit_after> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include <boost/test/unit_test.hpp> #include "Grappa.hpp" #include "CompletionEvent.hpp" #include "ParallelLoop.hpp" #include "Collective.hpp" #include "Statistics.hpp" #include <string> DECLARE_uint64( num_starting_workers ); DEFINE_uint64( num_test_workers, 4, "Number of workers for the tests"); DEFINE_uint64( iters_per_task, 10000, "Iterations per task" ); DEFINE_string( test_type, "yields", "options: {yields,sequential_updates, sequential_updates16" ); DEFINE_uint64( private_array_size, 1, "Size of private array of 8-bytes for each task" ); using namespace Grappa; CompletionEvent * final; CompletionEvent * task_barrier; struct SixteenBytes { uint64_t val1; uint64_t val2; }; struct Cacheline { uint64_t val; char padding[56]; }; uint64_t * values8; SixteenBytes * values16; // core-shared counter for counting progress uint64_t numst; uint64_t waitCount; // TODO: for traces, change to SimpleStatistic bool running; BOOST_AUTO_TEST_SUITE( ContextSwitchRate_tests ); void user_main( void * args ) { srand((unsigned int)Grappa_walltime()); // must have enough threads because they all join a barrier BOOST_CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers ); if (FLAGS_test_type.compare("yields")==0) { BOOST_MESSAGE( "Test yields" ); { struct runtimes_t { double runtime_avg, runtime_min, runtime_max; }; runtimes_t r; on_all_cores( [&r] { // per core timing double start, end; running = false; final = new CompletionEvent(FLAGS_num_test_workers); task_barrier = new CompletionEvent(FLAGS_num_test_workers); for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) { privateTask( [&start] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // first task to exit the local barrier will start the timer if ( !running ) { Grappa::Statistics::reset(); start = Grappa_walltime(); running = true; } // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { Grappa_yield(); } final->complete(); }); } BOOST_MESSAGE( "waiting" ); final->wait(); end = Grappa_walltime(); double runtime = end-start; BOOST_MESSAGE( "took time " << runtime ); Grappa::barrier(); BOOST_MESSAGE( "all done" ); // sort out timing double r_sum = Grappa::allreduce<double, collective_add>( runtime ); double r_min = Grappa::allreduce<double, collective_min>( runtime ); double r_max = Grappa::allreduce<double, collective_max>( runtime ); if ( Grappa::mycore()==0 ) { r.runtime_avg = r_sum / Grappa::cores(); r.runtime_min = r_min; r.runtime_max = r_max; } }); Grappa::Statistics::merge_and_print(); BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg << ", cores_time_max = " << r.runtime_max << ", cores_time_min = " << r.runtime_min); } } else if (FLAGS_test_type.compare("cvwakes")==0) { BOOST_MESSAGE( "Test cv wakes" ); { struct runtimes_t { double runtime_avg, runtime_min, runtime_max; }; runtimes_t r; on_all_cores( [&r] { // per core timing double start, end; ConditionVariable * cvs = new ConditionVariable[FLAGS_num_test_workers]; bool * asleep = new bool[FLAGS_num_test_workers]; for( int i=0; i<FLAGS_num_test_workers; i++) { asleep[i] = false; } final = new CompletionEvent(1); task_barrier = new CompletionEvent(FLAGS_num_test_workers); running = false; waitCount = 0; numst = 0; for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) { privateTask( [asleep,&start,cvs] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // first task to exit the local barrier will start the timer if ( !running ) { // can safely reset statistics here because // no messages are sent between cores in the // timed portion Grappa::Statistics::reset(); start = Grappa_walltime(); running = true; } uint64_t tid = numst++; uint64_t partner = (tid + FLAGS_num_test_workers/2)%FLAGS_num_test_workers; uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers; // do the work while( waitCount++ < total_iters ) { if ( asleep[partner] ) { // TODO also test just wake up case Grappa::signal( &cvs[partner] ); } asleep[tid] = true; Grappa::wait( &cvs[tid] ); asleep[tid] = false; } // only first if ( running ) { final->complete(); // signal to finish as soon as the parent task gets scheduled running = false; } }); } BOOST_MESSAGE( "waiting" ); final->wait(); end = Grappa_walltime(); double runtime = end-start; BOOST_MESSAGE( "took time " << runtime ); // wake all for (int i=0; i<FLAGS_num_test_workers; i++) { Grappa::signal(&cvs[i]); } BOOST_MESSAGE( "woke all" ); Grappa::barrier(); BOOST_MESSAGE( "all done" ); // sort out timing double r_sum = Grappa::allreduce<double, collective_add>( runtime ); double r_min = Grappa::allreduce<double, collective_min>( runtime ); double r_max = Grappa::allreduce<double, collective_max>( runtime ); if ( Grappa::mycore()==0 ) { r.runtime_avg = r_sum / Grappa::cores(); r.runtime_min = r_min; r.runtime_max = r_max; } }); Grappa::Statistics::merge_and_print(); BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg << ", cores_time_max = " << r.runtime_max << ", cores_time_min = " << r.runtime_min); } } else if (FLAGS_test_type.compare("sequential_updates")==0) { BOOST_MESSAGE( "Test sequential_updates" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { values8[t] += 1; Grappa_yield(); } final->complete(); }); } final->wait(); double end = Grappa_walltime(); double runtime = end-start; BOOST_MESSAGE( "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task) ); } } else if (FLAGS_test_type.compare("sequential_updates16")==0) { BOOST_MESSAGE( "Test sequential_updates16" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values16 = new SixteenBytes[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { values16[t].val1 += 1; values16[t].val2 += 1; Grappa_yield(); } final->complete(); }); } final->wait(); double end = Grappa_walltime(); double runtime = end-start; BOOST_MESSAGE( "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task) ); } } else if (FLAGS_test_type.compare("private_array")==0) { BOOST_MESSAGE( "Test private_array" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { uint64_t myarray[FLAGS_private_array_size]; // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { for (uint64_t j=0; j<FLAGS_private_array_size; j++) { myarray[j] += 1; } Grappa_yield(); } values8[t] = myarray[rand()%FLAGS_private_array_size]; final->complete(); }); } final->wait(); double end = Grappa_walltime(); BOOST_MESSAGE( "result = " << values8[rand()%FLAGS_num_starting_workers] ); double runtime = end-start; BOOST_MESSAGE( "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task) ); } } else if (FLAGS_test_type.compare("private_array_bycache")==0) { BOOST_MESSAGE( "Test private_array_bycache" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { Cacheline myarray[FLAGS_private_array_size]; // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { for (uint64_t j=0; j<FLAGS_private_array_size; j++) { myarray[j].val += 1; } Grappa_yield(); } values8[t] = myarray[rand()%FLAGS_private_array_size].val; final->complete(); }); } final->wait(); double end = Grappa_walltime(); BOOST_MESSAGE( "result = " << values8[rand()%FLAGS_num_starting_workers] ); double runtime = end-start; BOOST_MESSAGE( "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task) ); } } else { BOOST_CHECK( false ); // Unrecognized test_type } BOOST_MESSAGE( "user main is exiting" ); } BOOST_AUTO_TEST_CASE( test1 ) { Grappa_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); Grappa_activate(); DVLOG(1) << "Spawning user main Thread...."; Grappa_run_user_main( &user_main, (void*)NULL ); VLOG(5) << "run_user_main returned"; CHECK( Grappa_done() ); Grappa_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2016 Liav Turkia and Shahar Sandhaus 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. */ #define CATCH_CONFIG_RUNNER #include <Catch.h> int main(int argc, char* const argv[]) { //constant? get it? const int result = Catch::Session().run(argc, argv); system("pause"); return result; } <commit_msg>Removed pause from testng<commit_after>/* The MIT License (MIT) Copyright (c) 2016 Liav Turkia and Shahar Sandhaus 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. */ #define CATCH_CONFIG_RUNNER #include <Catch.h> int main(int argc, char* const argv[]) { //constant? get it? const int result = Catch::Session().run(argc, argv); return result; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "system_wrappers/interface/cpu_info.h" #if defined(_WIN32) #include <Windows.h> #elif defined(WEBRTC_MAC) #include <sys/sysctl.h> #include <sys/types.h> #elif defined(WEBRTC_ANDROID) // Not implemented yet, might be possible to use Linux implementation #else // defined(WEBRTC_LINUX) #include <sys/sysinfo.h> #endif #include "trace.h" namespace webrtc { WebRtc_UWord32 CpuInfo::number_of_cores_ = 0; WebRtc_UWord32 CpuInfo::DetectNumberOfCores() { if (!number_of_cores_) { #if defined(_WIN32) SYSTEM_INFO si; GetSystemInfo(&si); number_of_cores_ = static_cast<WebRtc_UWord32>(si.dwNumberOfProcessors); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); #elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) number_of_cores_ = get_nprocs(); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); #elif defined(WEBRTC_MAC) int name[] = {CTL_HW, HW_AVAILCPU}; int ncpu; size_t size = sizeof(ncpu); if (0 == sysctl(name, 2, &ncpu, &size, NULL, 0)) { number_of_cores_ = static_cast<WebRtc_UWord32>(ncpu); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); } else { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "Failed to get number of cores"); number_of_cores_ = 1; } #else WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1, "No function to get number of cores"); number_of_cores_ = 1; #endif } return number_of_cores_; } } // namespace webrtc <commit_msg>compile fix for get_nprocs() with uClibc<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "system_wrappers/interface/cpu_info.h" #if defined(_WIN32) #include <Windows.h> #elif defined(WEBRTC_MAC) #include <sys/sysctl.h> #include <sys/types.h> #elif defined(WEBRTC_ANDROID) // Not implemented yet, might be possible to use Linux implementation #else // defined(WEBRTC_LINUX) #include <unistd.h> // required for get_nprocs() with uClibc #include <sys/sysinfo.h> #endif #include "trace.h" namespace webrtc { WebRtc_UWord32 CpuInfo::number_of_cores_ = 0; WebRtc_UWord32 CpuInfo::DetectNumberOfCores() { if (!number_of_cores_) { #if defined(_WIN32) SYSTEM_INFO si; GetSystemInfo(&si); number_of_cores_ = static_cast<WebRtc_UWord32>(si.dwNumberOfProcessors); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); #elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) number_of_cores_ = get_nprocs(); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); #elif defined(WEBRTC_MAC) int name[] = {CTL_HW, HW_AVAILCPU}; int ncpu; size_t size = sizeof(ncpu); if (0 == sysctl(name, 2, &ncpu, &size, NULL, 0)) { number_of_cores_ = static_cast<WebRtc_UWord32>(ncpu); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); } else { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "Failed to get number of cores"); number_of_cores_ = 1; } #else WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1, "No function to get number of cores"); number_of_cores_ = 1; #endif } return number_of_cores_; } } // namespace webrtc <|endoftext|>
<commit_before>#include <iostream> #include <vector> using namespace std; template <typename T> class HeapSort { // make A[root] the max value of the subtree void heapify(vector<T> &A, int root, int end) { int max_val_idx = root; int left = 2 * root + 1, right = left + 1; if (left < end && A[left] > A[max_val_idx]) max_val_idx = left; if (right < end && A[right] > A[max_val_idx]) max_val_idx = right; if (max_val_idx != root) { swap(A[root], A[max_val_idx]); heapify(A, max_val_idx, end); } } public: void hs(vector<T> &A) { for(int i = A.size() / 2 - 1; i >= 0; --i) heapify(A, i, A.size()); for(int i = A.size() - 1; i >= 0; --i) { swap(A[0], A[i]); heapify(A, 0, i); } } }; int main() { vector<int> unsorted = {3, 2, 1, 5, 9, 7, 4}; HeapSort<int> sorter; sorter.hs(unsorted); for (auto x : unsorted) cout << x << ' '; cout << endl; return 0; }<commit_msg>update the comments to help understand better<commit_after>#include <iostream> #include <vector> using namespace std; template <typename T> class HeapSort { // make A[root-end) a heap void heapify(vector<T> &A, int root, int end) { int left = 2 * root + 1, right = left + 1; int max_of_three = root; // max of root and its childs if (left < end && A[left] > A[max_of_three]) max_of_three = left; if (right < end && A[right] > A[max_of_three]) max_of_three = right; if (max_of_three != root) { swap(A[root], A[max_of_three]); heapify(A, max_of_three, end); } } public: void hs(vector<T> &A) { // pre-build whole vector as heap, O(n) for (int i = A.size() / 2 - 1; i >= 0; --i) heapify(A, i, A.size()); // O(nlogn) // for each step: // select max, move down root to correct position for (int i = A.size() - 1; i >= 0; --i) { swap(A[0], A[i]); heapify(A, 0, i); } } }; int main() { vector<int> unsorted = {3, 2, 1, 5, 9, 7, 4}; HeapSort<int> sorter; sorter.hs(unsorted); for (auto x : unsorted) cout << x << ' '; cout << endl; return 0; }<|endoftext|>
<commit_before>/* HarwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ extern "C" { #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Serial.h" } #include "HardwareSerial.h" // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(uint8_t uart) { if(uart == 0){ _uart = 0; }else{ _uart = 1; } } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(long speed) { uart_init(_uart, speed); } uint8_t HardwareSerial::available(void) { return uart_available(_uart); } int HardwareSerial::read(void) { return uart_read(_uart); } void HardwareSerial::print(char c) { uart_write(_uart, &c, 1); } void HardwareSerial::print(char c[]) { uart_write(_uart, c, strlen(c)); } void HardwareSerial::print(uint8_t b) { char c = b; uart_write(_uart, &c, 1); } void HardwareSerial::print(int n) { print((long) n); } void HardwareSerial::print(long n) { if (n < 0) { print('-'); n = -n; } printNumber(n, 10); } void HardwareSerial::print(unsigned long n) { printNumber(n, 10); } void HardwareSerial::print(long n, int base) { if (base == 0) print((char) n); else if (base == 10) print(n); else printNumber(n, base); } void HardwareSerial::println(void) { print('\n'); } void HardwareSerial::println(char c) { print(c); println(); } void HardwareSerial::println(char c[]) { uart_write(_uart, c, strlen(c)); println(); } void HardwareSerial::println(uint8_t b) { print(b); println(); } void HardwareSerial::println(int n) { println((long) n); } void HardwareSerial::println(long n) { print(n); println(); } void HardwareSerial::println(unsigned long n) { print(n); println(); } void HardwareSerial::println(long n, int base) { print(n, base); println(); } // Private Methods ///////////////////////////////////////////////////////////// void HardwareSerial::printNumber(unsigned long n, uint8_t base) { uint8_t buf[8 * sizeof(long)]; // Assumes 8-bit chars. int i = 0; if (n == 0) { print('0'); return; } while (n > 0) { buf[i++] = n % base; n /= base; } for (i--; i >= 0; i--){ print((char)(buf[i] < 10 ? '0' + buf[i] : 'A' + buf[i] - 10)); } } // Preinstantiate Objects ////////////////////////////////////////////////////// HardwareSerial Serial = HardwareSerial(0); //HardwareSerial Serial1 = HardwareSerial(1); <commit_msg>Serial.println() now sends '\r', '\n' (instead of just '\n')<commit_after>/* HarwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ extern "C" { #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Serial.h" } #include "HardwareSerial.h" // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(uint8_t uart) { if(uart == 0){ _uart = 0; }else{ _uart = 1; } } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(long speed) { uart_init(_uart, speed); } uint8_t HardwareSerial::available(void) { return uart_available(_uart); } int HardwareSerial::read(void) { return uart_read(_uart); } void HardwareSerial::print(char c) { uart_write(_uart, &c, 1); } void HardwareSerial::print(char c[]) { uart_write(_uart, c, strlen(c)); } void HardwareSerial::print(uint8_t b) { char c = b; uart_write(_uart, &c, 1); } void HardwareSerial::print(int n) { print((long) n); } void HardwareSerial::print(long n) { if (n < 0) { print('-'); n = -n; } printNumber(n, 10); } void HardwareSerial::print(unsigned long n) { printNumber(n, 10); } void HardwareSerial::print(long n, int base) { if (base == 0) print((char) n); else if (base == 10) print(n); else printNumber(n, base); } void HardwareSerial::println(void) { print('\r'); print('\n'); } void HardwareSerial::println(char c) { print(c); println(); } void HardwareSerial::println(char c[]) { uart_write(_uart, c, strlen(c)); println(); } void HardwareSerial::println(uint8_t b) { print(b); println(); } void HardwareSerial::println(int n) { println((long) n); } void HardwareSerial::println(long n) { print(n); println(); } void HardwareSerial::println(unsigned long n) { print(n); println(); } void HardwareSerial::println(long n, int base) { print(n, base); println(); } // Private Methods ///////////////////////////////////////////////////////////// void HardwareSerial::printNumber(unsigned long n, uint8_t base) { uint8_t buf[8 * sizeof(long)]; // Assumes 8-bit chars. int i = 0; if (n == 0) { print('0'); return; } while (n > 0) { buf[i++] = n % base; n /= base; } for (i--; i >= 0; i--){ print((char)(buf[i] < 10 ? '0' + buf[i] : 'A' + buf[i] - 10)); } } // Preinstantiate Objects ////////////////////////////////////////////////////// HardwareSerial Serial = HardwareSerial(0); //HardwareSerial Serial1 = HardwareSerial(1); <|endoftext|>
<commit_before>#include <red_black_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { RedBlackTree<int> rbt; REQUIRE(rbt._root() == rbt._NIL()); } SCENARIO("insert") { RedBlackTree<int> rbt; rbt.insert(5); REQUIRE(rbt.findElement(5) != 0); } SCENARIO("insert2", "[init]") { RedBlackTree<int> rbt; rbt.insert(2); rbt.insert(3); rbt.insert(4); REQUIRE(tree._root() == tree.findElement(3)); REQUIRE(tree._color(3) == 1); REQUIRE(tree._color(2) == 0); REQUIRE(tree._color(4) == 0); REQUIRE(tree.findElement(2) != 0); REQUIRE(tree.findElement(3) != 0); REQUIRE(tree.findElement(4) != 0); } <commit_msg>Create init.cpp<commit_after>#include <red_black_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { RedBlackTree<int> rbt; REQUIRE(rbt._root() == rbt._NIL()); } SCENARIO("insert") { RedBlackTree<int> rbt; rbt.insert(5); REQUIRE(rbt.findElement(5) != 0); } SCENARIO("insert2", "[init]") { RedBlackTree<int> rbt; rbt.insert(2); rbt.insert(3); rbt.insert(4); REQUIRE(rbt._root() == rbt.findElement(3)); REQUIRE(rbt._color(3) == 1); REQUIRE(rbt._color(2) == 0); REQUIRE(rbt._color(4) == 0); REQUIRE(rbt.findElement(2) != 0); REQUIRE(rbt.findElement(3) != 0); REQUIRE(rbt.findElement(4) != 0); } <|endoftext|>
<commit_before>#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } <commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insert(7); REQUIRE(bst.findElement() == 7); REQUIRE(bst.count() == 1); } <|endoftext|>
<commit_before>// Copyright (c) 2019 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, 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 "mfx_common.h" #if defined(MFX_ENABLE_H265_VIDEO_ENCODE) #include "hevcehw_g12_caps.h" using namespace HEVCEHW; using namespace HEVCEHW::Gen12; void Caps::Query1NoCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push) { Push(BLK_SetDefaultsCallChain, [this](const mfxVideoParam&, mfxVideoParam&, StorageRW& strg) -> mfxStatus { auto& defaults = Glob::Defaults::GetOrConstruct(strg); auto& bSet = defaults.SetForFeature[GetID()]; MFX_CHECK(!bSet, MFX_ERR_NONE); defaults.GetMaxNumRef.Push([]( Gen9::Defaults::TChain<std::tuple<mfxU16, mfxU16>>::TExt , const Gen9::Defaults::Param& dpar) { const mfxU16 nRef[3][2][7] = { { // VME { 4, 4, 3, 3, 3, 1, 1 }, { 2, 2, 1, 1, 1, 1, 1 } }, { // VDENC P { 3, 3, 2, 2, 2, 1, 1 }, { 3, 3, 2, 2, 2, 1, 1 } }, { // Gen12 VDENC RA B { 2, 2, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1 } } }; bool bBFrames = (dpar.mvp.mfx.GopRefDist > 1); bool bVDEnc = IsOn(dpar.mvp.mfx.LowPower); mfxU16 tu = dpar.mvp.mfx.TargetUsage; mfxU32 idx = bVDEnc * (1 + bBFrames); CheckRangeOrSetDefault<mfxU16>(tu, 1, 7, 4); --tu; return std::make_tuple( std::min<mfxU16>(nRef[idx][0][tu], dpar.caps.MaxNum_Reference0) , std::min<mfxU16>(nRef[idx][1][tu], dpar.caps.MaxNum_Reference1)); }); bSet = true; return MFX_ERR_NONE; }); } void Caps::Query1WithCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push) { Push(BLK_HardcodeCaps , [this](const mfxVideoParam&, mfxVideoParam& par, StorageRW& strg) -> mfxStatus { auto& caps = Glob::EncodeCaps::Get(strg); caps.SliceIPOnly = IsOn(par.mfx.LowPower) && (par.mfx.TargetUsage == 7); caps.msdk.bSingleSliceMultiTile = false; caps.YUV422ReconSupport |= (!caps.Color420Only && IsOff(par.mfx.LowPower)); SetSpecificCaps(caps); return MFX_ERR_NONE; }); } #endif //defined(MFX_ENABLE_H265_VIDEO_ENCODE) <commit_msg>[HEVCe-r] Corrected def. num. ref. list. calc. on TGL+<commit_after>// Copyright (c) 2019-2020 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, 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 "mfx_common.h" #if defined(MFX_ENABLE_H265_VIDEO_ENCODE) #include "hevcehw_g12_caps.h" using namespace HEVCEHW; using namespace HEVCEHW::Gen12; void Caps::Query1NoCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push) { Push(BLK_SetDefaultsCallChain, [this](const mfxVideoParam&, mfxVideoParam&, StorageRW& strg) -> mfxStatus { auto& defaults = Glob::Defaults::GetOrConstruct(strg); auto& bSet = defaults.SetForFeature[GetID()]; MFX_CHECK(!bSet, MFX_ERR_NONE); defaults.GetMaxNumRef.Push([]( Gen9::Defaults::TChain<std::tuple<mfxU16, mfxU16>>::TExt , const Gen9::Defaults::Param& dpar) { const mfxU16 nRef[3][2][7] = { { // VME { 4, 4, 3, 3, 3, 1, 1 }, { 2, 2, 1, 1, 1, 1, 1 } }, { // VDENC P { 3, 3, 2, 2, 2, 1, 1 }, { 3, 3, 2, 2, 2, 1, 1 } }, { // Gen12 VDENC RA B { 2, 2, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1 } } }; bool bBFrames = (dpar.mvp.mfx.GopRefDist > 1); bool bVDEnc = IsOn(dpar.mvp.mfx.LowPower); mfxU16 tu = dpar.mvp.mfx.TargetUsage; mfxU32 idx = bVDEnc * (1 + bBFrames); CheckRangeOrSetDefault<mfxU16>(tu, 1, 7, 4); --tu; /* Same way like on Gen9 or Gen11 platforms */ mfxU16 numRefFrame = dpar.mvp.mfx.NumRefFrame + !dpar.mvp.mfx.NumRefFrame * 16; return std::make_tuple( std::min<mfxU16>(nRef[idx][0][tu], std::min<mfxU16>(dpar.caps.MaxNum_Reference0, numRefFrame)) , std::min<mfxU16>(nRef[idx][1][tu], std::min<mfxU16>(dpar.caps.MaxNum_Reference1, numRefFrame))); }); bSet = true; return MFX_ERR_NONE; }); } void Caps::Query1WithCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push) { Push(BLK_HardcodeCaps , [this](const mfxVideoParam&, mfxVideoParam& par, StorageRW& strg) -> mfxStatus { auto& caps = Glob::EncodeCaps::Get(strg); caps.SliceIPOnly = IsOn(par.mfx.LowPower) && (par.mfx.TargetUsage == 7); caps.msdk.bSingleSliceMultiTile = false; caps.YUV422ReconSupport |= (!caps.Color420Only && IsOff(par.mfx.LowPower)); SetSpecificCaps(caps); return MFX_ERR_NONE; }); } #endif //defined(MFX_ENABLE_H265_VIDEO_ENCODE) <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <fcntl.h> #ifndef _WIN32 #include <sys/mman.h> #else #include <windows.h> #endif #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "tensorflow/lite/allocation.h" #include "tensorflow/lite/core/api/error_reporter.h" namespace tflite { #ifdef _WIN32 static constexpr void* MAP_FAILED = nullptr; MMAPAllocation::MMAPAllocation(const char* filename, ErrorReporter* error_reporter) : Allocation(error_reporter) , mmapped_buffer_(MAP_FAILED) , file_handle_( nullptr ) , file_mapping_( nullptr ) { file_handle_ = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0); if (file_handle_ == INVALID_HANDLE_VALUE) { error_reporter_->Report("Could not open '%s'.", filename); return; } buffer_size_bytes_ = GetFileSize( file_handle_, nullptr ); file_mapping_ = CreateFileMapping(file_handle_, NULL, PAGE_READONLY, 0, 0, NULL); if (file_mapping_ == NULL) return; mmapped_buffer_ = MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, buffer_size_bytes_); if (mmapped_buffer_ == MAP_FAILED) { error_reporter_->Report("Mmap of '%s' failed.", filename); return; } } MMAPAllocation::~MMAPAllocation() { if (valid()) { UnmapViewOfFile( mmapped_buffer_ ); } if (file_mapping_ != nullptr) { CloseHandle( file_mapping_ ); } if (file_handle_ != nullptr){ CloseHandle( file_handle_ ); } } #else MMAPAllocation::MMAPAllocation(const char* filename, ErrorReporter* error_reporter) : Allocation(error_reporter), mmapped_buffer_(MAP_FAILED) { mmap_fd_ = open(filename, O_RDONLY); if (mmap_fd_ == -1) { error_reporter_->Report("Could not open '%s'.", filename); return; } struct stat sb; fstat(mmap_fd_, &sb); buffer_size_bytes_ = sb.st_size; mmapped_buffer_ = mmap(nullptr, buffer_size_bytes_, PROT_READ, MAP_SHARED, mmap_fd_, 0); if (mmapped_buffer_ == MAP_FAILED) { error_reporter_->Report("Mmap of '%s' failed.", filename); return; } } MMAPAllocation::~MMAPAllocation() { if (valid()) { munmap(const_cast<void*>(mmapped_buffer_), buffer_size_bytes_); } if (mmap_fd_ != -1) close(mmap_fd_); } #endif const void* MMAPAllocation::base() const { return mmapped_buffer_; } size_t MMAPAllocation::bytes() const { return buffer_size_bytes_; } bool MMAPAllocation::valid() const { return mmapped_buffer_ != MAP_FAILED; } bool MMAPAllocation::IsSupported() { return true; } } // namespace tflite <commit_msg>Use nullptr<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <fcntl.h> #ifndef _WIN32 #include <sys/mman.h> #else #include <windows.h> #endif #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "tensorflow/lite/allocation.h" #include "tensorflow/lite/core/api/error_reporter.h" namespace tflite { #ifdef _WIN32 static constexpr void* MAP_FAILED = nullptr; MMAPAllocation::MMAPAllocation(const char* filename, ErrorReporter* error_reporter) : Allocation(error_reporter) , mmapped_buffer_(MAP_FAILED) , file_handle_(nullptr) , file_mapping_(nullptr) { file_handle_ = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0); if (file_handle_ == INVALID_HANDLE_VALUE) { error_reporter_->Report("Could not open '%s'.", filename); return; } buffer_size_bytes_ = GetFileSize( file_handle_, nullptr ); file_mapping_ = CreateFileMapping(file_handle_, NULL, PAGE_READONLY, 0, 0, NULL); if (file_mapping_ == nullptr) return; mmapped_buffer_ = MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, buffer_size_bytes_); if (mmapped_buffer_ == MAP_FAILED) { error_reporter_->Report("Mmap of '%s' failed.", filename); return; } } MMAPAllocation::~MMAPAllocation() { if (valid()) { UnmapViewOfFile( mmapped_buffer_ ); } if (file_mapping_ != nullptr) { CloseHandle( file_mapping_ ); } if (file_handle_ != nullptr){ CloseHandle(file_handle_); } } #else MMAPAllocation::MMAPAllocation(const char* filename, ErrorReporter* error_reporter) : Allocation(error_reporter), mmapped_buffer_(MAP_FAILED) { mmap_fd_ = open(filename, O_RDONLY); if (mmap_fd_ == -1) { error_reporter_->Report("Could not open '%s'.", filename); return; } struct stat sb; fstat(mmap_fd_, &sb); buffer_size_bytes_ = sb.st_size; mmapped_buffer_ = mmap(nullptr, buffer_size_bytes_, PROT_READ, MAP_SHARED, mmap_fd_, 0); if (mmapped_buffer_ == MAP_FAILED) { error_reporter_->Report("Mmap of '%s' failed.", filename); return; } } MMAPAllocation::~MMAPAllocation() { if (valid()) { munmap(const_cast<void*>(mmapped_buffer_), buffer_size_bytes_); } if (mmap_fd_ != -1) close(mmap_fd_); } #endif const void* MMAPAllocation::base() const { return mmapped_buffer_; } size_t MMAPAllocation::bytes() const { return buffer_size_bytes_; } bool MMAPAllocation::valid() const { return mmapped_buffer_ != MAP_FAILED; } bool MMAPAllocation::IsSupported() { return true; } } // namespace tflite <|endoftext|>
<commit_before>#ifndef SMARTPOINTERS_HPP_ #define SMARTPOINTERS_HPP_ #define NOMINMAX // Removes windows min and max macros #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include "FAST/Exception.hpp" #include "FAST/Reporter.hpp" #include "FAST/Paths.hpp" #define FAST_OBJECT(className) \ public: \ typedef SharedPointer<className> pointer; \ static SharedPointer<className> New() { \ className * ptr = new className(); \ SharedPointer<className> smartPtr(ptr); \ ptr->setPtr(smartPtr); \ \ return smartPtr; \ } \ virtual std::string getNameOfClass() const { \ return std::string(#className); \ }; \ static std::string getStaticNameOfClass() { \ return std::string(#className); \ }; \ private: \ void setPtr(className::pointer ptr) { \ mPtr = ptr; \ } \ namespace fast { template <class T> class SharedPointer; template <class T> class WeakPointer { public: WeakPointer() {}; WeakPointer(const SharedPointer<T> object) { mWeakPtr = object.getPtr(); } SharedPointer<T> lock() const { return SharedPointer<T>(mWeakPtr.lock()); }; boost::weak_ptr<T> getPtr() const { return mWeakPtr; }; WeakPointer<T> &operator=(const SharedPointer<T> &other); bool operator==(const WeakPointer<T> &other) const { // Check if the two weak pointers, point to the same objecs SharedPointer<T> object1 = mWeakPtr.lock(); SharedPointer<T> object2 = other.lock(); if(object1.isValid() && object2.isValid()) { return object1 == object2; } else { return false; } } private: boost::weak_ptr<T> mWeakPtr; }; class Object; template <class T> class SharedPointer { public: SharedPointer() { } SharedPointer(T* object) { mSmartPtr = boost::shared_ptr<T>(object); } template <class D> SharedPointer(T* p, D d) { mSmartPtr = boost::shared_ptr<T>(p, d); } template <class U> SharedPointer(boost::shared_ptr<U> sharedPtr) { mSmartPtr = boost::dynamic_pointer_cast<T>(sharedPtr); } template <class U> SharedPointer(SharedPointer<U> object) { if(!object.isValid()) throw Exception("Cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass() + " failed because object was invalid (uninitialized or deleted)."); boost::shared_ptr<T> ptr = boost::dynamic_pointer_cast<T>(object.getPtr()); if(ptr == NULL) throw Exception("Illegal cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass()); mSmartPtr = boost::shared_ptr<T>(ptr); } template <class U> SharedPointer(WeakPointer<U> object) { if(!object.isValid()) throw Exception("Cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass() + " failed because object was invalid (uninitialized or deleted)."); boost::shared_ptr<T> ptr = boost::dynamic_pointer_cast<T>(object.getPtr().lock()); if(ptr == NULL) throw Exception("Illegal cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass()); mSmartPtr = boost::shared_ptr<T>(ptr); } template <class U> SharedPointer<T> &operator=(const SharedPointer<U> &other) { if(!other.isValid()) throw Exception("Cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass() + " failed because object was invalid (uninitialized or deleted)."); boost::shared_ptr<T> ptr = boost::dynamic_pointer_cast<T>(other.getPtr()); if(ptr == NULL) throw Exception("Illegal cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass()); mSmartPtr = boost::shared_ptr<T>(ptr); return *this; } template <class U> void swap(SharedPointer<U> &other) { mSmartPtr.swap(other.getReferenceToPointer()); } bool isValid() const { // Check if smart pointer actually points to something return mSmartPtr.get() != NULL; } operator unsigned long int() const { return (unsigned long int)mSmartPtr.get(); } bool operator==(const SharedPointer<T> &other) { return this->getPtr() == other.getPtr(); } T* operator->() { return mSmartPtr.get(); } T* operator->() const { return mSmartPtr.get(); } T* get() { return mSmartPtr.get(); } boost::shared_ptr<T> getPtr() const { return mSmartPtr; }; boost::shared_ptr<T> & getReferenceToPointer() { return mSmartPtr; }; private: boost::shared_ptr<T> mSmartPtr; }; template <class T> using UniquePointer = std::unique_ptr<T>; template <class T> WeakPointer<T> &WeakPointer<T>::operator=(const SharedPointer<T> &other) { mWeakPtr = other.getPtr(); return *this; } } // end namespace fast // A custum boost hashing function for the SharedPointers so that they can be used // in unordered data structures. TODO verify that this works namespace boost { template <class U> std::size_t hash_value(fast::SharedPointer<U> const& obj) { return (std::size_t)obj.getPtr().get(); } template <class U> std::size_t hash_value(fast::WeakPointer<U> const& obj) { return (std::size_t)obj.lock().getPtr().get(); } } #endif /* SMARTPOINTERS_HPP_ */ <commit_msg>Switched to using shared_ptr and weak_ptr from std instead of boost<commit_after>#ifndef SMARTPOINTERS_HPP_ #define SMARTPOINTERS_HPP_ #define NOMINMAX // Removes windows min and max macros #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include "FAST/Exception.hpp" #include "FAST/Reporter.hpp" #include "FAST/Paths.hpp" #define FAST_OBJECT(className) \ public: \ typedef SharedPointer<className> pointer; \ static SharedPointer<className> New() { \ className * ptr = new className(); \ SharedPointer<className> smartPtr(ptr); \ ptr->setPtr(smartPtr); \ \ return smartPtr; \ } \ virtual std::string getNameOfClass() const { \ return std::string(#className); \ }; \ static std::string getStaticNameOfClass() { \ return std::string(#className); \ }; \ private: \ void setPtr(className::pointer ptr) { \ mPtr = ptr; \ } \ namespace fast { template <class T> class SharedPointer; template <class T> class WeakPointer { public: WeakPointer() {}; WeakPointer(const SharedPointer<T> object) { mWeakPtr = object.getPtr(); } SharedPointer<T> lock() const { return SharedPointer<T>(mWeakPtr.lock()); }; std::weak_ptr<T> getPtr() const { return mWeakPtr; }; WeakPointer<T> &operator=(const SharedPointer<T> &other); bool operator==(const WeakPointer<T> &other) const { // Check if the two weak pointers, point to the same objecs SharedPointer<T> object1 = mWeakPtr.lock(); SharedPointer<T> object2 = other.lock(); if(object1.isValid() && object2.isValid()) { return object1 == object2; } else { return false; } } private: std::weak_ptr<T> mWeakPtr; }; class Object; template <class T> class SharedPointer { public: SharedPointer() { } SharedPointer(T* object) { mSmartPtr = std::shared_ptr<T>(object); } template <class D> SharedPointer(T* p, D d) { mSmartPtr = std::shared_ptr<T>(p, d); } template <class U> SharedPointer(std::shared_ptr<U> sharedPtr) { mSmartPtr = std::dynamic_pointer_cast<T>(sharedPtr); } template <class U> SharedPointer(SharedPointer<U> object) { if(!object.isValid()) throw Exception("Cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass() + " failed because object was invalid (uninitialized or deleted)."); std::shared_ptr<T> ptr = std::dynamic_pointer_cast<T>(object.getPtr()); if(ptr == NULL) throw Exception("Illegal cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass()); mSmartPtr = std::shared_ptr<T>(ptr); } template <class U> SharedPointer(WeakPointer<U> object) { if(!object.isValid()) throw Exception("Cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass() + " failed because object was invalid (uninitialized or deleted)."); std::shared_ptr<T> ptr = std::dynamic_pointer_cast<T>(object.getPtr().lock()); if(ptr == NULL) throw Exception("Illegal cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass()); mSmartPtr = std::shared_ptr<T>(ptr); } template <class U> SharedPointer<T> &operator=(const SharedPointer<U> &other) { if(!other.isValid()) throw Exception("Cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass() + " failed because object was invalid (uninitialized or deleted)."); std::shared_ptr<T> ptr = std::dynamic_pointer_cast<T>(other.getPtr()); if(ptr == NULL) throw Exception("Illegal cast from " + U::getStaticNameOfClass() + " to " + T::getStaticNameOfClass()); mSmartPtr = std::shared_ptr<T>(ptr); return *this; } template <class U> void swap(SharedPointer<U> &other) { mSmartPtr.swap(other.getReferenceToPointer()); } bool isValid() const { // Check if smart pointer actually points to something return mSmartPtr.get() != NULL; } operator unsigned long int() const { return (unsigned long int)mSmartPtr.get(); } bool operator==(const SharedPointer<T> &other) { return this->getPtr() == other.getPtr(); } T* operator->() { return mSmartPtr.get(); } T* operator->() const { return mSmartPtr.get(); } T* get() { return mSmartPtr.get(); } std::shared_ptr<T> getPtr() const { return mSmartPtr; }; std::shared_ptr<T> & getReferenceToPointer() { return mSmartPtr; }; private: std::shared_ptr<T> mSmartPtr; }; template <class T> using UniquePointer = std::unique_ptr<T>; template <class T> WeakPointer<T> &WeakPointer<T>::operator=(const SharedPointer<T> &other) { mWeakPtr = other.getPtr(); return *this; } } // end namespace fast // A custum boost hashing function for the SharedPointers so that they can be used // in unordered data structures. TODO verify that this works namespace boost { template <class U> std::size_t hash_value(fast::SharedPointer<U> const& obj) { return (std::size_t)obj.getPtr().get(); } template <class U> std::size_t hash_value(fast::WeakPointer<U> const& obj) { return (std::size_t)obj.lock().getPtr().get(); } } #endif /* SMARTPOINTERS_HPP_ */ <|endoftext|>
<commit_before>// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include <string.h> #include <targetPAL.h> #include "win_dev_i2c_native.h" #include "Esp32_DeviceMapping.h" /////////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cSharingMode (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////////// enum I2cSharingMode { Exclusive = 0, Shared }; /////////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cTransferStatus (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////////// enum I2cTransferStatus { I2cTransferStatus_FullTransfer = 0, I2cTransferStatus_ClockStretchTimeout, I2cTransferStatus_PartialTransfer, I2cTransferStatus_SlaveAddressNotAcknowledged, I2cTransferStatus_UnknownError }; /////////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cBusSpeed (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////////// enum I2cBusSpeed { I2cBusSpeed_StandardMode = 0, I2cBusSpeed_FastMode }; typedef Library_win_dev_i2c_native_Windows_Devices_I2c_I2cConnectionSettings I2cConnectionSettings; static char Esp_I2C_Initialised_Flag[I2C_NUM_MAX] = {0,0}; void Esp32_I2c_UnitializeAll() { for (int c = 0; c < I2C_NUM_MAX; c++) { if (Esp_I2C_Initialised_Flag[c]) { // Delete bus driver i2c_driver_delete((i2c_port_t)c); Esp_I2C_Initialised_Flag[c] = 0; } } } void Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::SetConfig(i2c_port_t bus, CLR_RT_HeapBlock* config) { int busSpeed = config[ I2cConnectionSettings::FIELD___busSpeed ].NumericByRef().s4; gpio_num_t DataPin = (gpio_num_t)Esp32_GetMappedDevicePins( DEV_TYPE_I2C, bus, 0); gpio_num_t ClockPin = (gpio_num_t)Esp32_GetMappedDevicePins( DEV_TYPE_I2C, bus, 1); i2c_config_t conf; conf.mode = I2C_MODE_MASTER; conf.sda_io_num = DataPin; conf.sda_pullup_en = GPIO_PULLUP_ENABLE; conf.scl_io_num = ClockPin; conf.scl_pullup_en = GPIO_PULLUP_ENABLE; conf.master.clk_speed = (busSpeed==0)? 100000 : 400000; i2c_param_config(bus, &conf); } HRESULT IRAM_ATTR Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::NativeInit___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { // get a pointer to the managed object instance and check that it's not NULL CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // get bus index // this is coded with a multiplication, need to perform and int division to get the number // see the comments in the SpiDevice() constructor in managed code for details, subtract 1 to get ESP32 bus number i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 / 1000) - 1); if ( bus != I2C_NUM_0 && bus != I2C_NUM_1) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // get a pointer to the managed spi connectionSettings object instance CLR_RT_HeapBlock* pConfig = pThis[ FIELD___connectionSettings ].Dereference(); // Set the Bus parameters SetConfig( bus, pConfig); esp_err_t res = i2c_driver_install( bus, I2C_MODE_MASTER, 0, 0, 0); if ( res != ESP_OK) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // Ensure driver gets unitialized during soft reboot HAL_AddSoftRebootHandler(Esp32_I2c_UnitializeAll); Esp_I2C_Initialised_Flag[bus] = 1; } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::DisposeNative___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { // get a pointer to the managed object instance and check that it's not NULL CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 / 1000) - 1); i2c_driver_delete(bus); Esp_I2C_Initialised_Flag[bus] = 0; } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::NativeTransmit___WindowsDevicesI2cI2cTransferResult__SZARRAY_U1__SZARRAY_U1( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { unsigned char * writeData = NULL; unsigned char * readData = NULL; int writeSize = 0; int readSize = 0; esp_err_t i2cStatus; int returnStatus = I2cTransferStatus_FullTransfer; CLR_RT_HeapBlock* result; // create the return object (I2cTransferResult) CLR_RT_HeapBlock& top = stack.PushValueAndClear(); // get a pointer to the managed object instance and check that it's not NULL CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // get a pointer to the managed spi connectionSettings object instance CLR_RT_HeapBlock* pConfig = pThis[ FIELD___connectionSettings ].Dereference(); // get bus index // this is coded with a multiplication, need to perform and int division to get the number // see the comments in the SpiDevice() constructor in managed code for details, subtract 1 to get ESP32 bus number i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 / 1000) - 1); // Set the Bus parameters SetConfig( bus, pConfig); int slaveAddress = pConfig[ I2cConnectionSettings::FIELD___slaveAddress ].NumericByRef().s4; // dereference the write and read buffers from the arguments CLR_RT_HeapBlock_Array* writeBuffer = stack.Arg1().DereferenceArray(); if (writeBuffer != NULL) { // grab the pointer to the array by getting the first element of the array writeData = writeBuffer->GetFirstElement(); // get the size of the buffer by reading the number of elements in the HeapBlock array writeSize = writeBuffer->m_numOfElements; } CLR_RT_HeapBlock_Array* readBuffer = stack.Arg3().DereferenceArray(); if (readBuffer != NULL) { // grab the pointer to the array by getting the first element of the array readData = readBuffer->GetFirstElement(); // get the size of the buffer by reading the number of elements in the HeapBlock array readSize = readBuffer->m_numOfElements; } i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte( cmd, ( slaveAddress << 1 ) | I2C_MASTER_WRITE, 1); if ( writeSize != 0 ) // Write { i2c_master_write(cmd, &writeData[0], writeSize, true); } if (readSize != 0 ) // Read { i2cStatus = i2c_master_read(cmd, &readData[0], readSize, true); } i2c_master_stop(cmd); i2cStatus = i2c_master_cmd_begin(bus, cmd, 1000 / portTICK_RATE_MS); i2c_cmd_link_delete(cmd); // create return object NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_I2cTransferResult)); result = top.Dereference(); FAULT_ON_NULL(result); if (i2cStatus != ESP_OK) { // set the result field if ( i2cStatus == ESP_FAIL ) { result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_SlaveAddressNotAcknowledged); } else { result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_UnknownError); } // set the bytes transferred field result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___bytesTransferred ].SetInteger(0); } else { result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_FullTransfer); // set the bytes transferred field result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___bytesTransferred ].SetInteger((CLR_UINT32)(writeSize + readSize)); if(readSize > 0) { // because this was a Read transaction, need to copy from DMA buffer to managed buffer memcpy(readBuffer->GetFirstElement(), &readData[0], readSize); } } // null pointers and vars writeData = NULL; readData = NULL; writeBuffer = NULL; readBuffer = NULL; pThis = NULL; stack.SetResult_I4(returnStatus); } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::GetDeviceSelector___STATIC__STRING( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { // declare the device selector string whose max size is "I2C1,I2C2,I2C3," + terminator and init with the terminator char deviceSelectorString[ 15 + 1] = { 0 }; strcat(deviceSelectorString, "I2C1,I2C2"); // because the caller is expecting a result to be returned // we need set a return result in the stack argument using the appropriate SetResult according to the variable type (a string here) stack.SetResult_String(deviceSelectorString); } NANOCLR_NOCLEANUP(); } <commit_msg>Fix error introduced in last ESP32 I2C change (#674)<commit_after>// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include <string.h> #include <targetPAL.h> #include "win_dev_i2c_native.h" #include "Esp32_DeviceMapping.h" /////////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cSharingMode (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////////// enum I2cSharingMode { Exclusive = 0, Shared }; /////////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cTransferStatus (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////////// enum I2cTransferStatus { I2cTransferStatus_FullTransfer = 0, I2cTransferStatus_ClockStretchTimeout, I2cTransferStatus_PartialTransfer, I2cTransferStatus_SlaveAddressNotAcknowledged, I2cTransferStatus_UnknownError }; /////////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cBusSpeed (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////////// enum I2cBusSpeed { I2cBusSpeed_StandardMode = 0, I2cBusSpeed_FastMode }; typedef Library_win_dev_i2c_native_Windows_Devices_I2c_I2cConnectionSettings I2cConnectionSettings; static char Esp_I2C_Initialised_Flag[I2C_NUM_MAX] = {0,0}; void Esp32_I2c_UnitializeAll() { for (int c = 0; c < I2C_NUM_MAX; c++) { if (Esp_I2C_Initialised_Flag[c]) { // Delete bus driver i2c_driver_delete((i2c_port_t)c); Esp_I2C_Initialised_Flag[c] = 0; } } } void Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::SetConfig(i2c_port_t bus, CLR_RT_HeapBlock* config) { int busSpeed = config[ I2cConnectionSettings::FIELD___busSpeed ].NumericByRef().s4; gpio_num_t DataPin = (gpio_num_t)Esp32_GetMappedDevicePins( DEV_TYPE_I2C, bus, 0); gpio_num_t ClockPin = (gpio_num_t)Esp32_GetMappedDevicePins( DEV_TYPE_I2C, bus, 1); i2c_config_t conf; conf.mode = I2C_MODE_MASTER; conf.sda_io_num = DataPin; conf.sda_pullup_en = GPIO_PULLUP_ENABLE; conf.scl_io_num = ClockPin; conf.scl_pullup_en = GPIO_PULLUP_ENABLE; conf.master.clk_speed = (busSpeed==0)? 100000 : 400000; i2c_param_config(bus, &conf); } HRESULT IRAM_ATTR Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::NativeInit___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { // get a pointer to the managed object instance and check that it's not NULL CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // get bus index // this is coded with a multiplication, need to perform and int division to get the number // see the comments in the SpiDevice() constructor in managed code for details, subtract 1 to get ESP32 bus number i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 / 1000) - 1); if ( bus != I2C_NUM_0 && bus != I2C_NUM_1) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // get a pointer to the managed spi connectionSettings object instance CLR_RT_HeapBlock* pConfig = pThis[ FIELD___connectionSettings ].Dereference(); // Set the Bus parameters SetConfig( bus, pConfig); esp_err_t res = i2c_driver_install( bus, I2C_MODE_MASTER, 0, 0, 0); if ( res != ESP_OK) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // Ensure driver gets unitialized during soft reboot HAL_AddSoftRebootHandler(Esp32_I2c_UnitializeAll); Esp_I2C_Initialised_Flag[bus] = 1; } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::DisposeNative___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { // get a pointer to the managed object instance and check that it's not NULL CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 / 1000) - 1); i2c_driver_delete(bus); Esp_I2C_Initialised_Flag[bus] = 0; } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::NativeTransmit___WindowsDevicesI2cI2cTransferResult__SZARRAY_U1__SZARRAY_U1( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { unsigned char * writeData = NULL; unsigned char * readData = NULL; int writeSize = 0; int readSize = 0; esp_err_t i2cStatus; int returnStatus = I2cTransferStatus_FullTransfer; CLR_RT_HeapBlock* result; // create the return object (I2cTransferResult) CLR_RT_HeapBlock& top = stack.PushValueAndClear(); // get a pointer to the managed object instance and check that it's not NULL CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // get a pointer to the managed spi connectionSettings object instance CLR_RT_HeapBlock* pConfig = pThis[ FIELD___connectionSettings ].Dereference(); // get bus index // this is coded with a multiplication, need to perform and int division to get the number // see the comments in the SpiDevice() constructor in managed code for details, subtract 1 to get ESP32 bus number i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 / 1000) - 1); // Set the Bus parameters SetConfig( bus, pConfig); int slaveAddress = pConfig[ I2cConnectionSettings::FIELD___slaveAddress ].NumericByRef().s4; // dereference the write and read buffers from the arguments CLR_RT_HeapBlock_Array* writeBuffer = stack.Arg1().DereferenceArray(); if (writeBuffer != NULL) { // grab the pointer to the array by getting the first element of the array writeData = writeBuffer->GetFirstElement(); // get the size of the buffer by reading the number of elements in the HeapBlock array writeSize = writeBuffer->m_numOfElements; } CLR_RT_HeapBlock_Array* readBuffer = stack.Arg2().DereferenceArray(); if (readBuffer != NULL) { // grab the pointer to the array by getting the first element of the array readData = readBuffer->GetFirstElement(); // get the size of the buffer by reading the number of elements in the HeapBlock array readSize = readBuffer->m_numOfElements; } i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte( cmd, ( slaveAddress << 1 ) | I2C_MASTER_WRITE, 1); if ( writeSize != 0 ) // Write { i2c_master_write(cmd, &writeData[0], writeSize, true); } if (readSize != 0 ) // Read { i2cStatus = i2c_master_read(cmd, &readData[0], readSize, true); } i2c_master_stop(cmd); i2cStatus = i2c_master_cmd_begin(bus, cmd, 1000 / portTICK_RATE_MS); i2c_cmd_link_delete(cmd); // create return object NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_I2cTransferResult)); result = top.Dereference(); FAULT_ON_NULL(result); if (i2cStatus != ESP_OK) { // set the result field if ( i2cStatus == ESP_FAIL ) { result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_SlaveAddressNotAcknowledged); } else { result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_UnknownError); } // set the bytes transferred field result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___bytesTransferred ].SetInteger(0); } else { result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_FullTransfer); // set the bytes transferred field result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___bytesTransferred ].SetInteger((CLR_UINT32)(writeSize + readSize)); if(readSize > 0) { // because this was a Read transaction, need to copy from DMA buffer to managed buffer memcpy(readBuffer->GetFirstElement(), &readData[0], readSize); } } // null pointers and vars writeData = NULL; readData = NULL; writeBuffer = NULL; readBuffer = NULL; pThis = NULL; stack.SetResult_I4(returnStatus); } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::GetDeviceSelector___STATIC__STRING( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { // declare the device selector string whose max size is "I2C1,I2C2,I2C3," + terminator and init with the terminator char deviceSelectorString[ 15 + 1] = { 0 }; strcat(deviceSelectorString, "I2C1,I2C2"); // because the caller is expecting a result to be returned // we need set a return result in the stack argument using the appropriate SetResult according to the variable type (a string here) stack.SetResult_String(deviceSelectorString); } NANOCLR_NOCLEANUP(); } <|endoftext|>
<commit_before>/* Copyright (C) 2003-2010 Egon Wanke <blitzortung@gmx.org> Copyright (C) 2010 Andreas Würl <awuerl@gmx.net> */ #include <iostream> #include <string> #include <boost/program_options.hpp> #include "namespaces.h" #include "hardware/comm/SerialPort.h" #include "hardware/comm/Serial.h" #include "hardware/gps/Garmin.h" #include "hardware/gps/Sirf.h" #include "hardware/gps/Sjn.h" #include "hardware/pcb/V4.h" #include "hardware/pcb/V6.h" #include "data/sample/V1.h" #include "network/Base.h" #include "util/RingBuffer.h" #include "exception/Base.h" #include "Logger.h" int main(int argc, char **argv) { std::string username, password, servername; unsigned short serverport; std::string serialPortName = "/dev/ttyUSB0"; std::string outputFile = ""; int serialBaudRate = 19200; int sleepTime = 20; int sampleVersion = 1; int pcbVersion = 6; double eventRateLimit = 1.0; std::string gpsType = "sirf"; bo::Logger logger(""); // programm arguments/options boost::program_options::options_description desc("program options"); desc.add_options() ("help", "show program help") ("serial-device,d", po::value<std::string>(&serialPortName)->default_value(serialPortName), "path to serial device") ("baud-rate,b", po::value<int>(&serialBaudRate)->default_value(serialBaudRate), "baud rate of serial port (4800, 9600, 19200, 38400)") ("username,u", po::value<std::string>(&username), "username of blitzortung.org") ("password,p", po::value<std::string>(&password), "password of blitzortung.org") ("server-host,h", po::value<std::string>(&servername), "blitzortung.org servername") ("server-port", po::value<unsigned short>(&serverport)->default_value(8308), "blitzortung.org serverport") ("sleep-time,s", po::value<int>(&sleepTime)->default_value(sleepTime), "sleep time between data transmission") ("gps-type,g", po::value<std::string>(&gpsType)->default_value(gpsType), "type of gps device (sjn, garmin or sirf)") ("pcb-version", po::value<int>(&pcbVersion)->default_value(pcbVersion), "version of PCB (4 or 6)") ("event-rate-limit,l", po::value<double>(&eventRateLimit)->default_value(eventRateLimit), "limit of event rate (in events per second) 1.0 means max. 3600 events per hour") ("output,o", po::value<std::string>(&outputFile), "output file name (e.g. Name_%Y%m%d.bor)") ("verbose,v", "verbose mode") ("debug", "debug mode") ; // parse command line options po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); po::notify(vm); // help output or no 'sql-statement' given if (vm.count("help")) { std::cout << argv[0] << " [options]" << std::endl << std::endl; std::cout << desc << std::endl; std::cout << std::endl; return 1; } if (! vm.count("username")) { std::cerr << "'username' missing\n"; return 5; } if (! vm.count("password")) { std::cerr << "'password' missing\n"; return 5; } if (! vm.count("server-host")) { std::cerr << "'server-host' missing\n"; return 5; } // logging setup logger.setPriority(log4cpp::Priority::NOTICE); if (vm.count("verbose")) { logger.setPriority(log4cpp::Priority::INFO); } if (vm.count("debug")) { logger.setPriority(log4cpp::Priority::DEBUG); } switch (serialBaudRate) { case 4800: case 9600: case 19200: case 38400: break; default: std::ostringstream oss; oss << "invalid serial baud rate: " << serialBaudRate; throw bo::exception::Base(oss.str()); } // create serial port object bo::hardware::comm::SerialPort serialPort(serialPortName, serialBaudRate); bo::hardware::comm::Serial serial(serialPort); // select type of gps hardware bo::hardware::gps::Base::AP gps; if (gpsType == "garmin") { gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Garmin(serial)); } else if (gpsType == "sirf") { gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Sirf(serial)); } else if (gpsType == "sjn") { gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Sjn(serial)); } else { std::ostringstream oss; oss << "invalid value of gps-type: '" << gpsType << "'"; throw bo::exception::Base(oss.str()); } // create sample creator object std::auto_ptr<bo::data::sample::Base::Creator> sampleCreator; switch (sampleVersion) { case 1: sampleCreator = std::auto_ptr<bo::data::sample::Base::Creator>(new bo::data::sample::V1::Creator()); break; default: std::ostringstream oss; oss << "invalid sample version: " << pcbVersion; throw bo::exception::Base(oss.str()); } // create hardware driver object for blitzortung measurement hardware bo::hardware::pcb::Base::AP hardware; switch (pcbVersion) { case 4: hardware = bo::hardware::pcb::Base::AP(new bo::hardware::pcb::V4(serial, *gps, *sampleCreator)); break; case 6: hardware = bo::hardware::pcb::Base::AP(new bo::hardware::pcb::V6(serial, *gps, *sampleCreator)); break; default: std::ostringstream oss; oss << "invalid pcb version: " << pcbVersion; throw bo::exception::Base(oss.str()); } //! set credentials/parameters for network connection bo::network::Creds creds; creds.setServername(servername); creds.setServerport(serverport); creds.setUsername(username); creds.setPassword(password); //! create object of network driver for sample transmission bo::network::Base::AP network(new bo::network::Base(creds, sleepTime, eventRateLimit, outputFile)); while (hardware->isOpen()) { bo::data::sample::Base::AP sample = hardware->read(); if (sample.get() != 0) { network->push(sample); } } } <commit_msg>fix error message<commit_after>/* Copyright (C) 2003-2010 Egon Wanke <blitzortung@gmx.org> Copyright (C) 2010 Andreas Würl <awuerl@gmx.net> */ #include <iostream> #include <string> #include <boost/program_options.hpp> #include "namespaces.h" #include "hardware/comm/SerialPort.h" #include "hardware/comm/Serial.h" #include "hardware/gps/Garmin.h" #include "hardware/gps/Sirf.h" #include "hardware/gps/Sjn.h" #include "hardware/pcb/V4.h" #include "hardware/pcb/V6.h" #include "data/sample/V1.h" #include "network/Base.h" #include "util/RingBuffer.h" #include "exception/Base.h" #include "Logger.h" int main(int argc, char **argv) { std::string username, password, servername; unsigned short serverport; std::string serialPortName = "/dev/ttyUSB0"; std::string outputFile = ""; int serialBaudRate = 19200; int sleepTime = 20; int sampleVersion = 1; int pcbVersion = 6; double eventRateLimit = 1.0; std::string gpsType = "sirf"; bo::Logger logger(""); // programm arguments/options boost::program_options::options_description desc("program options"); desc.add_options() ("help", "show program help") ("serial-device,d", po::value<std::string>(&serialPortName)->default_value(serialPortName), "path to serial device") ("baud-rate,b", po::value<int>(&serialBaudRate)->default_value(serialBaudRate), "baud rate of serial port (4800, 9600, 19200, 38400)") ("username,u", po::value<std::string>(&username), "username of blitzortung.org") ("password,p", po::value<std::string>(&password), "password of blitzortung.org") ("server-host,h", po::value<std::string>(&servername), "blitzortung.org servername") ("server-port", po::value<unsigned short>(&serverport)->default_value(8308), "blitzortung.org serverport") ("sleep-time,s", po::value<int>(&sleepTime)->default_value(sleepTime), "sleep time between data transmission") ("gps-type,g", po::value<std::string>(&gpsType)->default_value(gpsType), "type of gps device (sjn, garmin or sirf)") ("pcb-version", po::value<int>(&pcbVersion)->default_value(pcbVersion), "version of PCB (4 or 6)") ("event-rate-limit,l", po::value<double>(&eventRateLimit)->default_value(eventRateLimit), "limit of event rate (in events per second) 1.0 means max. 3600 events per hour") ("output,o", po::value<std::string>(&outputFile), "output file name (e.g. Name_%Y%m%d.bor)") ("verbose,v", "verbose mode") ("debug", "debug mode") ; // parse command line options po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); po::notify(vm); // help output or no 'sql-statement' given if (vm.count("help")) { std::cout << argv[0] << " [options]" << std::endl << std::endl; std::cout << desc << std::endl; std::cout << std::endl; return 1; } if (! vm.count("username")) { std::cerr << "'username' missing\n"; return 5; } if (! vm.count("password")) { std::cerr << "'password' missing\n"; return 5; } if (! vm.count("server-host")) { std::cerr << "'server-host' missing\n"; return 5; } // logging setup logger.setPriority(log4cpp::Priority::NOTICE); if (vm.count("verbose")) { logger.setPriority(log4cpp::Priority::INFO); } if (vm.count("debug")) { logger.setPriority(log4cpp::Priority::DEBUG); } switch (serialBaudRate) { case 4800: case 9600: case 19200: case 38400: break; default: std::ostringstream oss; oss << "invalid serial baud rate: " << serialBaudRate; throw bo::exception::Base(oss.str()); } // create serial port object bo::hardware::comm::SerialPort serialPort(serialPortName, serialBaudRate); bo::hardware::comm::Serial serial(serialPort); // select type of gps hardware bo::hardware::gps::Base::AP gps; if (gpsType == "garmin") { gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Garmin(serial)); } else if (gpsType == "sirf") { gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Sirf(serial)); } else if (gpsType == "sjn") { gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Sjn(serial)); } else { std::ostringstream oss; oss << "invalid value of gps-type: '" << gpsType << "'"; throw bo::exception::Base(oss.str()); } // create sample creator object std::auto_ptr<bo::data::sample::Base::Creator> sampleCreator; switch (sampleVersion) { case 1: sampleCreator = std::auto_ptr<bo::data::sample::Base::Creator>(new bo::data::sample::V1::Creator()); break; default: std::ostringstream oss; oss << "invalid sample version: " << sampleVersion; throw bo::exception::Base(oss.str()); } // create hardware driver object for blitzortung measurement hardware bo::hardware::pcb::Base::AP hardware; switch (pcbVersion) { case 4: hardware = bo::hardware::pcb::Base::AP(new bo::hardware::pcb::V4(serial, *gps, *sampleCreator)); break; case 6: hardware = bo::hardware::pcb::Base::AP(new bo::hardware::pcb::V6(serial, *gps, *sampleCreator)); break; default: std::ostringstream oss; oss << "invalid pcb version: " << pcbVersion; throw bo::exception::Base(oss.str()); } //! set credentials/parameters for network connection bo::network::Creds creds; creds.setServername(servername); creds.setServerport(serverport); creds.setUsername(username); creds.setPassword(password); //! create object of network driver for sample transmission bo::network::Base::AP network(new bo::network::Base(creds, sleepTime, eventRateLimit, outputFile)); while (hardware->isOpen()) { bo::data::sample::Base::AP sample = hardware->read(); if (sample.get() != 0) { network->push(sample); } } } <|endoftext|>
<commit_before>#include "StatScreen.h" #include "RenderTarget.h" #include "RenderContext.h" #include "gum/StringHelper.h" #include <gimg_typedef.h> #include <gimg_export.h> #include <unirender/UR_RenderContext.h> #include <dtex2/DebugDraw.h> #include <time.h> namespace gum { SINGLETON_DEFINITION(StatScreen); StatScreen::StatScreen() : m_enable(false) , m_rt(NULL) , m_x(0) , m_y(0) { } void StatScreen::Enable(bool enable) { if (m_enable == enable) { return; } m_enable = enable; if (enable) { m_rt = new RenderTarget(RT_EDGE, RT_EDGE); #ifdef __ANDROID__ std::string filepath = "/sdcard/lr_stat_screen.bin"; #else std::string filepath = "lr_stat_screen.bin"; #endif // __ANDROID__ m_fout.open(filepath.c_str(), std::ofstream::out | std::ofstream::binary | std::ofstream::app); } else { delete m_rt; m_fout.close(); } } void StatScreen::Print(const RenderTarget* src) { if (!m_enable) { return; } time_t t = time(NULL); m_timestamps[m_y * GRID_COUNT + m_x] = t; sm::rect r_src; r_src.xmin = r_src.ymin = 0; r_src.xmax = r_src.ymax = 1; sm::rect r_dst; static const float GRID_TEXCOORD_EDGE = 1.0f / GRID_COUNT; r_dst.xmin = static_cast<float>(m_x) / GRID_COUNT; r_dst.xmax = r_dst.xmin + GRID_TEXCOORD_EDGE; r_dst.ymin = static_cast<float>(m_y) / GRID_COUNT; r_dst.ymax = r_dst.ymin + GRID_TEXCOORD_EDGE; m_rt->Bind(); src->Draw(r_src, r_dst, RT_EDGE, RT_EDGE); m_rt->Unbind(); // to next grid ++m_x; if (m_x == GRID_COUNT) { m_x = 0; ++m_y; } if (m_y == GRID_COUNT) { m_y = 0; } } void StatScreen::Clear() { m_x = m_y = 0; memset(m_timestamps, 0, sizeof(m_timestamps)); } void StatScreen::Flush() { if (!m_enable) { return; } time_t first_time = m_timestamps[0]; for (int y = 0; y < GRID_COUNT; ++y) { for (int x = 0; x < GRID_COUNT; ++x) { int idx = y * GRID_COUNT + x; time_t time = m_timestamps[idx]; if (time != 0) { m_fout << "timestamp " << time << ", x " << x << ", y " << y << ", file " << first_time << ".png" << '\n'; } } } m_fout.flush(); int next = m_y * GRID_COUNT + m_x; m_rt->Bind(); uint8_t* pixels = new uint8_t[RT_EDGE * RT_EDGE * 3]; memset(pixels, 0, RT_EDGE * RT_EDGE * 3); RenderContext::Instance()->GetImpl()->ReadPixels(pixels, 3, 0, 0, RT_EDGE, RT_EDGE); std::string filepath = StringHelper::ToString(first_time) + ".png"; gimg_export(filepath.c_str(), pixels, RT_EDGE, RT_EDGE, GPF_RGB, true); delete[] pixels; m_rt->Unbind(); } void StatScreen::DebugDraw() const { if (m_enable) { int texid = m_rt->GetTexID(); dtex::DebugDraw::Draw(texid, 1); } } }<commit_msg>fix include<commit_after>#include "StatScreen.h" #include "RenderTarget.h" #include "RenderContext.h" #include "gum/StringHelper.h" #include <gimg_typedef.h> #include <gimg_export.h> #include <unirender/UR_RenderContext.h> #include <dtex2/DebugDraw.h> #include <time.h> #include <string.h> namespace gum { SINGLETON_DEFINITION(StatScreen); StatScreen::StatScreen() : m_enable(false) , m_rt(NULL) , m_x(0) , m_y(0) { } void StatScreen::Enable(bool enable) { if (m_enable == enable) { return; } m_enable = enable; if (enable) { m_rt = new RenderTarget(RT_EDGE, RT_EDGE); #ifdef __ANDROID__ std::string filepath = "/sdcard/lr_stat_screen.bin"; #else std::string filepath = "lr_stat_screen.bin"; #endif // __ANDROID__ m_fout.open(filepath.c_str(), std::ofstream::out | std::ofstream::binary | std::ofstream::app); } else { delete m_rt; m_fout.close(); } } void StatScreen::Print(const RenderTarget* src) { if (!m_enable) { return; } time_t t = time(NULL); m_timestamps[m_y * GRID_COUNT + m_x] = t; sm::rect r_src; r_src.xmin = r_src.ymin = 0; r_src.xmax = r_src.ymax = 1; sm::rect r_dst; static const float GRID_TEXCOORD_EDGE = 1.0f / GRID_COUNT; r_dst.xmin = static_cast<float>(m_x) / GRID_COUNT; r_dst.xmax = r_dst.xmin + GRID_TEXCOORD_EDGE; r_dst.ymin = static_cast<float>(m_y) / GRID_COUNT; r_dst.ymax = r_dst.ymin + GRID_TEXCOORD_EDGE; m_rt->Bind(); src->Draw(r_src, r_dst, RT_EDGE, RT_EDGE); m_rt->Unbind(); // to next grid ++m_x; if (m_x == GRID_COUNT) { m_x = 0; ++m_y; } if (m_y == GRID_COUNT) { m_y = 0; } } void StatScreen::Clear() { m_x = m_y = 0; memset(m_timestamps, 0, sizeof(m_timestamps)); } void StatScreen::Flush() { if (!m_enable) { return; } time_t first_time = m_timestamps[0]; for (int y = 0; y < GRID_COUNT; ++y) { for (int x = 0; x < GRID_COUNT; ++x) { int idx = y * GRID_COUNT + x; time_t time = m_timestamps[idx]; if (time != 0) { m_fout << "timestamp " << time << ", x " << x << ", y " << y << ", file " << first_time << ".png" << '\n'; } } } m_fout.flush(); int next = m_y * GRID_COUNT + m_x; m_rt->Bind(); uint8_t* pixels = new uint8_t[RT_EDGE * RT_EDGE * 3]; memset(pixels, 0, RT_EDGE * RT_EDGE * 3); RenderContext::Instance()->GetImpl()->ReadPixels(pixels, 3, 0, 0, RT_EDGE, RT_EDGE); std::string filepath = StringHelper::ToString(first_time) + ".png"; gimg_export(filepath.c_str(), pixels, RT_EDGE, RT_EDGE, GPF_RGB, true); delete[] pixels; m_rt->Unbind(); } void StatScreen::DebugDraw() const { if (m_enable) { int texid = m_rt->GetTexID(); dtex::DebugDraw::Draw(texid, 1); } } }<|endoftext|>
<commit_before>#include <efsw/FileWatcherWin32.hpp> #include <efsw/FileSystem.hpp> #include <efsw/System.hpp> #if EFSW_PLATFORM == EFSW_PLATFORM_WIN32 namespace efsw { FileWatcherWin32::FileWatcherWin32( FileWatcher * parent ) : FileWatcherImpl( parent ), mLastWatchID(0), mThread( NULL ) { mInitOK = true; } FileWatcherWin32::~FileWatcherWin32() { WatchVector::iterator iter = mWatches.begin(); for(; iter != mWatches.end(); ++iter) { DestroyWatch((*iter)); } mHandles.clear(); mWatches.clear(); mInitOK = false; mThread->wait(); efSAFE_DELETE( mThread ); } WatchID FileWatcherWin32::addWatch(const std::string& directory, FileWatchListener* watcher, bool recursive) { std::string dir( directory ); FileInfo fi( dir ); if ( !fi.isDirectory() ) { return Errors::Log::createLastError( Errors::FileNotFound, dir ); } else if ( !fi.isReadable() ) { return Errors::Log::createLastError( Errors::FileNotReadable, dir ); } FileSystem::dirAddSlashAtEnd( dir ); WatchID watchid = ++mLastWatchID; WatcherStructWin32 * watch = CreateWatch( dir.c_str(), recursive, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME ); if( NULL == watch ) { return Errors::Log::createLastError( Errors::FileNotFound, dir ); } if ( pathInWatches( dir ) ) { return Errors::Log::createLastError( Errors::FileRepeated, dir ); } // Add the handle to the handles vector watch->Watch->ID = watchid; watch->Watch->Watch = this; watch->Watch->Listener = watcher; watch->Watch->DirName = new char[dir.length()+1]; strcpy(watch->Watch->DirName, dir.c_str()); mWatchesLock.lock(); mHandles.push_back( watch->Watch->DirHandle ); mWatches.push_back( watch ); mWatchesLock.unlock(); return watchid; } void FileWatcherWin32::removeWatch(const std::string& directory) { mWatchesLock.lock(); WatchVector::iterator iter = mWatches.begin(); for(; iter != mWatches.end(); ++iter) { if(directory == (*iter)->Watch->DirName) { removeWatch((*iter)->Watch->ID); return; } } mWatchesLock.unlock(); } void FileWatcherWin32::removeWatch(WatchID watchid) { mWatchesLock.lock(); WatchVector::iterator iter = mWatches.begin(); WatcherStructWin32* watch = NULL; for(; iter != mWatches.end(); ++iter) { // Find the watch ID if ( (*iter)->Watch->ID == watchid ) { watch = (*iter); mWatches.erase( iter ); // Remove handle from the handle vector HandleVector::iterator it = mHandles.begin(); for ( ; it != mHandles.end(); it++ ) { if ( watch->Watch->DirHandle == (*it) ) { mHandles.erase( it ); break; } } DestroyWatch(watch); break; } } mWatchesLock.unlock(); } void FileWatcherWin32::watch() { if ( NULL == mThread ) { mThread = new Thread( &FileWatcherWin32::run, this ); mThread->launch(); } } void FileWatcherWin32::run() { do { DWORD wait_result = WaitForMultipleObjectsEx( mHandles.size(), &mHandles[0], FALSE, 1000, FALSE ); switch ( wait_result ) { case WAIT_ABANDONED_0: case WAIT_ABANDONED_0 + 1: //"Wait abandoned." break; case WAIT_TIMEOUT: break; case WAIT_FAILED: //"Wait failed." break; default: { mWatchesLock.lock(); // Don't trust the result - multiple objects may be signalled during a single call. if ( wait_result >= WAIT_OBJECT_0 && wait_result < WAIT_OBJECT_0 + mWatches.size() ) { WatcherStructWin32 * watch = mWatches[ wait_result ]; // First ensure that the handle is the same, this means that the watch was not removed. if ( mHandles[ wait_result ] == watch->Watch->DirHandle && HasOverlappedIoCompleted( &watch->Overlapped ) ) { DWORD bytes; if ( GetOverlappedResult( watch->Watch->DirHandle, &watch->Overlapped, &bytes, FALSE ) ) { WatchCallback( ERROR_SUCCESS, bytes, &watch->Overlapped ); } else { //"GetOverlappedResult failed." } break; } } else { //"Unknown return value from WaitForMultipleObjectsEx." } mWatchesLock.unlock(); } } } while ( mInitOK ); } void FileWatcherWin32::handleAction(Watcher* watch, const std::string& filename, unsigned long action, std::string oldFilename) { Action fwAction; switch(action) { case FILE_ACTION_RENAMED_OLD_NAME: watch->OldFileName = filename; break; case FILE_ACTION_ADDED: fwAction = Actions::Add; break; case FILE_ACTION_RENAMED_NEW_NAME: { fwAction = Actions::Moved; std::string fpath( watch->Directory + filename ); // Update the directory path if ( watch->Recursive && FileSystem::isDirectory( fpath ) ) { // Update the new directory path std::string opath( watch->Directory + watch->OldFileName ); FileSystem::dirAddSlashAtEnd( opath ); FileSystem::dirAddSlashAtEnd( fpath ); for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { if ( (*it)->Watch->Directory == opath ) { (*it)->Watch->Directory = fpath; break; } } } watch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction, watch->OldFileName); return; } case FILE_ACTION_REMOVED: fwAction = Actions::Delete; break; case FILE_ACTION_MODIFIED: fwAction = Actions::Modified; break; }; watch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction); } std::list<std::string> FileWatcherWin32::directories() { std::list<std::string> dirs; mWatchesLock.lock(); for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { dirs.push_back( std::string( (*it)->Watch->DirName ) ); } mWatchesLock.unlock(); return dirs; } bool FileWatcherWin32::pathInWatches( const std::string& path ) { for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { if ( (*it)->Watch->DirName == path ) { return true; } } return false; } } #endif <commit_msg>Small fix in Win32 backend.<commit_after>#include <efsw/FileWatcherWin32.hpp> #include <efsw/FileSystem.hpp> #include <efsw/System.hpp> #if EFSW_PLATFORM == EFSW_PLATFORM_WIN32 namespace efsw { FileWatcherWin32::FileWatcherWin32( FileWatcher * parent ) : FileWatcherImpl( parent ), mLastWatchID(0), mThread( NULL ) { mInitOK = true; } FileWatcherWin32::~FileWatcherWin32() { WatchVector::iterator iter = mWatches.begin(); for(; iter != mWatches.end(); ++iter) { DestroyWatch((*iter)); } mHandles.clear(); mWatches.clear(); mInitOK = false; mThread->wait(); efSAFE_DELETE( mThread ); } WatchID FileWatcherWin32::addWatch(const std::string& directory, FileWatchListener* watcher, bool recursive) { std::string dir( directory ); FileInfo fi( dir ); if ( !fi.isDirectory() ) { return Errors::Log::createLastError( Errors::FileNotFound, dir ); } else if ( !fi.isReadable() ) { return Errors::Log::createLastError( Errors::FileNotReadable, dir ); } FileSystem::dirAddSlashAtEnd( dir ); WatchID watchid = ++mLastWatchID; WatcherStructWin32 * watch = CreateWatch( dir.c_str(), recursive, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME ); if( NULL == watch ) { return Errors::Log::createLastError( Errors::FileNotFound, dir ); } if ( pathInWatches( dir ) ) { return Errors::Log::createLastError( Errors::FileRepeated, dir ); } // Add the handle to the handles vector watch->Watch->ID = watchid; watch->Watch->Watch = this; watch->Watch->Listener = watcher; watch->Watch->DirName = new char[dir.length()+1]; strcpy(watch->Watch->DirName, dir.c_str()); mWatchesLock.lock(); mHandles.push_back( watch->Watch->DirHandle ); mWatches.push_back( watch ); mWatchesLock.unlock(); return watchid; } void FileWatcherWin32::removeWatch(const std::string& directory) { mWatchesLock.lock(); WatchVector::iterator iter = mWatches.begin(); for(; iter != mWatches.end(); ++iter) { if(directory == (*iter)->Watch->DirName) { removeWatch((*iter)->Watch->ID); return; } } mWatchesLock.unlock(); } void FileWatcherWin32::removeWatch(WatchID watchid) { mWatchesLock.lock(); WatchVector::iterator iter = mWatches.begin(); WatcherStructWin32* watch = NULL; for(; iter != mWatches.end(); ++iter) { // Find the watch ID if ( (*iter)->Watch->ID == watchid ) { watch = (*iter); mWatches.erase( iter ); // Remove handle from the handle vector HandleVector::iterator it = mHandles.begin(); for ( ; it != mHandles.end(); it++ ) { if ( watch->Watch->DirHandle == (*it) ) { mHandles.erase( it ); break; } } DestroyWatch(watch); break; } } mWatchesLock.unlock(); } void FileWatcherWin32::watch() { if ( NULL == mThread ) { mThread = new Thread( &FileWatcherWin32::run, this ); mThread->launch(); } } void FileWatcherWin32::run() { do { DWORD wait_result = WaitForMultipleObjectsEx( mHandles.size(), &mHandles[0], FALSE, 1000, FALSE ); switch ( wait_result ) { case WAIT_ABANDONED_0: case WAIT_ABANDONED_0 + 1: //"Wait abandoned." break; case WAIT_TIMEOUT: break; case WAIT_FAILED: //"Wait failed." break; default: { mWatchesLock.lock(); // Don't trust the result - multiple objects may be signalled during a single call. if ( wait_result >= WAIT_OBJECT_0 && wait_result < WAIT_OBJECT_0 + mWatches.size() ) { WatcherStructWin32 * watch = mWatches[ wait_result ]; // First ensure that the handle is the same, this means that the watch was not removed. if ( mHandles[ wait_result ] == watch->Watch->DirHandle && HasOverlappedIoCompleted( &watch->Overlapped ) ) { DWORD bytes; if ( GetOverlappedResult( watch->Watch->DirHandle, &watch->Overlapped, &bytes, FALSE ) ) { WatchCallback( ERROR_SUCCESS, bytes, &watch->Overlapped ); } else { //"GetOverlappedResult failed." } break; } } else { //"Unknown return value from WaitForMultipleObjectsEx." } mWatchesLock.unlock(); } } } while ( mInitOK ); } void FileWatcherWin32::handleAction(Watcher* watch, const std::string& filename, unsigned long action, std::string oldFilename) { Action fwAction; switch(action) { case FILE_ACTION_RENAMED_OLD_NAME: watch->OldFileName = filename; return; case FILE_ACTION_ADDED: fwAction = Actions::Add; break; case FILE_ACTION_RENAMED_NEW_NAME: { fwAction = Actions::Moved; std::string fpath( watch->Directory + filename ); // Update the directory path if ( watch->Recursive && FileSystem::isDirectory( fpath ) ) { // Update the new directory path std::string opath( watch->Directory + watch->OldFileName ); FileSystem::dirAddSlashAtEnd( opath ); FileSystem::dirAddSlashAtEnd( fpath ); for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { if ( (*it)->Watch->Directory == opath ) { (*it)->Watch->Directory = fpath; break; } } } watch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction, watch->OldFileName); return; } case FILE_ACTION_REMOVED: fwAction = Actions::Delete; break; case FILE_ACTION_MODIFIED: fwAction = Actions::Modified; break; }; watch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction); } std::list<std::string> FileWatcherWin32::directories() { std::list<std::string> dirs; mWatchesLock.lock(); for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { dirs.push_back( std::string( (*it)->Watch->DirName ) ); } mWatchesLock.unlock(); return dirs; } bool FileWatcherWin32::pathInWatches( const std::string& path ) { for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { if ( (*it)->Watch->DirName == path ) { return true; } } return false; } } #endif <|endoftext|>
<commit_before>/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *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 Redis 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. */ #include "rocksdb_engine.hpp" #include "codec.hpp" #include "util/helpers.hpp" #include "rocksdb/env.h" #include "rocksdb/rate_limiter.h" #include "rocksdb/table.h" #include <string.h> #include <stdarg.h> #define ROCKSDB_SLICE(slice) rocksdb::Slice(slice.data(), slice.size()) #define ARDB_SLICE(slice) Slice(slice.data(), slice.size()) namespace ardb { class RocksDBLogger: public rocksdb::Logger { private: void Logv(const char* format, va_list ap) { char logbuf[1024]; int len = vsnprintf(logbuf, sizeof(logbuf), format, ap); if(len < sizeof(logbuf)) { INFO_LOG(logbuf); } } }; int RocksDBComparator::Compare(const rocksdb::Slice& a, const rocksdb::Slice& b) const { return CommonComparator::Compare(a.data(), a.size(), b.data(), b.size()); } void RocksDBComparator::FindShortestSeparator(std::string* start, const rocksdb::Slice& limit) const { } void RocksDBComparator::FindShortSuccessor(std::string* key) const { } RocksDBEngineFactory::RocksDBEngineFactory(const Properties& props) { ParseConfig(props, m_cfg); } void RocksDBEngineFactory::ParseConfig(const Properties& props, RocksDBConfig& cfg) { cfg.path = "."; conf_get_string(props, "data-dir", cfg.path); conf_get_int64(props, "rocksdb.block_cache_size", cfg.block_cache_size); conf_get_int64(props, "rocksdb.block_cache_compressed", cfg.block_cache_compressed_size); conf_get_int64(props, "rocksdb.write_buffer_size", cfg.write_buffer_size); conf_get_int64(props, "rocksdb.max_open_files", cfg.max_open_files); conf_get_int64(props, "rocksdb.block_size", cfg.block_size); conf_get_int64(props, "rocksdb.block_restart_interval", cfg.block_restart_interval); conf_get_int64(props, "rocksdb.bloom_bits", cfg.bloom_bits); conf_get_int64(props, "rocksdb.batch_commit_watermark", cfg.batch_commit_watermark); conf_get_string(props, "rocksdb.compression", cfg.compression); conf_get_bool(props, "rocksdb.logenable", cfg.logenable); conf_get_bool(props, "rocksdb.skip_log_error_on_recovery", cfg.skip_log_error_on_recovery); conf_get_int64(props, "rocksdb.flush_compact_rate_bytes_per_sec", cfg.flush_compact_rate_bytes_per_sec); conf_get_double(props, "rocksdb.hard_rate_limit", cfg.hard_rate_limit); conf_get_bool(props, "rocksdb.disableWAL", cfg.disableWAL); conf_get_int64(props, "rocksdb.max_manifest_file_size", cfg.max_manifest_file_size); conf_get_string(props, "rocksdb.compacton_style", cfg.compacton_style); } KeyValueEngine* RocksDBEngineFactory::CreateDB(const std::string& name) { RocksDBEngine* engine = new RocksDBEngine(); RocksDBConfig cfg = m_cfg; char tmp[cfg.path.size() + name.size() + 10]; sprintf(tmp, "%s/%s", cfg.path.c_str(), name.c_str()); cfg.path = tmp; if (engine->Init(cfg) != 0) { DELETE(engine); ERROR_LOG("Failed to create DB:%s", name.c_str()); return NULL; } return engine; } void RocksDBEngineFactory::DestroyDB(KeyValueEngine* engine) { RocksDBEngine* RocksDB = (RocksDBEngine*) engine; std::string path = RocksDB->m_db_path; DELETE(engine); rocksdb::Options options; rocksdb::DestroyDB(path, options); } void RocksDBEngineFactory::CloseDB(KeyValueEngine* engine) { DELETE(engine); } void RocksDBIterator::SeekToFirst() { m_iter->SeekToFirst(); } void RocksDBIterator::SeekToLast() { m_iter->SeekToLast(); } void RocksDBIterator::Seek(const Slice& target) { m_iter->Seek(ROCKSDB_SLICE(target)); } void RocksDBIterator::Next() { m_iter->Next(); } void RocksDBIterator::Prev() { m_iter->Prev(); } Slice RocksDBIterator::Key() const { return ARDB_SLICE(m_iter->key()); } Slice RocksDBIterator::Value() const { return ARDB_SLICE(m_iter->value()); } bool RocksDBIterator::Valid() { return m_iter->Valid(); } RocksDBEngine::RocksDBEngine() : m_db(NULL) { } RocksDBEngine::~RocksDBEngine() { DELETE(m_db); } int RocksDBEngine::Init(const RocksDBConfig& cfg) { m_cfg = cfg; m_options.create_if_missing = true; m_options.comparator = &m_comparator; rocksdb::BlockBasedTableOptions block_options; if (cfg.block_cache_size > 0) { block_options.block_cache = rocksdb::NewLRUCache(cfg.block_cache_size); //m_options.block_cache_compressed = rocksdb::NewLRUCache(cfg.block_cache_compressed_size); }else if(cfg.block_cache_size < 0) { block_options.no_block_cache = true; } if (cfg.block_size > 0) { block_options.block_size = cfg.block_size; } if (cfg.block_restart_interval > 0) { block_options.block_restart_interval = cfg.block_restart_interval; } m_options.table_factory.reset(rocksdb::NewBlockBasedTableFactory(block_options)); if (cfg.write_buffer_size > 0) { m_options.write_buffer_size = cfg.write_buffer_size; } m_options.max_open_files = cfg.max_open_files; if (cfg.bloom_bits > 0) { block_options.filter_policy = rocksdb::NewBloomFilterPolicy(cfg.bloom_bits); } if (!strcasecmp(cfg.compression.c_str(), "none")) { m_options.compression = rocksdb::kNoCompression; } else { m_options.compression = rocksdb::kSnappyCompression; } if(cfg.flush_compact_rate_bytes_per_sec > 0) { m_options.rate_limiter.reset(rocksdb::NewGenericRateLimiter(cfg.flush_compact_rate_bytes_per_sec)); } m_options.hard_rate_limit = cfg.hard_rate_limit; if(m_cfg.max_manifest_file_size > 0) { m_options.max_manifest_file_size = m_cfg.max_manifest_file_size; } if(!strcasecmp(m_cfg.compacton_style.c_str(), "universal")) { m_options.OptimizeUniversalStyleCompaction(); }else { m_options.OptimizeLevelStyleCompaction(); } m_options.IncreaseParallelism(); if(cfg.logenable) { m_options.info_log.reset(new RocksDBLogger); } make_dir(cfg.path); m_db_path = cfg.path; rocksdb::Status status = rocksdb::DB::Open(m_options, cfg.path.c_str(), &m_db); do { if (status.ok()) { break; } else if (status.IsCorruption()) { ERROR_LOG("Failed to init engine:%s", status.ToString().c_str()); status = rocksdb::RepairDB(cfg.path.c_str(), m_options); if (!status.ok()) { ERROR_LOG("Failed to repair:%s for %s", cfg.path.c_str(), status.ToString().c_str()); return -1; } status = rocksdb::DB::Open(m_options, cfg.path.c_str(), &m_db); } else { ERROR_LOG("Failed to init engine:%s", status.ToString().c_str()); break; } } while (1); return status.ok() ? 0 : -1; } int RocksDBEngine::BeginBatchWrite() { m_context.GetValue().AddRef(); return 0; } int RocksDBEngine::CommitBatchWrite() { ContextHolder& holder = m_context.GetValue(); holder.ReleaseRef(); if (holder.EmptyRef()) { return FlushWriteBatch(holder); } return 0; } int RocksDBEngine::DiscardBatchWrite() { ContextHolder& holder = m_context.GetValue(); holder.ReleaseRef(); holder.Clear(); return 0; } int RocksDBEngine::FlushWriteBatch(ContextHolder& holder) { rocksdb::WriteOptions options; options.disableWAL = m_cfg.disableWAL; rocksdb::Status s = m_db->Write(options, &holder.batch); holder.Clear(); return s.ok() ? 0 : -1; } void RocksDBEngine::CompactRange(const Slice& begin, const Slice& end) { rocksdb::Slice s(begin.data(), begin.size()); rocksdb::Slice e(end.data(), end.size()); rocksdb::Slice* start = s.size() > 0 ? &s : NULL; rocksdb::Slice* endpos = e.size() > 0 ? &e : NULL; m_db->CompactRange(start, endpos); } void RocksDBEngine::ContextHolder::Put(const Slice& key, const Slice& value) { batch.Put(ROCKSDB_SLICE(key), ROCKSDB_SLICE(value)); count++; } void RocksDBEngine::ContextHolder::Del(const Slice& key) { batch.Delete(ROCKSDB_SLICE(key)); count++; } int RocksDBEngine::Put(const Slice& key, const Slice& value, const Options& options) { rocksdb::Status s = rocksdb::Status::OK(); ContextHolder& holder = m_context.GetValue(); if (!holder.EmptyRef()) { holder.Put(key, value); if (holder.count >= (uint32) m_cfg.batch_commit_watermark) { FlushWriteBatch(holder); } } else { rocksdb::WriteOptions options; options.disableWAL = m_cfg.disableWAL; s = m_db->Put(options, ROCKSDB_SLICE(key), ROCKSDB_SLICE(value)); } return s.ok() ? 0 : -1; } int RocksDBEngine::Get(const Slice& key, std::string* value, const Options& options) { rocksdb::ReadOptions read_options; read_options.fill_cache = options.read_fill_cache; read_options.verify_checksums = false; ContextHolder& holder = m_context.GetValue(); read_options.snapshot = holder.snapshot; rocksdb::Status s = m_db->Get(read_options, ROCKSDB_SLICE(key), value); return s.ok() ? 0 : -1; } int RocksDBEngine::Del(const Slice& key, const Options& options) { rocksdb::Status s = rocksdb::Status::OK(); ContextHolder& holder = m_context.GetValue(); if (!holder.EmptyRef()) { holder.Del(key); if (holder.count >= (uint32) m_cfg.batch_commit_watermark) { FlushWriteBatch(holder); } } else { s = m_db->Delete(rocksdb::WriteOptions(), ROCKSDB_SLICE(key)); } return s.ok() ? 0 : -1; } Iterator* RocksDBEngine::Find(const Slice& findkey, const Options& options) { rocksdb::ReadOptions read_options; read_options.fill_cache = options.seek_fill_cache; ContextHolder& holder = m_context.GetValue(); if (NULL == holder.snapshot) { holder.snapshot = m_db->GetSnapshot(); } holder.snapshot_ref++; read_options.snapshot = holder.snapshot; rocksdb::Iterator* iter = m_db->NewIterator(read_options); iter->Seek(ROCKSDB_SLICE(findkey)); return new RocksDBIterator(this, iter); } void RocksDBEngine::ReleaseContextSnapshot() { ContextHolder& holder = m_context.GetValue(); if (NULL != holder.snapshot) { holder.snapshot_ref--; if (holder.snapshot_ref == 0) { m_db->ReleaseSnapshot(holder.snapshot); holder.snapshot = NULL; } } } const std::string RocksDBEngine::Stats() { std::string str, version_info; m_db->GetProperty("rocksdb.stats", &str); std::string numkeys; m_db->GetProperty("rocksdb.estimate-num-keys", &numkeys); numkeys = "estimate-num-keys: " + numkeys + "\r\n"; version_info.append("RocksDB version:").append(stringfromll(rocksdb::kMajorVersion)).append(".").append( stringfromll(rocksdb::kMinorVersion)).append(".").append(stringfromll(ROCKSDB_PATCH)).append("\r\n"); return version_info + numkeys + str; } int RocksDBEngine::MaxOpenFiles() { return m_options.max_open_files; } RocksDBIterator::~RocksDBIterator() { delete m_iter; m_engine->ReleaseContextSnapshot(); } } <commit_msg>fix compile error wirh rocksdb<commit_after>/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *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 Redis 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. */ #include "rocksdb_engine.hpp" #include "codec.hpp" #include "util/helpers.hpp" #include "rocksdb/env.h" #include "rocksdb/rate_limiter.h" #include "rocksdb/table.h" #include <string.h> #include <stdarg.h> #define ROCKSDB_SLICE(slice) rocksdb::Slice(slice.data(), slice.size()) #define ARDB_SLICE(slice) Slice(slice.data(), slice.size()) namespace ardb { class RocksDBLogger: public rocksdb::Logger { private: void Logv(const char* format, va_list ap) { char logbuf[1024]; int len = vsnprintf(logbuf, sizeof(logbuf), format, ap); if(len < sizeof(logbuf)) { INFO_LOG(logbuf); } } }; int RocksDBComparator::Compare(const rocksdb::Slice& a, const rocksdb::Slice& b) const { return CommonComparator::Compare(a.data(), a.size(), b.data(), b.size()); } void RocksDBComparator::FindShortestSeparator(std::string* start, const rocksdb::Slice& limit) const { } void RocksDBComparator::FindShortSuccessor(std::string* key) const { } RocksDBEngineFactory::RocksDBEngineFactory(const Properties& props) { ParseConfig(props, m_cfg); } void RocksDBEngineFactory::ParseConfig(const Properties& props, RocksDBConfig& cfg) { cfg.path = "."; conf_get_string(props, "data-dir", cfg.path); conf_get_int64(props, "rocksdb.block_cache_size", cfg.block_cache_size); conf_get_int64(props, "rocksdb.block_cache_compressed", cfg.block_cache_compressed_size); conf_get_int64(props, "rocksdb.write_buffer_size", cfg.write_buffer_size); conf_get_int64(props, "rocksdb.max_open_files", cfg.max_open_files); conf_get_int64(props, "rocksdb.block_size", cfg.block_size); conf_get_int64(props, "rocksdb.block_restart_interval", cfg.block_restart_interval); conf_get_int64(props, "rocksdb.bloom_bits", cfg.bloom_bits); conf_get_int64(props, "rocksdb.batch_commit_watermark", cfg.batch_commit_watermark); conf_get_string(props, "rocksdb.compression", cfg.compression); conf_get_bool(props, "rocksdb.logenable", cfg.logenable); conf_get_bool(props, "rocksdb.skip_log_error_on_recovery", cfg.skip_log_error_on_recovery); conf_get_int64(props, "rocksdb.flush_compact_rate_bytes_per_sec", cfg.flush_compact_rate_bytes_per_sec); conf_get_double(props, "rocksdb.hard_rate_limit", cfg.hard_rate_limit); conf_get_bool(props, "rocksdb.disableWAL", cfg.disableWAL); conf_get_int64(props, "rocksdb.max_manifest_file_size", cfg.max_manifest_file_size); conf_get_string(props, "rocksdb.compacton_style", cfg.compacton_style); } KeyValueEngine* RocksDBEngineFactory::CreateDB(const std::string& name) { RocksDBEngine* engine = new RocksDBEngine(); RocksDBConfig cfg = m_cfg; char tmp[cfg.path.size() + name.size() + 10]; sprintf(tmp, "%s/%s", cfg.path.c_str(), name.c_str()); cfg.path = tmp; if (engine->Init(cfg) != 0) { DELETE(engine); ERROR_LOG("Failed to create DB:%s", name.c_str()); return NULL; } return engine; } void RocksDBEngineFactory::DestroyDB(KeyValueEngine* engine) { RocksDBEngine* RocksDB = (RocksDBEngine*) engine; std::string path = RocksDB->m_db_path; DELETE(engine); rocksdb::Options options; rocksdb::DestroyDB(path, options); } void RocksDBEngineFactory::CloseDB(KeyValueEngine* engine) { DELETE(engine); } void RocksDBIterator::SeekToFirst() { m_iter->SeekToFirst(); } void RocksDBIterator::SeekToLast() { m_iter->SeekToLast(); } void RocksDBIterator::Seek(const Slice& target) { m_iter->Seek(ROCKSDB_SLICE(target)); } void RocksDBIterator::Next() { m_iter->Next(); } void RocksDBIterator::Prev() { m_iter->Prev(); } Slice RocksDBIterator::Key() const { return ARDB_SLICE(m_iter->key()); } Slice RocksDBIterator::Value() const { return ARDB_SLICE(m_iter->value()); } bool RocksDBIterator::Valid() { return m_iter->Valid(); } RocksDBEngine::RocksDBEngine() : m_db(NULL) { } RocksDBEngine::~RocksDBEngine() { DELETE(m_db); } int RocksDBEngine::Init(const RocksDBConfig& cfg) { m_cfg = cfg; m_options.create_if_missing = true; m_options.comparator = &m_comparator; rocksdb::BlockBasedTableOptions block_options; if (cfg.block_cache_size > 0) { block_options.block_cache = rocksdb::NewLRUCache(cfg.block_cache_size); //m_options.block_cache_compressed = rocksdb::NewLRUCache(cfg.block_cache_compressed_size); }else if(cfg.block_cache_size < 0) { block_options.no_block_cache = true; } if (cfg.block_size > 0) { block_options.block_size = cfg.block_size; } if (cfg.block_restart_interval > 0) { block_options.block_restart_interval = cfg.block_restart_interval; } if (cfg.bloom_bits > 0) { block_options.filter_policy.reset(rocksdb::NewBloomFilterPolicy(cfg.bloom_bits)); } m_options.table_factory.reset(rocksdb::NewBlockBasedTableFactory(block_options)); if (cfg.write_buffer_size > 0) { m_options.write_buffer_size = cfg.write_buffer_size; } m_options.max_open_files = cfg.max_open_files; if (!strcasecmp(cfg.compression.c_str(), "none")) { m_options.compression = rocksdb::kNoCompression; } else { m_options.compression = rocksdb::kSnappyCompression; } if(cfg.flush_compact_rate_bytes_per_sec > 0) { m_options.rate_limiter.reset(rocksdb::NewGenericRateLimiter(cfg.flush_compact_rate_bytes_per_sec)); } m_options.hard_rate_limit = cfg.hard_rate_limit; if(m_cfg.max_manifest_file_size > 0) { m_options.max_manifest_file_size = m_cfg.max_manifest_file_size; } if(!strcasecmp(m_cfg.compacton_style.c_str(), "universal")) { m_options.OptimizeUniversalStyleCompaction(); }else { m_options.OptimizeLevelStyleCompaction(); } m_options.IncreaseParallelism(); if(cfg.logenable) { m_options.info_log.reset(new RocksDBLogger); } make_dir(cfg.path); m_db_path = cfg.path; rocksdb::Status status = rocksdb::DB::Open(m_options, cfg.path.c_str(), &m_db); do { if (status.ok()) { break; } else if (status.IsCorruption()) { ERROR_LOG("Failed to init engine:%s", status.ToString().c_str()); status = rocksdb::RepairDB(cfg.path.c_str(), m_options); if (!status.ok()) { ERROR_LOG("Failed to repair:%s for %s", cfg.path.c_str(), status.ToString().c_str()); return -1; } status = rocksdb::DB::Open(m_options, cfg.path.c_str(), &m_db); } else { ERROR_LOG("Failed to init engine:%s", status.ToString().c_str()); break; } } while (1); return status.ok() ? 0 : -1; } int RocksDBEngine::BeginBatchWrite() { m_context.GetValue().AddRef(); return 0; } int RocksDBEngine::CommitBatchWrite() { ContextHolder& holder = m_context.GetValue(); holder.ReleaseRef(); if (holder.EmptyRef()) { return FlushWriteBatch(holder); } return 0; } int RocksDBEngine::DiscardBatchWrite() { ContextHolder& holder = m_context.GetValue(); holder.ReleaseRef(); holder.Clear(); return 0; } int RocksDBEngine::FlushWriteBatch(ContextHolder& holder) { rocksdb::WriteOptions options; options.disableWAL = m_cfg.disableWAL; rocksdb::Status s = m_db->Write(options, &holder.batch); holder.Clear(); return s.ok() ? 0 : -1; } void RocksDBEngine::CompactRange(const Slice& begin, const Slice& end) { rocksdb::Slice s(begin.data(), begin.size()); rocksdb::Slice e(end.data(), end.size()); rocksdb::Slice* start = s.size() > 0 ? &s : NULL; rocksdb::Slice* endpos = e.size() > 0 ? &e : NULL; m_db->CompactRange(start, endpos); } void RocksDBEngine::ContextHolder::Put(const Slice& key, const Slice& value) { batch.Put(ROCKSDB_SLICE(key), ROCKSDB_SLICE(value)); count++; } void RocksDBEngine::ContextHolder::Del(const Slice& key) { batch.Delete(ROCKSDB_SLICE(key)); count++; } int RocksDBEngine::Put(const Slice& key, const Slice& value, const Options& options) { rocksdb::Status s = rocksdb::Status::OK(); ContextHolder& holder = m_context.GetValue(); if (!holder.EmptyRef()) { holder.Put(key, value); if (holder.count >= (uint32) m_cfg.batch_commit_watermark) { FlushWriteBatch(holder); } } else { rocksdb::WriteOptions options; options.disableWAL = m_cfg.disableWAL; s = m_db->Put(options, ROCKSDB_SLICE(key), ROCKSDB_SLICE(value)); } return s.ok() ? 0 : -1; } int RocksDBEngine::Get(const Slice& key, std::string* value, const Options& options) { rocksdb::ReadOptions read_options; read_options.fill_cache = options.read_fill_cache; read_options.verify_checksums = false; ContextHolder& holder = m_context.GetValue(); read_options.snapshot = holder.snapshot; rocksdb::Status s = m_db->Get(read_options, ROCKSDB_SLICE(key), value); return s.ok() ? 0 : -1; } int RocksDBEngine::Del(const Slice& key, const Options& options) { rocksdb::Status s = rocksdb::Status::OK(); ContextHolder& holder = m_context.GetValue(); if (!holder.EmptyRef()) { holder.Del(key); if (holder.count >= (uint32) m_cfg.batch_commit_watermark) { FlushWriteBatch(holder); } } else { s = m_db->Delete(rocksdb::WriteOptions(), ROCKSDB_SLICE(key)); } return s.ok() ? 0 : -1; } Iterator* RocksDBEngine::Find(const Slice& findkey, const Options& options) { rocksdb::ReadOptions read_options; read_options.fill_cache = options.seek_fill_cache; ContextHolder& holder = m_context.GetValue(); if (NULL == holder.snapshot) { holder.snapshot = m_db->GetSnapshot(); } holder.snapshot_ref++; read_options.snapshot = holder.snapshot; rocksdb::Iterator* iter = m_db->NewIterator(read_options); iter->Seek(ROCKSDB_SLICE(findkey)); return new RocksDBIterator(this, iter); } void RocksDBEngine::ReleaseContextSnapshot() { ContextHolder& holder = m_context.GetValue(); if (NULL != holder.snapshot) { holder.snapshot_ref--; if (holder.snapshot_ref == 0) { m_db->ReleaseSnapshot(holder.snapshot); holder.snapshot = NULL; } } } const std::string RocksDBEngine::Stats() { std::string str, version_info; m_db->GetProperty("rocksdb.stats", &str); std::string numkeys; m_db->GetProperty("rocksdb.estimate-num-keys", &numkeys); numkeys = "estimate-num-keys: " + numkeys + "\r\n"; version_info.append("RocksDB version:").append(stringfromll(rocksdb::kMajorVersion)).append(".").append( stringfromll(rocksdb::kMinorVersion)).append(".").append(stringfromll(ROCKSDB_PATCH)).append("\r\n"); return version_info + numkeys + str; } int RocksDBEngine::MaxOpenFiles() { return m_options.max_open_files; } RocksDBIterator::~RocksDBIterator() { delete m_iter; m_engine->ReleaseContextSnapshot(); } } <|endoftext|>
<commit_before>// RUN: cat %s | %cling | FileCheck %s // This test makes sure the interpreter doesn't create many useless empty // transactions. // Author: Vassil Vassilev #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/Decl.h" #include <stdio.h> .rawInput 1 using namespace cling; void generateNestedTransaction(int depth) { if (!depth) return; cling::Interpreter::PushTransactionRAII RAIIT(gCling); if (depth | 0x1) { // if odd char buff[100]; sprintf(buff, "int i%d;", depth); gCling->process(buff); } // this will cause every even transaction to be reused. generateNestedTransaction(--depth); } .rawInput 0 generateNestedTransaction(5); const cling::Transaction* T = gCling->getFirstTransaction(); while(T) { if (!T->size()) printf("Empty transaction detected!\n"); if (T->getWrapperFD()->getKind() != clang::Decl::Function) printf("Unexpected wrapper kind!\n"); if (T->getState() != Transaction::kCommitted) printf("Unexpected transaction state!\n"); //T->printStructure(); T = T->getNext(); } printf("Just make FileCheck(CHECK-NOT) happy.\n") //CHECK-NOT:Empty transaction detected! //CHECK-NOT:Unexpected wrapper kind! //CHECK-NOT:Unexpected transaction state! .q <commit_msg>Some transactions don't have a wrapper.<commit_after>// RUN: cat %s | %cling | FileCheck %s // This test makes sure the interpreter doesn't create many useless empty // transactions. // Author: Vassil Vassilev #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/Decl.h" #include <stdio.h> .rawInput 1 using namespace cling; void generateNestedTransaction(int depth) { if (!depth) return; cling::Interpreter::PushTransactionRAII RAIIT(gCling); if (depth | 0x1) { // if odd char buff[100]; sprintf(buff, "int i%d;", depth); gCling->process(buff); } // this will cause every even transaction to be reused. generateNestedTransaction(--depth); } .rawInput 0 generateNestedTransaction(5); const cling::Transaction* T = gCling->getFirstTransaction(); while(T) { if (!T->size()) printf("Empty transaction detected!\n"); else if (T->getWrapperFD() && T->getWrapperFD()->getKind() != clang::Decl::Function) printf("Unexpected wrapper kind!\n"); if (T->getState() != Transaction::kCommitted) printf("Unexpected transaction state!\n"); //T->printStructure(); T = T->getNext(); } printf("Just make FileCheck(CHECK-NOT) happy.\n") //CHECK-NOT:Empty transaction detected! //CHECK-NOT:Unexpected wrapper kind! //CHECK-NOT:Unexpected transaction state! .q <|endoftext|>
<commit_before>/** * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io> * Authors: * - Paul Asmuth <paul@zscale.io> * - Laura Schlimmer <laura@zscale.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <eventql/cli/cli_config.h> #include <eventql/util/inspect.h> #include <eventql/util/io/fileutil.h> #include <inih/ini.h> namespace eventql { namespace cli { struct IniParserState { IniParserState(CLIConfig* _cfg) : cfg(_cfg), status(Status::success()) {} CLIConfig* cfg; Status status; }; static int ini_parse_handler( void* user, const char* section, const char* name, const char* value) { auto parser_state = (IniParserState*) user; auto status = parser_state->cfg->setConfigOption(section, name, value); if (status.isSuccess()) { return 1; } else { parser_state->status = status; return 0; } } CLIConfig::CLIConfig() {} Status CLIConfig::loadDefaultConfigFile() { char* homedir = getenv("HOME"); if (!homedir) { return Status::success(); } String confg_file_path = FileUtil::joinPaths(homedir, ".evqlrc"); if (!FileUtil::exists(confg_file_path)) { return Status::success(); } return loadConfigFile(confg_file_path); } Status CLIConfig::loadConfigFile(const String& config_file) { IniParserState parser_state(this); if (ini_parse(config_file.c_str(), &ini_parse_handler, &parser_state) < 0) { parser_state.status = Status(eParseError, "invalid config file"); } return parser_state.status; } Status CLIConfig::setConfigOption( const String& section, const String& key, const String& value) { if (section == "evql") { if (key == "host") { return setHost(value); } if (key == "port") { return setPort(stoi(value)); } if (key == "auth_token") { return setAuthToken(value); } if (key == "batch_mode") { return setBatchMode(value); } } return Status(eParseError); } Status CLIConfig::setHost(const String& host /* = "localhost" */) { //FIXME check host format server_host_ = host; return Status::success(); } Status CLIConfig::setPort(const int port /* = 80 */) { //FIXME check port format server_port_ = port; return Status::success(); } Status CLIConfig::setAuthToken(const String& auth_token) { //FIXME check auth format server_auth_token_ = auth_token; return Status::success(); } Status CLIConfig::setBatchMode(const String& batch_mode) { if (batch_mode == "false") { batch_mode_ = false; return Status::success(); } else if (batch_mode == "true") { batch_mode_ = true; return Status::success(); } else { return Status(eParseError); } } Option<String> CLIConfig::getHost() const { if (server_host_.size() > 0) { return Some<String>(server_host_); } else { return None<String>(); } } Option<int> CLIConfig::getPort() const { if (server_port_) { return Some<int>(server_port_); } else { return None<int>(); } } Option<String> CLIConfig::getAuthToken() const { if (server_auth_token_.size() > 0) { return Some<String>(server_auth_token_); } else { return None<String>(); } } Option<String> CLIConfig::getFile() const { return file_; } Option<String> CLIConfig::getExec() const { return exec_; } Option<bool> CLIConfig::getBatchMode() const { return batch_mode_; } } // namespace cli } // namespace eventql <commit_msg>validate port number<commit_after>/** * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io> * Authors: * - Paul Asmuth <paul@zscale.io> * - Laura Schlimmer <laura@zscale.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <eventql/cli/cli_config.h> #include <eventql/util/inspect.h> #include <eventql/util/io/fileutil.h> #include <inih/ini.h> namespace eventql { namespace cli { struct IniParserState { IniParserState(CLIConfig* _cfg) : cfg(_cfg), status(Status::success()) {} CLIConfig* cfg; Status status; }; static int ini_parse_handler( void* user, const char* section, const char* name, const char* value) { auto parser_state = (IniParserState*) user; auto status = parser_state->cfg->setConfigOption(section, name, value); if (status.isSuccess()) { return 1; } else { parser_state->status = status; return 0; } } CLIConfig::CLIConfig() {} Status CLIConfig::loadDefaultConfigFile() { char* homedir = getenv("HOME"); if (!homedir) { return Status::success(); } String confg_file_path = FileUtil::joinPaths(homedir, ".evqlrc"); if (!FileUtil::exists(confg_file_path)) { return Status::success(); } return loadConfigFile(confg_file_path); } Status CLIConfig::loadConfigFile(const String& config_file) { IniParserState parser_state(this); if (ini_parse(config_file.c_str(), &ini_parse_handler, &parser_state) < 0) { parser_state.status = Status(eParseError, "invalid config file"); } return parser_state.status; } Status CLIConfig::setConfigOption( const String& section, const String& key, const String& value) { if (section == "evql") { if (key == "host") { return setHost(value); } if (key == "port") { return setPort(stoi(value)); } if (key == "auth_token") { return setAuthToken(value); } if (key == "batch_mode") { return setBatchMode(value); } } return Status(eParseError); } Status CLIConfig::setHost(const String& host /* = "localhost" */) { server_host_ = host; //FIXME check host format return Status::success(); } Status CLIConfig::setPort(const int port /* = 80 */) { if (port < 0 || port > 65535) { return Status(eFlagError, StringUtil::format("invalid port: $0", port)); } server_port_ = port; return Status::success(); } Status CLIConfig::setAuthToken(const String& auth_token) { server_auth_token_ = auth_tokken; return Status::success(); } Status CLIConfig::setBatchMode(const String& batch_mode) { if (batch_mode == "false") { batch_mode_ = false; return Status::success(); } else if (batch_mode == "true") { batch_mode_ = true; return Status::success(); } else { return Status(eParseError); } } Option<String> CLIConfig::getHost() const { if (server_host_.size() > 0) { return Some<String>(server_host_); } else { return None<String>(); } } Option<int> CLIConfig::getPort() const { if (server_port_) { return Some<int>(server_port_); } else { return None<int>(); } } Option<String> CLIConfig::getAuthToken() const { if (server_auth_token_.size() > 0) { return Some<String>(server_auth_token_); } else { return None<String>(); } } Option<String> CLIConfig::getFile() const { return file_; } Option<String> CLIConfig::getExec() const { return exec_; } Option<bool> CLIConfig::getBatchMode() const { return batch_mode_; } } // namespace cli } // namespace eventql <|endoftext|>
<commit_before>//===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains routines that help determine which pointers are captured. // A pointer value is captured if the function makes a copy of any part of the // pointer that outlives the call. Not being captured means, more or less, that // the pointer is only dereferenced and not stored in a global. Returning part // of the pointer as the function return value may or may not count as capturing // the pointer, depending on the context. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/CaptureTracking.h" #include "llvm/Instructions.h" #include "llvm/Value.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/CallSite.h" using namespace llvm; /// As its comment mentions, PointerMayBeCaptured can be expensive. /// However, it's not easy for BasicAA to cache the result, because /// it's an ImmutablePass. To work around this, bound queries at a /// fixed number of uses. /// /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep /// a cache. Then we can move the code from BasicAliasAnalysis into /// that path, and remove this threshold. static int const Threshold = 20; /// PointerMayBeCaptured - Return true if this pointer value may be captured /// by the enclosing function (which is required to exist). This routine can /// be expensive, so consider caching the results. The boolean ReturnCaptures /// specifies whether returning the value (or part of it) from the function /// counts as capturing it or not. The boolean StoreCaptures specified whether /// storing the value (or part of it) into memory anywhere automatically /// counts as capturing it or not. bool llvm::PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures) { assert(isa<PointerType>(V->getType()) && "Capture is for pointers only!"); SmallVector<Use*, 16> Worklist; SmallSet<Use*, 16> Visited; int Count = 0; for (Value::use_const_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE; ++UI) { Use *U = &UI.getUse(); Visited.insert(U); Worklist.push_back(U); // If there are lots of uses, conservativelty say that the value // is captured to avoid taking too much compile time. if (Count++ >= Threshold) return true; } while (!Worklist.empty()) { Use *U = Worklist.pop_back_val(); Instruction *I = cast<Instruction>(U->getUser()); V = U->get(); switch (I->getOpcode()) { case Instruction::Call: case Instruction::Invoke: { CallSite CS = CallSite::get(I); // Not captured if the callee is readonly, doesn't return a copy through // its return value and doesn't unwind (a readonly function can leak bits // by throwing an exception or not depending on the input value). if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy()) break; // Not captured if only passed via 'nocapture' arguments. Note that // calling a function pointer does not in itself cause the pointer to // be captured. This is a subtle point considering that (for example) // the callee might return its own address. It is analogous to saying // that loading a value from a pointer does not cause the pointer to be // captured, even though the loaded value might be the pointer itself // (think of self-referential objects). CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end(); for (CallSite::arg_iterator A = B; A != E; ++A) if (A->get() == V && !CS.paramHasAttr(A - B + 1, Attribute::NoCapture)) // The parameter is not marked 'nocapture' - captured. return true; // Only passed via 'nocapture' arguments, or is the called function - not // captured. break; } case Instruction::Load: // Loading from a pointer does not cause it to be captured. break; case Instruction::Ret: if (ReturnCaptures) return true; break; case Instruction::Store: if (V == I->getOperand(0)) // Stored the pointer - conservatively assume it may be captured. // TODO: If StoreCaptures is not true, we could do Fancy analysis // to determine whether this store is not actually an escape point. // In that case, BasicAliasAnalysis should be updated as well to // take advantage of this. return true; // Storing to the pointee does not cause the pointer to be captured. break; case Instruction::BitCast: case Instruction::GetElementPtr: case Instruction::PHI: case Instruction::Select: // The original value is not captured via this if the new value isn't. for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) { Use *U = &UI.getUse(); if (Visited.insert(U)) Worklist.push_back(U); } break; case Instruction::ICmp: // Don't count comparisons of a no-alias return value against null as // captures. This allows us to ignore comparisons of malloc results // with null, for example. if (isNoAliasCall(V->stripPointerCasts())) if (ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(I->getOperand(1))) if (CPN->getType()->getAddressSpace() == 0) break; // Otherwise, be conservative. There are crazy ways to capture pointers // using comparisons. return true; default: // Something else - be conservative and say it is captured. return true; } } // All uses examined - not captured. return false; } <commit_msg>Fix a typo in a comment, and adjust SmallSet and SmallVector sizes, that Chris noticed.<commit_after>//===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains routines that help determine which pointers are captured. // A pointer value is captured if the function makes a copy of any part of the // pointer that outlives the call. Not being captured means, more or less, that // the pointer is only dereferenced and not stored in a global. Returning part // of the pointer as the function return value may or may not count as capturing // the pointer, depending on the context. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/CaptureTracking.h" #include "llvm/Instructions.h" #include "llvm/Value.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/CallSite.h" using namespace llvm; /// As its comment mentions, PointerMayBeCaptured can be expensive. /// However, it's not easy for BasicAA to cache the result, because /// it's an ImmutablePass. To work around this, bound queries at a /// fixed number of uses. /// /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep /// a cache. Then we can move the code from BasicAliasAnalysis into /// that path, and remove this threshold. static int const Threshold = 20; /// PointerMayBeCaptured - Return true if this pointer value may be captured /// by the enclosing function (which is required to exist). This routine can /// be expensive, so consider caching the results. The boolean ReturnCaptures /// specifies whether returning the value (or part of it) from the function /// counts as capturing it or not. The boolean StoreCaptures specified whether /// storing the value (or part of it) into memory anywhere automatically /// counts as capturing it or not. bool llvm::PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures) { assert(isa<PointerType>(V->getType()) && "Capture is for pointers only!"); SmallVector<Use*, 20> Worklist; SmallSet<Use*, 20> Visited; int Count = 0; for (Value::use_const_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE; ++UI) { // If there are lots of uses, conservatively say that the value // is captured to avoid taking too much compile time. if (Count++ >= Threshold) return true; Use *U = &UI.getUse(); Visited.insert(U); Worklist.push_back(U); } while (!Worklist.empty()) { Use *U = Worklist.pop_back_val(); Instruction *I = cast<Instruction>(U->getUser()); V = U->get(); switch (I->getOpcode()) { case Instruction::Call: case Instruction::Invoke: { CallSite CS = CallSite::get(I); // Not captured if the callee is readonly, doesn't return a copy through // its return value and doesn't unwind (a readonly function can leak bits // by throwing an exception or not depending on the input value). if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy()) break; // Not captured if only passed via 'nocapture' arguments. Note that // calling a function pointer does not in itself cause the pointer to // be captured. This is a subtle point considering that (for example) // the callee might return its own address. It is analogous to saying // that loading a value from a pointer does not cause the pointer to be // captured, even though the loaded value might be the pointer itself // (think of self-referential objects). CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end(); for (CallSite::arg_iterator A = B; A != E; ++A) if (A->get() == V && !CS.paramHasAttr(A - B + 1, Attribute::NoCapture)) // The parameter is not marked 'nocapture' - captured. return true; // Only passed via 'nocapture' arguments, or is the called function - not // captured. break; } case Instruction::Load: // Loading from a pointer does not cause it to be captured. break; case Instruction::Ret: if (ReturnCaptures) return true; break; case Instruction::Store: if (V == I->getOperand(0)) // Stored the pointer - conservatively assume it may be captured. // TODO: If StoreCaptures is not true, we could do Fancy analysis // to determine whether this store is not actually an escape point. // In that case, BasicAliasAnalysis should be updated as well to // take advantage of this. return true; // Storing to the pointee does not cause the pointer to be captured. break; case Instruction::BitCast: case Instruction::GetElementPtr: case Instruction::PHI: case Instruction::Select: // The original value is not captured via this if the new value isn't. for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) { Use *U = &UI.getUse(); if (Visited.insert(U)) Worklist.push_back(U); } break; case Instruction::ICmp: // Don't count comparisons of a no-alias return value against null as // captures. This allows us to ignore comparisons of malloc results // with null, for example. if (isNoAliasCall(V->stripPointerCasts())) if (ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(I->getOperand(1))) if (CPN->getType()->getAddressSpace() == 0) break; // Otherwise, be conservative. There are crazy ways to capture pointers // using comparisons. return true; default: // Something else - be conservative and say it is captured. return true; } } // All uses examined - not captured. return false; } <|endoftext|>
<commit_before> // STL includes #include <csignal> #include <iomanip> // QT includes #include <QImage> // getoptPlusPLus includes #include <getoptPlusPlus/getoptpp.h> // Dispmanx grabber includes #include <grabber/dispmanx/DispmanxFrameGrabber.h> using namespace vlofgren; static bool running = true; void signal_handler(int signum) { running = false; } int main(int argc, char** argv) { signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); int grabFlags = 0; int grabCount = -1; try { // create the option parser and initialize all parameters OptionsParser optionParser("Simple application to send a command to hyperion using the Json interface"); ParameterSet & parameters = optionParser.getParameters(); QString flagDescr = QString("Set the grab flags of the dispmanx frame grabber [default: 0x%1]").arg(grabFlags, 8, 16, QChar('0')); StringParameter & argFlags = parameters.add<StringParameter> ('f', "flags", flagDescr.toAscii().constData()); IntParameter & argCount = parameters.add<IntParameter> ('n', "count", "Number of images to capture (default infinite)"); argCount.setDefault(grabCount); SwitchParameter<> & argList = parameters.add<SwitchParameter<> >('l', "list", "List the possible flags"); SwitchParameter<> & argHelp = parameters.add<SwitchParameter<> >('h', "help", "Show this help message and exit"); // parse all options optionParser.parse(argc, const_cast<const char **>(argv)); // check if we need to display the usage. exit if we do. if (argHelp.isSet()) { optionParser.usage(); return 0; } if (argList.isSet()) { std::cout.width(15); std::cout.width(10); std::cout << "Possible DISPMANX flags: " << std::endl; std::cout << "Name | " << "Value" << std::endl; std::cout << "--------------------------------| " << "------" << std::endl; std::cout << "DISPMANX_NO_ROTATE | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_NO_ROTATE << std::endl; std::cout << "DISPMANX_ROTATE_90 | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_90 << std::endl; std::cout << "DISPMANX_ROTATE_180 | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_180 << std::endl; std::cout << "DISPMANX_ROTATE_270 | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_270 << std::endl; std::cout << "DISPMANX_FLIP_HRIZ | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_FLIP_HRIZ << std::endl; std::cout << "DISPMANX_FLIP_VERT | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_FLIP_VERT << std::endl; std::cout << "DISPMANX_SNAPSHOT_NO_YUV | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_NO_YUV << std::endl; std::cout << "DISPMANX_SNAPSHOT_NO_RGB | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_NO_RGB << std::endl; std::cout << "DISPMANX_SNAPSHOT_FILL | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_FILL << std::endl; std::cout << "DISPMANX_SNAPSHOT_SWAP_RED_BLUE | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_SWAP_RED_BLUE << std::endl; std::cout << "DISPMANX_SNAPSHOT_PACK | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_PACK << std::endl; return 0; } if (argFlags.isSet()) { QString flagStr = QString::fromStdString(argFlags.getValue()); bool ok = false; // grabFlags = flagStr.toInt(&ok); if (flagStr.startsWith("0x")) { grabFlags = flagStr.toInt(&ok, 16); } else { grabFlags = flagStr.toInt(&ok, 10); } std::cout << "Resulting flags: " << grabFlags << " (=0x" << std::hex << std::setfill('0') << std::setw(8) << grabFlags << ")" << std::dec << std::endl; if (!ok) { std::cerr << "Failed to parse flags (" << flagStr.toStdString().c_str() << ")" << std::endl; return -1; } } grabCount = argCount.getValue(); } catch (const std::runtime_error & e) { // An error occured. Display error and quit std::cerr << e.what() << std::endl; return 1; } DispmanxFrameGrabber frameGrabber(64, 64); frameGrabber.setFlags(grabFlags); unsigned iFrame = 0; QImage qImage(64, 64, QImage::Format_ARGB32); Image<ColorRgba> imageRgba(64, 64); for (int i=0; i<grabCount || grabCount < 0; ++i) { frameGrabber.grabFrame(imageRgba); for (int iScanline=0; iScanline<qImage.height(); ++iScanline) { unsigned char* scanLinePtr = qImage.scanLine(iScanline); memcpy(scanLinePtr, imageRgba.memptr()+imageRgba.width()*iScanline, imageRgba.width()*sizeof(ColorRgba)); } const QImage qImageSwp = qImage.rgbSwapped(); qImageSwp.save(QString("HYPERION_f0x%1_%2.png").arg(grabFlags, 8, 16, QChar('0')).arg(iFrame)); ++iFrame; timespec sleepTime; sleepTime.tv_sec = 1; sleepTime.tv_nsec = 0; nanosleep(&sleepTime, NULL); } return 0; } <commit_msg>fix compile on raspi<commit_after> // STL includes #include <csignal> #include <iomanip> // QT includes #include <QImage> // getoptPlusPLus includes #include <getoptPlusPlus/getoptpp.h> // Dispmanx grabber includes #include <grabber/DispmanxFrameGrabber.h> using namespace vlofgren; static bool running = true; void signal_handler(int signum) { running = false; } int main(int argc, char** argv) { signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); int grabFlags = 0; int grabCount = -1; try { // create the option parser and initialize all parameters OptionsParser optionParser("Simple application to send a command to hyperion using the Json interface"); ParameterSet & parameters = optionParser.getParameters(); QString flagDescr = QString("Set the grab flags of the dispmanx frame grabber [default: 0x%1]").arg(grabFlags, 8, 16, QChar('0')); StringParameter & argFlags = parameters.add<StringParameter> ('f', "flags", flagDescr.toAscii().constData()); IntParameter & argCount = parameters.add<IntParameter> ('n', "count", "Number of images to capture (default infinite)"); argCount.setDefault(grabCount); SwitchParameter<> & argList = parameters.add<SwitchParameter<> >('l', "list", "List the possible flags"); SwitchParameter<> & argHelp = parameters.add<SwitchParameter<> >('h', "help", "Show this help message and exit"); // parse all options optionParser.parse(argc, const_cast<const char **>(argv)); // check if we need to display the usage. exit if we do. if (argHelp.isSet()) { optionParser.usage(); return 0; } if (argList.isSet()) { std::cout.width(15); std::cout.width(10); std::cout << "Possible DISPMANX flags: " << std::endl; std::cout << "Name | " << "Value" << std::endl; std::cout << "--------------------------------| " << "------" << std::endl; std::cout << "DISPMANX_NO_ROTATE | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_NO_ROTATE << std::endl; std::cout << "DISPMANX_ROTATE_90 | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_90 << std::endl; std::cout << "DISPMANX_ROTATE_180 | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_180 << std::endl; std::cout << "DISPMANX_ROTATE_270 | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_270 << std::endl; std::cout << "DISPMANX_FLIP_HRIZ | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_FLIP_HRIZ << std::endl; std::cout << "DISPMANX_FLIP_VERT | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_FLIP_VERT << std::endl; std::cout << "DISPMANX_SNAPSHOT_NO_YUV | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_NO_YUV << std::endl; std::cout << "DISPMANX_SNAPSHOT_NO_RGB | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_NO_RGB << std::endl; std::cout << "DISPMANX_SNAPSHOT_FILL | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_FILL << std::endl; std::cout << "DISPMANX_SNAPSHOT_SWAP_RED_BLUE | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_SWAP_RED_BLUE << std::endl; std::cout << "DISPMANX_SNAPSHOT_PACK | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_PACK << std::endl; return 0; } if (argFlags.isSet()) { QString flagStr = QString::fromStdString(argFlags.getValue()); bool ok = false; // grabFlags = flagStr.toInt(&ok); if (flagStr.startsWith("0x")) { grabFlags = flagStr.toInt(&ok, 16); } else { grabFlags = flagStr.toInt(&ok, 10); } std::cout << "Resulting flags: " << grabFlags << " (=0x" << std::hex << std::setfill('0') << std::setw(8) << grabFlags << ")" << std::dec << std::endl; if (!ok) { std::cerr << "Failed to parse flags (" << flagStr.toStdString().c_str() << ")" << std::endl; return -1; } } grabCount = argCount.getValue(); } catch (const std::runtime_error & e) { // An error occured. Display error and quit std::cerr << e.what() << std::endl; return 1; } DispmanxFrameGrabber frameGrabber(64, 64); frameGrabber.setFlags(grabFlags); unsigned iFrame = 0; QImage qImage(64, 64, QImage::Format_ARGB32); Image<ColorRgba> imageRgba(64, 64); for (int i=0; i<grabCount || grabCount < 0; ++i) { frameGrabber.grabFrame(imageRgba); for (int iScanline=0; iScanline<qImage.height(); ++iScanline) { unsigned char* scanLinePtr = qImage.scanLine(iScanline); memcpy(scanLinePtr, imageRgba.memptr()+imageRgba.width()*iScanline, imageRgba.width()*sizeof(ColorRgba)); } const QImage qImageSwp = qImage.rgbSwapped(); qImageSwp.save(QString("HYPERION_f0x%1_%2.png").arg(grabFlags, 8, 16, QChar('0')).arg(iFrame)); ++iFrame; timespec sleepTime; sleepTime.tv_sec = 1; sleepTime.tv_nsec = 0; nanosleep(&sleepTime, NULL); } return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkObjectFactoryBase.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ // Disable warning for long symbol names in this file only #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif #include "itkObjectFactoryBase.h" #include "itkDynamicLoader.h" #include "itkDirectory.h" #include "itkVersion.h" #include <stdlib.h> #include <ctype.h> #include <algorithm> #include <map> // Create a sub class to shrink the size of the symbols // Also, so a forward reference can be put in itkObjectFactoryBase.h // and a pointer member can be used. This avoids other // classes including <map> and getting long symbol warnings. typedef std::multimap<std::string, itkObjectFactoryBase::OverrideInformation> itkStringOverMap; class itkOverRideMap : public itkStringOverMap { public: }; // Initialize static list of factories. // std::list<itkObjectFactoryBase*>* itkObjectFactoryBase::m_RegisteredFactories = 0; //---------------------------------------------------------------------------- // Create an instance of a named itk object using the loaded // factories itkObject* itkObjectFactoryBase ::CreateInstance(const char* itkclassname) { if ( !itkObjectFactoryBase::m_RegisteredFactories ) { itkObjectFactoryBase::Initialize(); } for ( std::list<itkObjectFactoryBase*>::iterator i = m_RegisteredFactories->begin(); i != m_RegisteredFactories->end(); ++i ) { itkObject* newobject = (*i)->CreateObject(itkclassname); if(newobject) { return newobject; } } return 0; } //---------------------------------------------------------------------------- // A one time initialization method. void itkObjectFactoryBase ::Initialize() { // Don't do anything if we are already initialized if ( itkObjectFactoryBase::m_RegisteredFactories ) { return; } itkObjectFactoryBase::m_RegisteredFactories = new std::list<itkObjectFactoryBase*>; itkObjectFactoryBase::RegisterDefaults(); itkObjectFactoryBase::LoadDynamicFactories(); } //---------------------------------------------------------------------------- // Register any factories that are always present in ITK like // the OpenGL factory, currently this is not done. void itkObjectFactoryBase ::RegisterDefaults() { } // Load all libraries in ITK_AUTOLOAD_PATH void itkObjectFactoryBase ::LoadDynamicFactories() { // follow PATH conventions #ifdef _WIN32 char PathSeparator = ';'; #else char PathSeparator = ':'; #endif std::string LoadPath; if (getenv("ITK_AUTOLOAD_PATH")) { LoadPath = getenv("ITK_AUTOLOAD_PATH"); } else { return; } if(LoadPath.size() == 0) { return; } std::string::size_type EndSeparatorPosition = 0; std::string::size_type StartSeparatorPosition = 0; while ( StartSeparatorPosition != std::string::npos ) { StartSeparatorPosition = EndSeparatorPosition; // find PathSeparator in LoadPath EndSeparatorPosition = LoadPath.find(PathSeparator, EndSeparatorPosition); if(EndSeparatorPosition != std::string::npos) { EndSeparatorPosition = LoadPath.size(); } std::string CurrentPath = LoadPath.substr(StartSeparatorPosition, EndSeparatorPosition); itkObjectFactoryBase::LoadLibrariesInPath(CurrentPath.c_str()); // move past separator EndSeparatorPosition++; } } //---------------------------------------------------------------------------- // A file scope helper function to concat path and file into // a full path static std::string CreateFullPath(const char* path, const char* file) { std::string ret; #ifdef _WIN32 const char sep = '\\'; #else const char sep = '/'; #endif // make sure the end of path is a separator ret = path; if ( ret[ret.size()-1] != sep ) { ret.append(1, sep); } ret.append(file); return ret; } // A file scope typedef to make the cast code to the load // function cleaner to read. typedef itkObjectFactoryBase* (* ITK_LOAD_FUNCTION)(); //---------------------------------------------------------------------------- // A file scoped function to determine if a file has // the shared library extension in its name, this converts name to lower // case before the compare, itkDynamicLoader always uses // lower case for LibExtension values. inline bool itkNameIsSharedLibrary(const char* name) { std::string sname = name; if ( sname.find(itkDynamicLoader::LibExtension()) != std::string::npos ) { return true; } return false; } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::LoadLibrariesInPath(const char* path) { itkDirectory* dir = itkDirectory::New(); if ( !dir->Load(path) ) { return; } // Attempt to load each file in the directory as a shared library for ( int i = 0; i < dir->GetNumberOfFiles(); i++ ) { const char* file = dir->GetFile(i); // try to make sure the file has at least the extension // for a shared library in it. if ( itkNameIsSharedLibrary(file) ) { std::string fullpath = CreateFullPath(path, file); itkLibHandle lib = itkDynamicLoader::OpenLibrary(fullpath.c_str()); if ( lib ) { // Look for the symbol itkLoad in the library ITK_LOAD_FUNCTION loadfunction = (ITK_LOAD_FUNCTION)itkDynamicLoader::GetSymbolAddress(lib, "itkLoad"); // if the symbol is found call it to create the factory // from the library if ( loadfunction ) { itkObjectFactoryBase* newfactory = (*loadfunction)(); // initialize class members if load worked newfactory->m_LibraryHandle = (void*)lib; newfactory->m_LibraryPath = fullpath; newfactory->m_LibraryDate = 0; // unused for now... itkObjectFactoryBase::RegisterFactory(newfactory); } } } } } //---------------------------------------------------------------------------- // Recheck the ITK_AUTOLOAD_PATH for new libraries void itkObjectFactoryBase ::ReHash() { itkObjectFactoryBase::UnRegisterAllFactories(); itkObjectFactoryBase::Initialize(); } // initialize class members itkObjectFactoryBase::itkObjectFactoryBase() { m_LibraryHandle = 0; m_LibraryDate = 0; m_OverrideMap = new itkOverRideMap; } //---------------------------------------------------------------------------- // Unload the library and free the path string itkObjectFactoryBase ::~itkObjectFactoryBase() { itkDynamicLoader::CloseLibrary((itkLibHandle)m_LibraryHandle); } //---------------------------------------------------------------------------- // Add a factory to the registered list void itkObjectFactoryBase ::RegisterFactory(itkObjectFactoryBase* factory) { if ( factory->m_LibraryHandle == 0 ) { const char* nonDynamicName = "Non-Dynamicly loaded factory"; factory->m_LibraryPath = nonDynamicName; } if ( strcmp(factory->GetITKSourceVersion(), itkVersion::GetITKSourceVersion()) != 0 ) { itkWarningMacro(<< "Possible incompatible factory load:" << "\nRunning itk version :\n" << itkVersion::GetITKSourceVersion() << "\nLoaded Factory version:\n" << factory->GetITKSourceVersion() << "\nLoading factory:\n" << factory->m_LibraryPath << "\n"); } itkObjectFactoryBase::Initialize(); itkObjectFactoryBase::m_RegisteredFactories->push_back(factory); factory->Register(); } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::PrintSelf(std::ostream& os, itkIndent indent) { itkObject::PrintSelf(os, indent); os << indent << "Factory DLL path: " << m_LibraryPath << "\n"; os << indent << "Factory description: " << this->GetDescription() << std::endl; int num = m_OverrideMap->size(); os << indent << "Factory overides " << num << " classes:" << std::endl; indent = indent.GetNextIndent(); for(itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i) { os << indent << "Class : " << (*i).first << std::endl; os << indent << "Overriden with: " << (*i).second.m_OverrideWithName << std::endl; os << indent << "Enable flag: " << (*i).second.m_EnabledFlag << std::endl; os << std::endl; } } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::UnRegisterFactory(itkObjectFactoryBase* factory) { for ( std::list<itkObjectFactoryBase*>::iterator i = m_RegisteredFactories->begin(); i != m_RegisteredFactories->end(); ++i ) { if ( factory == *i ) { m_RegisteredFactories->remove(factory); factory->UnRegister(); return; } } } //---------------------------------------------------------------------------- // unregister all factories and delete the RegisteredFactories list void itkObjectFactoryBase ::UnRegisterAllFactories() { itkObjectFactoryBase* factory = 0; for ( std::list<itkObjectFactoryBase*>::iterator i = m_RegisteredFactories->begin(); i != m_RegisteredFactories->end(); ++i ) { (*i)->UnRegister(); } delete itkObjectFactoryBase::m_RegisteredFactories; itkObjectFactoryBase::m_RegisteredFactories = 0; } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::RegisterOverride(const char* classOverride, const char* subclass, const char* description, bool enableFlag, itkCreateObjectFunctionBase* createFunction) { itkObjectFactoryBase::OverrideInformation info; info.m_Description = description; info.m_OverrideWithName = subclass; info.m_EnabledFlag = enableFlag; info.m_CreateObject = createFunction; m_OverrideMap->insert(itkOverRideMap::value_type(classOverride, info)); } //---------------------------------------------------------------------------- itkObject* itkObjectFactoryBase ::CreateObject(const char* itkclassname) { m_OverrideMap->find(itkclassname); itkOverRideMap::iterator pos = m_OverrideMap->find(itkclassname); if ( pos != m_OverrideMap->end() ) { return (*pos).second.m_CreateObject->CreateObject(); } return 0; } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::SetEnableFlag(bool flag, const char* className, const char* subclassName) { itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className); itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className); for ( itkOverRideMap::iterator i = start; i != end; ++i ) { if ( (*i).second.m_OverrideWithName == subclassName ) { (*i).second.m_EnabledFlag = flag; } } } //---------------------------------------------------------------------------- bool itkObjectFactoryBase ::GetEnableFlag(const char* className, const char* subclassName) { itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className); itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className); for ( itkOverRideMap::iterator i = start; i != end; ++i ) { if ( (*i).second.m_OverrideWithName == subclassName ) { return (*i).second.m_EnabledFlag; } } return 0; } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::Disable(const char* className) { itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className); itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className); for ( itkOverRideMap::iterator i = start; i != end; ++i ) { (*i).second.m_EnabledFlag = 0; } } //---------------------------------------------------------------------------- std::list<itkObjectFactoryBase*> itkObjectFactoryBase ::GetRegisteredFactories() { return *itkObjectFactoryBase::m_RegisteredFactories; } //---------------------------------------------------------------------------- // Return a list of classes that this factory overrides. std::list<std::string> itkObjectFactoryBase ::GetClassOverrideNames() { std::list<std::string> ret; for ( itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i ) { ret.push_back((*i).first); } return ret; } //---------------------------------------------------------------------------- // Return a list of the names of classes that override classes. std::list<std::string> itkObjectFactoryBase ::GetClassOverrideWithNames() { std::list<std::string> ret; for ( itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i ) { ret.push_back((*i).second.m_OverrideWithName); } return ret; } //---------------------------------------------------------------------------- // Retrun a list of descriptions for class overrides std::list<std::string> itkObjectFactoryBase ::GetClassOverrideDescriptions() { std::list<std::string> ret; for ( itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i ) { ret.push_back((*i).second.m_Description); } return ret; } //---------------------------------------------------------------------------- // Return a list of enable flags std::list<bool> itkObjectFactoryBase ::GetEnableFlags() { std::list<bool> ret; for( itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i) { ret.push_back((*i).second.m_EnabledFlag); } return ret; } <commit_msg>ENH: unused variable 'factory' removed.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkObjectFactoryBase.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ // Disable warning for long symbol names in this file only #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif #include "itkObjectFactoryBase.h" #include "itkDynamicLoader.h" #include "itkDirectory.h" #include "itkVersion.h" #include <stdlib.h> #include <ctype.h> #include <algorithm> #include <map> // Create a sub class to shrink the size of the symbols // Also, so a forward reference can be put in itkObjectFactoryBase.h // and a pointer member can be used. This avoids other // classes including <map> and getting long symbol warnings. typedef std::multimap<std::string, itkObjectFactoryBase::OverrideInformation> itkStringOverMap; class itkOverRideMap : public itkStringOverMap { public: }; // Initialize static list of factories. // std::list<itkObjectFactoryBase*>* itkObjectFactoryBase::m_RegisteredFactories = 0; //---------------------------------------------------------------------------- // Create an instance of a named itk object using the loaded // factories itkObject* itkObjectFactoryBase ::CreateInstance(const char* itkclassname) { if ( !itkObjectFactoryBase::m_RegisteredFactories ) { itkObjectFactoryBase::Initialize(); } for ( std::list<itkObjectFactoryBase*>::iterator i = m_RegisteredFactories->begin(); i != m_RegisteredFactories->end(); ++i ) { itkObject* newobject = (*i)->CreateObject(itkclassname); if(newobject) { return newobject; } } return 0; } //---------------------------------------------------------------------------- // A one time initialization method. void itkObjectFactoryBase ::Initialize() { // Don't do anything if we are already initialized if ( itkObjectFactoryBase::m_RegisteredFactories ) { return; } itkObjectFactoryBase::m_RegisteredFactories = new std::list<itkObjectFactoryBase*>; itkObjectFactoryBase::RegisterDefaults(); itkObjectFactoryBase::LoadDynamicFactories(); } //---------------------------------------------------------------------------- // Register any factories that are always present in ITK like // the OpenGL factory, currently this is not done. void itkObjectFactoryBase ::RegisterDefaults() { } // Load all libraries in ITK_AUTOLOAD_PATH void itkObjectFactoryBase ::LoadDynamicFactories() { // follow PATH conventions #ifdef _WIN32 char PathSeparator = ';'; #else char PathSeparator = ':'; #endif std::string LoadPath; if (getenv("ITK_AUTOLOAD_PATH")) { LoadPath = getenv("ITK_AUTOLOAD_PATH"); } else { return; } if(LoadPath.size() == 0) { return; } std::string::size_type EndSeparatorPosition = 0; std::string::size_type StartSeparatorPosition = 0; while ( StartSeparatorPosition != std::string::npos ) { StartSeparatorPosition = EndSeparatorPosition; // find PathSeparator in LoadPath EndSeparatorPosition = LoadPath.find(PathSeparator, EndSeparatorPosition); if(EndSeparatorPosition != std::string::npos) { EndSeparatorPosition = LoadPath.size(); } std::string CurrentPath = LoadPath.substr(StartSeparatorPosition, EndSeparatorPosition); itkObjectFactoryBase::LoadLibrariesInPath(CurrentPath.c_str()); // move past separator EndSeparatorPosition++; } } //---------------------------------------------------------------------------- // A file scope helper function to concat path and file into // a full path static std::string CreateFullPath(const char* path, const char* file) { std::string ret; #ifdef _WIN32 const char sep = '\\'; #else const char sep = '/'; #endif // make sure the end of path is a separator ret = path; if ( ret[ret.size()-1] != sep ) { ret.append(1, sep); } ret.append(file); return ret; } // A file scope typedef to make the cast code to the load // function cleaner to read. typedef itkObjectFactoryBase* (* ITK_LOAD_FUNCTION)(); //---------------------------------------------------------------------------- // A file scoped function to determine if a file has // the shared library extension in its name, this converts name to lower // case before the compare, itkDynamicLoader always uses // lower case for LibExtension values. inline bool itkNameIsSharedLibrary(const char* name) { std::string sname = name; if ( sname.find(itkDynamicLoader::LibExtension()) != std::string::npos ) { return true; } return false; } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::LoadLibrariesInPath(const char* path) { itkDirectory* dir = itkDirectory::New(); if ( !dir->Load(path) ) { return; } // Attempt to load each file in the directory as a shared library for ( int i = 0; i < dir->GetNumberOfFiles(); i++ ) { const char* file = dir->GetFile(i); // try to make sure the file has at least the extension // for a shared library in it. if ( itkNameIsSharedLibrary(file) ) { std::string fullpath = CreateFullPath(path, file); itkLibHandle lib = itkDynamicLoader::OpenLibrary(fullpath.c_str()); if ( lib ) { // Look for the symbol itkLoad in the library ITK_LOAD_FUNCTION loadfunction = (ITK_LOAD_FUNCTION)itkDynamicLoader::GetSymbolAddress(lib, "itkLoad"); // if the symbol is found call it to create the factory // from the library if ( loadfunction ) { itkObjectFactoryBase* newfactory = (*loadfunction)(); // initialize class members if load worked newfactory->m_LibraryHandle = (void*)lib; newfactory->m_LibraryPath = fullpath; newfactory->m_LibraryDate = 0; // unused for now... itkObjectFactoryBase::RegisterFactory(newfactory); } } } } } //---------------------------------------------------------------------------- // Recheck the ITK_AUTOLOAD_PATH for new libraries void itkObjectFactoryBase ::ReHash() { itkObjectFactoryBase::UnRegisterAllFactories(); itkObjectFactoryBase::Initialize(); } // initialize class members itkObjectFactoryBase::itkObjectFactoryBase() { m_LibraryHandle = 0; m_LibraryDate = 0; m_OverrideMap = new itkOverRideMap; } //---------------------------------------------------------------------------- // Unload the library and free the path string itkObjectFactoryBase ::~itkObjectFactoryBase() { itkDynamicLoader::CloseLibrary((itkLibHandle)m_LibraryHandle); } //---------------------------------------------------------------------------- // Add a factory to the registered list void itkObjectFactoryBase ::RegisterFactory(itkObjectFactoryBase* factory) { if ( factory->m_LibraryHandle == 0 ) { const char* nonDynamicName = "Non-Dynamicly loaded factory"; factory->m_LibraryPath = nonDynamicName; } if ( strcmp(factory->GetITKSourceVersion(), itkVersion::GetITKSourceVersion()) != 0 ) { itkWarningMacro(<< "Possible incompatible factory load:" << "\nRunning itk version :\n" << itkVersion::GetITKSourceVersion() << "\nLoaded Factory version:\n" << factory->GetITKSourceVersion() << "\nLoading factory:\n" << factory->m_LibraryPath << "\n"); } itkObjectFactoryBase::Initialize(); itkObjectFactoryBase::m_RegisteredFactories->push_back(factory); factory->Register(); } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::PrintSelf(std::ostream& os, itkIndent indent) { itkObject::PrintSelf(os, indent); os << indent << "Factory DLL path: " << m_LibraryPath << "\n"; os << indent << "Factory description: " << this->GetDescription() << std::endl; int num = m_OverrideMap->size(); os << indent << "Factory overides " << num << " classes:" << std::endl; indent = indent.GetNextIndent(); for(itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i) { os << indent << "Class : " << (*i).first << std::endl; os << indent << "Overriden with: " << (*i).second.m_OverrideWithName << std::endl; os << indent << "Enable flag: " << (*i).second.m_EnabledFlag << std::endl; os << std::endl; } } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::UnRegisterFactory(itkObjectFactoryBase* factory) { for ( std::list<itkObjectFactoryBase*>::iterator i = m_RegisteredFactories->begin(); i != m_RegisteredFactories->end(); ++i ) { if ( factory == *i ) { m_RegisteredFactories->remove(factory); factory->UnRegister(); return; } } } //---------------------------------------------------------------------------- // unregister all factories and delete the RegisteredFactories list void itkObjectFactoryBase ::UnRegisterAllFactories() { for ( std::list<itkObjectFactoryBase*>::iterator i = m_RegisteredFactories->begin(); i != m_RegisteredFactories->end(); ++i ) { (*i)->UnRegister(); } delete itkObjectFactoryBase::m_RegisteredFactories; itkObjectFactoryBase::m_RegisteredFactories = 0; } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::RegisterOverride(const char* classOverride, const char* subclass, const char* description, bool enableFlag, itkCreateObjectFunctionBase* createFunction) { itkObjectFactoryBase::OverrideInformation info; info.m_Description = description; info.m_OverrideWithName = subclass; info.m_EnabledFlag = enableFlag; info.m_CreateObject = createFunction; m_OverrideMap->insert(itkOverRideMap::value_type(classOverride, info)); } //---------------------------------------------------------------------------- itkObject* itkObjectFactoryBase ::CreateObject(const char* itkclassname) { m_OverrideMap->find(itkclassname); itkOverRideMap::iterator pos = m_OverrideMap->find(itkclassname); if ( pos != m_OverrideMap->end() ) { return (*pos).second.m_CreateObject->CreateObject(); } return 0; } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::SetEnableFlag(bool flag, const char* className, const char* subclassName) { itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className); itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className); for ( itkOverRideMap::iterator i = start; i != end; ++i ) { if ( (*i).second.m_OverrideWithName == subclassName ) { (*i).second.m_EnabledFlag = flag; } } } //---------------------------------------------------------------------------- bool itkObjectFactoryBase ::GetEnableFlag(const char* className, const char* subclassName) { itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className); itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className); for ( itkOverRideMap::iterator i = start; i != end; ++i ) { if ( (*i).second.m_OverrideWithName == subclassName ) { return (*i).second.m_EnabledFlag; } } return 0; } //---------------------------------------------------------------------------- void itkObjectFactoryBase ::Disable(const char* className) { itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className); itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className); for ( itkOverRideMap::iterator i = start; i != end; ++i ) { (*i).second.m_EnabledFlag = 0; } } //---------------------------------------------------------------------------- std::list<itkObjectFactoryBase*> itkObjectFactoryBase ::GetRegisteredFactories() { return *itkObjectFactoryBase::m_RegisteredFactories; } //---------------------------------------------------------------------------- // Return a list of classes that this factory overrides. std::list<std::string> itkObjectFactoryBase ::GetClassOverrideNames() { std::list<std::string> ret; for ( itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i ) { ret.push_back((*i).first); } return ret; } //---------------------------------------------------------------------------- // Return a list of the names of classes that override classes. std::list<std::string> itkObjectFactoryBase ::GetClassOverrideWithNames() { std::list<std::string> ret; for ( itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i ) { ret.push_back((*i).second.m_OverrideWithName); } return ret; } //---------------------------------------------------------------------------- // Retrun a list of descriptions for class overrides std::list<std::string> itkObjectFactoryBase ::GetClassOverrideDescriptions() { std::list<std::string> ret; for ( itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i ) { ret.push_back((*i).second.m_Description); } return ret; } //---------------------------------------------------------------------------- // Return a list of enable flags std::list<bool> itkObjectFactoryBase ::GetEnableFlags() { std::list<bool> ret; for( itkOverRideMap::iterator i = m_OverrideMap->begin(); i != m_OverrideMap->end(); ++i) { ret.push_back((*i).second.m_EnabledFlag); } return ret; } <|endoftext|>
<commit_before> /* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrBufferAllocPool.h" #include "GrTypes.h" #include "GrVertexBuffer.h" #include "GrIndexBuffer.h" #include "GrGpu.h" #if GR_DEBUG #define VALIDATE validate #else static void VALIDATE(bool x = false) {} #endif // page size #define GrBufferAllocPool_MIN_BLOCK_SIZE ((size_t)1 << 12) GrBufferAllocPool::GrBufferAllocPool(GrGpu* gpu, BufferType bufferType, bool frequentResetHint, size_t blockSize, int preallocBufferCnt) : fBlocks(GrMax(8, 2*preallocBufferCnt)) { GrAssert(NULL != gpu); fGpu = gpu; fGpu->ref(); fGpuIsReffed = true; fBufferType = bufferType; fFrequentResetHint = frequentResetHint; fBufferPtr = NULL; fMinBlockSize = GrMax(GrBufferAllocPool_MIN_BLOCK_SIZE, blockSize); fBytesInUse = 0; fPreallocBuffersInUse = 0; fFirstPreallocBuffer = 0; for (int i = 0; i < preallocBufferCnt; ++i) { GrGeometryBuffer* buffer = this->createBuffer(fMinBlockSize); if (NULL != buffer) { *fPreallocBuffers.append() = buffer; buffer->ref(); } } } GrBufferAllocPool::~GrBufferAllocPool() { VALIDATE(); if (fBlocks.count()) { GrGeometryBuffer* buffer = fBlocks.back().fBuffer; if (buffer->isLocked()) { buffer->unlock(); } } while (!fBlocks.empty()) { destroyBlock(); } fPreallocBuffers.unrefAll(); releaseGpuRef(); } void GrBufferAllocPool::releaseGpuRef() { if (fGpuIsReffed) { fGpu->unref(); fGpuIsReffed = false; } } void GrBufferAllocPool::reset() { VALIDATE(); fBytesInUse = 0; if (fBlocks.count()) { GrGeometryBuffer* buffer = fBlocks.back().fBuffer; if (buffer->isLocked()) { buffer->unlock(); } } while (!fBlocks.empty()) { destroyBlock(); } if (fPreallocBuffers.count()) { // must set this after above loop. fFirstPreallocBuffer = (fFirstPreallocBuffer + fPreallocBuffersInUse) % fPreallocBuffers.count(); } fCpuData.reset(fGpu->getCaps().fBufferLockSupport ? 0 : fMinBlockSize); GrAssert(0 == fPreallocBuffersInUse); VALIDATE(); } void GrBufferAllocPool::unlock() { VALIDATE(); if (NULL != fBufferPtr) { BufferBlock& block = fBlocks.back(); if (block.fBuffer->isLocked()) { block.fBuffer->unlock(); } else { size_t flushSize = block.fBuffer->sizeInBytes() - block.fBytesFree; flushCpuData(fBlocks.back().fBuffer, flushSize); } fBufferPtr = NULL; } VALIDATE(); } #if GR_DEBUG void GrBufferAllocPool::validate(bool unusedBlockAllowed) const { if (NULL != fBufferPtr) { GrAssert(!fBlocks.empty()); if (fBlocks.back().fBuffer->isLocked()) { GrGeometryBuffer* buf = fBlocks.back().fBuffer; GrAssert(buf->lockPtr() == fBufferPtr); } else { GrAssert(fCpuData.get() == fBufferPtr); } } else { GrAssert(fBlocks.empty() || !fBlocks.back().fBuffer->isLocked()); } size_t bytesInUse = 0; for (int i = 0; i < fBlocks.count() - 1; ++i) { GrAssert(!fBlocks[i].fBuffer->isLocked()); } for (int i = 0; i < fBlocks.count(); ++i) { size_t bytes = fBlocks[i].fBuffer->sizeInBytes() - fBlocks[i].fBytesFree; bytesInUse += bytes; GrAssert(bytes || unusedBlockAllowed); } GrAssert(bytesInUse == fBytesInUse); if (unusedBlockAllowed) { GrAssert((fBytesInUse && !fBlocks.empty()) || (!fBytesInUse && (fBlocks.count() < 2))); } else { GrAssert((0 == fBytesInUse) == fBlocks.empty()); } } #endif void* GrBufferAllocPool::makeSpace(size_t size, size_t alignment, const GrGeometryBuffer** buffer, size_t* offset) { VALIDATE(); GrAssert(NULL != buffer); GrAssert(NULL != offset); if (NULL != fBufferPtr) { BufferBlock& back = fBlocks.back(); size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree; size_t pad = GrSizeAlignUpPad(usedBytes, alignment); if ((size + pad) <= back.fBytesFree) { usedBytes += pad; *offset = usedBytes; *buffer = back.fBuffer; back.fBytesFree -= size + pad; fBytesInUse += size; return (void*)(reinterpret_cast<intptr_t>(fBufferPtr) + usedBytes); } } // We could honor the space request using by a partial update of the current // VB (if there is room). But we don't currently use draw calls to GL that // allow the driver to know that previously issued draws won't read from // the part of the buffer we update. Also, the GL buffer implementation // may be cheating on the actual buffer size by shrinking the buffer on // updateData() if the amount of data passed is less than the full buffer // size. if (!createBlock(size)) { return NULL; } GrAssert(NULL != fBufferPtr); *offset = 0; BufferBlock& back = fBlocks.back(); *buffer = back.fBuffer; back.fBytesFree -= size; fBytesInUse += size; VALIDATE(); return fBufferPtr; } int GrBufferAllocPool::currentBufferItems(size_t itemSize) const { VALIDATE(); if (NULL != fBufferPtr) { const BufferBlock& back = fBlocks.back(); size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree; size_t pad = GrSizeAlignUpPad(usedBytes, itemSize); return (back.fBytesFree - pad) / itemSize; } else if (fPreallocBuffersInUse < fPreallocBuffers.count()) { return fMinBlockSize / itemSize; } return 0; } int GrBufferAllocPool::preallocatedBuffersRemaining() const { return fPreallocBuffers.count() - fPreallocBuffersInUse; } int GrBufferAllocPool::preallocatedBufferCount() const { return fPreallocBuffers.count(); } void GrBufferAllocPool::putBack(size_t bytes) { VALIDATE(); while (bytes) { // caller shouldnt try to put back more than they've taken GrAssert(!fBlocks.empty()); BufferBlock& block = fBlocks.back(); size_t bytesUsed = block.fBuffer->sizeInBytes() - block.fBytesFree; if (bytes >= bytesUsed) { bytes -= bytesUsed; fBytesInUse -= bytesUsed; // if we locked a vb to satisfy the make space and we're releasing // beyond it, then unlock it. if (block.fBuffer->isLocked()) { block.fBuffer->unlock(); } this->destroyBlock(); } else { block.fBytesFree += bytes; fBytesInUse -= bytes; bytes = 0; break; } } VALIDATE(); } bool GrBufferAllocPool::createBlock(size_t requestSize) { size_t size = GrMax(requestSize, fMinBlockSize); GrAssert(size >= GrBufferAllocPool_MIN_BLOCK_SIZE); VALIDATE(); BufferBlock& block = fBlocks.push_back(); if (size == fMinBlockSize && fPreallocBuffersInUse < fPreallocBuffers.count()) { uint32_t nextBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer) % fPreallocBuffers.count(); block.fBuffer = fPreallocBuffers[nextBuffer]; block.fBuffer->ref(); ++fPreallocBuffersInUse; } else { block.fBuffer = this->createBuffer(size); if (NULL == block.fBuffer) { fBlocks.pop_back(); return false; } } block.fBytesFree = size; if (NULL != fBufferPtr) { GrAssert(fBlocks.count() > 1); BufferBlock& prev = fBlocks.fromBack(1); if (prev.fBuffer->isLocked()) { prev.fBuffer->unlock(); } else { flushCpuData(prev.fBuffer, prev.fBuffer->sizeInBytes() - prev.fBytesFree); } fBufferPtr = NULL; } GrAssert(NULL == fBufferPtr); if (fGpu->getCaps().fBufferLockSupport && size > GR_GEOM_BUFFER_LOCK_THRESHOLD && (!fFrequentResetHint || requestSize > GR_GEOM_BUFFER_LOCK_THRESHOLD)) { fBufferPtr = block.fBuffer->lock(); } if (NULL == fBufferPtr) { fBufferPtr = fCpuData.reset(size); } VALIDATE(true); return true; } void GrBufferAllocPool::destroyBlock() { GrAssert(!fBlocks.empty()); BufferBlock& block = fBlocks.back(); if (fPreallocBuffersInUse > 0) { uint32_t prevPreallocBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer + (fPreallocBuffers.count() - 1)) % fPreallocBuffers.count(); if (block.fBuffer == fPreallocBuffers[prevPreallocBuffer]) { --fPreallocBuffersInUse; } } GrAssert(!block.fBuffer->isLocked()); block.fBuffer->unref(); fBlocks.pop_back(); fBufferPtr = NULL; } void GrBufferAllocPool::flushCpuData(GrGeometryBuffer* buffer, size_t flushSize) { GrAssert(NULL != buffer); GrAssert(!buffer->isLocked()); GrAssert(fCpuData.get() == fBufferPtr); GrAssert(flushSize <= buffer->sizeInBytes()); bool updated = false; if (fGpu->getCaps().fBufferLockSupport && flushSize > GR_GEOM_BUFFER_LOCK_THRESHOLD) { void* data = buffer->lock(); if (NULL != data) { memcpy(data, fBufferPtr, flushSize); buffer->unlock(); updated = true; } } buffer->updateData(fBufferPtr, flushSize); } GrGeometryBuffer* GrBufferAllocPool::createBuffer(size_t size) { if (kIndex_BufferType == fBufferType) { return fGpu->createIndexBuffer(size, true); } else { GrAssert(kVertex_BufferType == fBufferType); return fGpu->createVertexBuffer(size, true); } } //////////////////////////////////////////////////////////////////////////////// GrVertexBufferAllocPool::GrVertexBufferAllocPool(GrGpu* gpu, bool frequentResetHint, size_t bufferSize, int preallocBufferCnt) : GrBufferAllocPool(gpu, kVertex_BufferType, frequentResetHint, bufferSize, preallocBufferCnt) { } void* GrVertexBufferAllocPool::makeSpace(GrVertexLayout layout, int vertexCount, const GrVertexBuffer** buffer, int* startVertex) { GrAssert(vertexCount >= 0); GrAssert(NULL != buffer); GrAssert(NULL != startVertex); size_t vSize = GrDrawTarget::VertexSize(layout); size_t offset = 0; // assign to suppress warning const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning void* ptr = INHERITED::makeSpace(vSize * vertexCount, vSize, &geomBuffer, &offset); *buffer = (const GrVertexBuffer*) geomBuffer; GrAssert(0 == offset % vSize); *startVertex = offset / vSize; return ptr; } bool GrVertexBufferAllocPool::appendVertices(GrVertexLayout layout, int vertexCount, const void* vertices, const GrVertexBuffer** buffer, int* startVertex) { void* space = makeSpace(layout, vertexCount, buffer, startVertex); if (NULL != space) { memcpy(space, vertices, GrDrawTarget::VertexSize(layout) * vertexCount); return true; } else { return false; } } int GrVertexBufferAllocPool::preallocatedBufferVertices(GrVertexLayout layout) const { return INHERITED::preallocatedBufferSize() / GrDrawTarget::VertexSize(layout); } int GrVertexBufferAllocPool::currentBufferVertices(GrVertexLayout layout) const { return currentBufferItems(GrDrawTarget::VertexSize(layout)); } //////////////////////////////////////////////////////////////////////////////// GrIndexBufferAllocPool::GrIndexBufferAllocPool(GrGpu* gpu, bool frequentResetHint, size_t bufferSize, int preallocBufferCnt) : GrBufferAllocPool(gpu, kIndex_BufferType, frequentResetHint, bufferSize, preallocBufferCnt) { } void* GrIndexBufferAllocPool::makeSpace(int indexCount, const GrIndexBuffer** buffer, int* startIndex) { GrAssert(indexCount >= 0); GrAssert(NULL != buffer); GrAssert(NULL != startIndex); size_t offset = 0; // assign to suppress warning const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning void* ptr = INHERITED::makeSpace(indexCount * sizeof(uint16_t), sizeof(uint16_t), &geomBuffer, &offset); *buffer = (const GrIndexBuffer*) geomBuffer; GrAssert(0 == offset % sizeof(uint16_t)); *startIndex = offset / sizeof(uint16_t); return ptr; } bool GrIndexBufferAllocPool::appendIndices(int indexCount, const void* indices, const GrIndexBuffer** buffer, int* startIndex) { void* space = makeSpace(indexCount, buffer, startIndex); if (NULL != space) { memcpy(space, indices, sizeof(uint16_t) * indexCount); return true; } else { return false; } } int GrIndexBufferAllocPool::preallocatedBufferIndices() const { return INHERITED::preallocatedBufferSize() / sizeof(uint16_t); } int GrIndexBufferAllocPool::currentBufferIndices() const { return currentBufferItems(sizeof(uint16_t)); } <commit_msg>Don't update vertex/index buffer twice! <commit_after> /* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrBufferAllocPool.h" #include "GrTypes.h" #include "GrVertexBuffer.h" #include "GrIndexBuffer.h" #include "GrGpu.h" #if GR_DEBUG #define VALIDATE validate #else static void VALIDATE(bool x = false) {} #endif // page size #define GrBufferAllocPool_MIN_BLOCK_SIZE ((size_t)1 << 12) GrBufferAllocPool::GrBufferAllocPool(GrGpu* gpu, BufferType bufferType, bool frequentResetHint, size_t blockSize, int preallocBufferCnt) : fBlocks(GrMax(8, 2*preallocBufferCnt)) { GrAssert(NULL != gpu); fGpu = gpu; fGpu->ref(); fGpuIsReffed = true; fBufferType = bufferType; fFrequentResetHint = frequentResetHint; fBufferPtr = NULL; fMinBlockSize = GrMax(GrBufferAllocPool_MIN_BLOCK_SIZE, blockSize); fBytesInUse = 0; fPreallocBuffersInUse = 0; fFirstPreallocBuffer = 0; for (int i = 0; i < preallocBufferCnt; ++i) { GrGeometryBuffer* buffer = this->createBuffer(fMinBlockSize); if (NULL != buffer) { *fPreallocBuffers.append() = buffer; buffer->ref(); } } } GrBufferAllocPool::~GrBufferAllocPool() { VALIDATE(); if (fBlocks.count()) { GrGeometryBuffer* buffer = fBlocks.back().fBuffer; if (buffer->isLocked()) { buffer->unlock(); } } while (!fBlocks.empty()) { destroyBlock(); } fPreallocBuffers.unrefAll(); releaseGpuRef(); } void GrBufferAllocPool::releaseGpuRef() { if (fGpuIsReffed) { fGpu->unref(); fGpuIsReffed = false; } } void GrBufferAllocPool::reset() { VALIDATE(); fBytesInUse = 0; if (fBlocks.count()) { GrGeometryBuffer* buffer = fBlocks.back().fBuffer; if (buffer->isLocked()) { buffer->unlock(); } } while (!fBlocks.empty()) { destroyBlock(); } if (fPreallocBuffers.count()) { // must set this after above loop. fFirstPreallocBuffer = (fFirstPreallocBuffer + fPreallocBuffersInUse) % fPreallocBuffers.count(); } fCpuData.reset(fGpu->getCaps().fBufferLockSupport ? 0 : fMinBlockSize); GrAssert(0 == fPreallocBuffersInUse); VALIDATE(); } void GrBufferAllocPool::unlock() { VALIDATE(); if (NULL != fBufferPtr) { BufferBlock& block = fBlocks.back(); if (block.fBuffer->isLocked()) { block.fBuffer->unlock(); } else { size_t flushSize = block.fBuffer->sizeInBytes() - block.fBytesFree; flushCpuData(fBlocks.back().fBuffer, flushSize); } fBufferPtr = NULL; } VALIDATE(); } #if GR_DEBUG void GrBufferAllocPool::validate(bool unusedBlockAllowed) const { if (NULL != fBufferPtr) { GrAssert(!fBlocks.empty()); if (fBlocks.back().fBuffer->isLocked()) { GrGeometryBuffer* buf = fBlocks.back().fBuffer; GrAssert(buf->lockPtr() == fBufferPtr); } else { GrAssert(fCpuData.get() == fBufferPtr); } } else { GrAssert(fBlocks.empty() || !fBlocks.back().fBuffer->isLocked()); } size_t bytesInUse = 0; for (int i = 0; i < fBlocks.count() - 1; ++i) { GrAssert(!fBlocks[i].fBuffer->isLocked()); } for (int i = 0; i < fBlocks.count(); ++i) { size_t bytes = fBlocks[i].fBuffer->sizeInBytes() - fBlocks[i].fBytesFree; bytesInUse += bytes; GrAssert(bytes || unusedBlockAllowed); } GrAssert(bytesInUse == fBytesInUse); if (unusedBlockAllowed) { GrAssert((fBytesInUse && !fBlocks.empty()) || (!fBytesInUse && (fBlocks.count() < 2))); } else { GrAssert((0 == fBytesInUse) == fBlocks.empty()); } } #endif void* GrBufferAllocPool::makeSpace(size_t size, size_t alignment, const GrGeometryBuffer** buffer, size_t* offset) { VALIDATE(); GrAssert(NULL != buffer); GrAssert(NULL != offset); if (NULL != fBufferPtr) { BufferBlock& back = fBlocks.back(); size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree; size_t pad = GrSizeAlignUpPad(usedBytes, alignment); if ((size + pad) <= back.fBytesFree) { usedBytes += pad; *offset = usedBytes; *buffer = back.fBuffer; back.fBytesFree -= size + pad; fBytesInUse += size; return (void*)(reinterpret_cast<intptr_t>(fBufferPtr) + usedBytes); } } // We could honor the space request using by a partial update of the current // VB (if there is room). But we don't currently use draw calls to GL that // allow the driver to know that previously issued draws won't read from // the part of the buffer we update. Also, the GL buffer implementation // may be cheating on the actual buffer size by shrinking the buffer on // updateData() if the amount of data passed is less than the full buffer // size. if (!createBlock(size)) { return NULL; } GrAssert(NULL != fBufferPtr); *offset = 0; BufferBlock& back = fBlocks.back(); *buffer = back.fBuffer; back.fBytesFree -= size; fBytesInUse += size; VALIDATE(); return fBufferPtr; } int GrBufferAllocPool::currentBufferItems(size_t itemSize) const { VALIDATE(); if (NULL != fBufferPtr) { const BufferBlock& back = fBlocks.back(); size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree; size_t pad = GrSizeAlignUpPad(usedBytes, itemSize); return (back.fBytesFree - pad) / itemSize; } else if (fPreallocBuffersInUse < fPreallocBuffers.count()) { return fMinBlockSize / itemSize; } return 0; } int GrBufferAllocPool::preallocatedBuffersRemaining() const { return fPreallocBuffers.count() - fPreallocBuffersInUse; } int GrBufferAllocPool::preallocatedBufferCount() const { return fPreallocBuffers.count(); } void GrBufferAllocPool::putBack(size_t bytes) { VALIDATE(); while (bytes) { // caller shouldnt try to put back more than they've taken GrAssert(!fBlocks.empty()); BufferBlock& block = fBlocks.back(); size_t bytesUsed = block.fBuffer->sizeInBytes() - block.fBytesFree; if (bytes >= bytesUsed) { bytes -= bytesUsed; fBytesInUse -= bytesUsed; // if we locked a vb to satisfy the make space and we're releasing // beyond it, then unlock it. if (block.fBuffer->isLocked()) { block.fBuffer->unlock(); } this->destroyBlock(); } else { block.fBytesFree += bytes; fBytesInUse -= bytes; bytes = 0; break; } } VALIDATE(); } bool GrBufferAllocPool::createBlock(size_t requestSize) { size_t size = GrMax(requestSize, fMinBlockSize); GrAssert(size >= GrBufferAllocPool_MIN_BLOCK_SIZE); VALIDATE(); BufferBlock& block = fBlocks.push_back(); if (size == fMinBlockSize && fPreallocBuffersInUse < fPreallocBuffers.count()) { uint32_t nextBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer) % fPreallocBuffers.count(); block.fBuffer = fPreallocBuffers[nextBuffer]; block.fBuffer->ref(); ++fPreallocBuffersInUse; } else { block.fBuffer = this->createBuffer(size); if (NULL == block.fBuffer) { fBlocks.pop_back(); return false; } } block.fBytesFree = size; if (NULL != fBufferPtr) { GrAssert(fBlocks.count() > 1); BufferBlock& prev = fBlocks.fromBack(1); if (prev.fBuffer->isLocked()) { prev.fBuffer->unlock(); } else { flushCpuData(prev.fBuffer, prev.fBuffer->sizeInBytes() - prev.fBytesFree); } fBufferPtr = NULL; } GrAssert(NULL == fBufferPtr); if (fGpu->getCaps().fBufferLockSupport && size > GR_GEOM_BUFFER_LOCK_THRESHOLD && (!fFrequentResetHint || requestSize > GR_GEOM_BUFFER_LOCK_THRESHOLD)) { fBufferPtr = block.fBuffer->lock(); } if (NULL == fBufferPtr) { fBufferPtr = fCpuData.reset(size); } VALIDATE(true); return true; } void GrBufferAllocPool::destroyBlock() { GrAssert(!fBlocks.empty()); BufferBlock& block = fBlocks.back(); if (fPreallocBuffersInUse > 0) { uint32_t prevPreallocBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer + (fPreallocBuffers.count() - 1)) % fPreallocBuffers.count(); if (block.fBuffer == fPreallocBuffers[prevPreallocBuffer]) { --fPreallocBuffersInUse; } } GrAssert(!block.fBuffer->isLocked()); block.fBuffer->unref(); fBlocks.pop_back(); fBufferPtr = NULL; } void GrBufferAllocPool::flushCpuData(GrGeometryBuffer* buffer, size_t flushSize) { GrAssert(NULL != buffer); GrAssert(!buffer->isLocked()); GrAssert(fCpuData.get() == fBufferPtr); GrAssert(flushSize <= buffer->sizeInBytes()); if (fGpu->getCaps().fBufferLockSupport && flushSize > GR_GEOM_BUFFER_LOCK_THRESHOLD) { void* data = buffer->lock(); if (NULL != data) { memcpy(data, fBufferPtr, flushSize); buffer->unlock(); return; } } buffer->updateData(fBufferPtr, flushSize); } GrGeometryBuffer* GrBufferAllocPool::createBuffer(size_t size) { if (kIndex_BufferType == fBufferType) { return fGpu->createIndexBuffer(size, true); } else { GrAssert(kVertex_BufferType == fBufferType); return fGpu->createVertexBuffer(size, true); } } //////////////////////////////////////////////////////////////////////////////// GrVertexBufferAllocPool::GrVertexBufferAllocPool(GrGpu* gpu, bool frequentResetHint, size_t bufferSize, int preallocBufferCnt) : GrBufferAllocPool(gpu, kVertex_BufferType, frequentResetHint, bufferSize, preallocBufferCnt) { } void* GrVertexBufferAllocPool::makeSpace(GrVertexLayout layout, int vertexCount, const GrVertexBuffer** buffer, int* startVertex) { GrAssert(vertexCount >= 0); GrAssert(NULL != buffer); GrAssert(NULL != startVertex); size_t vSize = GrDrawTarget::VertexSize(layout); size_t offset = 0; // assign to suppress warning const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning void* ptr = INHERITED::makeSpace(vSize * vertexCount, vSize, &geomBuffer, &offset); *buffer = (const GrVertexBuffer*) geomBuffer; GrAssert(0 == offset % vSize); *startVertex = offset / vSize; return ptr; } bool GrVertexBufferAllocPool::appendVertices(GrVertexLayout layout, int vertexCount, const void* vertices, const GrVertexBuffer** buffer, int* startVertex) { void* space = makeSpace(layout, vertexCount, buffer, startVertex); if (NULL != space) { memcpy(space, vertices, GrDrawTarget::VertexSize(layout) * vertexCount); return true; } else { return false; } } int GrVertexBufferAllocPool::preallocatedBufferVertices(GrVertexLayout layout) const { return INHERITED::preallocatedBufferSize() / GrDrawTarget::VertexSize(layout); } int GrVertexBufferAllocPool::currentBufferVertices(GrVertexLayout layout) const { return currentBufferItems(GrDrawTarget::VertexSize(layout)); } //////////////////////////////////////////////////////////////////////////////// GrIndexBufferAllocPool::GrIndexBufferAllocPool(GrGpu* gpu, bool frequentResetHint, size_t bufferSize, int preallocBufferCnt) : GrBufferAllocPool(gpu, kIndex_BufferType, frequentResetHint, bufferSize, preallocBufferCnt) { } void* GrIndexBufferAllocPool::makeSpace(int indexCount, const GrIndexBuffer** buffer, int* startIndex) { GrAssert(indexCount >= 0); GrAssert(NULL != buffer); GrAssert(NULL != startIndex); size_t offset = 0; // assign to suppress warning const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning void* ptr = INHERITED::makeSpace(indexCount * sizeof(uint16_t), sizeof(uint16_t), &geomBuffer, &offset); *buffer = (const GrIndexBuffer*) geomBuffer; GrAssert(0 == offset % sizeof(uint16_t)); *startIndex = offset / sizeof(uint16_t); return ptr; } bool GrIndexBufferAllocPool::appendIndices(int indexCount, const void* indices, const GrIndexBuffer** buffer, int* startIndex) { void* space = makeSpace(indexCount, buffer, startIndex); if (NULL != space) { memcpy(space, indices, sizeof(uint16_t) * indexCount); return true; } else { return false; } } int GrIndexBufferAllocPool::preallocatedBufferIndices() const { return INHERITED::preallocatedBufferSize() / sizeof(uint16_t); } int GrIndexBufferAllocPool::currentBufferIndices() const { return currentBufferItems(sizeof(uint16_t)); } <|endoftext|>
<commit_before>/*! * \file painter_dashed_stroke_shader_set.hpp * \brief file painter_dashed_stroke_shader_set.hpp * * Copyright 2016 by Intel. * * Contact: kevin.rogovin@intel.com * * This Source Code Form is subject to the * terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with * this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #pragma once #include <fastuidraw/util/reference_counted.hpp> #include <fastuidraw/painter/painter_stroke_shader.hpp> #include <fastuidraw/painter/painter_enums.hpp> namespace fastuidraw { class PainterItemShaderData; /*!\addtogroup Painter @{ */ /*! A DashEvaluator is used by Painter to realize the data to send to a PainterPacker for the purpose of dashed stroking. */ class DashEvaluator: public reference_counted<DashEvaluator>::default_base { public: /*! To be implemented by a derived class to give the distance to the next dash boundary. Giving a negative value indicates that the location passed is not drawn when dashed and giving a positive indicates it is. \param data PainterItemShaderData object holding the data to be sent to the shader \param distance the distance to use to use to compute the return value */ virtual float signed_distance_to_next_dash_boundary(const PainterItemShaderData &data, float distance) const; }; /*! A PainterDashedStrokeShaderSet holds a collection of PainterStrokeShaderSet objects for the purpose of dashed stroking. The shaders within a PainterDashedStrokeShaderSet are expected to draw any caps of dashed stroking from using just the edge data. In particular, attributes/indices for caps are NEVER given to a shader within a PainterDashedStrokeShaderSet. */ class PainterDashedStrokeShaderSet { public: /*! Ctor */ PainterDashedStrokeShaderSet(void); /*! Copy ctor. */ PainterDashedStrokeShaderSet(const PainterDashedStrokeShaderSet &obj); ~PainterDashedStrokeShaderSet(); /*! Assignment operator. */ PainterDashedStrokeShaderSet& operator=(const PainterDashedStrokeShaderSet &rhs); /*! Returns the DashEvaluator object to be used with the expected PainterItemShaderData passed to the PainterStrokeShader objects of this PainterDashedStrokeShaderSet. */ const reference_counted_ptr<const DashEvaluator>& dash_evaluator(void) const; /*! Set the value returned by dash_evaluator(void) const. Initial value is NULL. */ PainterDashedStrokeShaderSet& dash_evaluator(const reference_counted_ptr<const DashEvaluator>&); /*! Shader set for dashed stroking of paths where the stroking width is given in same units as the original path. The stroking parameters are given by PainterDashedStrokeParams. \param st cap style */ const PainterStrokeShader& shader(enum PainterEnums::dashed_cap_style st) const; /*! Set the value returned by dashed_stroke_shader(enum PainterEnums::dashed_cap_style) const. \param st cap style \param sh value to use */ PainterDashedStrokeShaderSet& shader(enum PainterEnums::dashed_cap_style st, const PainterStrokeShader &sh); private: void *m_d; }; /*! @} */ } <commit_msg>fastuidraw/painter: use DataBase object directly in DashEvaluator<commit_after>/*! * \file painter_dashed_stroke_shader_set.hpp * \brief file painter_dashed_stroke_shader_set.hpp * * Copyright 2016 by Intel. * * Contact: kevin.rogovin@intel.com * * This Source Code Form is subject to the * terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with * this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #pragma once #include <fastuidraw/util/reference_counted.hpp> #include <fastuidraw/painter/painter_value.hpp> #include <fastuidraw/painter/painter_stroke_shader.hpp> #include <fastuidraw/painter/painter_enums.hpp> namespace fastuidraw { /*!\addtogroup Painter @{ */ /*! A DashEvaluator is used by Painter to realize the data to send to a PainterPacker for the purpose of dashed stroking. */ class DashEvaluator: public reference_counted<DashEvaluator>::default_base { public: /*! To be implemented by a derived class to return the distance to the next dash boundary. A negative return value indicates that the location passed is not drawn when dashed and a positive indicates it is. \param data PainterItemShaderData::DataBase object holding the data to be sent to the shader \param distance the distance to use to compute the return value */ virtual float signed_distance_to_next_dash_boundary(const PainterShaderData::DataBase *data, float distance) const; }; /*! A PainterDashedStrokeShaderSet holds a collection of PainterStrokeShaderSet objects for the purpose of dashed stroking. The shaders within a PainterDashedStrokeShaderSet are expected to draw any caps of dashed stroking from using just the edge data. In particular, attributes/indices for caps are NEVER given to a shader within a PainterDashedStrokeShaderSet. */ class PainterDashedStrokeShaderSet { public: /*! Ctor */ PainterDashedStrokeShaderSet(void); /*! Copy ctor. */ PainterDashedStrokeShaderSet(const PainterDashedStrokeShaderSet &obj); ~PainterDashedStrokeShaderSet(); /*! Assignment operator. */ PainterDashedStrokeShaderSet& operator=(const PainterDashedStrokeShaderSet &rhs); /*! Returns the DashEvaluator object to be used with the expected PainterItemShaderData passed to the PainterStrokeShader objects of this PainterDashedStrokeShaderSet. */ const reference_counted_ptr<const DashEvaluator>& dash_evaluator(void) const; /*! Set the value returned by dash_evaluator(void) const. Initial value is NULL. */ PainterDashedStrokeShaderSet& dash_evaluator(const reference_counted_ptr<const DashEvaluator>&); /*! Shader set for dashed stroking of paths where the stroking width is given in same units as the original path. The stroking parameters are given by PainterDashedStrokeParams. \param st cap style */ const PainterStrokeShader& shader(enum PainterEnums::dashed_cap_style st) const; /*! Set the value returned by dashed_stroke_shader(enum PainterEnums::dashed_cap_style) const. \param st cap style \param sh value to use */ PainterDashedStrokeShaderSet& shader(enum PainterEnums::dashed_cap_style st, const PainterStrokeShader &sh); private: void *m_d; }; /*! @} */ } <|endoftext|>
<commit_before>/* opendatacon * * Copyright (c) 2020: * * DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi * yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA== * * 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. */ /* * BinaryControl.cpp * * Created on: 2021-02-08 * A year of hope that pandemic will end soon * Author: Rakesh Kumar <cpp.rakesh@gmail.com> */ #include "BinaryControl.h" void BinaryControl::CreateBinaryControl(std::size_t index, const std::shared_ptr<odc::EventInfo>& on, const std::shared_ptr<odc::EventInfo>& off, FeedbackMode mode, std::size_t update_interval) { { // for the scope of lock std::unique_lock<std::shared_timed_mutex> lck(feedback_mutex); m_binary_feedbacks[index].emplace_back(std::make_shared<BinaryFeedback>(on, off, mode, update_interval)); } if (!IsIndex(index)) { odc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload; payload.functionCode = odc::ControlCode::NUL; std::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, on->GetSourcePort(), odc::QualityFlags::COMM_LOST); control_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload)); control_event->SetTimestamp(0); { // for the scope of the lock std::unique_lock<std::shared_timed_mutex> lck(current_mutex); m_current_binary_events[index] = control_event; } } } std::vector<std::shared_ptr<BinaryFeedback>> BinaryControl::BinaryFeedbacks(std::size_t index) { std::shared_lock<std::shared_timed_mutex> lck(feedback_mutex); std::vector<std::shared_ptr<BinaryFeedback>> feedback; if (m_binary_feedbacks.find(index) != m_binary_feedbacks.end()) feedback = m_binary_feedbacks[index]; return feedback; } void BinaryControl::CreateBinaryControl(std::size_t index, const std::string& port_source, odc::FeedbackType type, const std::vector<std::size_t>& indexes, const std::vector<odc::PositionAction>& action, std::size_t lower_limit, std::size_t raise_limit) { odc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload; payload.functionCode = odc::ControlCode::NUL; std::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, port_source, odc::QualityFlags::COMM_LOST); control_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload)); control_event->SetTimestamp(0); { // scope of the lock std::unique_lock<std::shared_timed_mutex> lck(position_mutex); m_binary_positions[index] = std::make_shared<BinaryPosition>(type, action, indexes, lower_limit, raise_limit); } { // scope of the lock std::unique_lock<std::shared_timed_mutex> lck(current_mutex); m_current_binary_events[index] = control_event; } } std::shared_ptr<BinaryPosition> BinaryControl::GetBinaryPosition(std::size_t index) { std::shared_lock<std::shared_timed_mutex> lck(position_mutex); return m_binary_positions[index]; } void BinaryControl::CreateBinaryControl(std::size_t index) { std::unique_lock<std::shared_timed_mutex> lck(current_mutex); m_current_binary_events[index] = nullptr; } bool BinaryControl::IsIndex(std::size_t index) { std::shared_lock<std::shared_timed_mutex> lck(current_mutex); return m_current_binary_events.find(index) != m_current_binary_events.end(); } void BinaryControl::SetCurrentBinaryEvent(const std::shared_ptr<odc::EventInfo>& event, std::size_t index) { std::unique_lock<std::shared_timed_mutex> lck(current_mutex); m_current_binary_events[index] = event; } std::shared_ptr<odc::EventInfo> BinaryControl::GetCurrentBinaryEvent(std::size_t index) { std::shared_lock<std::shared_timed_mutex> lck(current_mutex); return m_current_binary_events[index]; } <commit_msg>initialise SimPort control status values not null<commit_after>/* opendatacon * * Copyright (c) 2020: * * DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi * yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA== * * 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. */ /* * BinaryControl.cpp * * Created on: 2021-02-08 * A year of hope that pandemic will end soon * Author: Rakesh Kumar <cpp.rakesh@gmail.com> */ #include "BinaryControl.h" void BinaryControl::CreateBinaryControl(std::size_t index, const std::shared_ptr<odc::EventInfo>& on, const std::shared_ptr<odc::EventInfo>& off, FeedbackMode mode, std::size_t update_interval) { { // for the scope of lock std::unique_lock<std::shared_timed_mutex> lck(feedback_mutex); m_binary_feedbacks[index].emplace_back(std::make_shared<BinaryFeedback>(on, off, mode, update_interval)); } if (!IsIndex(index)) { odc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload; payload.functionCode = odc::ControlCode::NUL; std::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, on->GetSourcePort(), odc::QualityFlags::COMM_LOST); control_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload)); control_event->SetTimestamp(0); { // for the scope of the lock std::unique_lock<std::shared_timed_mutex> lck(current_mutex); m_current_binary_events[index] = control_event; } } } std::vector<std::shared_ptr<BinaryFeedback>> BinaryControl::BinaryFeedbacks(std::size_t index) { std::shared_lock<std::shared_timed_mutex> lck(feedback_mutex); std::vector<std::shared_ptr<BinaryFeedback>> feedback; if (m_binary_feedbacks.find(index) != m_binary_feedbacks.end()) feedback = m_binary_feedbacks[index]; return feedback; } void BinaryControl::CreateBinaryControl(std::size_t index, const std::string& port_source, odc::FeedbackType type, const std::vector<std::size_t>& indexes, const std::vector<odc::PositionAction>& action, std::size_t lower_limit, std::size_t raise_limit) { odc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload; payload.functionCode = odc::ControlCode::NUL; std::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, port_source, odc::QualityFlags::COMM_LOST); control_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload)); control_event->SetTimestamp(0); { // scope of the lock std::unique_lock<std::shared_timed_mutex> lck(position_mutex); m_binary_positions[index] = std::make_shared<BinaryPosition>(type, action, indexes, lower_limit, raise_limit); } { // scope of the lock std::unique_lock<std::shared_timed_mutex> lck(current_mutex); m_current_binary_events[index] = control_event; } } std::shared_ptr<BinaryPosition> BinaryControl::GetBinaryPosition(std::size_t index) { std::shared_lock<std::shared_timed_mutex> lck(position_mutex); return m_binary_positions[index]; } void BinaryControl::CreateBinaryControl(std::size_t index) { odc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload; payload.functionCode = odc::ControlCode::NUL; std::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, "NULL", odc::QualityFlags::COMM_LOST); control_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload)); control_event->SetTimestamp(0); { // scope of the lock std::unique_lock<std::shared_timed_mutex> lck(current_mutex); m_current_binary_events[index] = control_event; } } bool BinaryControl::IsIndex(std::size_t index) { std::shared_lock<std::shared_timed_mutex> lck(current_mutex); return m_current_binary_events.find(index) != m_current_binary_events.end(); } void BinaryControl::SetCurrentBinaryEvent(const std::shared_ptr<odc::EventInfo>& event, std::size_t index) { std::unique_lock<std::shared_timed_mutex> lck(current_mutex); m_current_binary_events[index] = event; } std::shared_ptr<odc::EventInfo> BinaryControl::GetCurrentBinaryEvent(std::size_t index) { std::shared_lock<std::shared_timed_mutex> lck(current_mutex); return m_current_binary_events[index]; } <|endoftext|>
<commit_before>/* * File: ExponentiallyDecaying.hpp * Part of commonpp. * * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2015 Thomas Sanchez. All rights reserved. * */ #pragma once #include <algorithm> #include <random> #include <chrono> #include <mutex> #include <cmath> #include <map> #include <mutex> #include "types.hpp" namespace commonpp { namespace metric { namespace reservoir { // Implementation from: // https://github.com/dropwizard/metrics/blob/master/metrics-core/src/main/java/io/dropwizard/metrics/ExponentiallyDecayingReservoir.java template <size_t size_ = 1028, size_t alpha_time_1000 = 15, typename clock_ = std::chrono::system_clock, typename Mutex = std::mutex> class ExponentiallyDecaying { template <typename K, typename V> using MapType = std::map<K, V>; public: static const WeightedReservoirTag tag; static constexpr const double ALPHA = double(alpha_time_1000) * 0.001; using ElapsedTimeUnit = std::chrono::seconds; static constexpr const size_t MAX_SIZE = size_; using Clock = clock_; using Timepoint = typename Clock::time_point; using Weight = double; struct Sample { Weight weight; double value; }; const std::chrono::hours RESCALE_INTERVAL{1}; public: ExponentiallyDecaying(); ~ExponentiallyDecaying() = default; void pushValue(double value, Timepoint timepoint = Clock::now()); template <typename Summary> auto visit() const -> decltype(Summary::createAccumulator(0, tag)) { std::lock_guard<Mutex> lock(mutex_); auto acc = Summary::createAccumulator(size_unsafe(), tag); for (const auto& value : values_) { const auto& sample = value.second; acc(sample.weight, sample.value); } return acc; } size_t size() const; size_t size_unsafe() const; private: void rescale(); static Weight weight(ElapsedTimeUnit duration); private: mutable Mutex mutex_; std::random_device random_; std::mt19937 gen_; std::uniform_real_distribution<> dis_; MapType<Weight, Sample> values_; Timepoint start_time_; Timepoint next_rescale_; }; template <size_t s, size_t a, typename c, typename m> ExponentiallyDecaying<s, a, c, m>::ExponentiallyDecaying() : gen_(random_()) , dis_(0, 1) { start_time_ = Clock::now(); next_rescale_ = start_time_ + RESCALE_INTERVAL; } template <size_t s, size_t a, typename c, typename m> typename ExponentiallyDecaying<s, a, c, m>::Weight ExponentiallyDecaying<s, a, c, m>::weight(ElapsedTimeUnit duration) { return ::exp(ALPHA * duration.count()); } template <size_t s, size_t a, typename c, typename m> size_t ExponentiallyDecaying<s, a, c, m>::size() const { std::lock_guard<m> lock(mutex_); return values_.size(); } template <size_t s, size_t a, typename c, typename m> size_t ExponentiallyDecaying<s, a, c, m>::size_unsafe() const { return values_.size(); } template <size_t s, size_t a, typename c, typename m> void ExponentiallyDecaying<s, a, c, m>::pushValue(double value, Timepoint timestamp) { std::lock_guard<m> lock(mutex_); rescale(); auto elapsed_time = std::chrono::duration_cast<ElapsedTimeUnit>(timestamp - start_time_); Sample sample{weight(elapsed_time), value}; double priority = sample.weight / dis_(gen_); auto new_size = values_.size() + 1; if (new_size <= MAX_SIZE) { values_[priority] = sample; } else { auto it_first = values_.begin(); if (it_first->first < priority && values_.emplace(priority, sample).second) { values_.erase(it_first); } } } template <size_t s, size_t a, typename c, typename m> void ExponentiallyDecaying<s, a, c, m>::rescale() { Timepoint now = Clock::now(); if (now < next_rescale_) { return; } next_rescale_ = now + RESCALE_INTERVAL; auto old_start_time = start_time_; start_time_ = now; decltype(values_) values; values.swap(values_); const auto time = std::chrono::duration_cast<ElapsedTimeUnit>(start_time_ - old_start_time) .count(); auto scale_factor = ::exp(-ALPHA * time); for (const auto& v : values) { auto key = v.first; auto const& sample = v.second; values_[key * scale_factor] = {sample.weight * scale_factor, sample.value}; } } } // namespace reservoir } // namespace metric } // namespace commonpp <commit_msg>Instantiate static constant<commit_after>/* * File: ExponentiallyDecaying.hpp * Part of commonpp. * * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2015 Thomas Sanchez. All rights reserved. * */ #pragma once #include <algorithm> #include <random> #include <chrono> #include <mutex> #include <cmath> #include <map> #include <mutex> #include "types.hpp" namespace commonpp { namespace metric { namespace reservoir { // Implementation from: // https://github.com/dropwizard/metrics/blob/master/metrics-core/src/main/java/io/dropwizard/metrics/ExponentiallyDecayingReservoir.java template <size_t size_ = 1028, size_t alpha_time_1000 = 15, typename clock_ = std::chrono::system_clock, typename Mutex = std::mutex> class ExponentiallyDecaying { template <typename K, typename V> using MapType = std::map<K, V>; public: static const WeightedReservoirTag tag; static constexpr const double ALPHA = double(alpha_time_1000) * 0.001; using ElapsedTimeUnit = std::chrono::seconds; static constexpr const size_t MAX_SIZE = size_; using Clock = clock_; using Timepoint = typename Clock::time_point; using Weight = double; struct Sample { Weight weight; double value; }; const std::chrono::hours RESCALE_INTERVAL{1}; public: ExponentiallyDecaying(); ~ExponentiallyDecaying() = default; void pushValue(double value, Timepoint timepoint = Clock::now()); template <typename Summary> auto visit() const -> decltype(Summary::createAccumulator(0, tag)) { std::lock_guard<Mutex> lock(mutex_); auto acc = Summary::createAccumulator(size_unsafe(), tag); for (const auto& value : values_) { const auto& sample = value.second; acc(sample.weight, sample.value); } return acc; } size_t size() const; size_t size_unsafe() const; private: void rescale(); static Weight weight(ElapsedTimeUnit duration); private: mutable Mutex mutex_; std::random_device random_; std::mt19937 gen_; std::uniform_real_distribution<> dis_; MapType<Weight, Sample> values_; Timepoint start_time_; Timepoint next_rescale_; }; template <size_t s, size_t a, typename c, typename m> const WeightedReservoirTag ExponentiallyDecaying<s, a, c, m>::tag = {}; template <size_t s, size_t a, typename c, typename m> ExponentiallyDecaying<s, a, c, m>::ExponentiallyDecaying() : gen_(random_()) , dis_(0, 1) { start_time_ = Clock::now(); next_rescale_ = start_time_ + RESCALE_INTERVAL; } template <size_t s, size_t a, typename c, typename m> typename ExponentiallyDecaying<s, a, c, m>::Weight ExponentiallyDecaying<s, a, c, m>::weight(ElapsedTimeUnit duration) { return ::exp(ALPHA * duration.count()); } template <size_t s, size_t a, typename c, typename m> size_t ExponentiallyDecaying<s, a, c, m>::size() const { std::lock_guard<m> lock(mutex_); return values_.size(); } template <size_t s, size_t a, typename c, typename m> size_t ExponentiallyDecaying<s, a, c, m>::size_unsafe() const { return values_.size(); } template <size_t s, size_t a, typename c, typename m> void ExponentiallyDecaying<s, a, c, m>::pushValue(double value, Timepoint timestamp) { std::lock_guard<m> lock(mutex_); rescale(); auto elapsed_time = std::chrono::duration_cast<ElapsedTimeUnit>(timestamp - start_time_); Sample sample{weight(elapsed_time), value}; double priority = sample.weight / dis_(gen_); auto new_size = values_.size() + 1; if (new_size <= MAX_SIZE) { values_[priority] = sample; } else { auto it_first = values_.begin(); if (it_first->first < priority && values_.emplace(priority, sample).second) { values_.erase(it_first); } } } template <size_t s, size_t a, typename c, typename m> void ExponentiallyDecaying<s, a, c, m>::rescale() { Timepoint now = Clock::now(); if (now < next_rescale_) { return; } next_rescale_ = now + RESCALE_INTERVAL; auto old_start_time = start_time_; start_time_ = now; decltype(values_) values; values.swap(values_); const auto time = std::chrono::duration_cast<ElapsedTimeUnit>(start_time_ - old_start_time) .count(); auto scale_factor = ::exp(-ALPHA * time); for (const auto& v : values) { auto key = v.first; auto const& sample = v.second; values_[key * scale_factor] = {sample.weight * scale_factor, sample.value}; } } } // namespace reservoir } // namespace metric } // namespace commonpp <|endoftext|>
<commit_before>#ifndef VIRTUALROBOT_CPP #define VIRTUALROBOT_CPP #include <stdlib.h> #include <stdio.h> #include <GL/gl.h> #include <string.h> extern "C" { #include "logic/Robot.h" #include "logic/MazeAlgorithm.h" #include "logic/MazeMap.h" } #include "VirtualRobot.h" #include "Display.h" VirtualRobot::VirtualRobot(VirtualMaze* virtualMaze) { // create the robot using a blank maze map MazeMap* robotMM = (MazeMap*)calloc(1, sizeof(MazeMap)); robot = robot_create(0, 0, robotMM); // bind the robot maze map to the virtualmaze virtualMaze->bindRobotMap(robotMM); int blockWidthPX = VirtualMaze::getBlockWidthPX(); int x = robot->xPos * blockWidthPX + blockWidthPX/2 - robotSizePX/2; int y = robot->yPos * blockWidthPX + blockWidthPX/2 - robotSizePX/2; this->rectangle = new Rectangle(x, y, robotSizePX, robotSizePX); // save the pointer to the virtual maze this->virtualMaze = virtualMaze; // compute the flood fill //malgo_floodfill_compute(virtualMaze->getMazeMap(), floodFillMap); // //robot->ffMap = floodFillMap; } void VirtualRobot::run() { // feed in the raw wall sensor input feedSensorData(); // run the robot drive code robot_run(robot); // calculate and update the new position int blockWidthPX = VirtualMaze::getBlockWidthPX(); int offset = blockWidthPX / 2 - robotSizePX / 2; int newX = blockWidthPX * robot->xPos + offset; int newY = blockWidthPX * robot->yPos + offset; rectangle->setPos(newX, newY); } void VirtualRobot::feedSensorData() { // get the full map MazeMap* virtualMap = virtualMaze->getMazeMap(); int x = robot->xPos; int y = robot->yPos; // load in information about surroundings BOOL northWall = mazemap_does_wall_exist(virtualMap, x, y, NORTH); BOOL eastWall = mazemap_does_wall_exist(virtualMap, x, y, EAST); BOOL southWall = mazemap_does_wall_exist(virtualMap, x, y, SOUTH); BOOL westWall = mazemap_does_wall_exist(virtualMap, x, y, WEST); // plug the data from the virtual maze into the robot's maze map MazeMap* robotMap = robot->mazeMap; mazemap_set_wall(robotMap, northWall, x, y, NORTH); mazemap_set_wall(robotMap, eastWall, x, y, EAST); mazemap_set_wall(robotMap, southWall, x, y, SOUTH); mazemap_set_wall(robotMap, westWall, x, y, WEST); } void VirtualRobot::draw() { // draw the robot red rectangle->draw(1.0f, 0.0f, 0.0f); // draw the flood fill //ff_draw(robot->ffMap); } FFMapPtr VirtualRobot::getFloodFillMap() { return robot->ffMap; } VirtualRobot::~VirtualRobot() { // destroy the robot robot_destroy(robot); } #endif <commit_msg>robot now yellow when exploring, red when solving VirtualRobot checks the robot->isExploring flag when drawing<commit_after>#ifndef VIRTUALROBOT_CPP #define VIRTUALROBOT_CPP #include <stdlib.h> #include <stdio.h> #include <GL/gl.h> #include <string.h> extern "C" { #include "logic/Robot.h" #include "logic/MazeAlgorithm.h" #include "logic/MazeMap.h" } #include "VirtualRobot.h" #include "Display.h" VirtualRobot::VirtualRobot(VirtualMaze* virtualMaze) { // create the robot using a blank maze map MazeMap* robotMM = (MazeMap*)calloc(1, sizeof(MazeMap)); robot = robot_create(0, 0, robotMM); // bind the robot maze map to the virtualmaze virtualMaze->bindRobotMap(robotMM); int blockWidthPX = VirtualMaze::getBlockWidthPX(); int x = robot->xPos * blockWidthPX + blockWidthPX/2 - robotSizePX/2; int y = robot->yPos * blockWidthPX + blockWidthPX/2 - robotSizePX/2; this->rectangle = new Rectangle(x, y, robotSizePX, robotSizePX); // save the pointer to the virtual maze this->virtualMaze = virtualMaze; // compute the flood fill //malgo_floodfill_compute(virtualMaze->getMazeMap(), floodFillMap); // //robot->ffMap = floodFillMap; } void VirtualRobot::run() { // feed in the raw wall sensor input feedSensorData(); // run the robot drive code robot_run(robot); // calculate and update the new position int blockWidthPX = VirtualMaze::getBlockWidthPX(); int offset = blockWidthPX / 2 - robotSizePX / 2; int newX = blockWidthPX * robot->xPos + offset; int newY = blockWidthPX * robot->yPos + offset; rectangle->setPos(newX, newY); } void VirtualRobot::feedSensorData() { // get the full map MazeMap* virtualMap = virtualMaze->getMazeMap(); int x = robot->xPos; int y = robot->yPos; // load in information about surroundings BOOL northWall = mazemap_does_wall_exist(virtualMap, x, y, NORTH); BOOL eastWall = mazemap_does_wall_exist(virtualMap, x, y, EAST); BOOL southWall = mazemap_does_wall_exist(virtualMap, x, y, SOUTH); BOOL westWall = mazemap_does_wall_exist(virtualMap, x, y, WEST); // plug the data from the virtual maze into the robot's maze map MazeMap* robotMap = robot->mazeMap; mazemap_set_wall(robotMap, northWall, x, y, NORTH); mazemap_set_wall(robotMap, eastWall, x, y, EAST); mazemap_set_wall(robotMap, southWall, x, y, SOUTH); mazemap_set_wall(robotMap, westWall, x, y, WEST); } void VirtualRobot::draw() { // draw the robot yellow if exploring, red if solving if (robot->isExploring) { rectangle->draw(1.0f, 1.0f, 0.0f); } else { rectangle->draw(1.0f, 0.0f, 0.0f); } } FFMapPtr VirtualRobot::getFloodFillMap() { return robot->ffMap; } VirtualRobot::~VirtualRobot() { // destroy the robot robot_destroy(robot); } #endif <|endoftext|>
<commit_before>// // open horizon -- undefined_darkness@outlook.com // #include "shared.h" #include "memory/memory_reader.h" #include "memory/tmp_buffer.h" #include <assert.h> namespace shared { //------------------------------------------------------------ namespace { std::map<unsigned int,nya_scene::texture> textures; } //------------------------------------------------------------ void add_texture(unsigned int hash_id, const nya_scene::texture &tex) { textures[hash_id] = tex; } //------------------------------------------------------------ unsigned int load_texture(const char *name) { auto *res = nya_resources::get_resources_provider().access(name); if (!res) return 0; size_t size = res->get_size(); nya_memory::tmp_buffer_scoped buf(size); res->read_all(buf.get_data()); res->release(); return load_texture(buf.get_data(), size); } //------------------------------------------------------------ unsigned int load_texture(const void *tex_data, size_t tex_size) { assert(tex_data && tex_size); nya_memory::memory_reader reader(tex_data,tex_size); reader.seek(48); int offset = reader.read<int>(); reader.seek(offset + 8); auto hash_id = reader.read<unsigned int>(); //printf("%d\n", hash_id); reader.seek(offset + 16); if (reader.get_remained() < 128) //normal for ntxr return hash_id; /* if(hash_id > 1000000000) //ToDo { unsigned int *mip_count = (unsigned int *)reader.get_data()+7; assert(*mip_count > 10); *mip_count = 5; } */ nya_scene::shared_texture st; nya_scene::resource_data data(reader.get_remained()); data.copy_from(reader.get_data(), reader.get_remained()); nya_scene::texture::load_dds(st, data, ""); data.free(); nya_scene::texture tex; tex.create(st); shared::add_texture(hash_id, tex); return hash_id; } //------------------------------------------------------------ void clear_textures() { textures.clear(); } //------------------------------------------------------------ const nya_scene::texture &get_texture(unsigned int hash_id) { auto tex = textures.find(hash_id); //assert(tex != textures.end()); return tex->second; } const nya_scene::texture &get_black_texture() { static nya_scene::texture black; static bool initialised=false; if(!initialised) { const unsigned char data[4]={0,0,0,0}; nya_scene::shared_texture res; res.tex.build_texture(data,1,1,nya_render::texture::color_rgba); black.create(res); initialised=true; } return black; } //------------------------------------------------------------ nya_memory::tmp_buffer_ref load_resource(const char *name) { nya_resources::resource_data *res = nya_resources::get_resources_provider().access(name); if (!res) return nya_memory::tmp_buffer_ref(); nya_memory::tmp_buffer_ref buf(res->get_size()); res->read_all(buf.get_data()); res->release(); return buf; } //------------------------------------------------------------ } <commit_msg>land aniso<commit_after>// // open horizon -- undefined_darkness@outlook.com // #include "shared.h" #include "memory/memory_reader.h" #include "memory/tmp_buffer.h" #include <assert.h> namespace shared { //------------------------------------------------------------ namespace { std::map<unsigned int,nya_scene::texture> textures; } //------------------------------------------------------------ void add_texture(unsigned int hash_id, const nya_scene::texture &tex) { textures[hash_id] = tex; } //------------------------------------------------------------ unsigned int load_texture(const char *name) { auto *res = nya_resources::get_resources_provider().access(name); if (!res) return 0; size_t size = res->get_size(); nya_memory::tmp_buffer_scoped buf(size); res->read_all(buf.get_data()); res->release(); return load_texture(buf.get_data(), size); } //------------------------------------------------------------ unsigned int load_texture(const void *tex_data, size_t tex_size) { assert(tex_data && tex_size); nya_memory::memory_reader reader(tex_data,tex_size); reader.seek(48); int offset = reader.read<int>(); reader.seek(offset + 8); auto hash_id = reader.read<unsigned int>(); //printf("%d\n", hash_id); reader.seek(offset + 16); if (reader.get_remained() < 128) //normal for ntxr return hash_id; /* if(hash_id > 1000000000) //ToDo { unsigned int *mip_count = (unsigned int *)reader.get_data()+7; assert(*mip_count > 10); *mip_count = 5; } */ nya_scene::shared_texture st; nya_scene::resource_data data(reader.get_remained()); data.copy_from(reader.get_data(), reader.get_remained()); nya_scene::texture::load_dds(st, data, ""); data.free(); if(hash_id > 1000000000) //ToDo st.tex.set_aniso(16); nya_scene::texture tex; tex.create(st); shared::add_texture(hash_id, tex); return hash_id; } //------------------------------------------------------------ void clear_textures() { textures.clear(); } //------------------------------------------------------------ const nya_scene::texture &get_texture(unsigned int hash_id) { auto tex = textures.find(hash_id); //assert(tex != textures.end()); return tex->second; } const nya_scene::texture &get_black_texture() { static nya_scene::texture black; static bool initialised=false; if(!initialised) { const unsigned char data[4]={0,0,0,0}; nya_scene::shared_texture res; res.tex.build_texture(data,1,1,nya_render::texture::color_rgba); black.create(res); initialised=true; } return black; } //------------------------------------------------------------ nya_memory::tmp_buffer_ref load_resource(const char *name) { nya_resources::resource_data *res = nya_resources::get_resources_provider().access(name); if (!res) return nya_memory::tmp_buffer_ref(); nya_memory::tmp_buffer_ref buf(res->get_size()); res->read_all(buf.get_data()); res->release(); return buf; } //------------------------------------------------------------ } <|endoftext|>
<commit_before><commit_msg>Update CF471A<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qapplication.h" #ifndef QT_NO_SOUND #include "qsound.h" #include "qpaintdevice.h" #include "qwsdisplay_qws.h" #include "qsound_p.h" #include "qsoundqss_qws.h" #include "qhash.h" #include "qfileinfo.h" #include "qbytearray.h" #include "quuid.h" #include "qdatastream.h" #include "qcopchannel_qws.h" #include "qbuffer.h" QT_BEGIN_NAMESPACE #ifdef MEDIA_SERVER #define SERVER_CHANNEL "QPE/MediaServer" class QCopMessage : public QDataStream { public: QCopMessage( const QString& channel, const QString& message ) : QDataStream( new QBuffer ), m_channel( channel ), m_message( message ) { device()->open( QIODevice::WriteOnly ); } ~QCopMessage() { QCopChannel::send( m_channel, m_message, ((QBuffer*)device())->buffer() ); delete device(); } private: QString m_channel; QString m_message; }; #endif // MEDIA_SERVER class QAuServerQWS; class QAuBucketQWS : public QObject, public QAuBucket { Q_OBJECT public: QAuBucketQWS( QAuServerQWS*, QSound*, QObject* parent = 0 ); ~QAuBucketQWS(); #ifndef MEDIA_SERVER int id() const { return id_; } #endif QSound* sound() const { return sound_; } #ifdef MEDIA_SERVER void play(); void stop(); #endif signals: // Only for Media Server void done( QAuBucketQWS* ); private slots: // Only for Media Server void processMessage( const QString& msg, const QByteArray& data ); private: #ifdef MEDIA_SERVER QCopChannel *m_channel; QUuid m_id; #endif #ifndef MEDIA_SERVER int id_; #endif QSound *sound_; QAuServerQWS *server_; static int next; }; int QAuBucketQWS::next = 0; class QAuServerQWS : public QAuServer { Q_OBJECT public: QAuServerQWS( QObject* parent ); void init( QSound* s ) { QAuBucketQWS *bucket = new QAuBucketQWS( this, s ); #ifdef MEDIA_SERVER connect( bucket, SIGNAL(done(QAuBucketQWS*)), this, SLOT(complete(QAuBucketQWS*)) ); #endif setBucket( s, bucket ); } #ifndef MEDIA_SERVER // Register bucket void insert( QAuBucketQWS *bucket ) { buckets.insert( bucket->id(), bucket ); } // Remove bucket from register void remove( QAuBucketQWS *bucket ) { buckets.remove( bucket->id() ); } #endif void play( QSound* s ) { QString filepath = QFileInfo( s->fileName() ).absoluteFilePath(); #if defined(QT_NO_QWS_SOUNDSERVER) server->playFile( bucket( s )->id(), filepath ); #elif defined(MEDIA_SERVER) bucket( s )->play(); #else client->play( bucket( s )->id(), filepath ); #endif } void stop( QSound* s ) { #if defined(QT_NO_QWS_SOUNDSERVER) server->stopFile( bucket( s )->id() ); #elif defined(MEDIA_SERVER) bucket( s )->stop(); #else client->stop( bucket( s )->id() ); #endif } bool okay() { return true; } private slots: // Continue playing sound if loops remain void complete( int id ) { #ifndef MEDIA_SERVER QAuBucketQWS *bucket = find( id ); if( bucket ) { QSound *sound = bucket->sound(); if( decLoop( sound ) ) { play( sound ); } } #else Q_UNUSED(id); #endif } // Only for Media Server void complete( QAuBucketQWS* bucket ) { #ifndef MEDIA_SERVER Q_UNUSED(bucket); #else QSound *sound = bucket->sound(); if( decLoop( sound ) ) { play( sound ); } #endif } protected: QAuBucketQWS* bucket( QSound *s ) { return (QAuBucketQWS*)QAuServer::bucket( s ); } private: #ifndef MEDIA_SERVER // Find registered bucket with given id, return null if none found QAuBucketQWS* find( int id ) { QHash<int, QAuBucketQWS*>::Iterator it = buckets.find( id ); if( it != buckets.end() ) { return it.value(); } return 0; } QHash<int, QAuBucketQWS*> buckets; // ### possible problem with overlapping keys #ifdef QT_NO_QWS_SOUNDSERVER QWSSoundServer *server; #else QWSSoundClient *client; #endif #endif // MEDIA_SERVER }; QAuServerQWS::QAuServerQWS(QObject* parent) : QAuServer(parent) { #ifndef MEDIA_SERVER setObjectName(QLatin1String("qauserverqws")); #ifdef QT_NO_QWS_SOUNDSERVER server = new QWSSoundServer( this ); // ### only suitable for single application connect( server, SIGNAL(soundCompleted(int)), this, SLOT(complete(int)) ); #else client = new QWSSoundClient( this ); // ### requires successful connection connect( client, SIGNAL(soundCompleted(int)), this, SLOT(complete(int)) ); #endif #endif // MEDIA_SERVER } QAuBucketQWS::QAuBucketQWS( QAuServerQWS *server, QSound *sound, QObject* parent ) : QObject( parent ), sound_( sound ), server_( server ) { #ifdef MEDIA_SERVER m_id = QUuid::createUuid(); sound->setObjectName( m_id.toString() ); m_channel = new QCopChannel(QLatin1String("QPE/QSound/") + m_id ), this ); connect( m_channel, SIGNAL(received(QString,QByteArray)), this, SLOT(processMessage(QString,QByteArray)) ); { QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("subscribe(QUuid)") ); message << m_id; } { QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath(); QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("open(QUuid,QString)") ); message << m_id << filepath; } #else id_ = next++; server_->insert( this ); #endif } #ifdef MEDIA_SERVER void QAuBucketQWS::play() { QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath(); QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("play(QUuid)") ); message << m_id; } void QAuBucketQWS::stop() { QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("stop(QUuid)") ); message << m_id; } #endif // MEDIA_SERVER void QAuBucketQWS::processMessage( const QString& msg, const QByteArray& data ) { Q_UNUSED(data); #ifndef MEDIA_SERVER Q_UNUSED(msg); #else if( msg == QLatin1String("done()") ) { emit done( this ); } #endif } QAuBucketQWS::~QAuBucketQWS() { #ifdef MEDIA_SERVER QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("revoke(QUuid)") ); message << m_id; #else server_->remove( this ); #endif } QAuServer* qt_new_audio_server() { return new QAuServerQWS(qApp); } #include "qsound_qws.moc" #endif // QT_NO_SOUND QT_END_NAMESPACE <commit_msg>Fix compile error in MEDIA_SERVER code.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qapplication.h" #ifndef QT_NO_SOUND #include "qsound.h" #include "qpaintdevice.h" #include "qwsdisplay_qws.h" #include "qsound_p.h" #include "qsoundqss_qws.h" #include "qhash.h" #include "qfileinfo.h" #include "qbytearray.h" #include "quuid.h" #include "qdatastream.h" #include "qcopchannel_qws.h" #include "qbuffer.h" QT_BEGIN_NAMESPACE #ifdef MEDIA_SERVER #define SERVER_CHANNEL "QPE/MediaServer" class QCopMessage : public QDataStream { public: QCopMessage( const QString& channel, const QString& message ) : QDataStream( new QBuffer ), m_channel( channel ), m_message( message ) { device()->open( QIODevice::WriteOnly ); } ~QCopMessage() { QCopChannel::send( m_channel, m_message, ((QBuffer*)device())->buffer() ); delete device(); } private: QString m_channel; QString m_message; }; #endif // MEDIA_SERVER class QAuServerQWS; class QAuBucketQWS : public QObject, public QAuBucket { Q_OBJECT public: QAuBucketQWS( QAuServerQWS*, QSound*, QObject* parent = 0 ); ~QAuBucketQWS(); #ifndef MEDIA_SERVER int id() const { return id_; } #endif QSound* sound() const { return sound_; } #ifdef MEDIA_SERVER void play(); void stop(); #endif signals: // Only for Media Server void done( QAuBucketQWS* ); private slots: // Only for Media Server void processMessage( const QString& msg, const QByteArray& data ); private: #ifdef MEDIA_SERVER QCopChannel *m_channel; QUuid m_id; #endif #ifndef MEDIA_SERVER int id_; #endif QSound *sound_; QAuServerQWS *server_; static int next; }; int QAuBucketQWS::next = 0; class QAuServerQWS : public QAuServer { Q_OBJECT public: QAuServerQWS( QObject* parent ); void init( QSound* s ) { QAuBucketQWS *bucket = new QAuBucketQWS( this, s ); #ifdef MEDIA_SERVER connect( bucket, SIGNAL(done(QAuBucketQWS*)), this, SLOT(complete(QAuBucketQWS*)) ); #endif setBucket( s, bucket ); } #ifndef MEDIA_SERVER // Register bucket void insert( QAuBucketQWS *bucket ) { buckets.insert( bucket->id(), bucket ); } // Remove bucket from register void remove( QAuBucketQWS *bucket ) { buckets.remove( bucket->id() ); } #endif void play( QSound* s ) { QString filepath = QFileInfo( s->fileName() ).absoluteFilePath(); #if defined(QT_NO_QWS_SOUNDSERVER) server->playFile( bucket( s )->id(), filepath ); #elif defined(MEDIA_SERVER) bucket( s )->play(); #else client->play( bucket( s )->id(), filepath ); #endif } void stop( QSound* s ) { #if defined(QT_NO_QWS_SOUNDSERVER) server->stopFile( bucket( s )->id() ); #elif defined(MEDIA_SERVER) bucket( s )->stop(); #else client->stop( bucket( s )->id() ); #endif } bool okay() { return true; } private slots: // Continue playing sound if loops remain void complete( int id ) { #ifndef MEDIA_SERVER QAuBucketQWS *bucket = find( id ); if( bucket ) { QSound *sound = bucket->sound(); if( decLoop( sound ) ) { play( sound ); } } #else Q_UNUSED(id); #endif } // Only for Media Server void complete( QAuBucketQWS* bucket ) { #ifndef MEDIA_SERVER Q_UNUSED(bucket); #else QSound *sound = bucket->sound(); if( decLoop( sound ) ) { play( sound ); } #endif } protected: QAuBucketQWS* bucket( QSound *s ) { return (QAuBucketQWS*)QAuServer::bucket( s ); } private: #ifndef MEDIA_SERVER // Find registered bucket with given id, return null if none found QAuBucketQWS* find( int id ) { QHash<int, QAuBucketQWS*>::Iterator it = buckets.find( id ); if( it != buckets.end() ) { return it.value(); } return 0; } QHash<int, QAuBucketQWS*> buckets; // ### possible problem with overlapping keys #ifdef QT_NO_QWS_SOUNDSERVER QWSSoundServer *server; #else QWSSoundClient *client; #endif #endif // MEDIA_SERVER }; QAuServerQWS::QAuServerQWS(QObject* parent) : QAuServer(parent) { #ifndef MEDIA_SERVER setObjectName(QLatin1String("qauserverqws")); #ifdef QT_NO_QWS_SOUNDSERVER server = new QWSSoundServer( this ); // ### only suitable for single application connect( server, SIGNAL(soundCompleted(int)), this, SLOT(complete(int)) ); #else client = new QWSSoundClient( this ); // ### requires successful connection connect( client, SIGNAL(soundCompleted(int)), this, SLOT(complete(int)) ); #endif #endif // MEDIA_SERVER } QAuBucketQWS::QAuBucketQWS( QAuServerQWS *server, QSound *sound, QObject* parent ) : QObject( parent ), sound_( sound ), server_( server ) { #ifdef MEDIA_SERVER m_id = QUuid::createUuid(); sound->setObjectName( m_id.toString() ); m_channel = new QCopChannel(QLatin1String("QPE/QSound/") + m_id, this ); connect( m_channel, SIGNAL(received(QString,QByteArray)), this, SLOT(processMessage(QString,QByteArray)) ); { QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("subscribe(QUuid)") ); message << m_id; } { QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath(); QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("open(QUuid,QString)") ); message << m_id << filepath; } #else id_ = next++; server_->insert( this ); #endif } #ifdef MEDIA_SERVER void QAuBucketQWS::play() { QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath(); QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("play(QUuid)") ); message << m_id; } void QAuBucketQWS::stop() { QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("stop(QUuid)") ); message << m_id; } #endif // MEDIA_SERVER void QAuBucketQWS::processMessage( const QString& msg, const QByteArray& data ) { Q_UNUSED(data); #ifndef MEDIA_SERVER Q_UNUSED(msg); #else if( msg == QLatin1String("done()") ) { emit done( this ); } #endif } QAuBucketQWS::~QAuBucketQWS() { #ifdef MEDIA_SERVER QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("revoke(QUuid)") ); message << m_id; #else server_->remove( this ); #endif } QAuServer* qt_new_audio_server() { return new QAuServerQWS(qApp); } #include "qsound_qws.moc" #endif // QT_NO_SOUND QT_END_NAMESPACE <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPointSet.h" #include "mitkOperation.h" #include "mitkOperationActor.h" #include "mitkPointOperation.h" #include "mitkInteractionConst.h" #include "mitkXMLWriter.h" #include "mitkXMLReader.h" #include "mitkPointSetWriter.h" #include "mitkPointSetReader.h" #include "mitkRenderingManager.h" #include <itkSmartPointerForwardReference.txx> mitk::PointSet::PointSet() { m_Initialized = false; m_PointSetSeries.resize( 1 ); m_PointSetSeries[0] = DataType::New(); PointDataContainer::Pointer pointData = PointDataContainer::New(); m_PointSetSeries[0]->SetPointData( pointData ); this->Initialize( 1 ); } mitk::PointSet::~PointSet() { } void mitk::PointSet::Initialize( const mitk::Geometry3D *geometry ) { const mitk::TimeSlicedGeometry *timeGeometry = dynamic_cast< const mitk::TimeSlicedGeometry * >( geometry ); if ( timeGeometry ) { this->Initialize( timeGeometry->GetTimeSteps() ); } this->SetGeometry( static_cast< Geometry3D * >( geometry->Clone().GetPointer() ) ); } void mitk::PointSet::Initialize( int timeSteps ) { mitk::TimeSlicedGeometry::Pointer timeGeometry = this->GetTimeSlicedGeometry(); mitk::Geometry3D::Pointer g3d = mitk::Geometry3D::New(); g3d->Initialize(); if ( timeSteps > 1 ) { mitk::ScalarType timeBounds[] = {0.0, 1.0}; g3d->SetTimeBounds( timeBounds ); } // // The geometry is propagated automatically to the other items, // if EvenlyTimed is true... // timeGeometry->InitializeEvenlyTimed( g3d.GetPointer(), timeSteps ); m_Initialized = true; } bool mitk::PointSet::IsEmpty(int t) const { return IsInitialized() && (GetSize(t) <= 0); } void mitk::PointSet::AdaptPointSetSeriesSize( int timeSteps ) { // Check if the vector is long enouth to contain the new element // at the given position. If not, expand it with sufficient pre-initialized // elements. if ( timeSteps > m_PointSetSeries.size() ) { int oldSize = m_PointSetSeries.size(); m_PointSetSeries.resize( timeSteps ); int i; for ( i = oldSize; i < timeSteps; ++i ) { m_PointSetSeries[i] = DataType::New(); PointDataContainer::Pointer pointData = PointDataContainer::New(); m_PointSetSeries[i]->SetPointData( pointData ); } this->Initialize( timeSteps ); } } int mitk::PointSet::GetPointSetSeriesSize() const { return m_PointSetSeries.size(); } int mitk::PointSet::GetSize( int t ) const { if ( t < m_PointSetSeries.size() ) { return m_PointSetSeries[t]->GetNumberOfPoints(); } else { return 0; } } mitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet( int t ) const { if ( t < m_PointSetSeries.size() ) { return m_PointSetSeries[t]; } else { return NULL; } } int mitk::PointSet::SearchPoint( Point3D point, float distance, int t ) { if ( t >= m_PointSetSeries.size() ) { return -1; } // Out is the point which is checked to be the searched point PointType out; out.Fill( 0 ); PointType indexPoint; this->GetGeometry( t )->WorldToIndex(point, indexPoint); // Searching the first point in the Set, that is +- distance far away fro // the given point unsigned int i; PointsContainer::Iterator it, end; end = m_PointSetSeries[t]->GetPoints()->End(); int bestIndex = -1; distance = distance * distance; // To correct errors from converting index to world and world to index if (distance == 0.0) { distance = 0.000001; } ScalarType bestDist = distance; ScalarType dist, tmp; for ( it = m_PointSetSeries[t]->GetPoints()->Begin(), i = 0; it != end; ++it, ++i ) { bool ok = m_PointSetSeries[t]->GetPoints() ->GetElementIfIndexExists( it->Index(), &out ); if ( !ok ) { return -1; } else if ( indexPoint == out ) //if totaly equal { return it->Index(); } //distance calculation tmp = out[0] - indexPoint[0]; dist = tmp * tmp; tmp = out[1] - indexPoint[1]; dist += tmp * tmp; tmp = out[2] - indexPoint[2]; dist += tmp * tmp; if ( dist < bestDist ) { bestIndex = it->Index(); bestDist = dist; } } return bestIndex; } mitk::PointSet::PointType mitk::PointSet::GetPoint( int position, int t ) const { PointType out; out.Fill(0); if ( t >= m_PointSetSeries.size() ) { return out; } if ( m_PointSetSeries[t]->GetPoints()->IndexExists(position) ) { m_PointSetSeries[t]->GetPoint( position, &out ); this->GetGeometry(t)->IndexToWorld( out, out ); return out; } else { return out; } } bool mitk::PointSet ::GetPointIfExists( PointIdentifier id, PointType* point, int t ) { if ( t >= m_PointSetSeries.size() ) { return false; } if ( m_PointSetSeries[t]->GetPoints()->GetElementIfIndexExists(id, point) ) { this->GetGeometry( t )->IndexToWorld( *point, *point ); return true; } else { return false; } } void mitk::PointSet::SetPoint( PointIdentifier id, PointType point, int t ) { this->AdaptPointSetSeriesSize( t+1 ); mitk::Point3D indexPoint; this->GetGeometry( t )->WorldToIndex( point, indexPoint ); m_PointSetSeries[t]->SetPoint( id, indexPoint ); } void mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, int t ) { if ( t < m_PointSetSeries.size() ) { mitk::Point3D indexPoint; this->GetGeometry( t )->WorldToIndex( point, indexPoint ); m_PointSetSeries[t]->GetPoints()->InsertElement( id, indexPoint ); } } bool mitk::PointSet::IndexExists( int position, int t ) { if ( t < m_PointSetSeries.size() ) { return m_PointSetSeries[t]->GetPoints()->IndexExists( position ); } else { return false; } } bool mitk::PointSet::GetSelectInfo( int position, int t ) { if ( this->IndexExists( position, t ) ) { PointDataType pointData = { 0, false, PTUNDEFINED }; m_PointSetSeries[t]->GetPointData( position, &pointData ); return pointData.selected; } else { return false; } } const int mitk::PointSet::GetNumberOfSelected( int t ) { if ( t >= m_PointSetSeries.size() ) { return 0; } int numberOfSelected = 0; PointDataIterator it; for ( it = m_PointSetSeries[t]->GetPointData()->Begin(); it != m_PointSetSeries[t]->GetPointData()->End(); it++ ) { if (it->Value().selected == true) { ++numberOfSelected; } } return numberOfSelected; } int mitk::PointSet::SearchSelectedPoint( int t ) { if ( t >= m_PointSetSeries.size() ) { return -1; } PointDataIterator it; for ( it = m_PointSetSeries[t]->GetPointData()->Begin(); it != m_PointSetSeries[t]->GetPointData()->End(); it++ ) { if ( it->Value().selected == true ) { return it->Index(); } } return -1; } void mitk::PointSet::ExecuteOperation( Operation* operation ) { int timeStep = -1; mitkCheckOperationTypeMacro(PointOperation, operation, pointOp); if ( pointOp ) { timeStep = this->GetTimeSlicedGeometry() ->MSToTimeStep( pointOp->GetTimeInMS() ); } if ( timeStep == -1 ) { // Time outside of PointSet time bounds return; } switch (operation->GetOperationType()) { case OpNOTHING: break; case OpINSERT://inserts the point at the given position and selects it. { int position = pointOp->GetIndex(); PointType pt; pt.CastFrom(pointOp->GetPoint()); //transfer from world to index coordinates this->GetGeometry( timeStep )->WorldToIndex(pt, pt); m_PointSetSeries[timeStep]->GetPoints()->InsertElement(position, pt); PointDataType pointData = { pointOp->GetIndex(), pointOp->GetSelected(), pointOp->GetPointType() }; m_PointSetSeries[timeStep]->GetPointData() ->InsertElement(position, pointData); this->Modified(); ((const itk::Object*)this)->InvokeEvent( NewPointEvent() ); this->OnPointSetChange(); } break; case OpMOVE://moves the point given by index { PointType pt; pt.CastFrom(pointOp->GetPoint()); //transfer from world to index coordinates this->GetGeometry( timeStep )->WorldToIndex(pt, pt); m_PointSetSeries[timeStep]->SetPoint(pointOp->GetIndex(), pt); this->OnPointSetChange(); this->Modified(); } break; case OpREMOVE://removes the point at given by position { m_PointSetSeries[timeStep]->GetPoints() ->DeleteIndex((unsigned)pointOp->GetIndex()); m_PointSetSeries[timeStep]->GetPointData() ->DeleteIndex((unsigned)pointOp->GetIndex()); this->OnPointSetChange(); this->Modified(); ((const itk::Object*)this)->InvokeEvent( RemovedPointEvent() ); } break; case OpSELECTPOINT://select the given point { PointDataType pointData = {0, false, PTUNDEFINED}; m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData); pointData.selected = true; m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData); this->Modified(); } break; case OpDESELECTPOINT://unselect the given point { PointDataType pointData = {0, false, PTUNDEFINED}; m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData); pointData.selected = false; m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData); this->Modified(); } break; case OpSETPOINTTYPE: { PointDataType pointData = {0, false, PTUNDEFINED}; m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData); pointData.pointSpec = pointOp->GetPointType(); m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData); this->Modified(); } break; default: itkWarningMacro("mitkPointSet could not understrand the operation. Please check!"); break; } //to tell the mappers, that the data is modifierd and has to be updated //only call modified if anything is done, so call in cases //this->Modified(); mitk::OperationEndEvent endevent(operation); ((const itk::Object*)this)->InvokeEvent(endevent); //*todo has to be done here, cause of update-pipeline not working yet // As discussed lately, don't mess with the rendering from inside data structures //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::PointSet::UpdateOutputInformation() { if ( this->GetSource( ) ) { this->GetSource( )->UpdateOutputInformation( ); } const DataType::BoundingBoxType *bb = m_PointSetSeries[0]->GetBoundingBox(); BoundingBox::BoundsArrayType itkBounds = bb->GetBounds(); float mitkBounds[6]; //for assignment see Geometry3d::SetBounds(const float bounds) mitkBounds[0] = itkBounds[0]; mitkBounds[1] = itkBounds[1]; mitkBounds[2] = itkBounds[2]; mitkBounds[3] = itkBounds[3]; mitkBounds[4] = itkBounds[4]; mitkBounds[5] = itkBounds[5]; GetGeometry()->SetBounds(itkBounds); } void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::PointSet::VerifyRequestedRegion() { return true; } void mitk::PointSet::SetRequestedRegion( itk::DataObject * ) { } bool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter ) { BaseData::WriteXMLData( xmlWriter ); std::string fileName = xmlWriter.GetRelativePath(); if(!xmlWriter.IsFileExtension(".mps", fileName)) fileName += ".mps"; if(xmlWriter.SaveSourceFiles()){ PointSetWriter::Pointer writer = PointSetWriter::New(); fileName = xmlWriter.GetAbsolutePath(); if(!xmlWriter.IsFileExtension(".mps", fileName)) fileName += ".mps"; writer->SetFileName( fileName.c_str() ); writer->SetInput( this ); writer->Update(); } xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() ); return true; } bool mitk::PointSet::ReadXMLData( XMLReader& xmlReader ) { BaseData::ReadXMLData( xmlReader ); std::string fileName; xmlReader.GetAttribute( XMLReader::FILENAME, fileName ); if ( fileName.empty() ) return false; PointSetReader::Pointer reader = PointSetReader::New(); reader->SetFileName( fileName.c_str() ); reader->Update(); mitk::PointSet::Pointer psp = dynamic_cast<mitk::PointSet*>( reader->GetOutput() ); if (psp.IsNotNull()) { m_PointSetSeries[0] = psp->GetPointSet(); } if ( m_PointSetSeries[0].IsNull() ) { return false; } return true; } <commit_msg>FIX: Correct order for passing Geometry in initialization (cf. bug #460)<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPointSet.h" #include "mitkOperation.h" #include "mitkOperationActor.h" #include "mitkPointOperation.h" #include "mitkInteractionConst.h" #include "mitkXMLWriter.h" #include "mitkXMLReader.h" #include "mitkPointSetWriter.h" #include "mitkPointSetReader.h" #include "mitkRenderingManager.h" #include <itkSmartPointerForwardReference.txx> mitk::PointSet::PointSet() { m_Initialized = false; m_PointSetSeries.resize( 1 ); m_PointSetSeries[0] = DataType::New(); PointDataContainer::Pointer pointData = PointDataContainer::New(); m_PointSetSeries[0]->SetPointData( pointData ); this->Initialize( 1 ); } mitk::PointSet::~PointSet() { } void mitk::PointSet::Initialize( const mitk::Geometry3D *geometry ) { this->SetGeometry( static_cast< Geometry3D * >( geometry->Clone().GetPointer() ) ); const mitk::TimeSlicedGeometry *timeGeometry = dynamic_cast< const mitk::TimeSlicedGeometry * >( geometry ); if ( timeGeometry ) { this->Initialize( timeGeometry->GetTimeSteps() ); } else { this->Initialize( 1 ); } } void mitk::PointSet::Initialize( int timeSteps ) { mitk::TimeSlicedGeometry::Pointer timeGeometry = this->GetTimeSlicedGeometry(); mitk::Geometry3D::Pointer g3d = mitk::Geometry3D::New(); g3d->Initialize(); if ( timeSteps > 1 ) { mitk::ScalarType timeBounds[] = {0.0, 1.0}; g3d->SetTimeBounds( timeBounds ); } // // The geometry is propagated automatically to the other items, // if EvenlyTimed is true... // timeGeometry->InitializeEvenlyTimed( g3d.GetPointer(), timeSteps ); m_Initialized = true; } bool mitk::PointSet::IsEmpty(int t) const { return IsInitialized() && (GetSize(t) <= 0); } void mitk::PointSet::AdaptPointSetSeriesSize( int timeSteps ) { // Check if the vector is long enouth to contain the new element // at the given position. If not, expand it with sufficient pre-initialized // elements. if ( timeSteps > m_PointSetSeries.size() ) { int oldSize = m_PointSetSeries.size(); m_PointSetSeries.resize( timeSteps ); int i; for ( i = oldSize; i < timeSteps; ++i ) { m_PointSetSeries[i] = DataType::New(); PointDataContainer::Pointer pointData = PointDataContainer::New(); m_PointSetSeries[i]->SetPointData( pointData ); } this->Initialize( timeSteps ); } } int mitk::PointSet::GetPointSetSeriesSize() const { return m_PointSetSeries.size(); } int mitk::PointSet::GetSize( int t ) const { if ( t < m_PointSetSeries.size() ) { return m_PointSetSeries[t]->GetNumberOfPoints(); } else { return 0; } } mitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet( int t ) const { if ( t < m_PointSetSeries.size() ) { return m_PointSetSeries[t]; } else { return NULL; } } int mitk::PointSet::SearchPoint( Point3D point, float distance, int t ) { if ( t >= m_PointSetSeries.size() ) { return -1; } // Out is the point which is checked to be the searched point PointType out; out.Fill( 0 ); PointType indexPoint; this->GetGeometry( t )->WorldToIndex(point, indexPoint); // Searching the first point in the Set, that is +- distance far away fro // the given point unsigned int i; PointsContainer::Iterator it, end; end = m_PointSetSeries[t]->GetPoints()->End(); int bestIndex = -1; distance = distance * distance; // To correct errors from converting index to world and world to index if (distance == 0.0) { distance = 0.000001; } ScalarType bestDist = distance; ScalarType dist, tmp; for ( it = m_PointSetSeries[t]->GetPoints()->Begin(), i = 0; it != end; ++it, ++i ) { bool ok = m_PointSetSeries[t]->GetPoints() ->GetElementIfIndexExists( it->Index(), &out ); if ( !ok ) { return -1; } else if ( indexPoint == out ) //if totaly equal { return it->Index(); } //distance calculation tmp = out[0] - indexPoint[0]; dist = tmp * tmp; tmp = out[1] - indexPoint[1]; dist += tmp * tmp; tmp = out[2] - indexPoint[2]; dist += tmp * tmp; if ( dist < bestDist ) { bestIndex = it->Index(); bestDist = dist; } } return bestIndex; } mitk::PointSet::PointType mitk::PointSet::GetPoint( int position, int t ) const { PointType out; out.Fill(0); if ( t >= m_PointSetSeries.size() ) { return out; } if ( m_PointSetSeries[t]->GetPoints()->IndexExists(position) ) { m_PointSetSeries[t]->GetPoint( position, &out ); this->GetGeometry(t)->IndexToWorld( out, out ); return out; } else { return out; } } bool mitk::PointSet ::GetPointIfExists( PointIdentifier id, PointType* point, int t ) { if ( t >= m_PointSetSeries.size() ) { return false; } if ( m_PointSetSeries[t]->GetPoints()->GetElementIfIndexExists(id, point) ) { this->GetGeometry( t )->IndexToWorld( *point, *point ); return true; } else { return false; } } void mitk::PointSet::SetPoint( PointIdentifier id, PointType point, int t ) { this->AdaptPointSetSeriesSize( t+1 ); mitk::Point3D indexPoint; this->GetGeometry( t )->WorldToIndex( point, indexPoint ); m_PointSetSeries[t]->SetPoint( id, indexPoint ); } void mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, int t ) { if ( t < m_PointSetSeries.size() ) { mitk::Point3D indexPoint; this->GetGeometry( t )->WorldToIndex( point, indexPoint ); m_PointSetSeries[t]->GetPoints()->InsertElement( id, indexPoint ); } } bool mitk::PointSet::IndexExists( int position, int t ) { if ( t < m_PointSetSeries.size() ) { return m_PointSetSeries[t]->GetPoints()->IndexExists( position ); } else { return false; } } bool mitk::PointSet::GetSelectInfo( int position, int t ) { if ( this->IndexExists( position, t ) ) { PointDataType pointData = { 0, false, PTUNDEFINED }; m_PointSetSeries[t]->GetPointData( position, &pointData ); return pointData.selected; } else { return false; } } const int mitk::PointSet::GetNumberOfSelected( int t ) { if ( t >= m_PointSetSeries.size() ) { return 0; } int numberOfSelected = 0; PointDataIterator it; for ( it = m_PointSetSeries[t]->GetPointData()->Begin(); it != m_PointSetSeries[t]->GetPointData()->End(); it++ ) { if (it->Value().selected == true) { ++numberOfSelected; } } return numberOfSelected; } int mitk::PointSet::SearchSelectedPoint( int t ) { if ( t >= m_PointSetSeries.size() ) { return -1; } PointDataIterator it; for ( it = m_PointSetSeries[t]->GetPointData()->Begin(); it != m_PointSetSeries[t]->GetPointData()->End(); it++ ) { if ( it->Value().selected == true ) { return it->Index(); } } return -1; } void mitk::PointSet::ExecuteOperation( Operation* operation ) { int timeStep = -1; mitkCheckOperationTypeMacro(PointOperation, operation, pointOp); if ( pointOp ) { timeStep = this->GetTimeSlicedGeometry() ->MSToTimeStep( pointOp->GetTimeInMS() ); } if ( timeStep == -1 ) { // Time outside of PointSet time bounds return; } switch (operation->GetOperationType()) { case OpNOTHING: break; case OpINSERT://inserts the point at the given position and selects it. { int position = pointOp->GetIndex(); PointType pt; pt.CastFrom(pointOp->GetPoint()); //transfer from world to index coordinates this->GetGeometry( timeStep )->WorldToIndex(pt, pt); m_PointSetSeries[timeStep]->GetPoints()->InsertElement(position, pt); PointDataType pointData = { pointOp->GetIndex(), pointOp->GetSelected(), pointOp->GetPointType() }; m_PointSetSeries[timeStep]->GetPointData() ->InsertElement(position, pointData); this->Modified(); ((const itk::Object*)this)->InvokeEvent( NewPointEvent() ); this->OnPointSetChange(); } break; case OpMOVE://moves the point given by index { PointType pt; pt.CastFrom(pointOp->GetPoint()); //transfer from world to index coordinates this->GetGeometry( timeStep )->WorldToIndex(pt, pt); m_PointSetSeries[timeStep]->SetPoint(pointOp->GetIndex(), pt); this->OnPointSetChange(); this->Modified(); } break; case OpREMOVE://removes the point at given by position { m_PointSetSeries[timeStep]->GetPoints() ->DeleteIndex((unsigned)pointOp->GetIndex()); m_PointSetSeries[timeStep]->GetPointData() ->DeleteIndex((unsigned)pointOp->GetIndex()); this->OnPointSetChange(); this->Modified(); ((const itk::Object*)this)->InvokeEvent( RemovedPointEvent() ); } break; case OpSELECTPOINT://select the given point { PointDataType pointData = {0, false, PTUNDEFINED}; m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData); pointData.selected = true; m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData); this->Modified(); } break; case OpDESELECTPOINT://unselect the given point { PointDataType pointData = {0, false, PTUNDEFINED}; m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData); pointData.selected = false; m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData); this->Modified(); } break; case OpSETPOINTTYPE: { PointDataType pointData = {0, false, PTUNDEFINED}; m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData); pointData.pointSpec = pointOp->GetPointType(); m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData); this->Modified(); } break; default: itkWarningMacro("mitkPointSet could not understrand the operation. Please check!"); break; } //to tell the mappers, that the data is modifierd and has to be updated //only call modified if anything is done, so call in cases //this->Modified(); mitk::OperationEndEvent endevent(operation); ((const itk::Object*)this)->InvokeEvent(endevent); //*todo has to be done here, cause of update-pipeline not working yet // As discussed lately, don't mess with the rendering from inside data structures //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::PointSet::UpdateOutputInformation() { if ( this->GetSource( ) ) { this->GetSource( )->UpdateOutputInformation( ); } const DataType::BoundingBoxType *bb = m_PointSetSeries[0]->GetBoundingBox(); BoundingBox::BoundsArrayType itkBounds = bb->GetBounds(); float mitkBounds[6]; //for assignment see Geometry3d::SetBounds(const float bounds) mitkBounds[0] = itkBounds[0]; mitkBounds[1] = itkBounds[1]; mitkBounds[2] = itkBounds[2]; mitkBounds[3] = itkBounds[3]; mitkBounds[4] = itkBounds[4]; mitkBounds[5] = itkBounds[5]; GetGeometry()->SetBounds(itkBounds); } void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::PointSet::VerifyRequestedRegion() { return true; } void mitk::PointSet::SetRequestedRegion( itk::DataObject * ) { } bool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter ) { BaseData::WriteXMLData( xmlWriter ); std::string fileName = xmlWriter.GetRelativePath(); if(!xmlWriter.IsFileExtension(".mps", fileName)) fileName += ".mps"; if(xmlWriter.SaveSourceFiles()){ PointSetWriter::Pointer writer = PointSetWriter::New(); fileName = xmlWriter.GetAbsolutePath(); if(!xmlWriter.IsFileExtension(".mps", fileName)) fileName += ".mps"; writer->SetFileName( fileName.c_str() ); writer->SetInput( this ); writer->Update(); } xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() ); return true; } bool mitk::PointSet::ReadXMLData( XMLReader& xmlReader ) { BaseData::ReadXMLData( xmlReader ); std::string fileName; xmlReader.GetAttribute( XMLReader::FILENAME, fileName ); if ( fileName.empty() ) return false; PointSetReader::Pointer reader = PointSetReader::New(); reader->SetFileName( fileName.c_str() ); reader->Update(); mitk::PointSet::Pointer psp = dynamic_cast<mitk::PointSet*>( reader->GetOutput() ); if (psp.IsNotNull()) { m_PointSetSeries[0] = psp->GetPointSet(); } if ( m_PointSetSeries[0].IsNull() ) { return false; } return true; } <|endoftext|>
<commit_before>/* * SurveySessionImplementation.cpp * * Created on: May 22, 2012 * Author: Kyle */ #include "server/zone/objects/player/sessions/survey/SurveySession.h" #include "server/zone/Zone.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/managers/resource/ResourceManager.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/tangible/tool/SurveyTool.h" #include "server/zone/packets/scene/PlayClientEffectLocMessage.h" #include "server/zone/objects/creature/CreatureAttribute.h" #include "server/zone/objects/player/sessions/survey/sui/SurveyGMinigameSuiCallback.h" #include "server/zone/objects/player/sessions/survey/sui/SurveyCMinigameSuiCallback.h" #include "server/zone/managers/resource/resourcespawner/SampleTask.h" #include "server/zone/managers/resource/resourcespawner/SurveyTask.h" #include "server/zone/managers/resource/resourcespawner/SampleResultsTask.h" int SurveySessionImplementation::initializeSession(SurveyTool* tool) { activeSurveyTool = tool; surveyerGhost = surveyer.get()->getPlayerObject(); return startSession(); } int SurveySessionImplementation::startSession() { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get(); if(surveyer == NULL || activeSurveyTool == NULL || surveyerGhost == NULL) { cancelSession(); return false; } resourceManager = surveyer->getZoneServer()->getResourceManager(); if(resourceManager == NULL) { cancelSession(); return false; } surveyer->addActiveSession(SessionFacadeType::SURVEY, _this.get()); return true; } int SurveySessionImplementation::cancelSession() { ManagedReference<CreatureObject*> ref = surveyer.get(); if(ref != NULL) ref->dropActiveSession(SessionFacadeType::SURVEY); return clearSession(); } int SurveySessionImplementation::clearSession() { return 0; } void SurveySessionImplementation::startSurvey(const String& resname) { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); if (activeSurveyTool == NULL) { error("surveyTool is NULL"); return; } if (resourceManager == NULL) { error("ResourceManager is NULL"); return; } if (surveyer == NULL) { error("surveyer is NULL"); return; } if (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) { surveyer->sendSystemMessage("@error_message:survey_in_structure"); //You cannot perform survey-related actions inside a structure. return; } if (surveyer->isSwimming()) { surveyer->sendSystemMessage("@error_message:survey_swimming"); return; } if (surveyer->isRidingMount()) { if(surveyer->isInWater()) { surveyer->sendSystemMessage("@error_message:survey_cant"); return; } } else { if(surveyer->getPosture() != CreaturePosture::UPRIGHT) { surveyer->sendSystemMessage("@error_message:survey_standing"); return; } } //Get actual cost based upon player's Focus int mindCost = surveyer->calculateCostAdjustment(CreatureAttribute::FOCUS, 100); if (surveyer->getHAM(CreatureAttribute::MIND) < mindCost) { surveyer->setPosture(CreaturePosture::UPRIGHT, true); surveyer->sendSystemMessage("@error_message:survey_mind"); //You are exhausted. You nee to clear your head before you can survey again. return; } ManagedReference<ResourceSpawn*> spawn = resourceManager->getResourceSpawn(resname); if(spawn == NULL) { return; } if(spawn->getSurveyToolType() != activeSurveyTool->getToolType()) { StringIdChatParameter message("@survey:wrong_tool"); // %TO resources cannot be located with this tool message.setTO(spawn->getFinalClass()); surveyer->sendSystemMessage(message); return; } PlayClientEffectLoc* effect = new PlayClientEffectLoc(activeSurveyTool->getSurveyAnimation(), surveyer->getZone()->getZoneName(), surveyer->getPositionX(), surveyer->getPositionZ(), surveyer->getPositionY()); surveyer->broadcastMessage(effect, true); resourceManager->sendSurvey(surveyer, resname); } void SurveySessionImplementation::startSample(const String& resname) { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get(); if (activeSurveyTool == NULL) { error("surveyTool is NULL"); return; } if (resourceManager == NULL) { info("ResourceManager is NULL"); return; } if (surveyer == NULL) { info("surveyer is NULL"); return; } if (!resname.isEmpty()) lastResourceSampleName = resname; ManagedReference<ResourceSpawn* > resourceSpawn = resourceManager->getResourceSpawn(lastResourceSampleName); if (resourceSpawn == NULL) { return; } if (surveyer->isInCombat()) { surveyer->sendSystemMessage("@survey:sample_cancel_attack"); //You can't take samples while under attack! return; } if (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) { surveyer->sendSystemMessage("@error_message:survey_in_structure"); //You cannot perform survey-related actions inside a structure. return; } if (surveyer->isSwimming()) { surveyer->sendSystemMessage("@error_message:survey_swimming"); return; } if (surveyer->isRidingMount()) { surveyer->sendSystemMessage("@error_message:survey_on_mount"); return; } //Get actual cost based upon player's Quickness int actionCost = surveyer->calculateCostAdjustment(CreatureAttribute::QUICKNESS, 200); if (surveyer->getHAM(CreatureAttribute::ACTION) < actionCost) { surveyer->setPosture(CreaturePosture::UPRIGHT, true); surveyer->sendSystemMessage("@error_message:sample_mind"); //You are exhausted. You nee to clear your head before you can sample again. return; } if(resourceSpawn->getSurveyToolType() != activeSurveyTool->getToolType()) { StringIdChatParameter message("@survey:wrong_tool"); // %TO resources cannot be located with this tool message.setTO(resourceSpawn->getFinalClass()); surveyer->sendSystemMessage(message); return; } if(!lastResourceSampleName.isEmpty() && !activeSurveyTool->canSampleRadioactive()) { if(resourceSpawn->isType("radioactive") && !activeSurveyTool->canSampleRadioactive()) { activeSurveyTool->sendRadioactiveWarning(surveyer); return; } } // Player must be kneeling to sample if (!surveyer->isKneeling()) { surveyer->setPosture(CreaturePosture::CROUCHED, true); } if(surveyer->getPendingTask("sample") != NULL) { return; } StringIdChatParameter message("survey","start_sampling"); message.setTO(lastResourceSampleName); surveyer->sendSystemMessage(message); if (!doGamble && richSampleLocation == NULL && System::random(50) == 7) { if (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME)) { surveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME); } if (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2)) { surveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2); } if(System::random(1) == 1) surveyCnodeMinigameSui(); else surveyGnodeMinigameSui(); } else { if (!lastResourceSampleName.isEmpty()) resourceManager->sendSample(surveyer, lastResourceSampleName, activeSurveyTool->getSampleAnimation()); } } void SurveySessionImplementation::surveyCnodeMinigameSui() { ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); //int surveyMod = surveyer->getSkillMod("surveying"); ManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox( surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME, 0); suiConcMinigameBox->setPromptTitle("@survey:cnode_t"); suiConcMinigameBox->setPromptText("@survey:cnode_d"); suiConcMinigameBox->addMenuItem("@survey:cnode_1", 0); suiConcMinigameBox->addMenuItem("@survey:cnode_2", 1); suiConcMinigameBox->setCancelButton(true, "Cancel"); suiConcMinigameBox->setCallback(new SurveyCMinigameSuiCallback(surveyer->getZoneServer())); surveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox); surveyer->sendMessage(suiConcMinigameBox->generateMessage()); } void SurveySessionImplementation::surveyCnodeMinigame(int value) { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get(); if(value == 0) { // Add sampletask rescheduleSample(); return; } richSampleLocation = new Coordinate(surveyer->getPositionX(), surveyer->getPositionZ(), surveyer->getPositionY()); richSampleLocation->randomizePosition(50); ManagedReference<WaypointObject*> newwaypoint = NULL; PlayerObject* ghost = surveyer->getPlayerObject(); // Get previous survey waypoint ManagedReference<WaypointObject*> waypoint = ghost->getSurveyWaypoint(); // Create new waypoint if (waypoint == NULL) newwaypoint = ( surveyer->getZoneServer()->createObject(0xc456e788, 1)).castTo<WaypointObject*>(); else { ghost->removeWaypoint(waypoint->getObjectID(), true); newwaypoint = waypoint.get(); } // Update new waypoint newwaypoint->setCustomObjectName(UnicodeString("Resource Survey"), false); newwaypoint->setPlanetCRC(surveyer->getZone()->getZoneCRC()); newwaypoint->setPosition(richSampleLocation->getPositionX(), 0, richSampleLocation->getPositionY()); newwaypoint->setColor(WaypointObject::COLOR_BLUE); newwaypoint->setSpecialTypeID(WaypointObject::SPECIALTYPE_RESOURCE); newwaypoint->setActive(true); ghost->addWaypoint(newwaypoint, false, true); // Should second argument be true, and waypoints with the same name thus remove their old version? surveyer->sendSystemMessage("@survey:node_waypoint"); // Player must be kneeling to sample if (!surveyer->isStanding()) surveyer->setPosture(CreaturePosture::UPRIGHT, true); } void SurveySessionImplementation::surveyGnodeMinigameSui() { ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); //int surveyMod = surveyer->getSkillMod("surveying"); ManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2, 0); suiConcMinigameBox->setPromptTitle("@survey:gnode_t"); suiConcMinigameBox->setPromptText("@survey:gnode_d"); suiConcMinigameBox->addMenuItem("@survey:gnode_1", 0); suiConcMinigameBox->addMenuItem("@survey:gnode_2", 1); suiConcMinigameBox->setCancelButton(true, "Cancel"); suiConcMinigameBox->setCallback(new SurveyGMinigameSuiCallback(surveyer->getZoneServer())); surveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox); surveyer->sendMessage(suiConcMinigameBox->generateMessage()); } void SurveySessionImplementation::surveyGnodeMinigame(int value) { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); if(value == 1) { if(surveyer->getHAM(CreatureAttribute::ACTION) < 300) { surveyer->sendSystemMessage("@survey:gamble_no_action"); return; } surveyer->inflictDamage(surveyer, CreatureAttribute::ACTION, 300, false, true); doGamble = true; } rescheduleSample(); } void SurveySessionImplementation::rescheduleSurvey(SurveyMessage* surveyMessage, WaypointObject* waypoint, float maxDensity, ResourceSpawn* resourceSpawn) { surveyTask = new SurveyTask(surveyer, surveyMessage, waypoint, maxDensity * 100, resourceSpawn); surveyer.get()->addPendingTask("survey", surveyTask, 3000); } void SurveySessionImplementation::rescheduleSample() { // Add sampletask if(sampleTask == NULL) sampleTask = new SampleTask(surveyer.get(), activeSurveyTool.get()); if(surveyer.get()->getPendingTask("sample") == NULL) surveyer.get()->addPendingTask("sample", sampleTask, 25000); } void SurveySessionImplementation::rescheduleSampleResults(ResourceSpawner* resourceSpawner, float density, const String& resname) { // Add sampleresultstask if(surveyer.get()->getPendingTask("sampleresults") == NULL) { sampleResultsTask = new SampleResultsTask(surveyer, resourceSpawner, density, resname); surveyer.get()->addPendingTask("sampleresults", sampleResultsTask, 3000); } } <commit_msg>[added] player may sample resources while riding creatures<commit_after>/* * SurveySessionImplementation.cpp * * Created on: May 22, 2012 * Author: Kyle */ #include "server/zone/objects/player/sessions/survey/SurveySession.h" #include "server/zone/Zone.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/managers/resource/ResourceManager.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/tangible/tool/SurveyTool.h" #include "server/zone/packets/scene/PlayClientEffectLocMessage.h" #include "server/zone/objects/creature/CreatureAttribute.h" #include "server/zone/objects/player/sessions/survey/sui/SurveyGMinigameSuiCallback.h" #include "server/zone/objects/player/sessions/survey/sui/SurveyCMinigameSuiCallback.h" #include "server/zone/managers/resource/resourcespawner/SampleTask.h" #include "server/zone/managers/resource/resourcespawner/SurveyTask.h" #include "server/zone/managers/resource/resourcespawner/SampleResultsTask.h" int SurveySessionImplementation::initializeSession(SurveyTool* tool) { activeSurveyTool = tool; surveyerGhost = surveyer.get()->getPlayerObject(); return startSession(); } int SurveySessionImplementation::startSession() { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get(); if(surveyer == NULL || activeSurveyTool == NULL || surveyerGhost == NULL) { cancelSession(); return false; } resourceManager = surveyer->getZoneServer()->getResourceManager(); if(resourceManager == NULL) { cancelSession(); return false; } surveyer->addActiveSession(SessionFacadeType::SURVEY, _this.get()); return true; } int SurveySessionImplementation::cancelSession() { ManagedReference<CreatureObject*> ref = surveyer.get(); if(ref != NULL) ref->dropActiveSession(SessionFacadeType::SURVEY); return clearSession(); } int SurveySessionImplementation::clearSession() { return 0; } void SurveySessionImplementation::startSurvey(const String& resname) { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); if (activeSurveyTool == NULL) { error("surveyTool is NULL"); return; } if (resourceManager == NULL) { error("ResourceManager is NULL"); return; } if (surveyer == NULL) { error("surveyer is NULL"); return; } if (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) { surveyer->sendSystemMessage("@error_message:survey_in_structure"); //You cannot perform survey-related actions inside a structure. return; } if (surveyer->isSwimming()) { surveyer->sendSystemMessage("@error_message:survey_swimming"); return; } if (surveyer->isRidingMount()) { if(surveyer->isInWater()) { surveyer->sendSystemMessage("@error_message:survey_cant"); return; } } else { if(surveyer->getPosture() != CreaturePosture::UPRIGHT) { surveyer->sendSystemMessage("@error_message:survey_standing"); return; } } //Get actual cost based upon player's Focus int mindCost = surveyer->calculateCostAdjustment(CreatureAttribute::FOCUS, 100); if (surveyer->getHAM(CreatureAttribute::MIND) < mindCost) { surveyer->setPosture(CreaturePosture::UPRIGHT, true); surveyer->sendSystemMessage("@error_message:survey_mind"); //You are exhausted. You nee to clear your head before you can survey again. return; } ManagedReference<ResourceSpawn*> spawn = resourceManager->getResourceSpawn(resname); if(spawn == NULL) { return; } if(spawn->getSurveyToolType() != activeSurveyTool->getToolType()) { StringIdChatParameter message("@survey:wrong_tool"); // %TO resources cannot be located with this tool message.setTO(spawn->getFinalClass()); surveyer->sendSystemMessage(message); return; } PlayClientEffectLoc* effect = new PlayClientEffectLoc(activeSurveyTool->getSurveyAnimation(), surveyer->getZone()->getZoneName(), surveyer->getPositionX(), surveyer->getPositionZ(), surveyer->getPositionY()); surveyer->broadcastMessage(effect, true); resourceManager->sendSurvey(surveyer, resname); } void SurveySessionImplementation::startSample(const String& resname) { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get(); if (activeSurveyTool == NULL) { error("surveyTool is NULL"); return; } if (resourceManager == NULL) { info("ResourceManager is NULL"); return; } if (surveyer == NULL) { info("surveyer is NULL"); return; } if (!resname.isEmpty()) lastResourceSampleName = resname; ManagedReference<ResourceSpawn* > resourceSpawn = resourceManager->getResourceSpawn(lastResourceSampleName); if (resourceSpawn == NULL) { return; } if (surveyer->isInCombat()) { surveyer->sendSystemMessage("@survey:sample_cancel_attack"); //You can't take samples while under attack! return; } if (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) { surveyer->sendSystemMessage("@error_message:survey_in_structure"); //You cannot perform survey-related actions inside a structure. return; } if (surveyer->isSwimming()) { surveyer->sendSystemMessage("@error_message:survey_swimming"); return; } if (surveyer->getParent() != NULL && surveyer->getParent().get()->isVehicleObject() ) { surveyer->sendSystemMessage("You cannot perform that action while driving a vehicle."); return; } //Get actual cost based upon player's Quickness int actionCost = surveyer->calculateCostAdjustment(CreatureAttribute::QUICKNESS, 200); if (surveyer->getHAM(CreatureAttribute::ACTION) < actionCost) { surveyer->setPosture(CreaturePosture::UPRIGHT, true); surveyer->sendSystemMessage("@error_message:sample_mind"); //You are exhausted. You nee to clear your head before you can sample again. return; } if(resourceSpawn->getSurveyToolType() != activeSurveyTool->getToolType()) { StringIdChatParameter message("@survey:wrong_tool"); // %TO resources cannot be located with this tool message.setTO(resourceSpawn->getFinalClass()); surveyer->sendSystemMessage(message); return; } if(!lastResourceSampleName.isEmpty() && !activeSurveyTool->canSampleRadioactive()) { if(resourceSpawn->isType("radioactive") && !activeSurveyTool->canSampleRadioactive()) { activeSurveyTool->sendRadioactiveWarning(surveyer); return; } } // Player must be kneeling to sample (if unmounted) if (!surveyer->isKneeling() && !surveyer->isRidingMount() ) { surveyer->setPosture(CreaturePosture::CROUCHED, true); } if(surveyer->getPendingTask("sample") != NULL) { return; } StringIdChatParameter message("survey","start_sampling"); message.setTO(lastResourceSampleName); surveyer->sendSystemMessage(message); if (!doGamble && richSampleLocation == NULL && System::random(50) == 7) { if (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME)) { surveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME); } if (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2)) { surveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2); } if(System::random(1) == 1) surveyCnodeMinigameSui(); else surveyGnodeMinigameSui(); } else { if (!lastResourceSampleName.isEmpty()) resourceManager->sendSample(surveyer, lastResourceSampleName, activeSurveyTool->getSampleAnimation()); } } void SurveySessionImplementation::surveyCnodeMinigameSui() { ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); //int surveyMod = surveyer->getSkillMod("surveying"); ManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox( surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME, 0); suiConcMinigameBox->setPromptTitle("@survey:cnode_t"); suiConcMinigameBox->setPromptText("@survey:cnode_d"); suiConcMinigameBox->addMenuItem("@survey:cnode_1", 0); suiConcMinigameBox->addMenuItem("@survey:cnode_2", 1); suiConcMinigameBox->setCancelButton(true, "Cancel"); suiConcMinigameBox->setCallback(new SurveyCMinigameSuiCallback(surveyer->getZoneServer())); surveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox); surveyer->sendMessage(suiConcMinigameBox->generateMessage()); } void SurveySessionImplementation::surveyCnodeMinigame(int value) { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get(); if(value == 0) { // Add sampletask rescheduleSample(); return; } richSampleLocation = new Coordinate(surveyer->getPositionX(), surveyer->getPositionZ(), surveyer->getPositionY()); richSampleLocation->randomizePosition(50); ManagedReference<WaypointObject*> newwaypoint = NULL; PlayerObject* ghost = surveyer->getPlayerObject(); // Get previous survey waypoint ManagedReference<WaypointObject*> waypoint = ghost->getSurveyWaypoint(); // Create new waypoint if (waypoint == NULL) newwaypoint = ( surveyer->getZoneServer()->createObject(0xc456e788, 1)).castTo<WaypointObject*>(); else { ghost->removeWaypoint(waypoint->getObjectID(), true); newwaypoint = waypoint.get(); } // Update new waypoint newwaypoint->setCustomObjectName(UnicodeString("Resource Survey"), false); newwaypoint->setPlanetCRC(surveyer->getZone()->getZoneCRC()); newwaypoint->setPosition(richSampleLocation->getPositionX(), 0, richSampleLocation->getPositionY()); newwaypoint->setColor(WaypointObject::COLOR_BLUE); newwaypoint->setSpecialTypeID(WaypointObject::SPECIALTYPE_RESOURCE); newwaypoint->setActive(true); ghost->addWaypoint(newwaypoint, false, true); // Should second argument be true, and waypoints with the same name thus remove their old version? surveyer->sendSystemMessage("@survey:node_waypoint"); // Player must be kneeling to sample if (!surveyer->isStanding() && !surveyer->isRidingMount() ) surveyer->setPosture(CreaturePosture::UPRIGHT, true); } void SurveySessionImplementation::surveyGnodeMinigameSui() { ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); //int surveyMod = surveyer->getSkillMod("surveying"); ManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2, 0); suiConcMinigameBox->setPromptTitle("@survey:gnode_t"); suiConcMinigameBox->setPromptText("@survey:gnode_d"); suiConcMinigameBox->addMenuItem("@survey:gnode_1", 0); suiConcMinigameBox->addMenuItem("@survey:gnode_2", 1); suiConcMinigameBox->setCancelButton(true, "Cancel"); suiConcMinigameBox->setCallback(new SurveyGMinigameSuiCallback(surveyer->getZoneServer())); surveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox); surveyer->sendMessage(suiConcMinigameBox->generateMessage()); } void SurveySessionImplementation::surveyGnodeMinigame(int value) { ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get(); ManagedReference<CreatureObject*> surveyer = this->surveyer.get(); if(value == 1) { if(surveyer->getHAM(CreatureAttribute::ACTION) < 300) { surveyer->sendSystemMessage("@survey:gamble_no_action"); return; } surveyer->inflictDamage(surveyer, CreatureAttribute::ACTION, 300, false, true); doGamble = true; } rescheduleSample(); } void SurveySessionImplementation::rescheduleSurvey(SurveyMessage* surveyMessage, WaypointObject* waypoint, float maxDensity, ResourceSpawn* resourceSpawn) { surveyTask = new SurveyTask(surveyer, surveyMessage, waypoint, maxDensity * 100, resourceSpawn); surveyer.get()->addPendingTask("survey", surveyTask, 3000); } void SurveySessionImplementation::rescheduleSample() { // Add sampletask if(sampleTask == NULL) sampleTask = new SampleTask(surveyer.get(), activeSurveyTool.get()); if(surveyer.get()->getPendingTask("sample") == NULL) surveyer.get()->addPendingTask("sample", sampleTask, 25000); } void SurveySessionImplementation::rescheduleSampleResults(ResourceSpawner* resourceSpawner, float density, const String& resname) { // Add sampleresultstask if(surveyer.get()->getPendingTask("sampleresults") == NULL) { sampleResultsTask = new SampleResultsTask(surveyer, resourceSpawner, density, resname); surveyer.get()->addPendingTask("sampleresults", sampleResultsTask, 3000); } } <|endoftext|>
<commit_before>#include "mitkImageMapper2D.h" //#include "mitkRenderWindow.h" #include "widget.h" #include "picimage.h" #include "pic2vtk.h" #include "mitkPlaneGeometry.h" #include "mitkBaseRenderer.h" #include "mitkDataTreeNode.h" #include "mitkLookupTableProperty.h" #include "mitkBoolProperty.h" #include "mitkLevelWindowProperty.h" #include "mitkRenderWindow.h" #include "mitkAbstractTransformGeometry.h" #include <vtkImageReslice.h> #include <vtkTransform.h> #include <vtkMatrix4x4.h> #include <vtkLookupTable.h> int mitk::ImageMapper2D::numRenderer = 0; mitk::ImageMapper2D::ImageMapper2D() : m_SliceSelector(NULL) { // Modify superclass default values, can be overridden by subclasses this->SetNumberOfRequiredInputs(1); m_SliceSelector = ImageSliceSelector::New(); m_Reslicer = vtkImageReslice::New(); } //##ModelId=3E32DCF60043 mitk::ImageMapper2D::~ImageMapper2D() { //@FIXME: durch die folgende Zeile sollte doch wohl der desctructor von RendererInfo aufgerufen werden. Das passiert aber nie. Deshalb wird bei der Programm-Beendung auch das iilImage und damit die textur nicht rechtzeitig freigegeben und das Programm crashed. m_RendererInfo.clear(); } //##ModelId=3E3D834B003A void mitk::ImageMapper2D::GenerateData() { } void mitk::ImageMapper2D::Paint(mitk::BaseRenderer * renderer) { if(IsVisible(renderer)==false) return; RendererInfo& renderinfo=m_RendererInfo[renderer]; iilPicImage*& image = renderinfo.m_iilImage; Update(renderer); const mitk::DisplayGeometry* displayGeometry = renderer->GetDisplayGeometry(); Vector2D oldtopLeft=displayGeometry->GetOriginInUnits(); Vector2D oldbottomRight=displayGeometry->GetOriginInUnits()+displayGeometry->GetSizeInUnits(); Vector2D topLeft; Vector2D bottomRight; topLeft=displayGeometry->GetOriginInDisplayUnits(); bottomRight=topLeft+displayGeometry->GetSizeInDisplayUnits(); displayGeometry->DisplayToMM(topLeft, topLeft); topLeft.x*=renderinfo.m_PixelsPerMM.x; topLeft.y*=renderinfo.m_PixelsPerMM.y; displayGeometry->DisplayToMM(bottomRight, bottomRight); bottomRight.x*=renderinfo.m_PixelsPerMM.x; bottomRight.y*=renderinfo.m_PixelsPerMM.y; //test - small differences noticed for unisotropic datasets. if((Vector2D(oldtopLeft-topLeft).length()>0.1) || (Vector2D(oldbottomRight-bottomRight).length()>0.1)) { bottomRight*=1.0; } glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluOrtho2D(topLeft.x, bottomRight.x, topLeft.y, bottomRight.y ); glMatrixMode( GL_MODELVIEW ); GLdouble eqn0[4] = {0.0, 1.0, 0.0, 0.0}; GLdouble eqn1[4] = {1.0, 0.0, 0.0, 0.0}; GLdouble eqn2[4] = {-1.0, 0.0 , 0.0, image->width()}; GLdouble eqn3[4] = {0, -1.0, 0.0, image->height() }; glClipPlane (GL_CLIP_PLANE0, eqn0); glEnable (GL_CLIP_PLANE0); glClipPlane (GL_CLIP_PLANE1, eqn1); glEnable (GL_CLIP_PLANE1); glClipPlane (GL_CLIP_PLANE2, eqn2); glEnable (GL_CLIP_PLANE2); glClipPlane (GL_CLIP_PLANE3, eqn3); glEnable (GL_CLIP_PLANE3); image->display(renderer->GetRenderWindow()); glDisable (GL_CLIP_PLANE0); glDisable (GL_CLIP_PLANE1); glDisable (GL_CLIP_PLANE2); glDisable (GL_CLIP_PLANE3); glPushMatrix (); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluOrtho2D(0, displayGeometry->GetDisplayWidth(), 0, displayGeometry->GetDisplayHeight() ); glMatrixMode( GL_MODELVIEW ); glPopMatrix (); } //##ModelId=3E3D834B0008 const mitk::ImageMapper2D::InputImageType *mitk::ImageMapper2D::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::ImageMapper2D::InputImageType * > ( GetData() ); } //##ModelId=3E6E83B00343 int mitk::ImageMapper2D::GetAssociatedChannelNr(mitk::BaseRenderer *renderer) { RendererInfo& renderinfo=m_RendererInfo[renderer]; if(renderinfo.m_RendererId < 0) renderinfo.m_RendererId = ImageMapper2D::numRenderer++; return renderinfo.m_RendererId; } //##ModelId=3E8607D20380 void mitk::ImageMapper2D::GenerateOutputInformation() { mitk::Image::Pointer output = this->GetOutput(); mitk::PixelType pt(typeid(int)); unsigned int dim[]={256,256}; output->Initialize(mitk::PixelType(typeid(short int)), 2, dim, 10); } //##ModelId=3ED932B00140 void mitk::ImageMapper2D::GenerateData(mitk::BaseRenderer *renderer) { RendererInfo& renderinfo=m_RendererInfo[renderer]; iilPicImage*& image = renderinfo.m_iilImage; mitk::Image::Pointer input = const_cast<mitk::ImageMapper2D::InputImageType *>(this->GetInput()); if(image!= NULL) { delete image; image = NULL; } if(renderinfo.m_Pic) { ipPicFree(renderinfo.m_Pic); renderinfo.m_Pic = NULL; } if(renderinfo.m_RendererId < 0) renderinfo.m_RendererId = ImageMapper2D::numRenderer++; if(input.IsNotNull()) { vtkImageData* inputData = input->GetVtkImageData(); const PlaneView* planeview=NULL; const Geometry2D* worldgeometry = renderer->GetWorldGeometry(); if(dynamic_cast<const PlaneGeometry *>(worldgeometry)!=NULL) { planeview=&dynamic_cast<const PlaneGeometry *>(worldgeometry)->GetPlaneView(); m_Reslicer->SetResliceTransform(NULL); } else if(dynamic_cast<const AbstractTransformGeometry *>(worldgeometry)!=NULL) { const AbstractTransformGeometry *abstractGeometry=dynamic_cast<const AbstractTransformGeometry *>(worldgeometry); planeview=&abstractGeometry->GetPlaneView(); m_Reslicer->SetResliceTransform(abstractGeometry->GetVtkAbstractTransform()); //m_Reslicer->DebugOn(); } else return; assert(planeview!=NULL); assert(planeview->normal.length()>0.1); vtkMatrix4x4* geometry = vtkMatrix4x4::New(); geometry->Identity(); m_Reslicer->SetInput(inputData); m_Reslicer->SetOutputDimensionality(2); m_Reslicer->SetOutputOrigin(0,0,0); m_Reslicer->SetBackgroundLevel(-1024); int width, height; width=worldgeometry->GetWidthInUnits(); height=worldgeometry->GetHeightInUnits(); renderinfo.m_PixelsPerMM.set(planeview->getLengthOfOrientation1()/width, planeview->getLengthOfOrientation2()/height); m_Reslicer->SetOutputSpacing(renderinfo.m_PixelsPerMM.x, renderinfo.m_PixelsPerMM.y, 1.0); m_Reslicer->SetOutputExtent(0, width-1, 0, height-1, 0, 1); double origin[3]; origin[0]=planeview->point.x; origin[1]=planeview->point.y; origin[2]=planeview->point.z; m_Reslicer->SetResliceAxes(geometry); m_Reslicer->SetResliceAxesOrigin(origin); // m_Reslicer->SetInterpolationModeToLinear(); double cosines[9]; Vector3f orient1 = planeview->getOrientation1(); orient1.normalize(); Vector3f orient2 = planeview->getOrientation2(); orient2.normalize(); // Richtung der X-Achse der Ergebnisschicht im Volumen, cosines[0]=orient1.x; cosines[1]=orient1.y; cosines[2]=orient1.z; //Richtung der Y-Achse der Ergebnisschicht im Volumen cosines[3]=orient2.x; cosines[4]=orient2.y; cosines[5]=orient2.z; // Schichtfolge/Projektionsrichtung cosines[6]= planeview->normal.x; cosines[7]= planeview->normal.y; cosines[8]= planeview->normal.z; m_Reslicer->SetResliceAxesDirectionCosines(cosines); m_Reslicer->Update(); vtkImageData* vtkoutput = m_Reslicer->GetOutput(); assert(vtkoutput); // std::cout << vtkoutput <<std::endl; ipPicDescriptor* pic = Pic2vtk::convert(vtkoutput); assert(pic); if(pic->dim==1) { pic->dim=2; pic->n[1]=1; } assert(pic->dim == 2); renderinfo.m_Pic = pic; //std::cout << "Pic dimensions:" << pic->dim << std::endl; image = new iilPicImage(NULL, "ll", 512); ApplyProperties(renderer); // image->setImage(pic, iilImage::INTENSITY_ALPHA); image->setImage(pic, m_iilMode); image->setInterpolation(true); image->setRegion(0,0,pic->n[0],pic->n[1]); mitk::Image::Pointer output = this->GetOutput(); //if(renderinfo.m_RendererId < 10) // output->SetPicSlice(pic,0,0,renderinfo.m_RendererId); output->Modified(); renderinfo.m_LastUpdateTime=output->GetMTime(); } return; } void mitk::ImageMapper2D::GenerateAllData() { std::map<mitk::BaseRenderer*,RendererInfo>::iterator it=m_RendererInfo.begin(); for(;it!=m_RendererInfo.end();++it) Update(it->first); } void mitk::ImageMapper2D::ApplyProperties(mitk::BaseRenderer* renderer) { RendererInfo& renderinfo=m_RendererInfo[renderer]; iilPicImage*& image = renderinfo.m_iilImage; assert(image != NULL); float rgba[4]={1.0f,1.0f,1.0f,1.0f}; // check for color prop and use it for rendering if it exists GetColor(rgba, renderer); // check for opacity prop and use it for rendering if it exists GetOpacity(rgba[3], renderer); mitk::LevelWindow levelWindow; // check for level window prop and use it for display if it exists GetLevelWindow(levelWindow, renderer); mitk::LookupTableProperty::Pointer LookupTable; LookupTable = dynamic_cast<mitk::LookupTableProperty*>(this->GetDataTreeNode()->GetProperty("LookupTable").GetPointer()); if (LookupTable.IsNull() ) { m_iilMode = iilImage::INTENSITY_ALPHA; image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]); } else { m_iilMode = iilImage::COLOR_ALPHA; image->setColors(LookupTable->GetLookupTable().GetRawLookupTable()); } mitk::BoolProperty::Pointer binary; binary = dynamic_cast<mitk::BoolProperty*>(this->GetDataTreeNode()->GetProperty("binary").GetPointer()); mitk::LevelWindowProperty::Pointer overwriteLevelWindow; overwriteLevelWindow = dynamic_cast<mitk::LevelWindowProperty*>(this->GetDataTreeNode()->GetProperty("levelWindow").GetPointer()); if (binary.IsNotNull() ) { image->setExtrema(0, 1); } else if (overwriteLevelWindow.IsNotNull() ) { image->setExtrema(overwriteLevelWindow->GetLevelWindow().GetMin(), overwriteLevelWindow->GetLevelWindow().GetMax()); } else { // set the properties image->setExtrema(levelWindow.GetMin(), levelWindow.GetMax()); } // image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]); } void mitk::ImageMapper2D::Update(mitk::BaseRenderer* renderer) { RendererInfo& renderinfo=m_RendererInfo[renderer]; DataTreeNode* node=GetDataTreeNode(); iilPicImage*& image = renderinfo.m_iilImage; if( (image == NULL) || (renderinfo.m_RendererId < 0) || (renderinfo.m_LastUpdateTime < node->GetMTime()) || (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometryUpdateTime()) || (renderinfo.m_LastUpdateTime < renderer->GetDisplayGeometryUpdateTime()) ) GenerateData(renderer); else if( (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometry()->GetMTime()) //&& //(renderinfo.m_LastUpdateTime < renderer->GetMTime()) ) GenerateData(renderer); else if( (renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime()) || (renderinfo.m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) { ApplyProperties(renderer); // since we have checked that nothing important has changed, we can set m_LastUpdateTime // to the current time mitk::Image::Pointer output = this->GetOutput(); output->Modified(); renderinfo.m_LastUpdateTime=output->GetMTime(); } } <commit_msg>fixed bug concerning correct positioning of non-isotropic/non-1pixel==1mm-data.<commit_after>#include "mitkImageMapper2D.h" //#include "mitkRenderWindow.h" #include "widget.h" #include "picimage.h" #include "pic2vtk.h" #include "mitkPlaneGeometry.h" #include "mitkBaseRenderer.h" #include "mitkDataTreeNode.h" #include "mitkLookupTableProperty.h" #include "mitkBoolProperty.h" #include "mitkLevelWindowProperty.h" #include "mitkRenderWindow.h" #include "mitkAbstractTransformGeometry.h" #include <vtkImageReslice.h> #include <vtkTransform.h> #include <vtkMatrix4x4.h> #include <vtkLookupTable.h> int mitk::ImageMapper2D::numRenderer = 0; mitk::ImageMapper2D::ImageMapper2D() : m_SliceSelector(NULL) { // Modify superclass default values, can be overridden by subclasses this->SetNumberOfRequiredInputs(1); m_SliceSelector = ImageSliceSelector::New(); m_Reslicer = vtkImageReslice::New(); } //##ModelId=3E32DCF60043 mitk::ImageMapper2D::~ImageMapper2D() { //@FIXME: durch die folgende Zeile sollte doch wohl der desctructor von RendererInfo aufgerufen werden. Das passiert aber nie. Deshalb wird bei der Programm-Beendung auch das iilImage und damit die textur nicht rechtzeitig freigegeben und das Programm crashed. m_RendererInfo.clear(); } //##ModelId=3E3D834B003A void mitk::ImageMapper2D::GenerateData() { } void mitk::ImageMapper2D::Paint(mitk::BaseRenderer * renderer) { if(IsVisible(renderer)==false) return; RendererInfo& renderinfo=m_RendererInfo[renderer]; iilPicImage*& image = renderinfo.m_iilImage; Update(renderer); const mitk::DisplayGeometry* displayGeometry = renderer->GetDisplayGeometry(); Vector2D oldtopLeft=displayGeometry->GetOriginInUnits(); Vector2D oldbottomRight=displayGeometry->GetOriginInUnits()+displayGeometry->GetSizeInUnits(); Vector2D topLeft; Vector2D bottomRight; topLeft=displayGeometry->GetOriginInDisplayUnits(); bottomRight=topLeft+displayGeometry->GetSizeInDisplayUnits(); displayGeometry->DisplayToMM(topLeft, topLeft); topLeft.x*=renderinfo.m_PixelsPerMM.x; topLeft.y*=renderinfo.m_PixelsPerMM.y; displayGeometry->DisplayToMM(bottomRight, bottomRight); bottomRight.x*=renderinfo.m_PixelsPerMM.x; bottomRight.y*=renderinfo.m_PixelsPerMM.y; //test - small differences noticed for unisotropic datasets. if((Vector2D(oldtopLeft-topLeft).length()>0.1) || (Vector2D(oldbottomRight-bottomRight).length()>0.1)) { itkWarningMacro("oldtopLeft!=topLeft in ImageMapper2D"); } glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluOrtho2D(topLeft.x, bottomRight.x, topLeft.y, bottomRight.y ); glMatrixMode( GL_MODELVIEW ); GLdouble eqn0[4] = {0.0, 1.0, 0.0, 0.0}; GLdouble eqn1[4] = {1.0, 0.0, 0.0, 0.0}; GLdouble eqn2[4] = {-1.0, 0.0 , 0.0, image->width()}; GLdouble eqn3[4] = {0, -1.0, 0.0, image->height() }; glClipPlane (GL_CLIP_PLANE0, eqn0); glEnable (GL_CLIP_PLANE0); glClipPlane (GL_CLIP_PLANE1, eqn1); glEnable (GL_CLIP_PLANE1); glClipPlane (GL_CLIP_PLANE2, eqn2); glEnable (GL_CLIP_PLANE2); glClipPlane (GL_CLIP_PLANE3, eqn3); glEnable (GL_CLIP_PLANE3); image->display(renderer->GetRenderWindow()); glDisable (GL_CLIP_PLANE0); glDisable (GL_CLIP_PLANE1); glDisable (GL_CLIP_PLANE2); glDisable (GL_CLIP_PLANE3); glPushMatrix (); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluOrtho2D(0, displayGeometry->GetDisplayWidth(), 0, displayGeometry->GetDisplayHeight() ); glMatrixMode( GL_MODELVIEW ); glPopMatrix (); } //##ModelId=3E3D834B0008 const mitk::ImageMapper2D::InputImageType *mitk::ImageMapper2D::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::ImageMapper2D::InputImageType * > ( GetData() ); } //##ModelId=3E6E83B00343 int mitk::ImageMapper2D::GetAssociatedChannelNr(mitk::BaseRenderer *renderer) { RendererInfo& renderinfo=m_RendererInfo[renderer]; if(renderinfo.m_RendererId < 0) renderinfo.m_RendererId = ImageMapper2D::numRenderer++; return renderinfo.m_RendererId; } //##ModelId=3E8607D20380 void mitk::ImageMapper2D::GenerateOutputInformation() { mitk::Image::Pointer output = this->GetOutput(); mitk::PixelType pt(typeid(int)); unsigned int dim[]={256,256}; output->Initialize(mitk::PixelType(typeid(short int)), 2, dim, 10); } //##ModelId=3ED932B00140 void mitk::ImageMapper2D::GenerateData(mitk::BaseRenderer *renderer) { RendererInfo& renderinfo=m_RendererInfo[renderer]; iilPicImage*& image = renderinfo.m_iilImage; mitk::Image::Pointer input = const_cast<mitk::ImageMapper2D::InputImageType *>(this->GetInput()); if(image!= NULL) { delete image; image = NULL; } if(renderinfo.m_Pic) { ipPicFree(renderinfo.m_Pic); renderinfo.m_Pic = NULL; } if(renderinfo.m_RendererId < 0) renderinfo.m_RendererId = ImageMapper2D::numRenderer++; if(input.IsNotNull()) { vtkImageData* inputData = input->GetVtkImageData(); const PlaneView* planeview=NULL; const Geometry2D* worldgeometry = renderer->GetWorldGeometry(); if(dynamic_cast<const PlaneGeometry *>(worldgeometry)!=NULL) { planeview=&dynamic_cast<const PlaneGeometry *>(worldgeometry)->GetPlaneView(); m_Reslicer->SetResliceTransform(NULL); } else if(dynamic_cast<const AbstractTransformGeometry *>(worldgeometry)!=NULL) { const AbstractTransformGeometry *abstractGeometry=dynamic_cast<const AbstractTransformGeometry *>(worldgeometry); planeview=&abstractGeometry->GetPlaneView(); m_Reslicer->SetResliceTransform(abstractGeometry->GetVtkAbstractTransform()); //m_Reslicer->DebugOn(); } else return; assert(planeview!=NULL); assert(planeview->normal.length()>0.1); vtkMatrix4x4* geometry = vtkMatrix4x4::New(); geometry->Identity(); m_Reslicer->SetInput(inputData); m_Reslicer->SetOutputDimensionality(2); m_Reslicer->SetOutputOrigin(0,0,0); m_Reslicer->SetBackgroundLevel(-1024); //let's define how many pixels we really want to sample: width x height pixels int width, height; //let's use the values of worldgeometry->GetWidthInUnits() and worldgeometry->GetHeightInUnits() for that purpose //maybe it is useful to add here a more sophisticated rule that depends on the actual size of the current display, so not to //sample 1000x1000 pixels for a display of 10x10 pixels width=worldgeometry->GetWidthInUnits(); height=worldgeometry->GetHeightInUnits(); renderinfo.m_PixelsPerMM.set(width/planeview->getLengthOfOrientation1(), height/planeview->getLengthOfOrientation2()); m_Reslicer->SetOutputSpacing(1.0/renderinfo.m_PixelsPerMM.x, 1.0/renderinfo.m_PixelsPerMM.y, 1.0); m_Reslicer->SetOutputExtent(0, width-1, 0, height-1, 0, 1); //calulate the origin and the orientations for the reslice-filter double origin[3]; vec2vtk(planeview->point, origin); m_Reslicer->SetResliceAxes(geometry); m_Reslicer->SetResliceAxesOrigin(origin); // m_Reslicer->SetInterpolationModeToLinear(); double cosines[9]; Vector3f orient1 = planeview->getOrientation1(); orient1.normalize(); Vector3f orient2 = planeview->getOrientation2(); orient2.normalize(); // direction of the X-axis of the sampled result vec2vtk(orient1, cosines); // direction of the Y-axis of the sampled result vec2vtk(orient2, cosines+3); // normal of the plane vec2vtk(planeview->normal, cosines+6); m_Reslicer->SetResliceAxesDirectionCosines(cosines); //do the reslicing m_Reslicer->Update(); vtkImageData* vtkoutput = m_Reslicer->GetOutput(); assert(vtkoutput); // std::cout << vtkoutput <<std::endl; ipPicDescriptor* pic = Pic2vtk::convert(vtkoutput); assert(pic); if(pic->dim==1) { pic->dim=2; pic->n[1]=1; } assert(pic->dim == 2); renderinfo.m_Pic = pic; //std::cout << "Pic dimensions:" << pic->dim << std::endl; image = new iilPicImage(NULL, "ll", 512); ApplyProperties(renderer); // image->setImage(pic, iilImage::INTENSITY_ALPHA); image->setImage(pic, m_iilMode); image->setInterpolation(true); image->setRegion(0,0,pic->n[0],pic->n[1]); mitk::Image::Pointer output = this->GetOutput(); //if(renderinfo.m_RendererId < 10) // output->SetPicSlice(pic,0,0,renderinfo.m_RendererId); output->Modified(); renderinfo.m_LastUpdateTime=output->GetMTime(); } return; } void mitk::ImageMapper2D::GenerateAllData() { std::map<mitk::BaseRenderer*,RendererInfo>::iterator it=m_RendererInfo.begin(); for(;it!=m_RendererInfo.end();++it) Update(it->first); } void mitk::ImageMapper2D::ApplyProperties(mitk::BaseRenderer* renderer) { RendererInfo& renderinfo=m_RendererInfo[renderer]; iilPicImage*& image = renderinfo.m_iilImage; assert(image != NULL); float rgba[4]={1.0f,1.0f,1.0f,1.0f}; // check for color prop and use it for rendering if it exists GetColor(rgba, renderer); // check for opacity prop and use it for rendering if it exists GetOpacity(rgba[3], renderer); mitk::LevelWindow levelWindow; // check for level window prop and use it for display if it exists GetLevelWindow(levelWindow, renderer); mitk::LookupTableProperty::Pointer LookupTable; LookupTable = dynamic_cast<mitk::LookupTableProperty*>(this->GetDataTreeNode()->GetProperty("LookupTable").GetPointer()); if (LookupTable.IsNull() ) { m_iilMode = iilImage::INTENSITY_ALPHA; image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]); } else { m_iilMode = iilImage::COLOR_ALPHA; image->setColors(LookupTable->GetLookupTable().GetRawLookupTable()); } mitk::BoolProperty::Pointer binary; binary = dynamic_cast<mitk::BoolProperty*>(this->GetDataTreeNode()->GetProperty("binary").GetPointer()); mitk::LevelWindowProperty::Pointer overwriteLevelWindow; overwriteLevelWindow = dynamic_cast<mitk::LevelWindowProperty*>(this->GetDataTreeNode()->GetProperty("levelWindow").GetPointer()); if (binary.IsNotNull() ) { image->setExtrema(0, 1); } else if (overwriteLevelWindow.IsNotNull() ) { image->setExtrema(overwriteLevelWindow->GetLevelWindow().GetMin(), overwriteLevelWindow->GetLevelWindow().GetMax()); } else { // set the properties image->setExtrema(levelWindow.GetMin(), levelWindow.GetMax()); } // image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]); } void mitk::ImageMapper2D::Update(mitk::BaseRenderer* renderer) { RendererInfo& renderinfo=m_RendererInfo[renderer]; DataTreeNode* node=GetDataTreeNode(); iilPicImage*& image = renderinfo.m_iilImage; if( (image == NULL) || (renderinfo.m_RendererId < 0) || (renderinfo.m_LastUpdateTime < node->GetMTime()) || (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometryUpdateTime()) || (renderinfo.m_LastUpdateTime < renderer->GetDisplayGeometryUpdateTime()) ) GenerateData(renderer); else if( (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometry()->GetMTime()) //&& //(renderinfo.m_LastUpdateTime < renderer->GetMTime()) ) GenerateData(renderer); else if( (renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime()) || (renderinfo.m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) { ApplyProperties(renderer); // since we have checked that nothing important has changed, we can set m_LastUpdateTime // to the current time mitk::Image::Pointer output = this->GetOutput(); output->Modified(); renderinfo.m_LastUpdateTime=output->GetMTime(); } } <|endoftext|>
<commit_before>// Copyright 2013 Velodyne Acoustics, Inc. // // 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. /*========================================================================= Program: Visualization Toolkit Module: PacketFileSender.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME PacketFileSender - // .SECTION Description // This program reads a pcap file and sends the packets using UDP. #include "vtkPacketFileReader.h" #include "vvPacketSender.h" #include <cstdlib> #include <ctime> #include <iostream> #include <string> #include <boost/thread/thread.hpp> int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " <packet file> [loop] [ip] [dataPort] [position Port] [PlaybackSpeedMultiplier]" << std::endl; return 1; } std::string filename(argv[1]); int loop = 0; double speed = 1; std::string destinationIp = "127.0.0.1"; int dataPort=2368; int positionPort=8308; if(argc > 2) { loop = atoi(argv[2]); } if(argc > 3) { destinationIp = argv[3]; } if(argc>5) { dataPort=atoi(argv[4]); positionPort=atoi(argv[5]); } if(argc>6) { speed = static_cast<double>(atof(argv[6])); } // Default time to wait -> it is the elapsed // time between two firing of a HDL-32 sensor const int defaultTimeToWait = 553; // The sensor send one packet every hundreds microseconds // thus, the first initialization of timeToWait is defaultTimeToWait int timeToWaitPerPacket = static_cast<int>(1.0 / speed * defaultTimeToWait); // The timer's resolution is only 1000 microsecond // But we need to send packets every X microseconds // Thus, we send packet by group of NumberPacketsByPool // and then wait the necessary time int NumberPacketsByPool = 40; // The minimalTimeToWait resolution so that // timeToWait * NumberPacketsByPool > 1000 double minimalTimeToWait = 1000.0/NumberPacketsByPool; // Measurement of the sleep clock_t T1, T2; double elapsedTimeMeasured; double timeMicroSecond = 0; double elapsedTimeBetweenPackets = 0; std::cout << "Start sending" << std::endl; try { do { vvPacketSender sender(filename, destinationIp, dataPort, positionPort); // socket.connect(destinationEndpoint); sender.pumpPacket(); while (!sender.done()) { // Get the timestamp of the packet to compute // the next timeToWait int currentTimeDiff = sender.pumpPacket(); // Elapsed time measured from the timestamp of the packets // This timestamp will be used to compute the next time to wait elapsedTimeBetweenPackets += currentTimeDiff; // Every 1000 packets sent, give some information // about the number of packet sent, the elapsed time // and the next time to wait for the 1000 next packets if ((sender.packetCount() % 1000) == 0) { // Elapsed time measured from the clock of the computer // This timestamp will be used to inform the user // This timestamp should be greater than elapsedTime2 T2 = std::clock(); elapsedTimeMeasured = T2 - T1; std::cout << "total sent packets : " << sender.packetCount() << std::endl <<" Elapsed time per packets asked : " << timeToWaitPerPacket << " microseconds" << std::endl <<" Elapsed time per packets measured : " << elapsedTimeMeasured * 1e6 / 1000 << " microseconds" << std::endl << std::endl; timeToWaitPerPacket = static_cast<int>(1.0 / speed * elapsedTimeBetweenPackets / 1000); // If the computed timeToWait is too high we assume that // there is a corruption into the packets timestamp // then we set the timeToWait to the HDL-32 firing rate if(timeToWaitPerPacket > 2500) { timeToWaitPerPacket = static_cast<int>(1.0 / speed * defaultTimeToWait); } // If the computed timeToWait is under the minimal resolution // we set the timeToWait to this minimal resolution if(timeToWaitPerPacket < minimalTimeToWait) { timeToWaitPerPacket = static_cast<int>(minimalTimeToWait); } // Refresh the measured timestamps T1 = std::clock(); elapsedTimeBetweenPackets = 0; } // boost::this_thread::sleep(boost::posix_time::microseconds(553)); // Every NumberPacketsByPool packets we wait to be consistent with // the real recording of the data. The number of packets should not be // too small -> the clock resolution is 1000 microsecond. Hence, // NumberPacketsByPool * timeToWait should be greater than 1000 if ((sender.packetCount() % NumberPacketsByPool) == 0) { sleep(NumberPacketsByPool * timeToWaitPerPacket); } } } while(loop); } catch( std::exception & e ) { std::cout << "Caught Exception: " << e.what() << std::endl; return 1; } return 0; } <commit_msg>sleep is a GCC function. Changed by boost::this_thread::sleep<commit_after>// Copyright 2013 Velodyne Acoustics, Inc. // // 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. /*========================================================================= Program: Visualization Toolkit Module: PacketFileSender.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME PacketFileSender - // .SECTION Description // This program reads a pcap file and sends the packets using UDP. #include "vtkPacketFileReader.h" #include "vvPacketSender.h" #include <cstdlib> #include <ctime> #include <iostream> #include <string> #include <boost/thread/thread.hpp> int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " <packet file> [loop] [ip] [dataPort] [position Port] [PlaybackSpeedMultiplier]" << std::endl; return 1; } std::string filename(argv[1]); int loop = 0; double speed = 1; std::string destinationIp = "127.0.0.1"; int dataPort=2368; int positionPort=8308; if(argc > 2) { loop = atoi(argv[2]); } if(argc > 3) { destinationIp = argv[3]; } if(argc>5) { dataPort=atoi(argv[4]); positionPort=atoi(argv[5]); } if(argc>6) { speed = static_cast<double>(atof(argv[6])); } // Default time to wait -> it is the elapsed // time between two firing of a HDL-32 sensor const int defaultTimeToWait = 553; // The sensor send one packet every hundreds microseconds // thus, the first initialization of timeToWait is defaultTimeToWait int timeToWaitPerPacket = static_cast<int>(1.0 / speed * defaultTimeToWait); // The timer's resolution is only 1000 microsecond // But we need to send packets every X microseconds // Thus, we send packet by group of NumberPacketsByPool // and then wait the necessary time int NumberPacketsByPool = 40; // The minimalTimeToWait resolution so that // timeToWait * NumberPacketsByPool > 1000 double minimalTimeToWait = 1000.0/NumberPacketsByPool; // Measurement of the sleep clock_t T1, T2; double elapsedTimeMeasured; double timeMicroSecond = 0; double elapsedTimeBetweenPackets = 0; std::cout << "Start sending" << std::endl; try { do { vvPacketSender sender(filename, destinationIp, dataPort, positionPort); // socket.connect(destinationEndpoint); sender.pumpPacket(); while (!sender.done()) { // Get the timestamp of the packet to compute // the next timeToWait int currentTimeDiff = sender.pumpPacket(); // Elapsed time measured from the timestamp of the packets // This timestamp will be used to compute the next time to wait elapsedTimeBetweenPackets += currentTimeDiff; // Every 1000 packets sent, give some information // about the number of packet sent, the elapsed time // and the next time to wait for the 1000 next packets if ((sender.packetCount() % 1000) == 0) { // Elapsed time measured from the clock of the computer // This timestamp will be used to inform the user // This timestamp should be greater than elapsedTime2 T2 = std::clock(); elapsedTimeMeasured = T2 - T1; std::cout << "total sent packets : " << sender.packetCount() << std::endl <<" Elapsed time per packets asked : " << timeToWaitPerPacket << " microseconds" << std::endl <<" Elapsed time per packets measured : " << elapsedTimeMeasured << " microseconds" << std::endl << std::endl; timeToWaitPerPacket = static_cast<int>(1.0 / speed * elapsedTimeBetweenPackets / 1000); // If the computed timeToWait is too high we assume that // there is a corruption into the packets timestamp // then we set the timeToWait to the HDL-32 firing rate if(timeToWaitPerPacket > 2500) { timeToWaitPerPacket = static_cast<int>(1.0 / speed * defaultTimeToWait); } // If the computed timeToWait is under the minimal resolution // we set the timeToWait to this minimal resolution if(timeToWaitPerPacket < minimalTimeToWait) { timeToWaitPerPacket = static_cast<int>(minimalTimeToWait); } // Refresh the measured timestamps T1 = std::clock(); elapsedTimeBetweenPackets = 0; } // boost::this_thread::sleep(boost::posix_time::microseconds(553)); // Every NumberPacketsByPool packets we wait to be consistent with // the real recording of the data. The number of packets should not be // too small -> the clock resolution is 1000 microsecond. Hence, // NumberPacketsByPool * timeToWait should be greater than 1000 if ((sender.packetCount() % NumberPacketsByPool) == 0) { boost::this_thread::sleep(boost::posix_time::microseconds(NumberPacketsByPool * timeToWaitPerPacket)); } } } while(loop); } catch( std::exception & e ) { std::cout << "Caught Exception: " << e.what() << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** //************************* System Include Files **************************** #include <iostream> #include <unistd.h> // for 'getopt' //*************************** User Include Files **************************** #include "Args.h" #include <lib/support/String.h> #include <lib/support/Trace.h> //*************************** Forward Declarations ************************** using std::cerr; using std::endl; //*************************************************************************** const char* hpctoolsVerInfo= #include <include/HPCToolkitVersionInfo.h> void Args::Version() { cerr << cmd << ": " << hpctoolsVerInfo << endl; } void Args::Usage() { cerr << "Usage: " << endl << " " << cmd << " [-l | -L] <binary> <profile>\n" << " " << cmd << " [-V] [ [-M <mlist>] [-X <xlist>] [-R] ] <binary> <profile>\n" << endl; cerr << "Converts various types of profile output into the PROFILE format,\n" << "which, in particular, associates source file line information from\n" << "<binary> with profile data from <profile>. In effect, the output is\n" << "a [source-line -> PC-profile-data] map represented as a XML scope\n" << "tree (e.g. file, procedure, statement). Output is sent to stdout.\n" << "\n" << "By default, xprof determines a set of metrics available for the\n" << "given profile data and includes all of them in the PROFILE output.\n" << "\n" #if 0 // FIXME '[-m <bloop-pcmap>]' << "If no <bloop-pcmap> -- a map extended with analysis information\n" << "from 'bloop' -- is provided, the program attempts to construct\n" << "the PROFILE by querying the <binary>'s debugging information.\n" << "Because of the better analysis ability of 'bloop', a <bloop-pcmap>\n" << "usually improves the accuracy of the PROFILE. Moreover, because\n" << "no loop recovery is performed, providing <bloop-pcmap> enables\n" << "the PROFILE to represent loop nesting information.\n" << "[*Not fully implemented.*]\n" << "\n" << " -m: specify <bloop-pcmap>\n" #endif << "The following <profile> formats are currently supported: \n" << " - DEC/Compaq/HP's DCPI 'dcpicat' (including ProfileMe) \n" << "\n" << "Listing available metrics:\n" << " -l List all derived metrics, in compact form, available from\n" << " <profile> and suppress generation of PROFILE output.\n" << " Note that this output can be used with the -M option.\n" << " -L List all derived metrics, in long form, available from\n" << " <profile> and suppress generation of PROFILE output.\n" << "\n" << "Normal Mode:\n" << " -V Print version information.\n" << " -M mlist Optional colon-separated metric inclusion list. Replaces\n" << " the default metric list. Metrics in PROFILE output will.\n" << " follow this ordering. Duplicates are allowed (though\n" << " not recommended).\n" << " -X xlist Optional colon-separated metric exclusion list. Excludes\n" << " the listed metrics from either the default metric list or\n" << " the list specified with -M.\n" << " -R (Most will not find this useful.) For some profile data,\n" << " such as DCPI's ProfileMe, the default is to output derived\n" << " metrics, not the underlying raw metrics; this option\n" << " forces output of only the raw metrics. Should not be\n" << " used with -M or -X.\n" << endl; } Args::Args(int argc, char* const* argv) { cmd = argv[0]; bool printVersion = false; listAvailableMetrics = 0; // 0: no, 1: short, 2: long outputRawMetrics = false; extern char *optarg; extern int optind; bool error = false; trace = 0; int c; while ((c = getopt(argc, argv, "Vm:lLM:X:Rd")) != EOF) { switch (c) { case 'V': { printVersion = true; break; } case 'm': { // A non-null value of 'pcMapFile' indicates it has been set if (optarg == NULL) { error = true; } pcMapFile = optarg; break; } case 'l': { listAvailableMetrics = 1; break; } case 'L': { listAvailableMetrics = 2; break; } case 'M': { if (optarg == NULL) { error = true; } metricList = optarg; break; } case 'X': { if (optarg == NULL) { error = true; } excludeMList = optarg; break; } case 'R': { outputRawMetrics = true; break; } case 'd': { // debug trace++; break; } case ':': case '?': { // error error = true; break; } } } error = error || (optind != argc-2); if (!error) { progFile = argv[optind]; profFile = argv[optind+1]; } // Sanity check: -M,-X and -R should not be used at the same time if ( (!metricList.Empty() || !excludeMList.Empty()) && outputRawMetrics) { cerr << "Error: -M or -X cannot be used with -R.\n"; error = true; } IFTRACE << "Args.cmd= " << cmd << endl; IFTRACE << "Args.progFile= " << progFile << endl; IFTRACE << "Args.profFile= " << profFile << endl; IFTRACE << "Args.pcMapFile= " << pcMapFile << endl; IFTRACE << "::trace " << ::trace << endl; if (printVersion) { Version(); exit(1); } if (error) { Usage(); exit(1); } } <commit_msg>Allow multiple -M and -X options.<commit_after>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** //************************* System Include Files **************************** #include <iostream> #include <unistd.h> // for 'getopt' //*************************** User Include Files **************************** #include "Args.h" #include <lib/support/String.h> #include <lib/support/Trace.h> //*************************** Forward Declarations ************************** using std::cerr; using std::endl; //*************************************************************************** const char* hpctoolsVerInfo= #include <include/HPCToolkitVersionInfo.h> void Args::Version() { cerr << cmd << ": " << hpctoolsVerInfo << endl; } void Args::Usage() { cerr << "Usage: " << endl << " " << cmd << " [-l | -L] <binary> <profile>\n" << " " << cmd << " [-V] [ [-M <mlist> -M...] [-X <xlist> -X...] [-R] ] <binary> <profile>\n" << endl; cerr << "Converts various types of profile output into the PROFILE format,\n" << "which, in particular, associates source file line information from\n" << "<binary> with profile data from <profile>. In effect, the output is\n" << "a [source-line -> PC-profile-data] map represented as a XML scope\n" << "tree (e.g. file, procedure, statement). Output is sent to stdout.\n" << "\n" << "By default, xprof determines a set of metrics available for the\n" << "given profile data and includes all of them in the PROFILE output.\n" << "\n" #if 0 // FIXME '[-m <bloop-pcmap>]' << "If no <bloop-pcmap> -- a map extended with analysis information\n" << "from 'bloop' -- is provided, the program attempts to construct\n" << "the PROFILE by querying the <binary>'s debugging information.\n" << "Because of the better analysis ability of 'bloop', a <bloop-pcmap>\n" << "usually improves the accuracy of the PROFILE. Moreover, because\n" << "no loop recovery is performed, providing <bloop-pcmap> enables\n" << "the PROFILE to represent loop nesting information.\n" << "[*Not fully implemented.*]\n" << "\n" << " -m: specify <bloop-pcmap>\n" #endif << "The following <profile> formats are currently supported: \n" << " - DEC/Compaq/HP's DCPI 'dcpicat' (including ProfileMe) \n" << "\n" << "Listing available metrics:\n" << " -l List all derived metrics, in compact form, available from\n" << " <profile> and suppress generation of PROFILE output.\n" << " Note that this output can be used with the -M option.\n" << " -L List all derived metrics, in long form, available from\n" << " <profile> and suppress generation of PROFILE output.\n" << "\n" << "Normal Mode:\n" << " -V Print version information.\n" << " -M mlist Optional colon-separated metric inclusion list. Replaces\n" << " the default metric list. Metrics in PROFILE output will.\n" << " follow this ordering. Duplicates are allowed (though\n" << " not recommended).\n" << " -X xlist Optional colon-separated metric exclusion list. Excludes\n" << " the listed metrics from either the default metric list or\n" << " the list specified with -M.\n" << " -R (Most will not find this useful.) For some profile data,\n" << " such as DCPI's ProfileMe, the default is to output derived\n" << " metrics, not the underlying raw metrics; this option\n" << " forces output of only the raw metrics. Should not be\n" << " used with -M or -X.\n" << endl; } Args::Args(int argc, char* const* argv) { cmd = argv[0]; bool printVersion = false; listAvailableMetrics = 0; // 0: no, 1: short, 2: long outputRawMetrics = false; extern char *optarg; extern int optind; bool error = false; trace = 0; int c; while ((c = getopt(argc, argv, "Vm:lLM:X:Rd")) != EOF) { switch (c) { case 'V': { printVersion = true; break; } case 'm': { // A non-null value of 'pcMapFile' indicates it has been set if (optarg == NULL) { error = true; } pcMapFile = optarg; break; } case 'l': { listAvailableMetrics = 1; break; } case 'L': { listAvailableMetrics = 2; break; } case 'M': { // may occur multiple times if (optarg == NULL) { error = true; } if (!metricList.Empty()) { metricList += ":"; } metricList += optarg; break; } case 'X': { // may occur multiple times if (optarg == NULL) { error = true; } if (!excludeMList.Empty()) { excludeMList += ":"; } excludeMList += optarg; break; } case 'R': { outputRawMetrics = true; break; } case 'd': { // debug trace++; break; } case ':': case '?': { // error error = true; break; } } } error = error || (optind != argc-2); if (!error) { progFile = argv[optind]; profFile = argv[optind+1]; } // Sanity check: -M,-X and -R should not be used at the same time if ( (!metricList.Empty() || !excludeMList.Empty()) && outputRawMetrics) { cerr << "Error: -M or -X cannot be used with -R.\n"; error = true; } IFTRACE << "Args.cmd= " << cmd << endl; IFTRACE << "Args.progFile= " << progFile << endl; IFTRACE << "Args.profFile= " << profFile << endl; IFTRACE << "Args.pcMapFile= " << pcMapFile << endl; IFTRACE << "::trace " << ::trace << endl; if (printVersion) { Version(); exit(1); } if (error) { Usage(); exit(1); } } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "bochs.h" #include <assert.h> #include "state_file.h" static char *divider = "========================================================================"; // Just for the iofunctions #define LOG_THIS this->log-> int Allocio=0; void iofunctions::flush(void) { if(logfd && magic == MAGIC_LOGNUM) { fflush(logfd); } } void iofunctions::init(void) { // iofunctions methods must not be called before this magic // number is set. magic=MAGIC_LOGNUM; showtick = 1; n_logfn = 0; init_log(stderr); log = new logfunc_t(this); LOG_THIS put("IO"); LOG_THIS settype(IOLOG); BX_DEBUG(("Init(log file: '%s').",logfn)); } void iofunctions::add_logfn (logfunc_t *fn) { assert (n_logfn < MAX_LOGFNS); logfn_list[n_logfn++] = fn; } void iofunctions::set_log_action (int loglevel, int action) { for (int i=0; i<n_logfn; i++) logfn_list[i]->setonoff(loglevel, action); } void iofunctions::init_log(char *fn) { assert (magic==MAGIC_LOGNUM); // use newfd/newfn so that we can log the message to the OLD log // file descriptor. FILE *newfd = stderr; char *newfn = "/dev/stderr"; if( strcmp( fn, "-" ) != 0 ) { newfd = fopen(fn, "w"); if(newfd != NULL) { newfn = strdup(fn); BX_DEBUG(("Opened log file '%s'.", fn )); } else { BX_PANIC(("Couldn't open log file: %s", fn)); } } logfd = newfd; logfn = newfn; } void iofunctions::init_log(FILE *fs) { assert (magic==MAGIC_LOGNUM); logfd = fs; if(fs == stderr) { logfn = "/dev/stderr"; } else if(fs == stdout) { logfn = "/dev/stdout"; } else { logfn = "(unknown)"; } } void iofunctions::init_log(int fd) { assert (magic==MAGIC_LOGNUM); FILE *tmpfd; if( (tmpfd = fdopen(fd,"w")) == NULL ) { BX_PANIC(("Couldn't open fd %d as a stream for writing", fd)); return; } init_log(tmpfd); return; }; // iofunctions::out( class, level, prefix, fmt, ap) // DO NOT nest out() from ::info() and the like. // fmt and ap retained for direct printinf from iofunctions only! void iofunctions::out(int f, int l, char *prefix, char *fmt, va_list ap) { char c=' '; assert (magic==MAGIC_LOGNUM); assert (this != NULL); assert (logfd != NULL); if( showtick ) fprintf(logfd, "%011lld", bx_pc_system.time_ticks()); switch(l) { case LOGLEV_INFO: c='i'; break; case LOGLEV_PANIC: c='p'; break; case LOGLEV_ERROR: c='e'; break; case LOGLEV_DEBUG: c='d'; break; default: break; } fprintf(logfd, "%c",c); if(prefix != NULL) fprintf(logfd, "%s ", prefix); if(l==LOGLEV_PANIC) fprintf(logfd, ">>PANIC<< "); vfprintf(logfd, fmt, ap); fprintf(logfd, "\n"); fflush(logfd); return; } iofunctions::iofunctions(FILE *fs) { init(); init_log(fs); } iofunctions::iofunctions(char *fn) { init(); init_log(fn); } iofunctions::iofunctions(int fd) { init(); init_log(fd); } iofunctions::iofunctions(void) { this->init(); } iofunctions::~iofunctions(void) { // flush before erasing magic number, or flush does nothing. this->flush(); this->magic=0; } #undef LOG_THIS #define LOG_THIS genlog-> logfunctions::logfunctions(void) { put(" "); settype(GENLOG); if(io == NULL && Allocio == 0) { Allocio = 1; io = new iofunc_t(stderr); } setio(io); // BUG: unfortunately this can be called before the bochsrc is read, // which means that the bochsrc has no effect on the actions. for (int i=0; i<N_LOGLEV; i++) onoff[i] = bx_options.log.actions[i]; } logfunctions::logfunctions(iofunc_t *iofunc) { put(" "); settype(GENLOG); setio(iofunc); // BUG: unfortunately this can be called before the bochsrc is read, // which means that the bochsrc has no effect on the actions. for (int i=0; i<N_LOGLEV; i++) onoff[i] = bx_options.log.actions[i]; } logfunctions::~logfunctions(void) { } void logfunctions::setio(iofunc_t *i) { // add pointer to iofunction object to use this->logio = i; // give iofunction a pointer to me i->add_logfn (this); } void logfunctions::put(char *p) { char *tmpbuf; tmpbuf=strdup("[ ]");// if we ever have more than 32 chars, // we need to rethink this int len=strlen(p); for(int i=1;i<len+1;i++) { tmpbuf[i]=p[i-1]; } switch(len) { case 1: tmpbuf[2]=' '; case 2: tmpbuf[3]=' '; case 3: tmpbuf[4]=' '; case 4: tmpbuf[5]=' '; default: tmpbuf[6]=']'; tmpbuf[7]='\0'; break; } this->prefix=tmpbuf; } void logfunctions::settype(int t) { type=t; } void logfunctions::info(char *fmt, ...) { va_list ap; assert (this != NULL); assert (this->logio != NULL); if(!onoff[LOGLEV_INFO]) return; va_start(ap, fmt); this->logio->out(this->type,LOGLEV_INFO,this->prefix, fmt, ap); if (onoff[LOGLEV_INFO] == ACT_ASK) ask (LOGLEV_INFO, this->prefix, fmt, ap); if (onoff[LOGLEV_INFO] == ACT_FATAL) fatal (this->prefix, fmt, ap); va_end(ap); } void logfunctions::error(char *fmt, ...) { va_list ap; assert (this != NULL); assert (this->logio != NULL); if(!onoff[LOGLEV_ERROR]) return; va_start(ap, fmt); this->logio->out(this->type,LOGLEV_ERROR,this->prefix, fmt, ap); if (onoff[LOGLEV_ERROR] == ACT_ASK) ask (LOGLEV_ERROR, this->prefix, fmt, ap); if (onoff[LOGLEV_ERROR] == ACT_FATAL) fatal (this->prefix, fmt, ap); va_end(ap); } void logfunctions::panic(char *fmt, ...) { va_list ap; assert (this != NULL); assert (this->logio != NULL); if(!onoff[LOGLEV_PANIC]) return; va_start(ap, fmt); this->logio->out(this->type,LOGLEV_PANIC,this->prefix, fmt, ap); if (onoff[LOGLEV_PANIC] == ACT_ASK) ask (LOGLEV_PANIC, this->prefix, fmt, ap); if (onoff[LOGLEV_PANIC] == ACT_FATAL) fatal (this->prefix, fmt, ap); va_end(ap); } void logfunctions::ldebug(char *fmt, ...) { va_list ap; assert (this != NULL); assert (this->logio != NULL); if(!onoff[LOGLEV_DEBUG]) return; va_start(ap, fmt); this->logio->out(this->type,LOGLEV_DEBUG,this->prefix, fmt, ap); if (onoff[LOGLEV_DEBUG] == ACT_ASK) ask (LOGLEV_DEBUG, this->prefix, fmt, ap); if (onoff[LOGLEV_DEBUG] == ACT_FATAL) fatal (this->prefix, fmt, ap); va_end(ap); } void logfunctions::ask (int level, char *prefix, char *fmt, va_list ap) { char buf1[1024], buf2[1024]; vsprintf (buf1, fmt, ap); sprintf (buf2, "%s %s", prefix, buf1); // FIXME: facility set to 0 because it's unknown. int val = SIM->LOCAL_log_msg (prefix, level, buf2); switch (val) { case 0: // user chose continue break; case 1: // user said continue, and don't ask for this facility again. setonoff (level, ACT_REPORT); break; case 2: // user chose die fatal (prefix, fmt, ap); #if BX_DEBUGGER case 3: // user chose debugger. To "drop into the debugger" we just set the // interrupt_requested bit and continue execution. Before the next // instruction, it should notice the user interrupt and return to // the debugger. bx_guard.interrupt_requested = 1; break; #endif default: fprintf (stderr, "WARNING: LOCAL_log_msg returned unexpected value %d\n", val); } } void logfunctions::fatal (char *prefix, char *fmt, va_list ap) { static int fatal_reentry = 0; if (fatal_reentry) return; fatal_reentry++; bx_atexit(); fprintf (stderr, "%s\n", divider); fprintf (stderr, "Bochs is exiting with the following message:\n"); fprintf (stderr, "%s ", prefix); vfprintf (stderr, fmt, ap); fprintf (stderr, "\n%s\n", divider); #if 0 && defined(WIN32) #error disabled because it is not working yet! // wait for a keypress before quitting. Depending on how bochs is // installed, the console window can disappear before the user has // a chance to read the final message. fprintf (stderr, "\n\nPress Enter to exit...\n"); char buf[8]; fgets (buf, 8, stdin); #endif #if !BX_DEBUGGER exit(1); #else static Boolean dbg_exit_called = 0; if (dbg_exit_called == 0) { dbg_exit_called = 1; bx_dbg_exit(1); } #endif fatal_reentry--; } iofunc_t *io = NULL; logfunc_t *genlog = NULL; void bx_center_print (FILE *file, char *line, int maxwidth) { int imax; imax = (maxwidth - strlen(line)) >> 1; for (int i=0; i<imax; i++) fputc (' ', file); fputs (line, file); } <commit_msg>- bend the rules slightly so that panics get printed all the time, even if the user tried to set action=ignore.<commit_after>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "bochs.h" #include <assert.h> #include "state_file.h" static char *divider = "========================================================================"; // Just for the iofunctions #define LOG_THIS this->log-> int Allocio=0; void iofunctions::flush(void) { if(logfd && magic == MAGIC_LOGNUM) { fflush(logfd); } } void iofunctions::init(void) { // iofunctions methods must not be called before this magic // number is set. magic=MAGIC_LOGNUM; showtick = 1; n_logfn = 0; init_log(stderr); log = new logfunc_t(this); LOG_THIS put("IO"); LOG_THIS settype(IOLOG); BX_DEBUG(("Init(log file: '%s').",logfn)); } void iofunctions::add_logfn (logfunc_t *fn) { assert (n_logfn < MAX_LOGFNS); logfn_list[n_logfn++] = fn; } void iofunctions::set_log_action (int loglevel, int action) { for (int i=0; i<n_logfn; i++) logfn_list[i]->setonoff(loglevel, action); } void iofunctions::init_log(char *fn) { assert (magic==MAGIC_LOGNUM); // use newfd/newfn so that we can log the message to the OLD log // file descriptor. FILE *newfd = stderr; char *newfn = "/dev/stderr"; if( strcmp( fn, "-" ) != 0 ) { newfd = fopen(fn, "w"); if(newfd != NULL) { newfn = strdup(fn); BX_DEBUG(("Opened log file '%s'.", fn )); } else { BX_PANIC(("Couldn't open log file: %s", fn)); } } logfd = newfd; logfn = newfn; } void iofunctions::init_log(FILE *fs) { assert (magic==MAGIC_LOGNUM); logfd = fs; if(fs == stderr) { logfn = "/dev/stderr"; } else if(fs == stdout) { logfn = "/dev/stdout"; } else { logfn = "(unknown)"; } } void iofunctions::init_log(int fd) { assert (magic==MAGIC_LOGNUM); FILE *tmpfd; if( (tmpfd = fdopen(fd,"w")) == NULL ) { BX_PANIC(("Couldn't open fd %d as a stream for writing", fd)); return; } init_log(tmpfd); return; }; // iofunctions::out( class, level, prefix, fmt, ap) // DO NOT nest out() from ::info() and the like. // fmt and ap retained for direct printinf from iofunctions only! void iofunctions::out(int f, int l, char *prefix, char *fmt, va_list ap) { char c=' '; assert (magic==MAGIC_LOGNUM); assert (this != NULL); assert (logfd != NULL); if( showtick ) fprintf(logfd, "%011lld", bx_pc_system.time_ticks()); switch(l) { case LOGLEV_INFO: c='i'; break; case LOGLEV_PANIC: c='p'; break; case LOGLEV_ERROR: c='e'; break; case LOGLEV_DEBUG: c='d'; break; default: break; } fprintf(logfd, "%c",c); if(prefix != NULL) fprintf(logfd, "%s ", prefix); if(l==LOGLEV_PANIC) fprintf(logfd, ">>PANIC<< "); vfprintf(logfd, fmt, ap); fprintf(logfd, "\n"); fflush(logfd); return; } iofunctions::iofunctions(FILE *fs) { init(); init_log(fs); } iofunctions::iofunctions(char *fn) { init(); init_log(fn); } iofunctions::iofunctions(int fd) { init(); init_log(fd); } iofunctions::iofunctions(void) { this->init(); } iofunctions::~iofunctions(void) { // flush before erasing magic number, or flush does nothing. this->flush(); this->magic=0; } #undef LOG_THIS #define LOG_THIS genlog-> logfunctions::logfunctions(void) { put(" "); settype(GENLOG); if(io == NULL && Allocio == 0) { Allocio = 1; io = new iofunc_t(stderr); } setio(io); // BUG: unfortunately this can be called before the bochsrc is read, // which means that the bochsrc has no effect on the actions. for (int i=0; i<N_LOGLEV; i++) onoff[i] = bx_options.log.actions[i]; } logfunctions::logfunctions(iofunc_t *iofunc) { put(" "); settype(GENLOG); setio(iofunc); // BUG: unfortunately this can be called before the bochsrc is read, // which means that the bochsrc has no effect on the actions. for (int i=0; i<N_LOGLEV; i++) onoff[i] = bx_options.log.actions[i]; } logfunctions::~logfunctions(void) { } void logfunctions::setio(iofunc_t *i) { // add pointer to iofunction object to use this->logio = i; // give iofunction a pointer to me i->add_logfn (this); } void logfunctions::put(char *p) { char *tmpbuf; tmpbuf=strdup("[ ]");// if we ever have more than 32 chars, // we need to rethink this int len=strlen(p); for(int i=1;i<len+1;i++) { tmpbuf[i]=p[i-1]; } switch(len) { case 1: tmpbuf[2]=' '; case 2: tmpbuf[3]=' '; case 3: tmpbuf[4]=' '; case 4: tmpbuf[5]=' '; default: tmpbuf[6]=']'; tmpbuf[7]='\0'; break; } this->prefix=tmpbuf; } void logfunctions::settype(int t) { type=t; } void logfunctions::info(char *fmt, ...) { va_list ap; assert (this != NULL); assert (this->logio != NULL); if(!onoff[LOGLEV_INFO]) return; va_start(ap, fmt); this->logio->out(this->type,LOGLEV_INFO,this->prefix, fmt, ap); if (onoff[LOGLEV_INFO] == ACT_ASK) ask (LOGLEV_INFO, this->prefix, fmt, ap); if (onoff[LOGLEV_INFO] == ACT_FATAL) fatal (this->prefix, fmt, ap); va_end(ap); } void logfunctions::error(char *fmt, ...) { va_list ap; assert (this != NULL); assert (this->logio != NULL); if(!onoff[LOGLEV_ERROR]) return; va_start(ap, fmt); this->logio->out(this->type,LOGLEV_ERROR,this->prefix, fmt, ap); if (onoff[LOGLEV_ERROR] == ACT_ASK) ask (LOGLEV_ERROR, this->prefix, fmt, ap); if (onoff[LOGLEV_ERROR] == ACT_FATAL) fatal (this->prefix, fmt, ap); va_end(ap); } void logfunctions::panic(char *fmt, ...) { va_list ap; assert (this != NULL); assert (this->logio != NULL); // Special case for panics since they are so important. Always print // the panic to the log, no matter what the log action says. //if(!onoff[LOGLEV_PANIC]) return; va_start(ap, fmt); this->logio->out(this->type,LOGLEV_PANIC,this->prefix, fmt, ap); if (onoff[LOGLEV_PANIC] == ACT_ASK) ask (LOGLEV_PANIC, this->prefix, fmt, ap); if (onoff[LOGLEV_PANIC] == ACT_FATAL) fatal (this->prefix, fmt, ap); va_end(ap); } void logfunctions::ldebug(char *fmt, ...) { va_list ap; assert (this != NULL); assert (this->logio != NULL); if(!onoff[LOGLEV_DEBUG]) return; va_start(ap, fmt); this->logio->out(this->type,LOGLEV_DEBUG,this->prefix, fmt, ap); if (onoff[LOGLEV_DEBUG] == ACT_ASK) ask (LOGLEV_DEBUG, this->prefix, fmt, ap); if (onoff[LOGLEV_DEBUG] == ACT_FATAL) fatal (this->prefix, fmt, ap); va_end(ap); } void logfunctions::ask (int level, char *prefix, char *fmt, va_list ap) { char buf1[1024], buf2[1024]; vsprintf (buf1, fmt, ap); sprintf (buf2, "%s %s", prefix, buf1); // FIXME: facility set to 0 because it's unknown. int val = SIM->LOCAL_log_msg (prefix, level, buf2); switch (val) { case 0: // user chose continue break; case 1: // user said continue, and don't ask for this facility again. setonoff (level, ACT_REPORT); break; case 2: // user chose die fatal (prefix, fmt, ap); #if BX_DEBUGGER case 3: // user chose debugger. To "drop into the debugger" we just set the // interrupt_requested bit and continue execution. Before the next // instruction, it should notice the user interrupt and return to // the debugger. bx_guard.interrupt_requested = 1; break; #endif default: fprintf (stderr, "WARNING: LOCAL_log_msg returned unexpected value %d\n", val); } } void logfunctions::fatal (char *prefix, char *fmt, va_list ap) { static int fatal_reentry = 0; if (fatal_reentry) return; fatal_reentry++; bx_atexit(); fprintf (stderr, "%s\n", divider); fprintf (stderr, "Bochs is exiting with the following message:\n"); fprintf (stderr, "%s ", prefix); vfprintf (stderr, fmt, ap); fprintf (stderr, "\n%s\n", divider); #if 0 && defined(WIN32) #error disabled because it is not working yet! // wait for a keypress before quitting. Depending on how bochs is // installed, the console window can disappear before the user has // a chance to read the final message. fprintf (stderr, "\n\nPress Enter to exit...\n"); char buf[8]; fgets (buf, 8, stdin); #endif #if !BX_DEBUGGER exit(1); #else static Boolean dbg_exit_called = 0; if (dbg_exit_called == 0) { dbg_exit_called = 1; bx_dbg_exit(1); } #endif fatal_reentry--; } iofunc_t *io = NULL; logfunc_t *genlog = NULL; void bx_center_print (FILE *file, char *line, int maxwidth) { int imax; imax = (maxwidth - strlen(line)) >> 1; for (int i=0; i<imax; i++) fputc (' ', file); fputs (line, file); } <|endoftext|>
<commit_before>/* * VerifyNoOtherInvocationsVerificationProgress.hpp * Copyright (c) 2014 Eran Pe'er. * * This program is made available under the terms of the MIT License. * * Created on Jul 21, 2014 */ #ifndef VerifyNoOtherInvocationsVerificationProgress_hpp_ #define VerifyNoOtherInvocationsVerificationProgress_hpp_ #include "fakeit/FakeitContext.hpp" namespace fakeit { class VerifyNoOtherInvocationsVerificationProgress { friend class VerifyNoOtherInvocationsFunctor; struct VerifyNoOtherInvocationsExpectation { friend class VerifyNoOtherInvocationsVerificationProgress; ~VerifyNoOtherInvocationsExpectation() THROWS { if (std::uncaught_exception()) { return; } VerifyExpectation(); } void setFileInfo(std::string file, int line, std::string callingMethod) { _file = file; _line = line; _callingMethod = callingMethod; } private: FakeitContext& _fakeit; std::set<ActualInvocationsSource*> _mocks; std::string _file; int _line; std::string _callingMethod; VerifyNoOtherInvocationsExpectation(FakeitContext& fakeit, std::set<ActualInvocationsSource*> mocks) : _fakeit(fakeit), _mocks(mocks), _line(0) { } VerifyNoOtherInvocationsExpectation(VerifyNoOtherInvocationsExpectation& other) = default; void VerifyExpectation() { std::unordered_set<Invocation*> actualInvocations; InvocationUtils::collectActualInvocations(actualInvocations, _mocks); std::unordered_set<Invocation*> nonVerifedIvocations; InvocationUtils::selectNonVerifiedInvocations(actualInvocations, nonVerifedIvocations); if (nonVerifedIvocations.size() > 0) { std::vector<Invocation*> sortedNonVerifedIvocations; InvocationUtils::sortByInvocationOrder(nonVerifedIvocations, sortedNonVerifedIvocations); std::vector<Invocation*> sortedActualIvocations; InvocationUtils::sortByInvocationOrder(actualInvocations, sortedActualIvocations); NoMoreInvocationsVerificationEvent evt(sortedActualIvocations, sortedNonVerifedIvocations); evt.setFileInfo(_file, _line, _callingMethod); _fakeit.handle(evt); } } }; fakeit::smart_ptr<VerifyNoOtherInvocationsExpectation> _ptr; VerifyNoOtherInvocationsVerificationProgress(VerifyNoOtherInvocationsExpectation * ptr) : _ptr(ptr) { } VerifyNoOtherInvocationsVerificationProgress(FakeitContext& fakeit, std::set<ActualInvocationsSource*>& invocationSources) : VerifyNoOtherInvocationsVerificationProgress( new VerifyNoOtherInvocationsExpectation(fakeit, invocationSources) ) { } public: ~VerifyNoOtherInvocationsVerificationProgress() THROWS { }; VerifyNoOtherInvocationsVerificationProgress setFileInfo(std::string file, int line, std::string callingMethod) { _ptr->setFileInfo(file, line, callingMethod); return *this; } }; } #endif <commit_msg>Make VerifyNoOtherInvocations conviertible to bool<commit_after>/* * VerifyNoOtherInvocationsVerificationProgress.hpp * Copyright (c) 2014 Eran Pe'er. * * This program is made available under the terms of the MIT License. * * Created on Jul 21, 2014 */ #ifndef VerifyNoOtherInvocationsVerificationProgress_hpp_ #define VerifyNoOtherInvocationsVerificationProgress_hpp_ #include "fakeit/FakeitContext.hpp" namespace fakeit { class VerifyNoOtherInvocationsVerificationProgress { friend class VerifyNoOtherInvocationsFunctor; struct VerifyNoOtherInvocationsExpectation { friend class VerifyNoOtherInvocationsVerificationProgress; ~VerifyNoOtherInvocationsExpectation() THROWS { if (std::uncaught_exception()) { return; } VerifyExpectation(); } void setFileInfo(std::string file, int line, std::string callingMethod) { _file = file; _line = line; _callingMethod = callingMethod; } private: FakeitContext& _fakeit; std::set<ActualInvocationsSource*> _mocks; std::string _file; int _line; std::string _callingMethod; bool _isVerified; VerifyNoOtherInvocationsExpectation(FakeitContext& fakeit, std::set<ActualInvocationsSource*> mocks) : _fakeit(fakeit), _mocks(mocks), _line(0), _isVerified(false){ } VerifyNoOtherInvocationsExpectation(VerifyNoOtherInvocationsExpectation& other) = default; void VerifyExpectation() { if (_isVerified) return; _isVerified = true; std::unordered_set<Invocation*> actualInvocations; InvocationUtils::collectActualInvocations(actualInvocations, _mocks); std::unordered_set<Invocation*> nonVerifedIvocations; InvocationUtils::selectNonVerifiedInvocations(actualInvocations, nonVerifedIvocations); if (nonVerifedIvocations.size() > 0) { std::vector<Invocation*> sortedNonVerifedIvocations; InvocationUtils::sortByInvocationOrder(nonVerifedIvocations, sortedNonVerifedIvocations); std::vector<Invocation*> sortedActualIvocations; InvocationUtils::sortByInvocationOrder(actualInvocations, sortedActualIvocations); NoMoreInvocationsVerificationEvent evt(sortedActualIvocations, sortedNonVerifedIvocations); evt.setFileInfo(_file, _line, _callingMethod); _fakeit.handle(evt); } } }; fakeit::smart_ptr<VerifyNoOtherInvocationsExpectation> _ptr; VerifyNoOtherInvocationsVerificationProgress(VerifyNoOtherInvocationsExpectation * ptr) : _ptr(ptr) { } VerifyNoOtherInvocationsVerificationProgress(FakeitContext& fakeit, std::set<ActualInvocationsSource*>& invocationSources) : VerifyNoOtherInvocationsVerificationProgress( new VerifyNoOtherInvocationsExpectation(fakeit, invocationSources) ) { } bool toBool() { try{ _ptr->VerifyExpectation(); return true; } catch (...){ return false; } } public: ~VerifyNoOtherInvocationsVerificationProgress() THROWS { }; VerifyNoOtherInvocationsVerificationProgress setFileInfo(std::string file, int line, std::string callingMethod) { _ptr->setFileInfo(file, line, callingMethod); return *this; } operator bool() { return toBool(); } bool operator ! () const { return !const_cast<VerifyNoOtherInvocationsVerificationProgress*>(this)->toBool(); } }; } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2001-2004 The Regents of The University of Michigan * 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 the copyright holders 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. */ #ifndef __PROCESS_HH__ #define __PROCESS_HH__ // // The purpose of this code is to fake the loader & syscall mechanism // when there's no OS: thus there's no reason to use it in FULL_SYSTEM // mode when we do have an OS. // #ifndef FULL_SYSTEM #include <vector> #include "targetarch/isa_traits.hh" #include "sim/sim_object.hh" #include "sim/stats.hh" #include "base/statistics.hh" #include "base/trace.hh" class ExecContext; class FunctionalMemory; class Process : public SimObject { public: // have we initialized an execution context from this process? If // yes, subsequent contexts are assumed to be for dynamically // created threads and are not initialized. bool initialContextLoaded; // execution contexts associated with this process std::vector<ExecContext *> execContexts; // number of CPUs (esxec contexts, really) assigned to this process. unsigned int numCpus() { return execContexts.size(); } // record of blocked context struct WaitRec { Addr waitChan; ExecContext *waitingContext; WaitRec(Addr chan, ExecContext *ctx) : waitChan(chan), waitingContext(ctx) { } }; // list of all blocked contexts std::list<WaitRec> waitList; RegFile *init_regs; // initial register contents Addr text_base; // text (code) segment base unsigned text_size; // text (code) size in bytes Addr data_base; // initialized data segment base unsigned data_size; // initialized data + bss size in bytes Addr brk_point; // top of the data segment Addr stack_base; // stack segment base (highest address) unsigned stack_size; // initial stack size Addr stack_min; // lowest address accessed on the stack // addr to use for next stack region (for multithreaded apps) Addr next_thread_stack_base; // Base of region for mmaps (when user doesn't specify an address). Addr mmap_start; Addr mmap_end; // Base of region for nxm data Addr nxm_start; Addr nxm_end; std::string prog_fname; // file name Addr prog_entry; // entry point (initial PC) Stats::Scalar<> num_syscalls; // number of syscalls executed protected: // constructor Process(const std::string &nm, int stdin_fd, // initial I/O descriptors int stdout_fd, int stderr_fd); // post initialization startup virtual void startup(); protected: FunctionalMemory *memory; private: // file descriptor remapping support static const int MAX_FD = 100; // max legal fd value int fd_map[MAX_FD+1]; public: // static helper functions to generate file descriptors for constructor static int openInputFile(const std::string &filename); static int openOutputFile(const std::string &filename); // override of virtual SimObject method: register statistics virtual void regStats(); // register an execution context for this process. // returns xc's cpu number (index into execContexts[]) int registerExecContext(ExecContext *xc); void replaceExecContext(ExecContext *xc, int xcIndex); // map simulator fd sim_fd to target fd tgt_fd void dup_fd(int sim_fd, int tgt_fd); // generate new target fd for sim_fd int open_fd(int sim_fd); // look up simulator fd for given target fd int sim_fd(int tgt_fd); // is this a valid instruction fetch address? bool validInstAddr(Addr addr) { return (text_base <= addr && addr < text_base + text_size && !(addr & (sizeof(MachInst)-1))); } // is this a valid address? (used to filter data fetches) // note that we just assume stack size <= 16MB // this may be alpha-specific bool validDataAddr(Addr addr) { return ((data_base <= addr && addr < brk_point) || #ifdef FULLSYSTEM ((stack_base - 16*1024*1024) <= addr && addr < stack_base) || #else (next_thread_stack_base <= addr && addr < stack_base) || #endif (text_base <= addr && addr < (text_base + text_size)) || (mmap_start <= addr && addr < mmap_end) || (nxm_start <= addr && addr < nxm_end)); } virtual void syscall(ExecContext *xc) = 0; virtual FunctionalMemory *getMemory() { return memory; } }; // // "Live" process with system calls redirected to host system // class ObjectFile; class LiveProcess : public Process { protected: LiveProcess(const std::string &nm, ObjectFile *objFile, int stdin_fd, int stdout_fd, int stderr_fd, std::vector<std::string> &argv, std::vector<std::string> &envp); public: // this function is used to create the LiveProcess object, since // we can't tell which subclass of LiveProcess to use until we // open and look at the object file. static LiveProcess *create(const std::string &nm, int stdin_fd, int stdout_fd, int stderr_fd, std::vector<std::string> &argv, std::vector<std::string> &envp); }; #endif // !FULL_SYSTEM #endif // __PROCESS_HH__ <commit_msg>No need for this ifdef, since the entire process.hh is surounded by an ifndef FULL_SYSTEM<commit_after>/* * Copyright (c) 2001-2004 The Regents of The University of Michigan * 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 the copyright holders 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. */ #ifndef __PROCESS_HH__ #define __PROCESS_HH__ // // The purpose of this code is to fake the loader & syscall mechanism // when there's no OS: thus there's no reason to use it in FULL_SYSTEM // mode when we do have an OS. // #ifndef FULL_SYSTEM #include <vector> #include "targetarch/isa_traits.hh" #include "sim/sim_object.hh" #include "sim/stats.hh" #include "base/statistics.hh" #include "base/trace.hh" class ExecContext; class FunctionalMemory; class Process : public SimObject { public: // have we initialized an execution context from this process? If // yes, subsequent contexts are assumed to be for dynamically // created threads and are not initialized. bool initialContextLoaded; // execution contexts associated with this process std::vector<ExecContext *> execContexts; // number of CPUs (esxec contexts, really) assigned to this process. unsigned int numCpus() { return execContexts.size(); } // record of blocked context struct WaitRec { Addr waitChan; ExecContext *waitingContext; WaitRec(Addr chan, ExecContext *ctx) : waitChan(chan), waitingContext(ctx) { } }; // list of all blocked contexts std::list<WaitRec> waitList; RegFile *init_regs; // initial register contents Addr text_base; // text (code) segment base unsigned text_size; // text (code) size in bytes Addr data_base; // initialized data segment base unsigned data_size; // initialized data + bss size in bytes Addr brk_point; // top of the data segment Addr stack_base; // stack segment base (highest address) unsigned stack_size; // initial stack size Addr stack_min; // lowest address accessed on the stack // addr to use for next stack region (for multithreaded apps) Addr next_thread_stack_base; // Base of region for mmaps (when user doesn't specify an address). Addr mmap_start; Addr mmap_end; // Base of region for nxm data Addr nxm_start; Addr nxm_end; std::string prog_fname; // file name Addr prog_entry; // entry point (initial PC) Stats::Scalar<> num_syscalls; // number of syscalls executed protected: // constructor Process(const std::string &nm, int stdin_fd, // initial I/O descriptors int stdout_fd, int stderr_fd); // post initialization startup virtual void startup(); protected: FunctionalMemory *memory; private: // file descriptor remapping support static const int MAX_FD = 100; // max legal fd value int fd_map[MAX_FD+1]; public: // static helper functions to generate file descriptors for constructor static int openInputFile(const std::string &filename); static int openOutputFile(const std::string &filename); // override of virtual SimObject method: register statistics virtual void regStats(); // register an execution context for this process. // returns xc's cpu number (index into execContexts[]) int registerExecContext(ExecContext *xc); void replaceExecContext(ExecContext *xc, int xcIndex); // map simulator fd sim_fd to target fd tgt_fd void dup_fd(int sim_fd, int tgt_fd); // generate new target fd for sim_fd int open_fd(int sim_fd); // look up simulator fd for given target fd int sim_fd(int tgt_fd); // is this a valid instruction fetch address? bool validInstAddr(Addr addr) { return (text_base <= addr && addr < text_base + text_size && !(addr & (sizeof(MachInst)-1))); } // is this a valid address? (used to filter data fetches) // note that we just assume stack size <= 16MB // this may be alpha-specific bool validDataAddr(Addr addr) { return ((data_base <= addr && addr < brk_point) || (next_thread_stack_base <= addr && addr < stack_base) || (text_base <= addr && addr < (text_base + text_size)) || (mmap_start <= addr && addr < mmap_end) || (nxm_start <= addr && addr < nxm_end)); } virtual void syscall(ExecContext *xc) = 0; virtual FunctionalMemory *getMemory() { return memory; } }; // // "Live" process with system calls redirected to host system // class ObjectFile; class LiveProcess : public Process { protected: LiveProcess(const std::string &nm, ObjectFile *objFile, int stdin_fd, int stdout_fd, int stderr_fd, std::vector<std::string> &argv, std::vector<std::string> &envp); public: // this function is used to create the LiveProcess object, since // we can't tell which subclass of LiveProcess to use until we // open and look at the object file. static LiveProcess *create(const std::string &nm, int stdin_fd, int stdout_fd, int stderr_fd, std::vector<std::string> &argv, std::vector<std::string> &envp); }; #endif // !FULL_SYSTEM #endif // __PROCESS_HH__ <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <fstream> // template <class charT, class traits = char_traits<charT> > // class basic_fstream // explicit basic_fstream(const string& s, ios_base::openmode mode = ios_base::in|ios_base::out); #include <fstream> #include <cassert> int main() { { std::fstream fs(std::string("test.dat"), std::ios_base::in | std::ios_base::out | std::ios_base::trunc); double x = 0; fs << 3.25; fs.seekg(0); fs >> x; assert(x == 3.25); } std::remove("test.dat"); { std::wfstream fs(std::string("test.dat"), std::ios_base::in | std::ios_base::out | std::ios_base::trunc); double x = 0; fs << 3.25; fs.seekg(0); fs >> x; assert(x == 3.25); } std::remove("test.dat"); } <commit_msg>Do a litmus test of using tmpnam to generate safe temporary file names for the tests that open new data files.<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <fstream> // template <class charT, class traits = char_traits<charT> > // class basic_fstream // explicit basic_fstream(const string& s, ios_base::openmode mode = ios_base::in|ios_base::out); #include <fstream> #include <cassert> int main() { char temp [L_tmpnam]; tmpnam(temp); { std::fstream fs(std::string(temp), std::ios_base::in | std::ios_base::out | std::ios_base::trunc); double x = 0; fs << 3.25; fs.seekg(0); fs >> x; assert(x == 3.25); } std::remove(temp); { std::wfstream fs(std::string(temp), std::ios_base::in | std::ios_base::out | std::ios_base::trunc); double x = 0; fs << 3.25; fs.seekg(0); fs >> x; assert(x == 3.25); } std::remove(temp); } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Elisavet Sakellari <elisavet.sakellari@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "ExternalInterpreterSource.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Utils/Diagnostics.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/ASTImporter.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Sema.h" using namespace clang; namespace { class ClingASTImporter : public ASTImporter { private: cling::ExternalInterpreterSource &m_Source; public: ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager, ASTContext &FromContext, FileManager &FromFileManager, bool MinimalImport, cling::ExternalInterpreterSource& source): ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager, MinimalImport), m_Source(source) {} virtual ~ClingASTImporter() = default; void Imported(Decl *From, Decl *To) override { ASTImporter::Imported(From, To); if (clang::TagDecl* toTagDecl = dyn_cast<TagDecl>(To)) { toTagDecl->setHasExternalLexicalStorage(); toTagDecl->setMustBuildLookupTable(); toTagDecl->setHasExternalVisibleStorage(); } if (NamespaceDecl *toNamespaceDecl = dyn_cast<NamespaceDecl>(To)) { toNamespaceDecl->setHasExternalVisibleStorage(); } if (ObjCContainerDecl *toContainerDecl = dyn_cast<ObjCContainerDecl>(To)) { toContainerDecl->setHasExternalLexicalStorage(); toContainerDecl->setHasExternalVisibleStorage(); } // Put the name of the Decl imported with the // DeclarationName coming from the parent, in my map. if (NamedDecl *toNamedDecl = llvm::dyn_cast<NamedDecl>(To)) { NamedDecl *fromNamedDecl = llvm::dyn_cast<NamedDecl>(From); m_Source.addToImportedDecls(toNamedDecl->getDeclName(), fromNamedDecl->getDeclName()); } if (DeclContext *toDeclContext = llvm::dyn_cast<DeclContext>(To)) { DeclContext *fromDeclContext = llvm::dyn_cast<DeclContext>(From); m_Source.addToImportedDeclContexts(toDeclContext, fromDeclContext); } } }; } namespace cling { ExternalInterpreterSource::ExternalInterpreterSource( const cling::Interpreter *parent, cling::Interpreter *child) : m_ParentInterpreter(parent), m_ChildInterpreter(child) { clang::DeclContext *parentTUDeclContext = m_ParentInterpreter->getCI()->getASTContext().getTranslationUnitDecl(); clang::DeclContext *childTUDeclContext = m_ChildInterpreter->getCI()->getASTContext().getTranslationUnitDecl(); // Also keep in the map of Decl Contexts the Translation Unit Decl Context m_ImportedDeclContexts[childTUDeclContext] = parentTUDeclContext; FileManager &childFM = m_ChildInterpreter->getCI()->getFileManager(); FileManager &parentFM = m_ParentInterpreter->getCI()->getFileManager(); ASTContext &fromASTContext = m_ParentInterpreter->getCI()->getASTContext(); ASTContext &toASTContext = m_ChildInterpreter->getCI()->getASTContext(); ClingASTImporter* importer = new ClingASTImporter(toASTContext, childFM, fromASTContext, parentFM, /*MinimalImport : ON*/ true, *this); m_Importer.reset(llvm::dyn_cast<ASTImporter>(importer)); } ExternalInterpreterSource::~ExternalInterpreterSource() {} void ExternalInterpreterSource::ImportDecl(Decl *declToImport, DeclarationName &childDeclName, DeclarationName &parentDeclName, const DeclContext *childCurrentDeclContext) { // Don't do the import if we have a Function Template or using decls. They // are not supported by clang. // FIXME: These are temporary checks and should be de-activated once clang // supports their import. if ((declToImport->isFunctionOrFunctionTemplate() && declToImport->isTemplateDecl()) || dyn_cast<UsingDecl>(declToImport) || dyn_cast<UsingShadowDecl>(declToImport)) { #ifndef NDEBUG utils::DiagnosticsStore DS( m_Importer->getFromContext().getDiagnostics(), false, false, true); llvm::Expected<const Decl *> To = m_Importer->Import(declToImport); assert(To.get() && "Import did not work!"); assert(!DS.empty() && DS[0].getID() == clang::diag::err_unsupported_ast_node && "Import may be supported"); #endif return; } if (auto toOrErr = m_Importer->Import(declToImport)) { if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(*toOrErr)) { SetExternalVisibleDeclsForName(childCurrentDeclContext, importedNamedDecl->getDeclName(), importedNamedDecl); } // Put the name of the Decl imported with the // DeclarationName coming from the parent, in my map. m_ImportedDecls[childDeclName] = parentDeclName; } else { logAllUnhandledErrors(toOrErr.takeError(), llvm::errs(), "Error importing decl"); } } void ExternalInterpreterSource::ImportDeclContext( DeclContext *declContextToImport, DeclarationName &childDeclName, DeclarationName &parentDeclName, const DeclContext *childCurrentDeclContext) { if (auto toOrErr = m_Importer->ImportContext(declContextToImport)) { DeclContext *importedDC = *toOrErr; importedDC->setHasExternalVisibleStorage(true); if (NamedDecl *importedND = llvm::dyn_cast<NamedDecl>(importedDC)) { SetExternalVisibleDeclsForName(childCurrentDeclContext, importedND->getDeclName(), importedND); } // Put the name of the DeclContext imported with the // DeclarationName coming from the parent, in my map. m_ImportedDecls[childDeclName] = parentDeclName; // And also put the declaration context I found from the parent Interpreter // in the map of the child Interpreter to have it for the future. m_ImportedDeclContexts[importedDC] = declContextToImport; } else { logAllUnhandledErrors(toOrErr.takeError(), llvm::errs(), "Error importing decl context"); } } bool ExternalInterpreterSource::Import(DeclContext::lookup_result lookup_result, const DeclContext *childCurrentDeclContext, DeclarationName &childDeclName, DeclarationName &parentDeclName) { for (DeclContext::lookup_iterator I = lookup_result.begin(), E = lookup_result.end(); I != E; ++I) { // Check if this Name we are looking for is // a DeclContext (for example a Namespace, function etc.). if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) { ImportDeclContext(declContextToImport, childDeclName, parentDeclName, childCurrentDeclContext); } ImportDecl(*I, childDeclName, parentDeclName, childCurrentDeclContext); } return true; } ///\brief This is the one of the most important function of the class /// since from here initiates the lookup and import part of the missing /// Decl(s) (Contexts). /// bool ExternalInterpreterSource::FindExternalVisibleDeclsByName( const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) { assert(childDeclName && "Child Decl name is empty"); assert(childCurrentDeclContext->hasExternalVisibleStorage() && "DeclContext has no visible decls in storage"); //Check if we have already found this declaration Name before DeclarationName parentDeclName; std::map<clang::DeclarationName, clang::DeclarationName>::iterator IDecl = m_ImportedDecls.find(childDeclName); if (IDecl != m_ImportedDecls.end()) { parentDeclName = IDecl->second; } else { // Get the identifier info from the parent interpreter // for this Name. std::string name = childDeclName.getAsString(); IdentifierTable &parentIdentifierTable = m_ParentInterpreter->getCI()->getASTContext().Idents; IdentifierInfo &parentIdentifierInfo = parentIdentifierTable.get(name); parentDeclName = DeclarationName(&parentIdentifierInfo); } // Search in the map of the stored Decl Contexts for this // Decl Context. std::map<const clang::DeclContext *, clang::DeclContext *>::iterator IDeclContext = m_ImportedDeclContexts.find(childCurrentDeclContext); // If childCurrentDeclContext was found before and is already in the map, // then do the lookup using the stored pointer. if (IDeclContext == m_ImportedDeclContexts.end()) return false; DeclContext *parentDeclContext = IDeclContext->second; DeclContext::lookup_result lookup_result = parentDeclContext->lookup(parentDeclName); // Check if we found this Name in the parent interpreter if (!lookup_result.empty()) { if (Import(lookup_result, childCurrentDeclContext, childDeclName, parentDeclName)) return true; } return false; } ///\brief Make available to child all decls in parent's decl context /// that corresponds to child decl context. void ExternalInterpreterSource::completeVisibleDeclsMap( const clang::DeclContext *childDeclContext) { assert (childDeclContext && "No child decl context!"); if (!childDeclContext->hasExternalVisibleStorage()) return; // Search in the map of the stored Decl Contexts for this // Decl Context. std::map<const clang::DeclContext *, clang::DeclContext *>::iterator IDeclContext = m_ImportedDeclContexts.find(childDeclContext); // If childCurrentDeclContext was found before and is already in the map, // then do the lookup using the stored pointer. if (IDeclContext == m_ImportedDeclContexts.end()) return ; DeclContext *parentDeclContext = IDeclContext->second; // Filter the decls from the external source using the stem information // stored in Sema. StringRef filter = m_ChildInterpreter->getCI()->getPreprocessor().getCodeCompletionFilter(); for (DeclContext::decl_iterator IDeclContext = parentDeclContext->decls_begin(), EDeclContext = parentDeclContext->decls_end(); IDeclContext != EDeclContext; ++IDeclContext) { if (NamedDecl* parentDecl = llvm::dyn_cast<NamedDecl>(*IDeclContext)) { DeclarationName childDeclName = parentDecl->getDeclName(); if (auto II = childDeclName.getAsIdentifierInfo()) { StringRef name = II->getName(); if (!name.empty() && name.startswith(filter)) ImportDecl(parentDecl, childDeclName, childDeclName, childDeclContext); } } } const_cast<DeclContext *>(childDeclContext)-> setHasExternalVisibleStorage(false); } } // end namespace cling <commit_msg>Fix wrong asserts.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Elisavet Sakellari <elisavet.sakellari@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "ExternalInterpreterSource.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Utils/Diagnostics.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/ASTImporter.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Sema.h" using namespace clang; namespace { class ClingASTImporter : public ASTImporter { private: cling::ExternalInterpreterSource &m_Source; public: ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager, ASTContext &FromContext, FileManager &FromFileManager, bool MinimalImport, cling::ExternalInterpreterSource& source): ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager, MinimalImport), m_Source(source) {} virtual ~ClingASTImporter() = default; void Imported(Decl *From, Decl *To) override { ASTImporter::Imported(From, To); if (clang::TagDecl* toTagDecl = dyn_cast<TagDecl>(To)) { toTagDecl->setHasExternalLexicalStorage(); toTagDecl->setMustBuildLookupTable(); toTagDecl->setHasExternalVisibleStorage(); } if (NamespaceDecl *toNamespaceDecl = dyn_cast<NamespaceDecl>(To)) { toNamespaceDecl->setHasExternalVisibleStorage(); } if (ObjCContainerDecl *toContainerDecl = dyn_cast<ObjCContainerDecl>(To)) { toContainerDecl->setHasExternalLexicalStorage(); toContainerDecl->setHasExternalVisibleStorage(); } // Put the name of the Decl imported with the // DeclarationName coming from the parent, in my map. if (NamedDecl *toNamedDecl = llvm::dyn_cast<NamedDecl>(To)) { NamedDecl *fromNamedDecl = llvm::dyn_cast<NamedDecl>(From); m_Source.addToImportedDecls(toNamedDecl->getDeclName(), fromNamedDecl->getDeclName()); } if (DeclContext *toDeclContext = llvm::dyn_cast<DeclContext>(To)) { DeclContext *fromDeclContext = llvm::dyn_cast<DeclContext>(From); m_Source.addToImportedDeclContexts(toDeclContext, fromDeclContext); } } }; } namespace cling { ExternalInterpreterSource::ExternalInterpreterSource( const cling::Interpreter *parent, cling::Interpreter *child) : m_ParentInterpreter(parent), m_ChildInterpreter(child) { clang::DeclContext *parentTUDeclContext = m_ParentInterpreter->getCI()->getASTContext().getTranslationUnitDecl(); clang::DeclContext *childTUDeclContext = m_ChildInterpreter->getCI()->getASTContext().getTranslationUnitDecl(); // Also keep in the map of Decl Contexts the Translation Unit Decl Context m_ImportedDeclContexts[childTUDeclContext] = parentTUDeclContext; FileManager &childFM = m_ChildInterpreter->getCI()->getFileManager(); FileManager &parentFM = m_ParentInterpreter->getCI()->getFileManager(); ASTContext &fromASTContext = m_ParentInterpreter->getCI()->getASTContext(); ASTContext &toASTContext = m_ChildInterpreter->getCI()->getASTContext(); ClingASTImporter* importer = new ClingASTImporter(toASTContext, childFM, fromASTContext, parentFM, /*MinimalImport : ON*/ true, *this); m_Importer.reset(llvm::dyn_cast<ASTImporter>(importer)); } ExternalInterpreterSource::~ExternalInterpreterSource() {} void ExternalInterpreterSource::ImportDecl(Decl *declToImport, DeclarationName &childDeclName, DeclarationName &parentDeclName, const DeclContext *childCurrentDeclContext) { // Don't do the import if we have a Function Template or using decls. They // are not supported by clang. // FIXME: These are temporary checks and should be de-activated once clang // supports their import. if ((declToImport->isFunctionOrFunctionTemplate() && declToImport->isTemplateDecl()) || dyn_cast<UsingDecl>(declToImport) || dyn_cast<UsingShadowDecl>(declToImport)) { #ifndef NDEBUG utils::DiagnosticsStore DS( m_Importer->getFromContext().getDiagnostics(), false, false, true); const Decl* To = llvm::cantFail(m_Importer->Import(declToImport)); assert(To && "Import did not work!"); assert((DS.empty() || DS[0].getID() == clang::diag::err_unsupported_ast_node) && "Import not supported!"); #endif return; } if (auto toOrErr = m_Importer->Import(declToImport)) { if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(*toOrErr)) { SetExternalVisibleDeclsForName(childCurrentDeclContext, importedNamedDecl->getDeclName(), importedNamedDecl); } // Put the name of the Decl imported with the // DeclarationName coming from the parent, in my map. m_ImportedDecls[childDeclName] = parentDeclName; } else { logAllUnhandledErrors(toOrErr.takeError(), llvm::errs(), "Error importing decl"); } } void ExternalInterpreterSource::ImportDeclContext( DeclContext *declContextToImport, DeclarationName &childDeclName, DeclarationName &parentDeclName, const DeclContext *childCurrentDeclContext) { if (auto toOrErr = m_Importer->ImportContext(declContextToImport)) { DeclContext *importedDC = *toOrErr; importedDC->setHasExternalVisibleStorage(true); if (NamedDecl *importedND = llvm::dyn_cast<NamedDecl>(importedDC)) { SetExternalVisibleDeclsForName(childCurrentDeclContext, importedND->getDeclName(), importedND); } // Put the name of the DeclContext imported with the // DeclarationName coming from the parent, in my map. m_ImportedDecls[childDeclName] = parentDeclName; // And also put the declaration context I found from the parent Interpreter // in the map of the child Interpreter to have it for the future. m_ImportedDeclContexts[importedDC] = declContextToImport; } else { logAllUnhandledErrors(toOrErr.takeError(), llvm::errs(), "Error importing decl context"); } } bool ExternalInterpreterSource::Import(DeclContext::lookup_result lookup_result, const DeclContext *childCurrentDeclContext, DeclarationName &childDeclName, DeclarationName &parentDeclName) { for (DeclContext::lookup_iterator I = lookup_result.begin(), E = lookup_result.end(); I != E; ++I) { // Check if this Name we are looking for is // a DeclContext (for example a Namespace, function etc.). if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) { ImportDeclContext(declContextToImport, childDeclName, parentDeclName, childCurrentDeclContext); } ImportDecl(*I, childDeclName, parentDeclName, childCurrentDeclContext); } return true; } ///\brief This is the one of the most important function of the class /// since from here initiates the lookup and import part of the missing /// Decl(s) (Contexts). /// bool ExternalInterpreterSource::FindExternalVisibleDeclsByName( const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) { assert(childDeclName && "Child Decl name is empty"); assert(childCurrentDeclContext->hasExternalVisibleStorage() && "DeclContext has no visible decls in storage"); //Check if we have already found this declaration Name before DeclarationName parentDeclName; std::map<clang::DeclarationName, clang::DeclarationName>::iterator IDecl = m_ImportedDecls.find(childDeclName); if (IDecl != m_ImportedDecls.end()) { parentDeclName = IDecl->second; } else { // Get the identifier info from the parent interpreter // for this Name. std::string name = childDeclName.getAsString(); IdentifierTable &parentIdentifierTable = m_ParentInterpreter->getCI()->getASTContext().Idents; IdentifierInfo &parentIdentifierInfo = parentIdentifierTable.get(name); parentDeclName = DeclarationName(&parentIdentifierInfo); } // Search in the map of the stored Decl Contexts for this // Decl Context. std::map<const clang::DeclContext *, clang::DeclContext *>::iterator IDeclContext = m_ImportedDeclContexts.find(childCurrentDeclContext); // If childCurrentDeclContext was found before and is already in the map, // then do the lookup using the stored pointer. if (IDeclContext == m_ImportedDeclContexts.end()) return false; DeclContext *parentDeclContext = IDeclContext->second; DeclContext::lookup_result lookup_result = parentDeclContext->lookup(parentDeclName); // Check if we found this Name in the parent interpreter if (!lookup_result.empty()) { if (Import(lookup_result, childCurrentDeclContext, childDeclName, parentDeclName)) return true; } return false; } ///\brief Make available to child all decls in parent's decl context /// that corresponds to child decl context. void ExternalInterpreterSource::completeVisibleDeclsMap( const clang::DeclContext *childDeclContext) { assert (childDeclContext && "No child decl context!"); if (!childDeclContext->hasExternalVisibleStorage()) return; // Search in the map of the stored Decl Contexts for this // Decl Context. std::map<const clang::DeclContext *, clang::DeclContext *>::iterator IDeclContext = m_ImportedDeclContexts.find(childDeclContext); // If childCurrentDeclContext was found before and is already in the map, // then do the lookup using the stored pointer. if (IDeclContext == m_ImportedDeclContexts.end()) return ; DeclContext *parentDeclContext = IDeclContext->second; // Filter the decls from the external source using the stem information // stored in Sema. StringRef filter = m_ChildInterpreter->getCI()->getPreprocessor().getCodeCompletionFilter(); for (DeclContext::decl_iterator IDeclContext = parentDeclContext->decls_begin(), EDeclContext = parentDeclContext->decls_end(); IDeclContext != EDeclContext; ++IDeclContext) { if (NamedDecl* parentDecl = llvm::dyn_cast<NamedDecl>(*IDeclContext)) { DeclarationName childDeclName = parentDecl->getDeclName(); if (auto II = childDeclName.getAsIdentifierInfo()) { StringRef name = II->getName(); if (!name.empty() && name.startswith(filter)) ImportDecl(parentDecl, childDeclName, childDeclName, childDeclContext); } } } const_cast<DeclContext *>(childDeclContext)-> setHasExternalVisibleStorage(false); } } // end namespace cling <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkWin32OutputWindow.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkWin32OutputWindow.h" #include "vtkObjectFactory.h" #include "vtkWindows.h" vtkStandardNewMacro(vtkWin32OutputWindow); HWND vtkWin32OutputWindowOutputWindow = 0; //---------------------------------------------------------------------------- LRESULT APIENTRY vtkWin32OutputWindowWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_SIZE: { int w = LOWORD(lParam); // width of client area int h = HIWORD(lParam); // height of client area MoveWindow(vtkWin32OutputWindowOutputWindow, 0, 0, w, h, true); } break; case WM_DESTROY: vtkWin32OutputWindowOutputWindow = NULL; vtkObject::GlobalWarningDisplayOff(); break; case WM_CREATE: break; } return DefWindowProc(hWnd, message, wParam, lParam); } //---------------------------------------------------------------------------- vtkWin32OutputWindow::vtkWin32OutputWindow() { // Default to sending output to stderr/cerr when running a dashboard: // if(getenv("DART_TEST_FROM_DART") || getenv("DASHBOARD_TEST_FROM_CTEST")) { this->SendToStdErr = true; } else { this->SendToStdErr = false; } } //---------------------------------------------------------------------------- vtkWin32OutputWindow::~vtkWin32OutputWindow() { } //---------------------------------------------------------------------------- // Display text in the window, and translate the \n to \r\n. // void vtkWin32OutputWindow::DisplayText(const char* someText) { if(!someText) { return; } if(this->PromptUser) { this->PromptText(someText); return; } // Create a buffer big enough to hold the entire text char* buffer = new char[strlen(someText)+1]; // Start at the beginning const char* NewLinePos = someText; while(NewLinePos) { int len = 0; // Find the next new line in text NewLinePos = strchr(someText, '\n'); // if no new line is found then just add the text if(NewLinePos == 0) { vtkWin32OutputWindow::AddText(someText); OutputDebugString(someText); if (this->SendToStdErr) { cerr << someText; } } // if a new line is found copy it to the buffer // and add the buffer with a control new line else { len = NewLinePos - someText; strncpy(buffer, someText, len); buffer[len] = 0; someText = NewLinePos+1; vtkWin32OutputWindow::AddText(buffer); vtkWin32OutputWindow::AddText("\r\n"); OutputDebugString(buffer); OutputDebugString("\r\n"); if (this->SendToStdErr) { cerr << buffer; cerr << "\r\n"; } } } delete [] buffer; } //---------------------------------------------------------------------------- // Add some text to the EDIT control. // void vtkWin32OutputWindow::AddText(const char* someText) { if(!Initialize() || (strlen(someText) == 0)) { return; } #ifdef UNICODE // move to the end of the text area SendMessageW( vtkWin32OutputWindowOutputWindow, EM_SETSEL, (WPARAM)-1, (LPARAM)-1 ); wchar_t *wmsg = new wchar_t [mbstowcs(NULL, someText, 32000)+1]; mbstowcs(wmsg, someText, 32000); // Append the text to the control SendMessageW( vtkWin32OutputWindowOutputWindow, EM_REPLACESEL, 0, (LPARAM)wmsg ); delete [] wmsg; #else // move to the end of the text area SendMessageA( vtkWin32OutputWindowOutputWindow, EM_SETSEL, (WPARAM)-1, (LPARAM)-1 ); // Append the text to the control SendMessageA( vtkWin32OutputWindowOutputWindow, EM_REPLACESEL, 0, (LPARAM)someText ); #endif } //---------------------------------------------------------------------------- // initialize the output window with an EDIT control and // a container window. // int vtkWin32OutputWindow::Initialize() { // check to see if it is already initialized if(vtkWin32OutputWindowOutputWindow) { return 1; } // Initialize the output window WNDCLASS wndClass; // has the class been registered ? #ifdef UNICODE if (!GetClassInfo(GetModuleHandle(NULL),L"vtkOutputWindow",&wndClass)) #else if (!GetClassInfo(GetModuleHandle(NULL),"vtkOutputWindow",&wndClass)) #endif { wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = vtkWin32OutputWindowWndProc; wndClass.cbClsExtra = 0; wndClass.hInstance = GetModuleHandle(NULL); #ifndef _WIN32_WCE wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); #endif wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndClass.lpszMenuName = NULL; #ifdef UNICODE wndClass.lpszClassName = L"vtkOutputWindow"; #else wndClass.lpszClassName = "vtkOutputWindow"; #endif // vtk doesn't use these extra bytes, but app writers // may want them, so we provide them -- big enough for // one run time pointer: 4 bytes on 32-bit builds, 8 bytes // on 64-bit builds wndClass.cbWndExtra = sizeof(vtkLONG); RegisterClass(&wndClass); } // create parent container window #ifdef _WIN32_WCE HWND win = CreateWindow( L"vtkOutputWindow", L"vtkOutputWindow", WS_OVERLAPPED | WS_CLIPCHILDREN, 0, 0, 512, 512, NULL, NULL, GetModuleHandle(NULL), NULL); #elif UNICODE HWND win = CreateWindow( L"vtkOutputWindow", L"vtkOutputWindow", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 0, 0, 512, 512, NULL, NULL, GetModuleHandle(NULL), NULL); #else HWND win = CreateWindow( "vtkOutputWindow", "vtkOutputWindow", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 0, 0, 512, 512, NULL, NULL, GetModuleHandle(NULL), NULL); #endif // Now create child window with text display box CREATESTRUCT lpParam; lpParam.hInstance = GetModuleHandle(NULL); lpParam.hMenu = NULL; lpParam.hwndParent = win; lpParam.cx = 512; lpParam.cy = 512; lpParam.x = 0; lpParam.y = 0; #if defined(_WIN32_WCE) || defined(UNICODE) lpParam.lpszName = L"Output Control"; lpParam.lpszClass = L"EDIT"; // use the RICHEDIT control widget #else lpParam.lpszName = "Output Control"; lpParam.lpszClass = "EDIT"; // use the RICHEDIT control widget #endif #ifdef _WIN32_WCE lpParam.style = ES_MULTILINE | ES_READONLY | WS_CHILD | ES_AUTOVSCROLL | ES_AUTOHSCROLL | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL; #else lpParam.style = ES_MULTILINE | ES_READONLY | WS_CHILD | ES_AUTOVSCROLL | ES_AUTOHSCROLL | WS_VISIBLE | WS_MAXIMIZE | WS_VSCROLL | WS_HSCROLL; #endif lpParam.dwExStyle = 0; // Create the EDIT window as a child of win #if defined(_WIN32_WCE) || defined(UNICODE) vtkWin32OutputWindowOutputWindow = CreateWindow( lpParam.lpszClass, // pointer to registered class name L"", // pointer to window name lpParam.style, // window style lpParam.x, // horizontal position of window lpParam.y, // vertical position of window lpParam.cx, // window width lpParam.cy, // window height lpParam.hwndParent, // handle to parent or owner window NULL, // handle to menu or child-window identifier lpParam.hInstance, // handle to application instance &lpParam // pointer to window-creation data ); #else vtkWin32OutputWindowOutputWindow = CreateWindow( lpParam.lpszClass, // pointer to registered class name "", // pointer to window name lpParam.style, // window style lpParam.x, // horizontal position of window lpParam.y, // vertical position of window lpParam.cx, // window width lpParam.cy, // window height lpParam.hwndParent, // handle to parent or owner window NULL, // handle to menu or child-window identifier lpParam.hInstance, // handle to application instance &lpParam // pointer to window-creation data ); #endif const int maxsize = 5242880; #ifdef UNICODE SendMessageW(vtkWin32OutputWindowOutputWindow, EM_LIMITTEXT, maxsize, 0L); #else SendMessageA(vtkWin32OutputWindowOutputWindow, EM_LIMITTEXT, maxsize, 0L); #endif // show the top level container window ShowWindow(win, SW_SHOW); return 1; } //---------------------------------------------------------------------------- void vtkWin32OutputWindow::PromptText(const char* someText) { char *vtkmsg = new char [strlen(someText) + 100]; sprintf(vtkmsg,"%s\nPress Cancel to suppress any further messages.", someText); #ifdef UNICODE wchar_t *wmsg = new wchar_t [mbstowcs(NULL, vtkmsg, 32000)+1]; mbstowcs(wmsg, vtkmsg, 32000); if (MessageBox(NULL, wmsg, L"Error", MB_ICONERROR | MB_OKCANCEL) == IDCANCEL) { vtkObject::GlobalWarningDisplayOff(); } delete [] wmsg; #else if (MessageBox(NULL, vtkmsg, "Error", MB_ICONERROR | MB_OKCANCEL) == IDCANCEL) { vtkObject::GlobalWarningDisplayOff(); } #endif delete [] vtkmsg; } //---------------------------------------------------------------------------- void vtkWin32OutputWindow::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if (vtkWin32OutputWindowOutputWindow) { os << indent << "OutputWindow: " << vtkWin32OutputWindowOutputWindow << "\n"; } else { os << indent << "OutputWindow: (null)\n"; } os << indent << "SendToStdErr: " << this->SendToStdErr << "\n"; } <commit_msg>make wider so we can see errors<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkWin32OutputWindow.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkWin32OutputWindow.h" #include "vtkObjectFactory.h" #include "vtkWindows.h" vtkStandardNewMacro(vtkWin32OutputWindow); HWND vtkWin32OutputWindowOutputWindow = 0; //---------------------------------------------------------------------------- LRESULT APIENTRY vtkWin32OutputWindowWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_SIZE: { int w = LOWORD(lParam); // width of client area int h = HIWORD(lParam); // height of client area MoveWindow(vtkWin32OutputWindowOutputWindow, 0, 0, w, h, true); } break; case WM_DESTROY: vtkWin32OutputWindowOutputWindow = NULL; vtkObject::GlobalWarningDisplayOff(); break; case WM_CREATE: break; } return DefWindowProc(hWnd, message, wParam, lParam); } //---------------------------------------------------------------------------- vtkWin32OutputWindow::vtkWin32OutputWindow() { // Default to sending output to stderr/cerr when running a dashboard: // if(getenv("DART_TEST_FROM_DART") || getenv("DASHBOARD_TEST_FROM_CTEST")) { this->SendToStdErr = true; } else { this->SendToStdErr = false; } } //---------------------------------------------------------------------------- vtkWin32OutputWindow::~vtkWin32OutputWindow() { } //---------------------------------------------------------------------------- // Display text in the window, and translate the \n to \r\n. // void vtkWin32OutputWindow::DisplayText(const char* someText) { if(!someText) { return; } if(this->PromptUser) { this->PromptText(someText); return; } // Create a buffer big enough to hold the entire text char* buffer = new char[strlen(someText)+1]; // Start at the beginning const char* NewLinePos = someText; while(NewLinePos) { int len = 0; // Find the next new line in text NewLinePos = strchr(someText, '\n'); // if no new line is found then just add the text if(NewLinePos == 0) { vtkWin32OutputWindow::AddText(someText); OutputDebugString(someText); if (this->SendToStdErr) { cerr << someText; } } // if a new line is found copy it to the buffer // and add the buffer with a control new line else { len = NewLinePos - someText; strncpy(buffer, someText, len); buffer[len] = 0; someText = NewLinePos+1; vtkWin32OutputWindow::AddText(buffer); vtkWin32OutputWindow::AddText("\r\n"); OutputDebugString(buffer); OutputDebugString("\r\n"); if (this->SendToStdErr) { cerr << buffer; cerr << "\r\n"; } } } delete [] buffer; } //---------------------------------------------------------------------------- // Add some text to the EDIT control. // void vtkWin32OutputWindow::AddText(const char* someText) { if(!Initialize() || (strlen(someText) == 0)) { return; } #ifdef UNICODE // move to the end of the text area SendMessageW( vtkWin32OutputWindowOutputWindow, EM_SETSEL, (WPARAM)-1, (LPARAM)-1 ); wchar_t *wmsg = new wchar_t [mbstowcs(NULL, someText, 32000)+1]; mbstowcs(wmsg, someText, 32000); // Append the text to the control SendMessageW( vtkWin32OutputWindowOutputWindow, EM_REPLACESEL, 0, (LPARAM)wmsg ); delete [] wmsg; #else // move to the end of the text area SendMessageA( vtkWin32OutputWindowOutputWindow, EM_SETSEL, (WPARAM)-1, (LPARAM)-1 ); // Append the text to the control SendMessageA( vtkWin32OutputWindowOutputWindow, EM_REPLACESEL, 0, (LPARAM)someText ); #endif } //---------------------------------------------------------------------------- // initialize the output window with an EDIT control and // a container window. // int vtkWin32OutputWindow::Initialize() { // check to see if it is already initialized if(vtkWin32OutputWindowOutputWindow) { return 1; } // Initialize the output window WNDCLASS wndClass; // has the class been registered ? #ifdef UNICODE if (!GetClassInfo(GetModuleHandle(NULL),L"vtkOutputWindow",&wndClass)) #else if (!GetClassInfo(GetModuleHandle(NULL),"vtkOutputWindow",&wndClass)) #endif { wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = vtkWin32OutputWindowWndProc; wndClass.cbClsExtra = 0; wndClass.hInstance = GetModuleHandle(NULL); #ifndef _WIN32_WCE wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); #endif wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndClass.lpszMenuName = NULL; #ifdef UNICODE wndClass.lpszClassName = L"vtkOutputWindow"; #else wndClass.lpszClassName = "vtkOutputWindow"; #endif // vtk doesn't use these extra bytes, but app writers // may want them, so we provide them -- big enough for // one run time pointer: 4 bytes on 32-bit builds, 8 bytes // on 64-bit builds wndClass.cbWndExtra = sizeof(vtkLONG); RegisterClass(&wndClass); } // create parent container window #ifdef _WIN32_WCE HWND win = CreateWindow( L"vtkOutputWindow", L"vtkOutputWindow", WS_OVERLAPPED | WS_CLIPCHILDREN, 0, 0, 800, 512, NULL, NULL, GetModuleHandle(NULL), NULL); #elif UNICODE HWND win = CreateWindow( L"vtkOutputWindow", L"vtkOutputWindow", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 0, 0, 800, 512, NULL, NULL, GetModuleHandle(NULL), NULL); #else HWND win = CreateWindow( "vtkOutputWindow", "vtkOutputWindow", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 0, 0, 800, 512, NULL, NULL, GetModuleHandle(NULL), NULL); #endif // Now create child window with text display box CREATESTRUCT lpParam; lpParam.hInstance = GetModuleHandle(NULL); lpParam.hMenu = NULL; lpParam.hwndParent = win; lpParam.cx = 800; lpParam.cy = 512; lpParam.x = 0; lpParam.y = 0; #if defined(_WIN32_WCE) || defined(UNICODE) lpParam.lpszName = L"Output Control"; lpParam.lpszClass = L"EDIT"; // use the RICHEDIT control widget #else lpParam.lpszName = "Output Control"; lpParam.lpszClass = "EDIT"; // use the RICHEDIT control widget #endif #ifdef _WIN32_WCE lpParam.style = ES_MULTILINE | ES_READONLY | WS_CHILD | ES_AUTOVSCROLL | ES_AUTOHSCROLL | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL; #else lpParam.style = ES_MULTILINE | ES_READONLY | WS_CHILD | ES_AUTOVSCROLL | ES_AUTOHSCROLL | WS_VISIBLE | WS_MAXIMIZE | WS_VSCROLL | WS_HSCROLL; #endif lpParam.dwExStyle = 0; // Create the EDIT window as a child of win #if defined(_WIN32_WCE) || defined(UNICODE) vtkWin32OutputWindowOutputWindow = CreateWindow( lpParam.lpszClass, // pointer to registered class name L"", // pointer to window name lpParam.style, // window style lpParam.x, // horizontal position of window lpParam.y, // vertical position of window lpParam.cx, // window width lpParam.cy, // window height lpParam.hwndParent, // handle to parent or owner window NULL, // handle to menu or child-window identifier lpParam.hInstance, // handle to application instance &lpParam // pointer to window-creation data ); #else vtkWin32OutputWindowOutputWindow = CreateWindow( lpParam.lpszClass, // pointer to registered class name "", // pointer to window name lpParam.style, // window style lpParam.x, // horizontal position of window lpParam.y, // vertical position of window lpParam.cx, // window width lpParam.cy, // window height lpParam.hwndParent, // handle to parent or owner window NULL, // handle to menu or child-window identifier lpParam.hInstance, // handle to application instance &lpParam // pointer to window-creation data ); #endif const int maxsize = 5242880; #ifdef UNICODE SendMessageW(vtkWin32OutputWindowOutputWindow, EM_LIMITTEXT, maxsize, 0L); #else SendMessageA(vtkWin32OutputWindowOutputWindow, EM_LIMITTEXT, maxsize, 0L); #endif // show the top level container window ShowWindow(win, SW_SHOW); return 1; } //---------------------------------------------------------------------------- void vtkWin32OutputWindow::PromptText(const char* someText) { char *vtkmsg = new char [strlen(someText) + 100]; sprintf(vtkmsg,"%s\nPress Cancel to suppress any further messages.", someText); #ifdef UNICODE wchar_t *wmsg = new wchar_t [mbstowcs(NULL, vtkmsg, 32000)+1]; mbstowcs(wmsg, vtkmsg, 32000); if (MessageBox(NULL, wmsg, L"Error", MB_ICONERROR | MB_OKCANCEL) == IDCANCEL) { vtkObject::GlobalWarningDisplayOff(); } delete [] wmsg; #else if (MessageBox(NULL, vtkmsg, "Error", MB_ICONERROR | MB_OKCANCEL) == IDCANCEL) { vtkObject::GlobalWarningDisplayOff(); } #endif delete [] vtkmsg; } //---------------------------------------------------------------------------- void vtkWin32OutputWindow::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if (vtkWin32OutputWindowOutputWindow) { os << indent << "OutputWindow: " << vtkWin32OutputWindowOutputWindow << "\n"; } else { os << indent << "OutputWindow: (null)\n"; } os << indent << "SendToStdErr: " << this->SendToStdErr << "\n"; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9a/procedures/hwp/memory/p9a_mss_eff_config_thermal.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ <commit_msg>Add L1 procedures for p9a and makefiles<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9a/procedures/hwp/memory/p9a_mss_eff_config_thermal.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9a_mss_eff_config_thermal.H /// @brief Perform thermal calculations as part of the effective configuration /// // *HWP HWP Owner: Andre A. Marin <aamarin@us.ibm.com> // *HWP HWP Backup: Michael Pardeik <pardeik@us.ibm.com> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #ifndef P9A_MSS_EFF_CONFIG_THERMAL_H_ #define P9A_MSS_EFF_CONFIG_THERMAL_H_ #include <fapi2.H> #include <vector> typedef fapi2::ReturnCode (*p9a_mss_eff_config_thermal_FP_t) (const std::vector <fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>>&); extern "C" { /// /// @brief Perform thermal calculations as part of the effective configuration /// @param[in] i_targets vector of ports (e.g., MEM_PORT) all on the same VDDR domain /// @return FAPI2_RC_SUCCESS iff ok /// @note sets ATTR_MSS_MEM_WATT_TARGET, ATTR_MSS_RUNTIME_MEM_THROTTLED_N_COMMANDS_PER_PORT and _PER_SLOT, and ATTR_MSS_PORT_MAXPOWER /// fapi2::ReturnCode p9a_mss_eff_config_thermal( const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT> >& i_targets ); } #endif <|endoftext|>
<commit_before> #include "typedatabase.h" #include "../customtypes.h" #include <QDebug> #include <qfile.h> #include <qxml.h> #include "handler.h" #include "../reporthandler.h" static void addRemoveFunctionToTemplates(TypeDatabase *db); TypeDatabase::TypeDatabase() : m_suppressWarnings(true), m_includeEclipseWarnings(false) { addType(new StringTypeEntry("QString")); StringTypeEntry *e = new StringTypeEntry("QLatin1String"); e->setPreferredConversion(false); addType(e); // We need the generator to perform type conversion in C++ with the // construct: // QString qstring = QString("string"); QStringRef(&qstring)" // not with: // (const QStringRef &)QString("string") StringRefTypeEntry *sr = new StringRefTypeEntry("QStringRef"); addType(sr); // TODO: Use of StringRefTypeEntry for QXmlStreamStringRef has not been tested, // I am sure the previous code would cause a crash. sr = new StringRefTypeEntry("QXmlStreamStringRef"); sr->setPreferredConversion(false); addType(sr); addType(new CharTypeEntry("QChar")); CharTypeEntry *c = new CharTypeEntry("QLatin1Char"); c->setPreferredConversion(false); addType(c); { VariantTypeEntry *qvariant = new VariantTypeEntry("QVariant"); qvariant->setCodeGeneration(TypeEntry::GenerateNothing); addType(qvariant); } { JObjectWrapperTypeEntry *wrapper = new JObjectWrapperTypeEntry("JObjectWrapper"); wrapper->setCodeGeneration(TypeEntry::GenerateNothing); addType(wrapper); } addType(new ThreadTypeEntry()); addType(new VoidTypeEntry()); // Predefined containers... addType(new ContainerTypeEntry("QList", ContainerTypeEntry::ListContainer)); addType(new ContainerTypeEntry("QStringList", ContainerTypeEntry::StringListContainer)); addType(new ContainerTypeEntry("QLinkedList", ContainerTypeEntry::LinkedListContainer)); addType(new ContainerTypeEntry("QVector", ContainerTypeEntry::VectorContainer)); addType(new ContainerTypeEntry("QStack", ContainerTypeEntry::StackContainer)); addType(new ContainerTypeEntry("QSet", ContainerTypeEntry::SetContainer)); addType(new ContainerTypeEntry("QMap", ContainerTypeEntry::MapContainer)); addType(new ContainerTypeEntry("QHash", ContainerTypeEntry::HashContainer)); addType(new ContainerTypeEntry("QPair", ContainerTypeEntry::PairContainer)); addType(new ContainerTypeEntry("QQueue", ContainerTypeEntry::QueueContainer)); addType(new ContainerTypeEntry("QMultiMap", ContainerTypeEntry::MultiMapContainer)); // Custom types... addType(new QModelIndexTypeEntry()); addRemoveFunctionToTemplates(this); } TypeDatabase *TypeDatabase::instance() { static TypeDatabase *db = new TypeDatabase(); return db; } TypeEntry *TypeDatabase::findType(const QString &name) const { QList<TypeEntry *> entries = findTypes(name); foreach(TypeEntry *entry, entries) { //qDebug()<<"findType()"<<entry; if (entry != 0 && (!entry->isPrimitive() || static_cast<PrimitiveTypeEntry *>(entry)->preferredTargetLangType())) { return entry; } } return 0; } SingleTypeEntryHash TypeDatabase::entries() { TypeEntryHash entries = allEntries(); SingleTypeEntryHash returned; QList<QString> keys = entries.keys(); foreach(QString key, keys) { returned[key] = findType(key); } return returned; } bool TypeDatabase::isSuppressedWarning(const QString &s) { if (!m_suppressWarnings) return false; foreach(const QString &_warning, m_suppressedWarnings) { QString warning(QString(_warning).replace("\\*", "&place_holder_for_asterisk;")); QStringList segs = warning.split("*", QString::SkipEmptyParts); if (segs.size() == 0) continue ; int i = 0; int pos = s.indexOf(QString(segs.at(i++)).replace("&place_holder_for_asterisk;", "*")); //qDebug() << "s == " << s << ", warning == " << segs; while (pos != -1) { if (i == segs.size()) return true; pos = s.indexOf(QString(segs.at(i++)).replace("&place_holder_for_asterisk;", "*"), pos); } } return false; } PrimitiveTypeEntry *TypeDatabase::findPrimitiveType(const QString &name) { QList<TypeEntry *> entries = findTypes(name); foreach(TypeEntry *entry, entries) { if (entry != 0 && entry->isPrimitive() && static_cast<PrimitiveTypeEntry *>(entry)->preferredTargetLangType()) return static_cast<PrimitiveTypeEntry *>(entry); } return 0; } ComplexTypeEntry *TypeDatabase::findComplexType(const QString &name) { TypeEntry *entry = findType(name); if (entry != 0 && entry->isComplex()) return static_cast<ComplexTypeEntry *>(entry); else return 0; } ObjectTypeEntry *TypeDatabase::findObjectType(const QString &name) { TypeEntry *entry = findType(name); if (entry != 0 && entry->isObject()) return static_cast<ObjectTypeEntry *>(entry); else return 0; } NamespaceTypeEntry *TypeDatabase::findNamespaceType(const QString &name) { TypeEntry *entry = findType(name); if (entry != 0 && entry->isNamespace()) return static_cast<NamespaceTypeEntry *>(entry); else return 0; } bool TypeDatabase::parseFile(const QString &filename, const QString &importInputDirectory, bool generate) { qDebug() << "Parsing file: " << filename; QFile file(filename); Q_ASSERT(file.exists()); QXmlInputSource source(&file); int count = m_entries.size(); QXmlSimpleReader reader; Handler handler(this, generate); if (!importInputDirectory.isNull()) handler.setImportInputDirectory(importInputDirectory); reader.setContentHandler(&handler); reader.setErrorHandler(&handler); bool ok = reader.parse(&source, false); int newCount = m_entries.size(); QString string = QString::fromLatin1("Parsed: '%1', %2 new entries") .arg(filename) .arg(newCount - count); qDebug() << string; //ReportHandler::debugSparse(string); return ok; } ContainerTypeEntry *TypeDatabase::findContainerType(const QString &name) { QString template_name = name; int pos = name.indexOf('<'); if (pos > 0) template_name = name.left(pos); TypeEntry *type_entry = findType(template_name); if (type_entry && type_entry->isContainer()) return static_cast<ContainerTypeEntry *>(type_entry); return 0; } PrimitiveTypeEntry *TypeDatabase::findTargetLangPrimitiveType(const QString &java_name) { foreach(QList<TypeEntry *> entries, m_entries.values()) { foreach(TypeEntry *e, entries) { if (e && e->isPrimitive()) { PrimitiveTypeEntry *pe = static_cast<PrimitiveTypeEntry *>(e); if (pe->targetLangName() == java_name && pe->preferredConversion()) return pe; } } } return 0; } IncludeList TypeDatabase::extraIncludes(const QString &className) { ComplexTypeEntry *typeEntry = findComplexType(className); if (typeEntry != 0) return typeEntry->extraIncludes(); else return IncludeList(); } void TypeDatabase::addRejection(const QString &class_name, const QString &function_name, const QString &field_name, const QString &enum_name) { TypeRejection r; r.class_name = class_name; r.function_name = function_name; r.field_name = field_name; r.enum_name = enum_name; m_rejections << r; } bool TypeDatabase::isClassRejected(const QString &class_name) { if (!m_rebuild_classes.isEmpty()) return !m_rebuild_classes.contains(class_name); foreach(const TypeRejection &r, m_rejections) if (r.class_name == class_name && r.function_name == "*" && r.field_name == "*" && r.enum_name == "*") { return true; } return false; } bool TypeDatabase::isEnumRejected(const QString &class_name, const QString &enum_name) { foreach(const TypeRejection &r, m_rejections) { if (r.enum_name == enum_name && (r.class_name == class_name || r.class_name == "*")) { return true; } } return false; } bool TypeDatabase::isFunctionRejected(const QString &class_name, const QString &function_name) { foreach(const TypeRejection &r, m_rejections) if (r.function_name == function_name && (r.class_name == class_name || r.class_name == "*")) return true; return false; } bool TypeDatabase::isFieldRejected(const QString &class_name, const QString &field_name) { foreach(const TypeRejection &r, m_rejections) if (r.field_name == field_name && (r.class_name == class_name || r.class_name == "*")) return true; return false; } FlagsTypeEntry *TypeDatabase::findFlagsType(const QString &name) const { FlagsTypeEntry *fte = (FlagsTypeEntry *) findType(name); return fte ? fte : (FlagsTypeEntry *) m_flags_entries.value(name); } QString TypeDatabase::globalNamespaceClassName(const TypeEntry * /*entry*/) { return QLatin1String("Global"); } static void removeFunction(ComplexTypeEntry *e, const char *signature) { FunctionModification mod; mod.signature = QMetaObject::normalizedSignature(signature); mod.removal = TypeSystem::All; e->addFunctionModification(mod); } static void injectCode(ComplexTypeEntry *e, const char *signature, const QByteArray &code, const ArgumentMap &args) { CodeSnip snip; snip.language = TypeSystem::NativeCode; snip.position = CodeSnip::Beginning; snip.addCode(QString::fromLatin1(code)); snip.argumentMap = args; FunctionModification mod; mod.signature = QMetaObject::normalizedSignature(signature); mod.snips << snip; mod.modifiers = Modification::CodeInjection; e->addFunctionModification(mod); } static void addRemoveFunctionToTemplates(TypeDatabase *db) { ContainerTypeEntry *qvector = db->findContainerType(QLatin1String("QVector")); removeFunction(qvector, "constData() const"); removeFunction(qvector, "data() const"); removeFunction(qvector, "data()"); removeFunction(qvector, "first()"); removeFunction(qvector, "last()"); removeFunction(qvector, "operator[](int)"); removeFunction(qvector, "operator[](int) const"); removeFunction(qvector, "operator=(QVector<T>)"); ContainerTypeEntry *qlist = db->findContainerType(QLatin1String("QList")); removeFunction(qlist, "constData() const"); removeFunction(qlist, "data() const"); removeFunction(qlist, "data()"); removeFunction(qlist, "back()"); removeFunction(qlist, "front()"); removeFunction(qlist, "first()"); removeFunction(qlist, "last()"); removeFunction(qlist, "operator[](int)"); removeFunction(qlist, "operator[](int) const"); removeFunction(qlist, "operator=(QList<T>)"); ContainerTypeEntry *qqueue = db->findContainerType(QLatin1String("QQueue")); removeFunction(qqueue, "head() const"); ArgumentMap args1; args1[1] = QLatin1String("$1"); ArgumentMap args2 = args1; args2[2] = QLatin1String("$2"); QByteArray code = "\nif ($1 >= __qt_this->size() || $1 < 0) {" "\n __jni_env->ThrowNew(__jni_env->FindClass(\"java/lang/IndexOutOfBoundsException\")," "\n QString::fromLatin1(\"Accessing container of size %3 at %4\")" "\n .arg(__qt_this->size()).arg($1).toLatin1());" "\n return;" "\n}"; QByteArray code_with_return = QByteArray(code).replace("return;", "return 0;"); QByteArray code_index_length = "\nif ($1 < 0 || $2 < 0 || ($1 + $2) >= __qt_this->size()) {" "\n __jni_env->ThrowNew(__jni_env->FindClass(\"java/lang/IndexOutOfBoundsException\")," "\n QString::fromLatin1(\"Accessing container of size %3 from %4 to %5\")" "\n .arg(__qt_this->size()).arg($1).arg($1+$2).toLatin1());" "\n return;" "\n}"; QByteArray code_non_empty = "\nif (__qt_this->isEmpty()) {" "\n __jni_env->ThrowNew(__jni_env->FindClass(\"java/lang/IndexOutOfBoundsException\")," "\n QString::fromLatin1(\"Accessing empty container...\").toLatin1());" "\n return;" "\n}"; QByteArray code_two_indices = "\nif ($1 < 0 || $2 < 0 || $1 >= __qt_this->size() || $2 >= __qt_this->size()) {" "\n __jni_env->ThrowNew(__jni_env->FindClass(\"java/lang/IndexOutOfBoundsException\")," "\n QString::fromLatin1(\"Accessing container of size %3 at %4 and at %5\")" "\n .arg(__qt_this->size()).arg($1).arg($1+$2).toLatin1());" "\n return;" "\n}"; { // QVector safty... injectCode(qvector, "at(int) const", code_with_return, args1); injectCode(qvector, "replace(int,T)", code, args1); injectCode(qvector, "remove(int)", code, args1); injectCode(qvector, "remove(int, int)", code_index_length, args2); injectCode(qvector, "pop_back()", code_non_empty, ArgumentMap()); injectCode(qvector, "pop_front()", code_non_empty, ArgumentMap()); } { // QList safty... injectCode(qlist, "at(int) const", code_with_return, args1); injectCode(qlist, "replace(int, T)", code, args1); injectCode(qlist, "pop_back()", code_non_empty, ArgumentMap()); injectCode(qlist, "pop_front()", code_non_empty, ArgumentMap()); injectCode(qlist, "swap(int, int)", code_two_indices, args2); injectCode(qlist, "move(int, int)", code_two_indices, args2); injectCode(qlist, "removeAt(int)", code, args1); injectCode(qlist, "takeAt(int)", code_with_return, args1); } } <commit_msg>(split) remove extra addition from exception message text so that message text has correct values<commit_after> #include "typedatabase.h" #include "../customtypes.h" #include <QDebug> #include <qfile.h> #include <qxml.h> #include "handler.h" #include "../reporthandler.h" static void addRemoveFunctionToTemplates(TypeDatabase *db); TypeDatabase::TypeDatabase() : m_suppressWarnings(true), m_includeEclipseWarnings(false) { addType(new StringTypeEntry("QString")); StringTypeEntry *e = new StringTypeEntry("QLatin1String"); e->setPreferredConversion(false); addType(e); // We need the generator to perform type conversion in C++ with the // construct: // QString qstring = QString("string"); QStringRef(&qstring)" // not with: // (const QStringRef &)QString("string") StringRefTypeEntry *sr = new StringRefTypeEntry("QStringRef"); addType(sr); // TODO: Use of StringRefTypeEntry for QXmlStreamStringRef has not been tested, // I am sure the previous code would cause a crash. sr = new StringRefTypeEntry("QXmlStreamStringRef"); sr->setPreferredConversion(false); addType(sr); addType(new CharTypeEntry("QChar")); CharTypeEntry *c = new CharTypeEntry("QLatin1Char"); c->setPreferredConversion(false); addType(c); { VariantTypeEntry *qvariant = new VariantTypeEntry("QVariant"); qvariant->setCodeGeneration(TypeEntry::GenerateNothing); addType(qvariant); } { JObjectWrapperTypeEntry *wrapper = new JObjectWrapperTypeEntry("JObjectWrapper"); wrapper->setCodeGeneration(TypeEntry::GenerateNothing); addType(wrapper); } addType(new ThreadTypeEntry()); addType(new VoidTypeEntry()); // Predefined containers... addType(new ContainerTypeEntry("QList", ContainerTypeEntry::ListContainer)); addType(new ContainerTypeEntry("QStringList", ContainerTypeEntry::StringListContainer)); addType(new ContainerTypeEntry("QLinkedList", ContainerTypeEntry::LinkedListContainer)); addType(new ContainerTypeEntry("QVector", ContainerTypeEntry::VectorContainer)); addType(new ContainerTypeEntry("QStack", ContainerTypeEntry::StackContainer)); addType(new ContainerTypeEntry("QSet", ContainerTypeEntry::SetContainer)); addType(new ContainerTypeEntry("QMap", ContainerTypeEntry::MapContainer)); addType(new ContainerTypeEntry("QHash", ContainerTypeEntry::HashContainer)); addType(new ContainerTypeEntry("QPair", ContainerTypeEntry::PairContainer)); addType(new ContainerTypeEntry("QQueue", ContainerTypeEntry::QueueContainer)); addType(new ContainerTypeEntry("QMultiMap", ContainerTypeEntry::MultiMapContainer)); // Custom types... addType(new QModelIndexTypeEntry()); addRemoveFunctionToTemplates(this); } TypeDatabase *TypeDatabase::instance() { static TypeDatabase *db = new TypeDatabase(); return db; } TypeEntry *TypeDatabase::findType(const QString &name) const { QList<TypeEntry *> entries = findTypes(name); foreach(TypeEntry *entry, entries) { //qDebug()<<"findType()"<<entry; if (entry != 0 && (!entry->isPrimitive() || static_cast<PrimitiveTypeEntry *>(entry)->preferredTargetLangType())) { return entry; } } return 0; } SingleTypeEntryHash TypeDatabase::entries() { TypeEntryHash entries = allEntries(); SingleTypeEntryHash returned; QList<QString> keys = entries.keys(); foreach(QString key, keys) { returned[key] = findType(key); } return returned; } bool TypeDatabase::isSuppressedWarning(const QString &s) { if (!m_suppressWarnings) return false; foreach(const QString &_warning, m_suppressedWarnings) { QString warning(QString(_warning).replace("\\*", "&place_holder_for_asterisk;")); QStringList segs = warning.split("*", QString::SkipEmptyParts); if (segs.size() == 0) continue ; int i = 0; int pos = s.indexOf(QString(segs.at(i++)).replace("&place_holder_for_asterisk;", "*")); //qDebug() << "s == " << s << ", warning == " << segs; while (pos != -1) { if (i == segs.size()) return true; pos = s.indexOf(QString(segs.at(i++)).replace("&place_holder_for_asterisk;", "*"), pos); } } return false; } PrimitiveTypeEntry *TypeDatabase::findPrimitiveType(const QString &name) { QList<TypeEntry *> entries = findTypes(name); foreach(TypeEntry *entry, entries) { if (entry != 0 && entry->isPrimitive() && static_cast<PrimitiveTypeEntry *>(entry)->preferredTargetLangType()) return static_cast<PrimitiveTypeEntry *>(entry); } return 0; } ComplexTypeEntry *TypeDatabase::findComplexType(const QString &name) { TypeEntry *entry = findType(name); if (entry != 0 && entry->isComplex()) return static_cast<ComplexTypeEntry *>(entry); else return 0; } ObjectTypeEntry *TypeDatabase::findObjectType(const QString &name) { TypeEntry *entry = findType(name); if (entry != 0 && entry->isObject()) return static_cast<ObjectTypeEntry *>(entry); else return 0; } NamespaceTypeEntry *TypeDatabase::findNamespaceType(const QString &name) { TypeEntry *entry = findType(name); if (entry != 0 && entry->isNamespace()) return static_cast<NamespaceTypeEntry *>(entry); else return 0; } bool TypeDatabase::parseFile(const QString &filename, const QString &importInputDirectory, bool generate) { qDebug() << "Parsing file: " << filename; QFile file(filename); Q_ASSERT(file.exists()); QXmlInputSource source(&file); int count = m_entries.size(); QXmlSimpleReader reader; Handler handler(this, generate); if (!importInputDirectory.isNull()) handler.setImportInputDirectory(importInputDirectory); reader.setContentHandler(&handler); reader.setErrorHandler(&handler); bool ok = reader.parse(&source, false); int newCount = m_entries.size(); QString string = QString::fromLatin1("Parsed: '%1', %2 new entries") .arg(filename) .arg(newCount - count); qDebug() << string; //ReportHandler::debugSparse(string); return ok; } ContainerTypeEntry *TypeDatabase::findContainerType(const QString &name) { QString template_name = name; int pos = name.indexOf('<'); if (pos > 0) template_name = name.left(pos); TypeEntry *type_entry = findType(template_name); if (type_entry && type_entry->isContainer()) return static_cast<ContainerTypeEntry *>(type_entry); return 0; } PrimitiveTypeEntry *TypeDatabase::findTargetLangPrimitiveType(const QString &java_name) { foreach(QList<TypeEntry *> entries, m_entries.values()) { foreach(TypeEntry *e, entries) { if (e && e->isPrimitive()) { PrimitiveTypeEntry *pe = static_cast<PrimitiveTypeEntry *>(e); if (pe->targetLangName() == java_name && pe->preferredConversion()) return pe; } } } return 0; } IncludeList TypeDatabase::extraIncludes(const QString &className) { ComplexTypeEntry *typeEntry = findComplexType(className); if (typeEntry != 0) return typeEntry->extraIncludes(); else return IncludeList(); } void TypeDatabase::addRejection(const QString &class_name, const QString &function_name, const QString &field_name, const QString &enum_name) { TypeRejection r; r.class_name = class_name; r.function_name = function_name; r.field_name = field_name; r.enum_name = enum_name; m_rejections << r; } bool TypeDatabase::isClassRejected(const QString &class_name) { if (!m_rebuild_classes.isEmpty()) return !m_rebuild_classes.contains(class_name); foreach(const TypeRejection &r, m_rejections) if (r.class_name == class_name && r.function_name == "*" && r.field_name == "*" && r.enum_name == "*") { return true; } return false; } bool TypeDatabase::isEnumRejected(const QString &class_name, const QString &enum_name) { foreach(const TypeRejection &r, m_rejections) { if (r.enum_name == enum_name && (r.class_name == class_name || r.class_name == "*")) { return true; } } return false; } bool TypeDatabase::isFunctionRejected(const QString &class_name, const QString &function_name) { foreach(const TypeRejection &r, m_rejections) if (r.function_name == function_name && (r.class_name == class_name || r.class_name == "*")) return true; return false; } bool TypeDatabase::isFieldRejected(const QString &class_name, const QString &field_name) { foreach(const TypeRejection &r, m_rejections) if (r.field_name == field_name && (r.class_name == class_name || r.class_name == "*")) return true; return false; } FlagsTypeEntry *TypeDatabase::findFlagsType(const QString &name) const { FlagsTypeEntry *fte = (FlagsTypeEntry *) findType(name); return fte ? fte : (FlagsTypeEntry *) m_flags_entries.value(name); } QString TypeDatabase::globalNamespaceClassName(const TypeEntry * /*entry*/) { return QLatin1String("Global"); } static void removeFunction(ComplexTypeEntry *e, const char *signature) { FunctionModification mod; mod.signature = QMetaObject::normalizedSignature(signature); mod.removal = TypeSystem::All; e->addFunctionModification(mod); } static void injectCode(ComplexTypeEntry *e, const char *signature, const QByteArray &code, const ArgumentMap &args) { CodeSnip snip; snip.language = TypeSystem::NativeCode; snip.position = CodeSnip::Beginning; snip.addCode(QString::fromLatin1(code)); snip.argumentMap = args; FunctionModification mod; mod.signature = QMetaObject::normalizedSignature(signature); mod.snips << snip; mod.modifiers = Modification::CodeInjection; e->addFunctionModification(mod); } static void addRemoveFunctionToTemplates(TypeDatabase *db) { ContainerTypeEntry *qvector = db->findContainerType(QLatin1String("QVector")); removeFunction(qvector, "constData() const"); removeFunction(qvector, "data() const"); removeFunction(qvector, "data()"); removeFunction(qvector, "first()"); removeFunction(qvector, "last()"); removeFunction(qvector, "operator[](int)"); removeFunction(qvector, "operator[](int) const"); removeFunction(qvector, "operator=(QVector<T>)"); ContainerTypeEntry *qlist = db->findContainerType(QLatin1String("QList")); removeFunction(qlist, "constData() const"); removeFunction(qlist, "data() const"); removeFunction(qlist, "data()"); removeFunction(qlist, "back()"); removeFunction(qlist, "front()"); removeFunction(qlist, "first()"); removeFunction(qlist, "last()"); removeFunction(qlist, "operator[](int)"); removeFunction(qlist, "operator[](int) const"); removeFunction(qlist, "operator=(QList<T>)"); ContainerTypeEntry *qqueue = db->findContainerType(QLatin1String("QQueue")); removeFunction(qqueue, "head() const"); ArgumentMap args1; args1[1] = QLatin1String("$1"); ArgumentMap args2 = args1; args2[2] = QLatin1String("$2"); QByteArray code = "\nif ($1 >= __qt_this->size() || $1 < 0) {" "\n __jni_env->ThrowNew(__jni_env->FindClass(\"java/lang/IndexOutOfBoundsException\")," "\n QString::fromLatin1(\"Accessing container of size %3 at %4\")" "\n .arg(__qt_this->size()).arg($1).toLatin1());" "\n return;" "\n}"; QByteArray code_with_return = QByteArray(code).replace("return;", "return 0;"); QByteArray code_index_length = "\nif ($1 < 0 || $2 < 0 || ($1 + $2) >= __qt_this->size()) {" "\n __jni_env->ThrowNew(__jni_env->FindClass(\"java/lang/IndexOutOfBoundsException\")," "\n QString::fromLatin1(\"Accessing container of size %3 from %4 to %5\")" "\n .arg(__qt_this->size()).arg($1).arg($1+$2).toLatin1());" "\n return;" "\n}"; QByteArray code_non_empty = "\nif (__qt_this->isEmpty()) {" "\n __jni_env->ThrowNew(__jni_env->FindClass(\"java/lang/IndexOutOfBoundsException\")," "\n QString::fromLatin1(\"Accessing empty container...\").toLatin1());" "\n return;" "\n}"; QByteArray code_two_indices = "\nif ($1 < 0 || $2 < 0 || $1 >= __qt_this->size() || $2 >= __qt_this->size()) {" "\n __jni_env->ThrowNew(__jni_env->FindClass(\"java/lang/IndexOutOfBoundsException\")," "\n QString::fromLatin1(\"Accessing container of size %3 at %4 and at %5\")" "\n .arg(__qt_this->size()).arg($1).arg($2).toLatin1());" "\n return;" "\n}"; { // QVector safty... injectCode(qvector, "at(int) const", code_with_return, args1); injectCode(qvector, "replace(int,T)", code, args1); injectCode(qvector, "remove(int)", code, args1); injectCode(qvector, "remove(int, int)", code_index_length, args2); injectCode(qvector, "pop_back()", code_non_empty, ArgumentMap()); injectCode(qvector, "pop_front()", code_non_empty, ArgumentMap()); } { // QList safty... injectCode(qlist, "at(int) const", code_with_return, args1); injectCode(qlist, "replace(int, T)", code, args1); injectCode(qlist, "pop_back()", code_non_empty, ArgumentMap()); injectCode(qlist, "pop_front()", code_non_empty, ArgumentMap()); injectCode(qlist, "swap(int, int)", code_two_indices, args2); injectCode(qlist, "move(int, int)", code_two_indices, args2); injectCode(qlist, "removeAt(int)", code, args1); injectCode(qlist, "takeAt(int)", code_with_return, args1); } } <|endoftext|>
<commit_before>#include "text_element.hpp" #include "screen.hpp" #include "resource_cache.hpp" #include "resource_manager.hpp" #include "overlay_renderer.hpp" #include "glyph.hpp" #include "resource.hpp" #include "../base/logging.hpp" namespace graphics { TextElement::TextElement(Params const & p) : OverlayElement(p), m_fontDesc(p.m_fontDesc), m_auxFontDesc(p.m_auxFontDesc), m_logText(p.m_logText), m_auxLogText(p.m_auxLogText), m_log2vis(p.m_log2vis) { if (m_log2vis) { m_visText = p.m_glyphCache->log2vis(m_logText); if (!m_auxLogText.empty()) m_auxVisText = p.m_glyphCache->log2vis(m_auxLogText); } else { m_visText = m_logText; m_auxVisText = m_auxLogText; } } strings::UniString const & TextElement::logText() const { return m_logText; } strings::UniString const & TextElement::auxLogText() const { return m_auxLogText; } strings::UniString const & TextElement::visText() const { return m_visText; } strings::UniString const & TextElement::auxVisText() const { return m_auxVisText; } FontDesc const & TextElement::fontDesc() const { return m_fontDesc; } FontDesc const & TextElement::auxFontDesc() const { return m_auxFontDesc; } bool TextElement::isBidi() const { return m_logText != m_visText; } bool TextElement::isAuxBidi() const { return m_auxLogText != m_auxVisText; } void TextElement::drawTextImpl(GlyphLayout const & layout, OverlayRenderer * screen, math::Matrix<double, 3, 3> const & m, bool doTransformPivotOnly, bool doAlignPivot, FontDesc const & fontDesc, double depth) const { if (!fontDesc.IsValid()) return; m2::PointD pv = layout.pivot(); m2::PointD offs = layout.offset(); double deltaA = 0; if (doTransformPivotOnly) pv *= m; else { double k = (sqrt((m(0, 0) * m(0, 0) + m(0, 1) * m(0, 1) + m(1, 0) * m(1, 0) + m(1, 1) * m(1, 1)) / 2)); if ((k > 1.1) || (k < 1 / 1.1)) return; deltaA = (ang::AngleD(0) * m).val(); } size_t cnt = layout.entries().size(); buffer_vector<Glyph::Info, 32> glyphInfos(cnt); buffer_vector<Resource::Info const *, 32> resInfos(cnt); buffer_vector<uint32_t, 32> glyphIDs(cnt); unsigned firstVis = layout.firstVisible(); unsigned lastVis = layout.lastVisible(); /// collecting all glyph infos in one array and packing them as a whole. for (unsigned i = firstVis; i < lastVis; ++i) { GlyphKey glyphKey(layout.entries()[i].m_sym, fontDesc.m_size, fontDesc.m_isMasked, fontDesc.m_isMasked ? fontDesc.m_maskColor : fontDesc.m_color); glyphInfos[i] = Glyph::Info(glyphKey, screen->glyphCache()); resInfos[i] = &glyphInfos[i]; } if ((firstVis != lastVis) && !screen->mapInfo(&resInfos[firstVis], &glyphIDs[firstVis], lastVis - firstVis)) { LOG(LINFO, ("cannot render string", lastVis - firstVis, "characters long")); return; } for (unsigned i = firstVis; i < lastVis; ++i) { GlyphLayoutElem const & elem = layout.entries()[i]; Glyph const * glyph = static_cast<Glyph const *>(screen->fromID(glyphIDs[i])); m2::PointD glyphPt; ang::AngleD glyphAngle; if (doTransformPivotOnly) { m2::PointD offsPt = offs + elem.m_pt; m2::PointD fullPt = pv + offs + elem.m_pt; offsPt.x -= fullPt.x - floor(fullPt.x); offsPt.y -= fullPt.y - floor(fullPt.y); screen->drawStraightGlyph(pv, offsPt, glyph, depth); } else { glyphPt = (pv + offs + elem.m_pt) * m; glyphAngle = ang::AngleD(elem.m_angle.val() + deltaA); screen->drawGlyph(glyphPt, m2::PointD(0.0, 0.0), glyphAngle, 0, glyph, depth); } } } } <commit_msg>[graphics] remove text jittering on drag<commit_after>#include "text_element.hpp" #include "screen.hpp" #include "resource_cache.hpp" #include "resource_manager.hpp" #include "overlay_renderer.hpp" #include "glyph.hpp" #include "resource.hpp" #include "../base/logging.hpp" namespace graphics { TextElement::TextElement(Params const & p) : OverlayElement(p), m_fontDesc(p.m_fontDesc), m_auxFontDesc(p.m_auxFontDesc), m_logText(p.m_logText), m_auxLogText(p.m_auxLogText), m_log2vis(p.m_log2vis) { if (m_log2vis) { m_visText = p.m_glyphCache->log2vis(m_logText); if (!m_auxLogText.empty()) m_auxVisText = p.m_glyphCache->log2vis(m_auxLogText); } else { m_visText = m_logText; m_auxVisText = m_auxLogText; } } strings::UniString const & TextElement::logText() const { return m_logText; } strings::UniString const & TextElement::auxLogText() const { return m_auxLogText; } strings::UniString const & TextElement::visText() const { return m_visText; } strings::UniString const & TextElement::auxVisText() const { return m_auxVisText; } FontDesc const & TextElement::fontDesc() const { return m_fontDesc; } FontDesc const & TextElement::auxFontDesc() const { return m_auxFontDesc; } bool TextElement::isBidi() const { return m_logText != m_visText; } bool TextElement::isAuxBidi() const { return m_auxLogText != m_auxVisText; } void TextElement::drawTextImpl(GlyphLayout const & layout, OverlayRenderer * screen, math::Matrix<double, 3, 3> const & m, bool doTransformPivotOnly, bool doAlignPivot, FontDesc const & fontDesc, double depth) const { if (!fontDesc.IsValid()) return; m2::PointD pv = layout.pivot(); m2::PointD offs = layout.offset(); double deltaA = 0; if (doTransformPivotOnly) pv *= m; else { double k = (sqrt((m(0, 0) * m(0, 0) + m(0, 1) * m(0, 1) + m(1, 0) * m(1, 0) + m(1, 1) * m(1, 1)) / 2)); if ((k > 1.1) || (k < 1 / 1.1)) return; deltaA = (ang::AngleD(0) * m).val(); } size_t cnt = layout.entries().size(); buffer_vector<Glyph::Info, 32> glyphInfos(cnt); buffer_vector<Resource::Info const *, 32> resInfos(cnt); buffer_vector<uint32_t, 32> glyphIDs(cnt); unsigned firstVis = layout.firstVisible(); unsigned lastVis = layout.lastVisible(); /// collecting all glyph infos in one array and packing them as a whole. for (unsigned i = firstVis; i < lastVis; ++i) { GlyphKey glyphKey(layout.entries()[i].m_sym, fontDesc.m_size, fontDesc.m_isMasked, fontDesc.m_isMasked ? fontDesc.m_maskColor : fontDesc.m_color); glyphInfos[i] = Glyph::Info(glyphKey, screen->glyphCache()); resInfos[i] = &glyphInfos[i]; } if ((firstVis != lastVis) && !screen->mapInfo(&resInfos[firstVis], &glyphIDs[firstVis], lastVis - firstVis)) { LOG(LINFO, ("cannot render string", lastVis - firstVis, "characters long")); return; } for (unsigned i = firstVis; i < lastVis; ++i) { GlyphLayoutElem const & elem = layout.entries()[i]; Glyph const * glyph = static_cast<Glyph const *>(screen->fromID(glyphIDs[i])); m2::PointD glyphPt; ang::AngleD glyphAngle; if (doTransformPivotOnly) { m2::PointD offsPt = offs + elem.m_pt; screen->drawStraightGlyph(pv, offsPt, glyph, depth); } else { glyphPt = (pv + offs + elem.m_pt) * m; glyphAngle = ang::AngleD(elem.m_angle.val() + deltaA); screen->drawGlyph(glyphPt, m2::PointD(0.0, 0.0), glyphAngle, 0, glyph, depth); } } } } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "AsyncVideoDecoder.h" #include "EOFVideoMsg.h" #include "ErrorVideoMsg.h" #include "SeekDoneVideoMsg.h" #include "../base/ObjectCounter.h" #include <boost/thread/thread.hpp> #include <boost/bind.hpp> #include <math.h> #include <iostream> using namespace boost; using namespace std; namespace avg { AsyncVideoDecoder::AsyncVideoDecoder(VideoDecoderPtr pSyncDecoder) : m_pSyncDecoder(pSyncDecoder), m_pVDecoderThread(0), m_pADecoderThread(0), m_Size(0,0), m_NumFrames(0), m_FPS(0), m_PF(NO_PIXELFORMAT), m_Duration(0), m_bAudioEOF(false), m_bVideoEOF(false), m_bSeekPending(false), m_Volume(1.0), m_LastVideoFrameTime(-1000), m_LastAudioFrameTime(-1000) { ObjectCounter::get()->incRef(&typeid(*this)); } AsyncVideoDecoder::~AsyncVideoDecoder() { if (m_pVDecoderThread || m_pADecoderThread) { close(); } ObjectCounter::get()->decRef(&typeid(*this)); } void AsyncVideoDecoder::open(const std::string& sFilename, const AudioParams* pAP, YCbCrMode ycbcrMode, bool bThreadedDemuxer) { m_bAudioEOF = false; m_bVideoEOF = false; m_bSeekPending = false; m_sFilename = sFilename; m_pSyncDecoder->open(m_sFilename, pAP, ycbcrMode, bThreadedDemuxer); m_bHasVideo = m_pSyncDecoder->hasVideo(); m_bHasAudio = m_pSyncDecoder->hasAudio(); m_Duration = m_pSyncDecoder->getDuration(); if (m_bHasVideo) { m_LastVideoFrameTime = -1000; m_Size = m_pSyncDecoder->getSize(); m_NumFrames = m_pSyncDecoder->getNumFrames(); m_FPS = m_pSyncDecoder->getFPS(); m_PF = m_pSyncDecoder->getPixelFormat(); m_StreamFPS = m_pSyncDecoder->getNominalFPS(); m_pVCmdQ = VideoDecoderThread::CmdQueuePtr(new VideoDecoderThread::CmdQueue); m_pVMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8)); m_pVDecoderThread = new boost::thread( VideoDecoderThread(*m_pVCmdQ, *m_pVMsgQ, m_pSyncDecoder)); } if (m_bHasAudio) { m_pACmdQ = AudioDecoderThread::CmdQueuePtr(new AudioDecoderThread::CmdQueue); m_pAMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8)); m_pADecoderThread = new boost::thread( AudioDecoderThread(*m_pACmdQ, *m_pAMsgQ, m_pSyncDecoder, *pAP)); m_AudioMsgData = 0; m_AudioMsgSize = 0; m_LastAudioFrameTime = 0; } } void AsyncVideoDecoder::close() { if (m_pVDecoderThread) { m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind( &VideoDecoderThread::stop, _1))); getNextBmps(false); // If the Queue is full, this breaks the lock in the thread. m_pVDecoderThread->join(); delete m_pVDecoderThread; m_pVDecoderThread = 0; } { scoped_lock Lock1(m_AudioMutex); if (m_pADecoderThread) { m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind( &AudioDecoderThread::stop, _1))); try { m_pAMsgQ->pop(false); } catch(Exception&) {} m_pADecoderThread->join(); delete m_pADecoderThread; m_pADecoderThread = 0; } m_pSyncDecoder->close(); } } void AsyncVideoDecoder::seek(long long DestTime) { waitForSeekDone(); scoped_lock Lock1(m_AudioMutex); scoped_lock Lock2(m_SeekMutex); m_bAudioEOF = false; m_bVideoEOF = false; m_bSeekPending = false; m_LastVideoFrameTime = -1000; m_bSeekPending = true; if (m_pVCmdQ) { m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind( &VideoDecoderThread::seek, _1, DestTime))); } else { m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind( &AudioDecoderThread::seek, _1, DestTime))); } try { while (m_bSeekPending) { VideoMsgPtr pMsg; if (m_pVCmdQ) { pMsg = m_pVMsgQ->pop(false); } else { pMsg = m_pAMsgQ->pop(false); } SeekDoneVideoMsgPtr pSeekDoneMsg = dynamic_pointer_cast<SeekDoneVideoMsg>(pMsg); if (pSeekDoneMsg) { m_bSeekPending = false; m_LastVideoFrameTime = pSeekDoneMsg->getVideoFrameTime(); m_LastAudioFrameTime = pSeekDoneMsg->getAudioFrameTime(); } } } catch (Exception&) { } } StreamSelect AsyncVideoDecoder::getMasterStream() { if (m_bHasAudio) { return SS_AUDIO; } else { return SS_VIDEO; } } bool AsyncVideoDecoder::hasVideo() { return m_bHasVideo; } bool AsyncVideoDecoder::hasAudio() { return m_bHasAudio; } IntPoint AsyncVideoDecoder::getSize() { return m_Size; } int AsyncVideoDecoder::getCurFrame() { return int(getCurTime(SS_VIDEO)*m_StreamFPS/1000.0+0.5); } int AsyncVideoDecoder::getNumFrames() { if (m_NumFrames == 0) { throw Exception(AVG_ERR_VIDEO_GENERAL, "Error in AsyncVideoDecoder::getNumFrames: Video not loaded."); } return m_NumFrames; } int AsyncVideoDecoder::getNumFramesQueued() { return m_pVMsgQ->size(); } long long AsyncVideoDecoder::getCurTime(StreamSelect Stream) { switch(Stream) { case SS_VIDEO: assert(m_bHasVideo); return m_LastVideoFrameTime; break; case SS_AUDIO: assert(m_bHasAudio); return m_LastAudioFrameTime; break; case SS_DEFAULT: return getCurTime(getMasterStream()); break; default: assert(false); } return -1; } long long AsyncVideoDecoder::getDuration() { return m_Duration; } double AsyncVideoDecoder::getNominalFPS() { return m_StreamFPS; } double AsyncVideoDecoder::getFPS() { assert(m_pVDecoderThread); return m_FPS; } void AsyncVideoDecoder::setFPS(double FPS) { assert(!m_pADecoderThread); m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind( &VideoDecoderThread::setFPS, _1, FPS))); if (FPS != 0) { m_FPS = FPS; } } double AsyncVideoDecoder::getVolume() { return m_Volume; } void AsyncVideoDecoder::setVolume(double Volume) { m_Volume = Volume; if (m_bHasAudio) { m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind( &AudioDecoderThread::setVolume, _1, Volume))); } } PixelFormat AsyncVideoDecoder::getPixelFormat() { assert(m_pVDecoderThread); return m_PF; } FrameAvailableCode AsyncVideoDecoder::renderToBmp(BitmapPtr pBmp, long long TimeWanted) { FrameAvailableCode FrameAvailable; FrameVideoMsgPtr pFrameMsg = getBmpsForTime(TimeWanted, FrameAvailable); if (FrameAvailable == FA_NEW_FRAME) { pBmp->copyPixels(*(pFrameMsg->getBitmap(0))); } return FrameAvailable; } FrameAvailableCode AsyncVideoDecoder::renderToYCbCr420p(BitmapPtr pBmpY, BitmapPtr pBmpCb, BitmapPtr pBmpCr, long long TimeWanted) { FrameAvailableCode FrameAvailable; FrameVideoMsgPtr pFrameMsg = getBmpsForTime(TimeWanted, FrameAvailable); if (FrameAvailable == FA_NEW_FRAME) { pBmpY->copyPixels(*(pFrameMsg->getBitmap(0))); pBmpCb->copyPixels(*(pFrameMsg->getBitmap(1))); pBmpCr->copyPixels(*(pFrameMsg->getBitmap(2))); } return FrameAvailable; } bool AsyncVideoDecoder::isEOF(StreamSelect Stream) { switch(Stream) { case SS_AUDIO: return (!m_bHasAudio || m_bAudioEOF); case SS_VIDEO: return (!m_bHasVideo || m_bVideoEOF); case SS_ALL: return isEOF(SS_VIDEO) && isEOF(SS_AUDIO); default: return false; } } int AsyncVideoDecoder::fillAudioBuffer(AudioBufferPtr pBuffer) { assert (m_pADecoderThread); if (m_bAudioEOF) { return 0; } scoped_lock Lock(m_AudioMutex); waitForSeekDone(); unsigned char* audioBuffer = (unsigned char *)(pBuffer->getData()); int audioBufferSize = pBuffer->getNumBytes(); int bufferLeftToFill = audioBufferSize; while (bufferLeftToFill > 0) { while (m_AudioMsgSize > 0 && bufferLeftToFill > 0) { int copyBytes = min(bufferLeftToFill, m_AudioMsgSize); memcpy(audioBuffer, m_AudioMsgData, copyBytes); m_AudioMsgSize -= copyBytes; m_AudioMsgData += copyBytes; bufferLeftToFill -= copyBytes; audioBuffer += copyBytes; m_LastAudioFrameTime += (long long)(1000.0 * copyBytes / (pBuffer->getFrameSize() * pBuffer->getRate())); } if (bufferLeftToFill != 0) { try { VideoMsgPtr pMsg = m_pAMsgQ->pop(false); EOFVideoMsgPtr pEOFMsg(dynamic_pointer_cast<EOFVideoMsg>(pMsg)); if (pEOFMsg) { m_bAudioEOF = true; return pBuffer->getNumFrames()-bufferLeftToFill/pBuffer->getFrameSize(); } m_pAudioMsg = dynamic_pointer_cast<AudioVideoMsg>(pMsg); assert(m_pAudioMsg); m_AudioMsgSize = m_pAudioMsg->getBuffer()->getNumFrames() *pBuffer->getFrameSize(); m_AudioMsgData = (unsigned char *)(m_pAudioMsg->getBuffer()->getData()); m_LastAudioFrameTime = m_pAudioMsg->getTime(); } catch (Exception &) { return pBuffer->getNumFrames()-bufferLeftToFill/pBuffer->getFrameSize(); } } } return pBuffer->getNumFrames(); } FrameVideoMsgPtr AsyncVideoDecoder::getBmpsForTime(long long TimeWanted, FrameAvailableCode& FrameAvailable) { // XXX: This code is sort-of duplicated in FFMpegDecoder::readFrameForTime() long long FrameTime = -1000; FrameVideoMsgPtr pFrameMsg; if (TimeWanted == -1) { pFrameMsg = getNextBmps(true); FrameAvailable = FA_NEW_FRAME; } else { if (getMasterStream() == SS_AUDIO) { TimeWanted = m_LastAudioFrameTime; } // cerr << "getBmpsForTime " << TimeWanted << ", LastFrameTime= " << m_LastVideoFrameTime // << ", diff= " << TimeWanted-m_LastVideoFrameTime << endl; double TimePerFrame = 1000.0/getFPS(); if (fabs(double(TimeWanted-m_LastVideoFrameTime)) < 0.5*TimePerFrame || m_LastVideoFrameTime > TimeWanted+TimePerFrame) { // cerr << " LastFrameTime = " << m_LastVideoFrameTime << ", display again." << endl; // The last frame is still current. Display it again. FrameAvailable = FA_USE_LAST_FRAME; return FrameVideoMsgPtr(); } else { if (m_bVideoEOF) { // cerr << " EOF." << endl; FrameAvailable = FA_USE_LAST_FRAME; return FrameVideoMsgPtr(); } while (FrameTime-TimeWanted < -0.5*TimePerFrame && !m_bVideoEOF) { pFrameMsg = getNextBmps(false); if (pFrameMsg) { FrameTime = pFrameMsg->getFrameTime(); // cerr << " readFrame returned time " << FrameTime << "." << endl; } else { // cerr << " no frame available." << endl; FrameAvailable = FA_STILL_DECODING; return FrameVideoMsgPtr(); } } FrameAvailable = FA_NEW_FRAME; // cerr << " frame ok." << endl; } } if (pFrameMsg) { m_LastVideoFrameTime = pFrameMsg->getFrameTime(); } return pFrameMsg; } FrameVideoMsgPtr AsyncVideoDecoder::getNextBmps(bool bWait) { try { waitForSeekDone(); VideoMsgPtr pMsg = m_pVMsgQ->pop(bWait); FrameVideoMsgPtr pFrameMsg = dynamic_pointer_cast<FrameVideoMsg>(pMsg); while (!pFrameMsg) { EOFVideoMsgPtr pEOFMsg(dynamic_pointer_cast<EOFVideoMsg>(pMsg)); ErrorVideoMsgPtr pErrorMsg(dynamic_pointer_cast<ErrorVideoMsg>(pMsg)); if (pEOFMsg) { m_bVideoEOF = true; return FrameVideoMsgPtr(); } else if (pErrorMsg) { m_bVideoEOF = true; return FrameVideoMsgPtr(); } else { // Unhandled message type. assert(false); } pMsg = m_pVMsgQ->pop(bWait); pFrameMsg = dynamic_pointer_cast<FrameVideoMsg>(pMsg); } return pFrameMsg; } catch (Exception&) { return FrameVideoMsgPtr(); } } void AsyncVideoDecoder::waitForSeekDone() { scoped_lock Lock(m_SeekMutex); if (m_bSeekPending) { do { VideoMsgPtr pMsg; if (m_pVCmdQ) { pMsg = m_pVMsgQ->pop(true); } else { pMsg = m_pAMsgQ->pop(true); } SeekDoneVideoMsgPtr pSeekDoneMsg = dynamic_pointer_cast<SeekDoneVideoMsg>(pMsg); if (pSeekDoneMsg) { m_bSeekPending = false; m_LastVideoFrameTime = pSeekDoneMsg->getVideoFrameTime(); m_LastAudioFrameTime = pSeekDoneMsg->getAudioFrameTime(); } } while (m_bSeekPending); } } } <commit_msg>workaround for audio threading issue<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "AsyncVideoDecoder.h" #include "EOFVideoMsg.h" #include "ErrorVideoMsg.h" #include "SeekDoneVideoMsg.h" #include "../base/ObjectCounter.h" #include <boost/thread/thread.hpp> #include <boost/bind.hpp> #include <math.h> #include <iostream> using namespace boost; using namespace std; namespace avg { AsyncVideoDecoder::AsyncVideoDecoder(VideoDecoderPtr pSyncDecoder) : m_pSyncDecoder(pSyncDecoder), m_pVDecoderThread(0), m_pADecoderThread(0), m_Size(0,0), m_NumFrames(0), m_FPS(0), m_PF(NO_PIXELFORMAT), m_Duration(0), m_bAudioEOF(false), m_bVideoEOF(false), m_bSeekPending(false), m_Volume(1.0), m_LastVideoFrameTime(-1000), m_LastAudioFrameTime(-1000) { ObjectCounter::get()->incRef(&typeid(*this)); } AsyncVideoDecoder::~AsyncVideoDecoder() { if (m_pVDecoderThread || m_pADecoderThread) { close(); } ObjectCounter::get()->decRef(&typeid(*this)); } void AsyncVideoDecoder::open(const std::string& sFilename, const AudioParams* pAP, YCbCrMode ycbcrMode, bool bThreadedDemuxer) { m_bAudioEOF = false; m_bVideoEOF = false; m_bSeekPending = false; m_sFilename = sFilename; m_pSyncDecoder->open(m_sFilename, pAP, ycbcrMode, bThreadedDemuxer); m_bHasVideo = m_pSyncDecoder->hasVideo(); m_bHasAudio = m_pSyncDecoder->hasAudio(); m_Duration = m_pSyncDecoder->getDuration(); if (m_bHasVideo) { m_LastVideoFrameTime = -1000; m_Size = m_pSyncDecoder->getSize(); m_NumFrames = m_pSyncDecoder->getNumFrames(); m_FPS = m_pSyncDecoder->getFPS(); m_PF = m_pSyncDecoder->getPixelFormat(); m_StreamFPS = m_pSyncDecoder->getNominalFPS(); m_pVCmdQ = VideoDecoderThread::CmdQueuePtr(new VideoDecoderThread::CmdQueue); m_pVMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8)); m_pVDecoderThread = new boost::thread( VideoDecoderThread(*m_pVCmdQ, *m_pVMsgQ, m_pSyncDecoder)); } if (m_bHasAudio) { m_pACmdQ = AudioDecoderThread::CmdQueuePtr(new AudioDecoderThread::CmdQueue); m_pAMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8)); m_pADecoderThread = new boost::thread( AudioDecoderThread(*m_pACmdQ, *m_pAMsgQ, m_pSyncDecoder, *pAP)); m_AudioMsgData = 0; m_AudioMsgSize = 0; m_LastAudioFrameTime = 0; } } void AsyncVideoDecoder::close() { if (m_pVDecoderThread) { m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind( &VideoDecoderThread::stop, _1))); getNextBmps(false); // If the Queue is full, this breaks the lock in the thread. m_pVDecoderThread->join(); delete m_pVDecoderThread; m_pVDecoderThread = 0; } { scoped_lock Lock1(m_AudioMutex); if (m_pADecoderThread) { m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind( &AudioDecoderThread::stop, _1))); try { m_pAMsgQ->pop(false); m_pAMsgQ->pop(false); } catch(Exception&) {} m_pADecoderThread->join(); delete m_pADecoderThread; m_pADecoderThread = 0; } m_pSyncDecoder->close(); } } void AsyncVideoDecoder::seek(long long DestTime) { waitForSeekDone(); scoped_lock Lock1(m_AudioMutex); scoped_lock Lock2(m_SeekMutex); m_bAudioEOF = false; m_bVideoEOF = false; m_bSeekPending = false; m_LastVideoFrameTime = -1000; m_bSeekPending = true; if (m_pVCmdQ) { m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind( &VideoDecoderThread::seek, _1, DestTime))); } else { m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind( &AudioDecoderThread::seek, _1, DestTime))); } try { while (m_bSeekPending) { VideoMsgPtr pMsg; if (m_pVCmdQ) { pMsg = m_pVMsgQ->pop(false); } else { pMsg = m_pAMsgQ->pop(false); } SeekDoneVideoMsgPtr pSeekDoneMsg = dynamic_pointer_cast<SeekDoneVideoMsg>(pMsg); if (pSeekDoneMsg) { m_bSeekPending = false; m_LastVideoFrameTime = pSeekDoneMsg->getVideoFrameTime(); m_LastAudioFrameTime = pSeekDoneMsg->getAudioFrameTime(); } } } catch (Exception&) { } } StreamSelect AsyncVideoDecoder::getMasterStream() { if (m_bHasAudio) { return SS_AUDIO; } else { return SS_VIDEO; } } bool AsyncVideoDecoder::hasVideo() { return m_bHasVideo; } bool AsyncVideoDecoder::hasAudio() { return m_bHasAudio; } IntPoint AsyncVideoDecoder::getSize() { return m_Size; } int AsyncVideoDecoder::getCurFrame() { return int(getCurTime(SS_VIDEO)*m_StreamFPS/1000.0+0.5); } int AsyncVideoDecoder::getNumFrames() { if (m_NumFrames == 0) { throw Exception(AVG_ERR_VIDEO_GENERAL, "Error in AsyncVideoDecoder::getNumFrames: Video not loaded."); } return m_NumFrames; } int AsyncVideoDecoder::getNumFramesQueued() { return m_pVMsgQ->size(); } long long AsyncVideoDecoder::getCurTime(StreamSelect Stream) { switch(Stream) { case SS_VIDEO: assert(m_bHasVideo); return m_LastVideoFrameTime; break; case SS_AUDIO: assert(m_bHasAudio); return m_LastAudioFrameTime; break; case SS_DEFAULT: return getCurTime(getMasterStream()); break; default: assert(false); } return -1; } long long AsyncVideoDecoder::getDuration() { return m_Duration; } double AsyncVideoDecoder::getNominalFPS() { return m_StreamFPS; } double AsyncVideoDecoder::getFPS() { assert(m_pVDecoderThread); return m_FPS; } void AsyncVideoDecoder::setFPS(double FPS) { assert(!m_pADecoderThread); m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind( &VideoDecoderThread::setFPS, _1, FPS))); if (FPS != 0) { m_FPS = FPS; } } double AsyncVideoDecoder::getVolume() { return m_Volume; } void AsyncVideoDecoder::setVolume(double Volume) { m_Volume = Volume; if (m_bHasAudio) { m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind( &AudioDecoderThread::setVolume, _1, Volume))); } } PixelFormat AsyncVideoDecoder::getPixelFormat() { assert(m_pVDecoderThread); return m_PF; } FrameAvailableCode AsyncVideoDecoder::renderToBmp(BitmapPtr pBmp, long long TimeWanted) { FrameAvailableCode FrameAvailable; FrameVideoMsgPtr pFrameMsg = getBmpsForTime(TimeWanted, FrameAvailable); if (FrameAvailable == FA_NEW_FRAME) { pBmp->copyPixels(*(pFrameMsg->getBitmap(0))); } return FrameAvailable; } FrameAvailableCode AsyncVideoDecoder::renderToYCbCr420p(BitmapPtr pBmpY, BitmapPtr pBmpCb, BitmapPtr pBmpCr, long long TimeWanted) { FrameAvailableCode FrameAvailable; FrameVideoMsgPtr pFrameMsg = getBmpsForTime(TimeWanted, FrameAvailable); if (FrameAvailable == FA_NEW_FRAME) { pBmpY->copyPixels(*(pFrameMsg->getBitmap(0))); pBmpCb->copyPixels(*(pFrameMsg->getBitmap(1))); pBmpCr->copyPixels(*(pFrameMsg->getBitmap(2))); } return FrameAvailable; } bool AsyncVideoDecoder::isEOF(StreamSelect Stream) { switch(Stream) { case SS_AUDIO: return (!m_bHasAudio || m_bAudioEOF); case SS_VIDEO: return (!m_bHasVideo || m_bVideoEOF); case SS_ALL: return isEOF(SS_VIDEO) && isEOF(SS_AUDIO); default: return false; } } int AsyncVideoDecoder::fillAudioBuffer(AudioBufferPtr pBuffer) { assert (m_pADecoderThread); if (m_bAudioEOF) { return 0; } scoped_lock Lock(m_AudioMutex); waitForSeekDone(); unsigned char* audioBuffer = (unsigned char *)(pBuffer->getData()); int audioBufferSize = pBuffer->getNumBytes(); int bufferLeftToFill = audioBufferSize; while (bufferLeftToFill > 0) { while (m_AudioMsgSize > 0 && bufferLeftToFill > 0) { int copyBytes = min(bufferLeftToFill, m_AudioMsgSize); memcpy(audioBuffer, m_AudioMsgData, copyBytes); m_AudioMsgSize -= copyBytes; m_AudioMsgData += copyBytes; bufferLeftToFill -= copyBytes; audioBuffer += copyBytes; m_LastAudioFrameTime += (long long)(1000.0 * copyBytes / (pBuffer->getFrameSize() * pBuffer->getRate())); } if (bufferLeftToFill != 0) { try { VideoMsgPtr pMsg = m_pAMsgQ->pop(false); EOFVideoMsgPtr pEOFMsg(dynamic_pointer_cast<EOFVideoMsg>(pMsg)); if (pEOFMsg) { m_bAudioEOF = true; return pBuffer->getNumFrames()-bufferLeftToFill/pBuffer->getFrameSize(); } m_pAudioMsg = dynamic_pointer_cast<AudioVideoMsg>(pMsg); assert(m_pAudioMsg); m_AudioMsgSize = m_pAudioMsg->getBuffer()->getNumFrames() *pBuffer->getFrameSize(); m_AudioMsgData = (unsigned char *)(m_pAudioMsg->getBuffer()->getData()); m_LastAudioFrameTime = m_pAudioMsg->getTime(); } catch (Exception &) { return pBuffer->getNumFrames()-bufferLeftToFill/pBuffer->getFrameSize(); } } } return pBuffer->getNumFrames(); } FrameVideoMsgPtr AsyncVideoDecoder::getBmpsForTime(long long TimeWanted, FrameAvailableCode& FrameAvailable) { // XXX: This code is sort-of duplicated in FFMpegDecoder::readFrameForTime() long long FrameTime = -1000; FrameVideoMsgPtr pFrameMsg; if (TimeWanted == -1) { pFrameMsg = getNextBmps(true); FrameAvailable = FA_NEW_FRAME; } else { if (getMasterStream() == SS_AUDIO) { TimeWanted = m_LastAudioFrameTime; } // cerr << "getBmpsForTime " << TimeWanted << ", LastFrameTime= " << m_LastVideoFrameTime // << ", diff= " << TimeWanted-m_LastVideoFrameTime << endl; double TimePerFrame = 1000.0/getFPS(); if (fabs(double(TimeWanted-m_LastVideoFrameTime)) < 0.5*TimePerFrame || m_LastVideoFrameTime > TimeWanted+TimePerFrame) { // cerr << " LastFrameTime = " << m_LastVideoFrameTime << ", display again." << endl; // The last frame is still current. Display it again. FrameAvailable = FA_USE_LAST_FRAME; return FrameVideoMsgPtr(); } else { if (m_bVideoEOF) { // cerr << " EOF." << endl; FrameAvailable = FA_USE_LAST_FRAME; return FrameVideoMsgPtr(); } while (FrameTime-TimeWanted < -0.5*TimePerFrame && !m_bVideoEOF) { pFrameMsg = getNextBmps(false); if (pFrameMsg) { FrameTime = pFrameMsg->getFrameTime(); // cerr << " readFrame returned time " << FrameTime << "." << endl; } else { // cerr << " no frame available." << endl; FrameAvailable = FA_STILL_DECODING; return FrameVideoMsgPtr(); } } FrameAvailable = FA_NEW_FRAME; // cerr << " frame ok." << endl; } } if (pFrameMsg) { m_LastVideoFrameTime = pFrameMsg->getFrameTime(); } return pFrameMsg; } FrameVideoMsgPtr AsyncVideoDecoder::getNextBmps(bool bWait) { try { waitForSeekDone(); VideoMsgPtr pMsg = m_pVMsgQ->pop(bWait); FrameVideoMsgPtr pFrameMsg = dynamic_pointer_cast<FrameVideoMsg>(pMsg); while (!pFrameMsg) { EOFVideoMsgPtr pEOFMsg(dynamic_pointer_cast<EOFVideoMsg>(pMsg)); ErrorVideoMsgPtr pErrorMsg(dynamic_pointer_cast<ErrorVideoMsg>(pMsg)); if (pEOFMsg) { m_bVideoEOF = true; return FrameVideoMsgPtr(); } else if (pErrorMsg) { m_bVideoEOF = true; return FrameVideoMsgPtr(); } else { // Unhandled message type. assert(false); } pMsg = m_pVMsgQ->pop(bWait); pFrameMsg = dynamic_pointer_cast<FrameVideoMsg>(pMsg); } return pFrameMsg; } catch (Exception&) { return FrameVideoMsgPtr(); } } void AsyncVideoDecoder::waitForSeekDone() { scoped_lock Lock(m_SeekMutex); if (m_bSeekPending) { do { VideoMsgPtr pMsg; if (m_pVCmdQ) { pMsg = m_pVMsgQ->pop(true); } else { pMsg = m_pAMsgQ->pop(true); } SeekDoneVideoMsgPtr pSeekDoneMsg = dynamic_pointer_cast<SeekDoneVideoMsg>(pMsg); if (pSeekDoneMsg) { m_bSeekPending = false; m_LastVideoFrameTime = pSeekDoneMsg->getVideoFrameTime(); m_LastAudioFrameTime = pSeekDoneMsg->getAudioFrameTime(); } } while (m_bSeekPending); } } } <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/logging.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/objects/xthread.h" #include "xenia/kernel/util/shim_utils.h" #include "xenia/kernel/xboxkrnl_private.h" #include "xenia/kernel/xobject.h" #include "xenia/xbox.h" namespace xe { namespace kernel { SHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_context, KernelState* kernel_state) { // r3 = ptr to info? // +0 = -4 // +4 = name ptr // +8 = 0 // r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType // r5 = 0 // r6 = out_ptr (handle?) uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0); uint32_t object_type_ptr = SHIM_GET_ARG_32(1); uint32_t unk = SHIM_GET_ARG_32(2); uint32_t handle_ptr = SHIM_GET_ARG_32(3); uint32_t name_str_ptr = SHIM_MEM_32(obj_attributes_ptr + 4); X_ANSI_STRING name_str(SHIM_MEM_BASE, name_str_ptr); auto name = name_str.to_string(); XELOGD("ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)", obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr); X_HANDLE handle = X_INVALID_HANDLE_VALUE; X_STATUS result = kernel_state->object_table()->GetObjectByName(name, &handle); if (XSUCCEEDED(result)) { SHIM_SET_MEM_32(handle_ptr, handle); } SHIM_SET_RETURN_32(result); } SHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_context, KernelState* kernel_state) { uint32_t handle = SHIM_GET_ARG_32(0); uint32_t object_type_ptr = SHIM_GET_ARG_32(1); uint32_t out_object_ptr = SHIM_GET_ARG_32(2); XELOGD("ObReferenceObjectByHandle(%.8X, %.8X, %.8X)", handle, object_type_ptr, out_object_ptr); X_STATUS result = X_STATUS_SUCCESS; auto object = kernel_state->object_table()->LookupObject<XObject>(handle); if (object) { // TODO(benvanik): verify type with object_type_ptr // TODO(benvanik): get native value, if supported. uint32_t native_ptr; switch (object_type_ptr) { case 0x00000000: { // whatever? switch (object->type()) { // TODO(benvanik): need to track native_ptr in XObject, allocate as // needed? /*case XObject::kTypeEvent: { XEvent* ev = (XEvent*)object; } break;*/ case XObject::kTypeThread: { auto thread = object.get<XThread>(); native_ptr = thread->thread_state_ptr(); } break; default: { assert_unhandled_case(object->type()); native_ptr = 0xDEADF00D; } break; } } break; case 0xD017BEEF: { // ExSemaphoreObjectType // TODO(benvanik): implement. assert_unhandled_case(object_type_ptr); native_ptr = 0xDEADF00D; } break; case 0xD01BBEEF: { // ExThreadObjectType auto thread = object.get<XThread>(); native_ptr = thread->thread_state_ptr(); } break; default: { assert_unhandled_case(object_type_ptr); native_ptr = 0xDEADF00D; } break; } // Caller takes the reference. // It's released in ObDereferenceObject. object->Retain(); if (out_object_ptr) { SHIM_SET_MEM_32(out_object_ptr, native_ptr); } } else { result = X_STATUS_INVALID_HANDLE; } SHIM_SET_RETURN_32(result); } SHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_context, KernelState* kernel_state) { uint32_t native_ptr = SHIM_GET_ARG_32(0); XELOGD("ObDereferenceObject(%.8X)", native_ptr); // Check if a dummy value from ObReferenceObjectByHandle. if (native_ptr == 0xDEADF00D) { SHIM_SET_RETURN_32(0); return; } void* object_ptr = SHIM_MEM_ADDR(native_ptr); auto object = XObject::GetNativeObject<XObject>(kernel_state, object_ptr); if (object) { object->Release(); } SHIM_SET_RETURN_32(0); } dword_result_t NtDuplicateObject(dword_t handle, lpdword_t new_handle_ptr, dword_t options) { // NOTE: new_handle_ptr can be zero to just close a handle. // NOTE: this function seems to be used to get the current thread handle // (passed handle=-2). // This function actually just creates a new handle to the same object. // Most games use it to get real handles to the current thread or whatever. X_HANDLE new_handle = X_INVALID_HANDLE_VALUE; X_STATUS result = kernel_state()->object_table()->DuplicateHandle(handle, &new_handle); if (options == 1 /* DUPLICATE_CLOSE_SOURCE */) { // Always close the source object. kernel_state()->object_table()->RemoveHandle(handle); } return result; } DECLARE_XBOXKRNL_EXPORT(NtDuplicateObject, ExportTag::kImplemented); dword_result_t NtClose(dword_t handle) { return kernel_state()->object_table()->RemoveHandle(handle); } DECLARE_XBOXKRNL_EXPORT(NtClose, ExportTag::kImplemented); } // namespace kernel } // namespace xe void xe::kernel::xboxkrnl::RegisterObExports( xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) { SHIM_SET_MAPPING("xboxkrnl.exe", ObOpenObjectByName, state); SHIM_SET_MAPPING("xboxkrnl.exe", ObReferenceObjectByHandle, state); SHIM_SET_MAPPING("xboxkrnl.exe", ObDereferenceObject, state); } <commit_msg>Actually give the game the new handle<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/logging.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/objects/xthread.h" #include "xenia/kernel/util/shim_utils.h" #include "xenia/kernel/xboxkrnl_private.h" #include "xenia/kernel/xobject.h" #include "xenia/xbox.h" namespace xe { namespace kernel { SHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_context, KernelState* kernel_state) { // r3 = ptr to info? // +0 = -4 // +4 = name ptr // +8 = 0 // r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType // r5 = 0 // r6 = out_ptr (handle?) uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0); uint32_t object_type_ptr = SHIM_GET_ARG_32(1); uint32_t unk = SHIM_GET_ARG_32(2); uint32_t handle_ptr = SHIM_GET_ARG_32(3); uint32_t name_str_ptr = SHIM_MEM_32(obj_attributes_ptr + 4); X_ANSI_STRING name_str(SHIM_MEM_BASE, name_str_ptr); auto name = name_str.to_string(); XELOGD("ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)", obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr); X_HANDLE handle = X_INVALID_HANDLE_VALUE; X_STATUS result = kernel_state->object_table()->GetObjectByName(name, &handle); if (XSUCCEEDED(result)) { SHIM_SET_MEM_32(handle_ptr, handle); } SHIM_SET_RETURN_32(result); } SHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_context, KernelState* kernel_state) { uint32_t handle = SHIM_GET_ARG_32(0); uint32_t object_type_ptr = SHIM_GET_ARG_32(1); uint32_t out_object_ptr = SHIM_GET_ARG_32(2); XELOGD("ObReferenceObjectByHandle(%.8X, %.8X, %.8X)", handle, object_type_ptr, out_object_ptr); X_STATUS result = X_STATUS_SUCCESS; auto object = kernel_state->object_table()->LookupObject<XObject>(handle); if (object) { // TODO(benvanik): verify type with object_type_ptr // TODO(benvanik): get native value, if supported. uint32_t native_ptr; switch (object_type_ptr) { case 0x00000000: { // whatever? switch (object->type()) { // TODO(benvanik): need to track native_ptr in XObject, allocate as // needed? /*case XObject::kTypeEvent: { XEvent* ev = (XEvent*)object; } break;*/ case XObject::kTypeThread: { auto thread = object.get<XThread>(); native_ptr = thread->thread_state_ptr(); } break; default: { assert_unhandled_case(object->type()); native_ptr = 0xDEADF00D; } break; } } break; case 0xD017BEEF: { // ExSemaphoreObjectType // TODO(benvanik): implement. assert_unhandled_case(object_type_ptr); native_ptr = 0xDEADF00D; } break; case 0xD01BBEEF: { // ExThreadObjectType auto thread = object.get<XThread>(); native_ptr = thread->thread_state_ptr(); } break; default: { assert_unhandled_case(object_type_ptr); native_ptr = 0xDEADF00D; } break; } // Caller takes the reference. // It's released in ObDereferenceObject. object->Retain(); if (out_object_ptr) { SHIM_SET_MEM_32(out_object_ptr, native_ptr); } } else { result = X_STATUS_INVALID_HANDLE; } SHIM_SET_RETURN_32(result); } SHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_context, KernelState* kernel_state) { uint32_t native_ptr = SHIM_GET_ARG_32(0); XELOGD("ObDereferenceObject(%.8X)", native_ptr); // Check if a dummy value from ObReferenceObjectByHandle. if (native_ptr == 0xDEADF00D) { SHIM_SET_RETURN_32(0); return; } void* object_ptr = SHIM_MEM_ADDR(native_ptr); auto object = XObject::GetNativeObject<XObject>(kernel_state, object_ptr); if (object) { object->Release(); } SHIM_SET_RETURN_32(0); } dword_result_t NtDuplicateObject(dword_t handle, lpdword_t new_handle_ptr, dword_t options) { // NOTE: new_handle_ptr can be zero to just close a handle. // NOTE: this function seems to be used to get the current thread handle // (passed handle=-2). // This function actually just creates a new handle to the same object. // Most games use it to get real handles to the current thread or whatever. X_HANDLE new_handle = X_INVALID_HANDLE_VALUE; X_STATUS result = kernel_state()->object_table()->DuplicateHandle(handle, &new_handle); if (new_handle_ptr) { *new_handle_ptr = new_handle; } if (options == 1 /* DUPLICATE_CLOSE_SOURCE */) { // Always close the source object. kernel_state()->object_table()->RemoveHandle(handle); } return result; } DECLARE_XBOXKRNL_EXPORT(NtDuplicateObject, ExportTag::kImplemented); dword_result_t NtClose(dword_t handle) { return kernel_state()->object_table()->RemoveHandle(handle); } DECLARE_XBOXKRNL_EXPORT(NtClose, ExportTag::kImplemented); } // namespace kernel } // namespace xe void xe::kernel::xboxkrnl::RegisterObExports( xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) { SHIM_SET_MAPPING("xboxkrnl.exe", ObOpenObjectByName, state); SHIM_SET_MAPPING("xboxkrnl.exe", ObReferenceObjectByHandle, state); SHIM_SET_MAPPING("xboxkrnl.exe", ObDereferenceObject, state); } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <unistd.h> #include "zbase/api/LogfileService.h" #include "stx/RegExp.h" #include "stx/human.h" #include "stx/protobuf/msg.h" #include "stx/protobuf/MessageSchema.h" #include "stx/protobuf/MessagePrinter.h" #include "stx/protobuf/MessageEncoder.h" #include "stx/protobuf/DynamicMessage.h" #include "csql/qtree/SelectListNode.h" #include "csql/qtree/ColumnReferenceNode.h" #include "csql/CSTableScan.h" #include "zbase/core/TimeWindowPartitioner.h" using namespace stx; namespace zbase { LogfileService::LogfileService( ConfigDirectory* cdir, AnalyticsAuth* auth, zbase::TSDBService* tsdb, zbase::PartitionMap* pmap, zbase::ReplicationScheme* repl, csql::Runtime* sql) : cdir_(cdir), auth_(auth), tsdb_(tsdb), pmap_(pmap), repl_(repl), sql_(sql) {} void LogfileService::scanLogfile( const AnalyticsSession& session, const String& logfile_name, const LogfileScanParams& params, LogfileScanResult* result, Function<void (bool done)> on_progress) { auto logfile_definition = findLogfileDefinition( session.customer(), logfile_name); if (logfile_definition.isEmpty()) { RAISEF(kNotFoundError, "logfile not found: $0", logfile_name); } auto table_name = "logs." + logfile_name; auto lookback_limit = params.end_time() - 1 * kMicrosPerDay; auto partition_size = 10 * kMicrosPerMinute; result->setColumns( Vector<String>(params.columns().begin(), params.columns().end())); iputs("end time: $0", UnixTime(params.end_time())); for (auto time = params.end_time(); time > lookback_limit; time -= partition_size) { auto partition = zbase::TimeWindowPartitioner::partitionKeyFor( table_name, time, partition_size); iputs("scan time: $0 -> $1", UnixTime(time), partition.toString()); if (repl_->hasLocalReplica(partition)) { scanLocalLogfilePartition( session, table_name, partition, params, result); } else { scanRemoteLogfilePartition( session, table_name, partition, params, repl_->replicaAddrsFor(partition), result); } result->setScannedUntil(time); bool done = result->isFull(); on_progress(done); if (done) { break; } } } void LogfileService::scanLocalLogfilePartition( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition_key, const LogfileScanParams& params, LogfileScanResult* result) { auto partition = pmap_->findPartition( session.customer(), table_name, partition_key); if (partition.isEmpty()) { return; } logDebug( "zbase", "Scanning local logfile partition $0/$1/$2", session.customer(), table_name, partition_key.toString()); Vector<RefPtr<csql::SelectListNode>> select_list; select_list.emplace_back( new csql::SelectListNode( new csql::ColumnReferenceNode("time"))); if (params.return_raw()) { select_list.emplace_back( new csql::SelectListNode( new csql::ColumnReferenceNode("raw"))); } for (const auto& c : params.columns()) { select_list.emplace_back( new csql::SelectListNode( new csql::ColumnReferenceNode(c))); } Option<RefPtr<csql::ValueExpressionNode>> where_cond; switch (params.scan_type()) { case LOGSCAN_SQL: { const auto& sql_str = params.condition(); csql::Parser parser; parser.parseValueExpression(sql_str.data(), sql_str.size()); auto stmts = parser.getStatements(); if (stmts.size() != 1) { RAISE( kParseError, "SQL filter expression must consist of exactly one statement"); } where_cond = Some( mkRef(sql_->queryPlanBuilder()->buildValueExpression(stmts[0]))); break; } } auto seqscan = mkRef( new csql::SequentialScanNode( table_name, select_list, where_cond)); auto reader = partition.get()->getReader(); auto cstable_filename = reader->cstableFilename(); if (cstable_filename.isEmpty()) { return; } csql::CSTableScan cstable_scan( seqscan, cstable_filename.get(), sql_->queryBuilder().get()); csql::ExecutionContext context(sql_->scheduler()); cstable_scan.execute( &context, [result, &params] (int argc, const csql::SValue* argv) -> bool { int colidx = 0; auto time = UnixTime(argv[colidx++].getInteger()); if (time >= params.end_time()) { return true; } auto line = result->addLine(time); if (!line) { return true; } if (params.return_raw()) { line->raw = argv[colidx++].toString(); } for (; colidx < argc; ++colidx) { line->columns.emplace_back(argv[colidx].toString()); } return true; }); result->incrRowsScanned(cstable_scan.rowsScanned()); } void LogfileService::scanRemoteLogfilePartition( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition_key, const LogfileScanParams& params, const Vector<InetAddr>& hosts, LogfileScanResult* result) { Vector<String> errors; for (const auto& host : hosts) { try { if(scanRemoteLogfilePartition( session, table_name, partition_key, params, host, result)) { return; } } catch (const StandardException& e) { logError( "zbase", e, "LogfileService::scanRemoteLogfilePartition failed"); errors.emplace_back(e.what()); } } if (!errors.empty()) { RAISEF( kRuntimeError, "LogfileService::scanRemoteLogfilePartition failed: $0", StringUtil::join(errors, ", ")); } } bool LogfileService::scanRemoteLogfilePartition( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition_key, const LogfileScanParams& params, const InetAddr& host, LogfileScanResult* result) { logDebug( "zbase", "Scanning remote logfile partition $0/$1/$2 on $3", session.customer(), table_name, partition_key.toString(), host.hostAndPort()); auto url = StringUtil::format( "http://$0/api/v1/logfiles/scan_partition?table=$1&partition=$2&limit=$3", host.hostAndPort(), URI::urlEncode(table_name), partition_key.toString(), result->capacity()); auto api_token = auth_->encodeAuthToken(session); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", api_token)); http::HTTPClient http_client; auto req_body = msg::encode(params); auto req = http::HTTPRequest::mkPost(url, *req_body, auth_headers); auto res = http_client.executeRequest(req); if (res.statusCode() == 404) { iputs("got 404..", 1); return false; } if (res.statusCode() != 200) { RAISEF( kRuntimeError, "received non-200 response: $0", res.body().toString()); } iputs("got $0 bytes", res.body().size()); auto body_is = BufferInputStream::fromBuffer(&res.body()); result->decode(body_is.get()); return true; } void LogfileService::insertLoglines( const String& customer, const String& logfile_name, const Vector<Pair<String, String>>& source_fields, InputStream* is) { auto logfile_definition = findLogfileDefinition(customer, logfile_name); if (logfile_definition.isEmpty()) { RAISEF(kNotFoundError, "logfile not found: $0", logfile_name); } insertLoglines( customer, logfile_definition.get(), source_fields, is); } void LogfileService::insertLoglines( const String& customer, const LogfileDefinition& logfile, const Vector<Pair<String, String>>& source_fields, InputStream* is) { String line; auto table_name = "logs." + logfile.name(); auto schema = tsdb_->tableSchema(customer, table_name); auto partitioner = tsdb_->tablePartitioner(customer, table_name); if (schema.isEmpty() || partitioner.isEmpty()) { RAISEF(kNotFoundError, "table not found: $0", table_name); } msg::DynamicMessage row_base(schema.get()); for (const auto& f : source_fields) { row_base.addField(f.first, f.second); } RegExp regex(logfile.regex()); HashMap<size_t, LogfileField> match_fields; size_t time_idx = -1; String time_format; for (const auto& f : logfile.row_fields()) { auto match_idx = regex.getNamedCaptureIndex(f.name()); if (match_idx != size_t(-1)) { match_fields.emplace(match_idx, f); if (f.name() == "time") { time_idx = match_idx; time_format = f.format(); } } } if (time_idx == size_t(-1)) { RAISE(kIllegalStateError, "can't import logfile row without time column"); } for (; is->readLine(&line); line.clear()) { Vector<Pair<const char*, size_t>> match; if (!regex.match(line, &match)) { continue; } Option<UnixTime> time; if (time_format.empty()) { time = Human::parseTime( String(match[time_idx].first, match[time_idx].second)); } else { time = UnixTime::parseString( match[time_idx].first, match[time_idx].second, time_format.c_str()); } if (time.isEmpty()) { continue; } auto row = row_base; row.addField("raw", line); for (size_t i = 0; i < match.size(); ++i) { auto mfield = match_fields.find(i); if (mfield == match_fields.end()) { continue; } if (mfield->second.has_format() && mfield->second.type() == "DATETIME") { auto t = UnixTime::parseString( match[i].first, match[i].second, mfield->second.format().c_str()); if (!t.isEmpty()) { row.addDateTimeField(mfield->second.id(), t.get()); } continue; } row.addField( mfield->second.id(), String(match[i].first, match[i].second)); } Buffer row_buf; msg::MessageEncoder::encode(row.data(), *row.schema(), &row_buf); auto record_id = Random::singleton()->sha1(); auto partition_key = partitioner.get()->partitionKeyFor( StringUtil::toString(time.get().unixMicros())); tsdb_->insertRecord( customer, table_name, partition_key, record_id, row_buf); } } Option<LogfileDefinition> LogfileService::findLogfileDefinition( const String& customer, const String& logfile_name) { auto cconf = cdir_->configFor(customer); for (const auto& logfile : cconf->config.logfile_import_config().logfiles()) { if (logfile.name() == logfile_name) { return Some(logfile); } } return None<LogfileDefinition>(); } RefPtr<msg::MessageSchema> LogfileService::getSchema( const LogfileDefinition& cfg) { Vector<msg::MessageSchemaField> fields; fields.emplace_back( msg::MessageSchemaField( 1, "raw", msg::FieldType::STRING, 0, false, true)); for (const auto& field : cfg.source_fields()) { fields.emplace_back( msg::MessageSchemaField( field.id(), field.name(), msg::fieldTypeFromString(field.type()), 0, false, true)); } for (const auto& field : cfg.row_fields()) { fields.emplace_back( msg::MessageSchemaField( field.id(), field.name(), msg::fieldTypeFromString(field.type()), 0, false, true)); } return new msg::MessageSchema(cfg.name(), fields); } Vector<TableDefinition> LogfileService::getTableDefinitions( const CustomerConfig& cfg) { Vector<TableDefinition> tbls; if (!cfg.has_logfile_import_config()) { return tbls; } for (const auto& logfile : cfg.logfile_import_config().logfiles()) { TableDefinition td; td.set_customer(cfg.customer()); td.set_table_name("logs." + logfile.name()); auto tblcfg = td.mutable_config(); tblcfg->set_schema(getSchema(logfile)->encode().toString()); tblcfg->set_partitioner(zbase::TBL_PARTITION_TIMEWINDOW); tblcfg->set_storage(zbase::TBL_STORAGE_LOG); auto partcfg = tblcfg->mutable_time_window_partitioner_config(); partcfg->set_partition_size(10 * kMicrosPerMinute); tbls.emplace_back(td); } return tbls; } } // namespace zbase <commit_msg>Revert "debug"<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <unistd.h> #include "zbase/api/LogfileService.h" #include "stx/RegExp.h" #include "stx/human.h" #include "stx/protobuf/msg.h" #include "stx/protobuf/MessageSchema.h" #include "stx/protobuf/MessagePrinter.h" #include "stx/protobuf/MessageEncoder.h" #include "stx/protobuf/DynamicMessage.h" #include "csql/qtree/SelectListNode.h" #include "csql/qtree/ColumnReferenceNode.h" #include "csql/CSTableScan.h" #include "zbase/core/TimeWindowPartitioner.h" using namespace stx; namespace zbase { LogfileService::LogfileService( ConfigDirectory* cdir, AnalyticsAuth* auth, zbase::TSDBService* tsdb, zbase::PartitionMap* pmap, zbase::ReplicationScheme* repl, csql::Runtime* sql) : cdir_(cdir), auth_(auth), tsdb_(tsdb), pmap_(pmap), repl_(repl), sql_(sql) {} void LogfileService::scanLogfile( const AnalyticsSession& session, const String& logfile_name, const LogfileScanParams& params, LogfileScanResult* result, Function<void (bool done)> on_progress) { auto logfile_definition = findLogfileDefinition( session.customer(), logfile_name); if (logfile_definition.isEmpty()) { RAISEF(kNotFoundError, "logfile not found: $0", logfile_name); } auto table_name = "logs." + logfile_name; auto lookback_limit = params.end_time() - 90 * kMicrosPerDay; auto partition_size = 10 * kMicrosPerMinute; result->setColumns( Vector<String>(params.columns().begin(), params.columns().end())); for (auto time = params.end_time(); time > lookback_limit; time -= partition_size) { auto partition = zbase::TimeWindowPartitioner::partitionKeyFor( table_name, time, partition_size); if (repl_->hasLocalReplica(partition)) { scanLocalLogfilePartition( session, table_name, partition, params, result); } else { scanRemoteLogfilePartition( session, table_name, partition, params, repl_->replicaAddrsFor(partition), result); } result->setScannedUntil(time); bool done = result->isFull(); on_progress(done); if (done) { break; } } } void LogfileService::scanLocalLogfilePartition( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition_key, const LogfileScanParams& params, LogfileScanResult* result) { auto partition = pmap_->findPartition( session.customer(), table_name, partition_key); if (partition.isEmpty()) { return; } logDebug( "zbase", "Scanning local logfile partition $0/$1/$2", session.customer(), table_name, partition_key.toString()); Vector<RefPtr<csql::SelectListNode>> select_list; select_list.emplace_back( new csql::SelectListNode( new csql::ColumnReferenceNode("time"))); if (params.return_raw()) { select_list.emplace_back( new csql::SelectListNode( new csql::ColumnReferenceNode("raw"))); } for (const auto& c : params.columns()) { select_list.emplace_back( new csql::SelectListNode( new csql::ColumnReferenceNode(c))); } Option<RefPtr<csql::ValueExpressionNode>> where_cond; switch (params.scan_type()) { case LOGSCAN_SQL: { const auto& sql_str = params.condition(); csql::Parser parser; parser.parseValueExpression(sql_str.data(), sql_str.size()); auto stmts = parser.getStatements(); if (stmts.size() != 1) { RAISE( kParseError, "SQL filter expression must consist of exactly one statement"); } where_cond = Some( mkRef(sql_->queryPlanBuilder()->buildValueExpression(stmts[0]))); break; } } auto seqscan = mkRef( new csql::SequentialScanNode( table_name, select_list, where_cond)); auto reader = partition.get()->getReader(); auto cstable_filename = reader->cstableFilename(); if (cstable_filename.isEmpty()) { return; } csql::CSTableScan cstable_scan( seqscan, cstable_filename.get(), sql_->queryBuilder().get()); csql::ExecutionContext context(sql_->scheduler()); cstable_scan.execute( &context, [result, &params] (int argc, const csql::SValue* argv) -> bool { int colidx = 0; auto time = UnixTime(argv[colidx++].getInteger()); if (time >= params.end_time()) { return true; } auto line = result->addLine(time); if (!line) { return true; } if (params.return_raw()) { line->raw = argv[colidx++].toString(); } for (; colidx < argc; ++colidx) { line->columns.emplace_back(argv[colidx].toString()); } return true; }); result->incrRowsScanned(cstable_scan.rowsScanned()); } void LogfileService::scanRemoteLogfilePartition( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition_key, const LogfileScanParams& params, const Vector<InetAddr>& hosts, LogfileScanResult* result) { Vector<String> errors; for (const auto& host : hosts) { try { if(scanRemoteLogfilePartition( session, table_name, partition_key, params, host, result)) { return; } } catch (const StandardException& e) { logError( "zbase", e, "LogfileService::scanRemoteLogfilePartition failed"); errors.emplace_back(e.what()); } } if (!errors.empty()) { RAISEF( kRuntimeError, "LogfileService::scanRemoteLogfilePartition failed: $0", StringUtil::join(errors, ", ")); } } bool LogfileService::scanRemoteLogfilePartition( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition_key, const LogfileScanParams& params, const InetAddr& host, LogfileScanResult* result) { logDebug( "zbase", "Scanning remote logfile partition $0/$1/$2 on $3", session.customer(), table_name, partition_key.toString(), host.hostAndPort()); auto url = StringUtil::format( "http://$0/api/v1/logfiles/scan_partition?table=$1&partition=$2&limit=$3", host.hostAndPort(), URI::urlEncode(table_name), partition_key.toString(), result->capacity()); auto api_token = auth_->encodeAuthToken(session); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", api_token)); http::HTTPClient http_client; auto req_body = msg::encode(params); auto req = http::HTTPRequest::mkPost(url, *req_body, auth_headers); auto res = http_client.executeRequest(req); if (res.statusCode() == 404) { return false; } if (res.statusCode() != 200) { RAISEF( kRuntimeError, "received non-200 response: $0", res.body().toString()); } auto body_is = BufferInputStream::fromBuffer(&res.body()); result->decode(body_is.get()); return true; } void LogfileService::insertLoglines( const String& customer, const String& logfile_name, const Vector<Pair<String, String>>& source_fields, InputStream* is) { auto logfile_definition = findLogfileDefinition(customer, logfile_name); if (logfile_definition.isEmpty()) { RAISEF(kNotFoundError, "logfile not found: $0", logfile_name); } insertLoglines( customer, logfile_definition.get(), source_fields, is); } void LogfileService::insertLoglines( const String& customer, const LogfileDefinition& logfile, const Vector<Pair<String, String>>& source_fields, InputStream* is) { String line; auto table_name = "logs." + logfile.name(); auto schema = tsdb_->tableSchema(customer, table_name); auto partitioner = tsdb_->tablePartitioner(customer, table_name); if (schema.isEmpty() || partitioner.isEmpty()) { RAISEF(kNotFoundError, "table not found: $0", table_name); } msg::DynamicMessage row_base(schema.get()); for (const auto& f : source_fields) { row_base.addField(f.first, f.second); } RegExp regex(logfile.regex()); HashMap<size_t, LogfileField> match_fields; size_t time_idx = -1; String time_format; for (const auto& f : logfile.row_fields()) { auto match_idx = regex.getNamedCaptureIndex(f.name()); if (match_idx != size_t(-1)) { match_fields.emplace(match_idx, f); if (f.name() == "time") { time_idx = match_idx; time_format = f.format(); } } } if (time_idx == size_t(-1)) { RAISE(kIllegalStateError, "can't import logfile row without time column"); } for (; is->readLine(&line); line.clear()) { Vector<Pair<const char*, size_t>> match; if (!regex.match(line, &match)) { continue; } Option<UnixTime> time; if (time_format.empty()) { time = Human::parseTime( String(match[time_idx].first, match[time_idx].second)); } else { time = UnixTime::parseString( match[time_idx].first, match[time_idx].second, time_format.c_str()); } if (time.isEmpty()) { continue; } auto row = row_base; row.addField("raw", line); for (size_t i = 0; i < match.size(); ++i) { auto mfield = match_fields.find(i); if (mfield == match_fields.end()) { continue; } if (mfield->second.has_format() && mfield->second.type() == "DATETIME") { auto t = UnixTime::parseString( match[i].first, match[i].second, mfield->second.format().c_str()); if (!t.isEmpty()) { row.addDateTimeField(mfield->second.id(), t.get()); } continue; } row.addField( mfield->second.id(), String(match[i].first, match[i].second)); } Buffer row_buf; msg::MessageEncoder::encode(row.data(), *row.schema(), &row_buf); auto record_id = Random::singleton()->sha1(); auto partition_key = partitioner.get()->partitionKeyFor( StringUtil::toString(time.get().unixMicros())); tsdb_->insertRecord( customer, table_name, partition_key, record_id, row_buf); } } Option<LogfileDefinition> LogfileService::findLogfileDefinition( const String& customer, const String& logfile_name) { auto cconf = cdir_->configFor(customer); for (const auto& logfile : cconf->config.logfile_import_config().logfiles()) { if (logfile.name() == logfile_name) { return Some(logfile); } } return None<LogfileDefinition>(); } RefPtr<msg::MessageSchema> LogfileService::getSchema( const LogfileDefinition& cfg) { Vector<msg::MessageSchemaField> fields; fields.emplace_back( msg::MessageSchemaField( 1, "raw", msg::FieldType::STRING, 0, false, true)); for (const auto& field : cfg.source_fields()) { fields.emplace_back( msg::MessageSchemaField( field.id(), field.name(), msg::fieldTypeFromString(field.type()), 0, false, true)); } for (const auto& field : cfg.row_fields()) { fields.emplace_back( msg::MessageSchemaField( field.id(), field.name(), msg::fieldTypeFromString(field.type()), 0, false, true)); } return new msg::MessageSchema(cfg.name(), fields); } Vector<TableDefinition> LogfileService::getTableDefinitions( const CustomerConfig& cfg) { Vector<TableDefinition> tbls; if (!cfg.has_logfile_import_config()) { return tbls; } for (const auto& logfile : cfg.logfile_import_config().logfiles()) { TableDefinition td; td.set_customer(cfg.customer()); td.set_table_name("logs." + logfile.name()); auto tblcfg = td.mutable_config(); tblcfg->set_schema(getSchema(logfile)->encode().toString()); tblcfg->set_partitioner(zbase::TBL_PARTITION_TIMEWINDOW); tblcfg->set_storage(zbase::TBL_STORAGE_LOG); auto partcfg = tblcfg->mutable_time_window_partitioner_config(); partcfg->set_partition_size(10 * kMicrosPerMinute); tbls.emplace_back(td); } return tbls; } } // namespace zbase <|endoftext|>
<commit_before>#include "SolverModule.h" using namespace std; /** * Constructor for SolverModule. * * The solver module holds a WaveSolver object and contains all the accessor methods related to it. * The Solvermodule starts off being stored online in the DatabaseRef singleton class, but is passed * to other controller classes as needed. */ SolverModule::SolverModule() : mSolver(WaveSolver<double>(X, Y)) { } /** * GetSolver() * * Gets the WaveSolver * * Returns a shared pointer to the current WaveSolver */ shared_ptr<WaveSolver<double>> SolverModule::GetSolver() const { return shared_ptr<WaveSolver<double>>(); } /** * AddRectangle(const int x, const int y, const int width, const int height, const double vel) * x: The x coordinate of the top left corner of the rectangle to be added * y: The y coordinate of the top left corner of the rectangle to be added * width: The width of the rectangle to be added * height: The height of the rectangle to be added * vel: The amount of influence the shape will have over its area, 1 having no effect and 0 completely * blocking all movement * * Addes a rectangle to the current WaveSovler */ const void SolverModule::AddRectangle(const int x, const int y, const int width, const int height, const double vel) { mSolver.addRectangle(x - 1, y - 1, x + width - 1, y + height - 1, vel); } /** * AddCircle(const int x, const int y, const int radius, const int vel) * x: The x coordinate of the center of the circle to be added * y: The y coordinate of the center of the rectangle to be added * radius: The radius of the circle to be added * vel: The amount of influence the shape will have over its area, 1 having no effect and 0 completely * blocking all movement * * Addes a rectangle to the current WaveSovler */ const void SolverModule::AddCircle(const int x, const int y, const int radius, const double vel) { mSolver.addCircle(x - 1, y - 1, radius, vel); } /** * ResetMaterials() * * Removes all the shapes from the current WaveSolver but leaves the current simulation running */ const void SolverModule::ResetMaterials() { mSolver.resetMaterials(); } /** * ResetField() * * Sets the field back to the initial poisitoin but leaves all shapes */ const void SolverModule::ResetField() { mSolver.resetField(); } /** * GetField() * * Returns a raw pointer to field of the current WaveSolver */ WaveSolver<double>* SolverModule::GetField() { return &mSolver; } <commit_msg>Tweaked adding circle<commit_after>#include "SolverModule.h" using namespace std; /** * Constructor for SolverModule. * * The solver module holds a WaveSolver object and contains all the accessor methods related to it. * The Solvermodule starts off being stored online in the DatabaseRef singleton class, but is passed * to other controller classes as needed. */ SolverModule::SolverModule() : mSolver(WaveSolver<double>(X, Y)) { } /** * GetSolver() * * Gets the WaveSolver * * Returns a shared pointer to the current WaveSolver */ shared_ptr<WaveSolver<double>> SolverModule::GetSolver() const { return shared_ptr<WaveSolver<double>>(); } /** * AddRectangle(const int x, const int y, const int width, const int height, const double vel) * x: The x coordinate of the top left corner of the rectangle to be added * y: The y coordinate of the top left corner of the rectangle to be added * width: The width of the rectangle to be added * height: The height of the rectangle to be added * vel: The amount of influence the shape will have over its area, 1 having no effect and 0 completely * blocking all movement * * Addes a rectangle to the current WaveSovler */ const void SolverModule::AddRectangle(const int x, const int y, const int width, const int height, const double vel) { mSolver.addRectangle(x - 1, y - 1, x + width - 1, y + height - 1, vel); } /** * AddCircle(const int x, const int y, const int radius, const int vel) * x: The x coordinate of the center of the circle to be added * y: The y coordinate of the center of the rectangle to be added * radius: The radius of the circle to be added * vel: The amount of influence the shape will have over its area, 1 having no effect and 0 completely * blocking all movement * * Addes a rectangle to the current WaveSovler */ const void SolverModule::AddCircle(const int x, const int y, const int radius, const double vel) { mSolver.addCircle(x, y, radius - 1, vel); } /** * ResetMaterials() * * Removes all the shapes from the current WaveSolver but leaves the current simulation running */ const void SolverModule::ResetMaterials() { mSolver.resetMaterials(); } /** * ResetField() * * Sets the field back to the initial poisitoin but leaves all shapes */ const void SolverModule::ResetField() { mSolver.resetField(); } /** * GetField() * * Returns a raw pointer to field of the current WaveSolver */ WaveSolver<double>* SolverModule::GetField() { return &mSolver; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/congestion_controller/rtp/transport_feedback_adapter.h" #include <algorithm> #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/mod_ops.h" namespace webrtc { namespace { void SortPacketFeedbackVector(std::vector<webrtc::PacketFeedback>* input) { std::sort(input->begin(), input->end(), PacketFeedbackComparator()); } PacketResult NetworkPacketFeedbackFromRtpPacketFeedback( const webrtc::PacketFeedback& pf) { PacketResult feedback; if (pf.arrival_time_ms == webrtc::PacketFeedback::kNotReceived) feedback.receive_time = Timestamp::PlusInfinity(); else feedback.receive_time = Timestamp::ms(pf.arrival_time_ms); if (pf.send_time_ms != webrtc::PacketFeedback::kNoSendTime) { feedback.sent_packet = SentPacket(); feedback.sent_packet->sequence_number = pf.long_sequence_number; feedback.sent_packet->send_time = Timestamp::ms(pf.send_time_ms); feedback.sent_packet->size = DataSize::bytes(pf.payload_size); feedback.sent_packet->pacing_info = pf.pacing_info; } return feedback; } std::vector<PacketResult> PacketResultsFromRtpFeedbackVector( const std::vector<PacketFeedback>& feedback_vector) { RTC_DCHECK(std::is_sorted(feedback_vector.begin(), feedback_vector.end(), PacketFeedbackComparator())); std::vector<PacketResult> packet_feedbacks; packet_feedbacks.reserve(feedback_vector.size()); for (const PacketFeedback& rtp_feedback : feedback_vector) { auto feedback = NetworkPacketFeedbackFromRtpPacketFeedback(rtp_feedback); packet_feedbacks.push_back(feedback); } return packet_feedbacks; } } // namespace const int64_t kNoTimestamp = -1; const int64_t kSendTimeHistoryWindowMs = 60000; const int64_t kBaseTimestampScaleFactor = rtcp::TransportFeedback::kDeltaScaleFactor * (1 << 8); const int64_t kBaseTimestampRangeSizeUs = kBaseTimestampScaleFactor * (1 << 24); TransportFeedbackAdapter::TransportFeedbackAdapter(const Clock* clock) : send_time_history_(clock, kSendTimeHistoryWindowMs), clock_(clock), current_offset_ms_(kNoTimestamp), last_timestamp_us_(kNoTimestamp), local_net_id_(0), remote_net_id_(0) {} TransportFeedbackAdapter::~TransportFeedbackAdapter() { RTC_DCHECK(observers_.empty()); } void TransportFeedbackAdapter::RegisterPacketFeedbackObserver( PacketFeedbackObserver* observer) { rtc::CritScope cs(&observers_lock_); RTC_DCHECK(observer); RTC_DCHECK(std::find(observers_.begin(), observers_.end(), observer) == observers_.end()); observers_.push_back(observer); } void TransportFeedbackAdapter::DeRegisterPacketFeedbackObserver( PacketFeedbackObserver* observer) { rtc::CritScope cs(&observers_lock_); RTC_DCHECK(observer); const auto it = std::find(observers_.begin(), observers_.end(), observer); RTC_DCHECK(it != observers_.end()); observers_.erase(it); } void TransportFeedbackAdapter::AddPacket(uint32_t ssrc, uint16_t sequence_number, size_t length, const PacedPacketInfo& pacing_info) { { rtc::CritScope cs(&lock_); const int64_t creation_time_ms = clock_->TimeInMilliseconds(); send_time_history_.AddAndRemoveOld( PacketFeedback(creation_time_ms, sequence_number, length, local_net_id_, remote_net_id_, pacing_info)); } { rtc::CritScope cs(&observers_lock_); for (auto* observer : observers_) { observer->OnPacketAdded(ssrc, sequence_number); } } } absl::optional<SentPacket> TransportFeedbackAdapter::ProcessSentPacket( const rtc::SentPacket& sent_packet) { rtc::CritScope cs(&lock_); // TODO(srte): Only use one way to indicate that packet feedback is used. if (sent_packet.info.included_in_feedback || sent_packet.packet_id != -1) { send_time_history_.OnSentPacket(sent_packet.packet_id, sent_packet.send_time_ms); absl::optional<PacketFeedback> packet = send_time_history_.GetPacket(sent_packet.packet_id); if (packet) { SentPacket msg; msg.size = DataSize::bytes(packet->payload_size); msg.send_time = Timestamp::ms(packet->send_time_ms); msg.sequence_number = packet->long_sequence_number; msg.prior_unacked_data = DataSize::bytes(packet->unacknowledged_data); msg.data_in_flight = send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_); return msg; } } else if (sent_packet.info.included_in_allocation) { send_time_history_.AddUntracked(sent_packet.info.packet_size_bytes, sent_packet.send_time_ms); } return absl::nullopt; } absl::optional<TransportPacketsFeedback> TransportFeedbackAdapter::ProcessTransportFeedback( const rtcp::TransportFeedback& feedback) { int64_t feedback_time_ms = clock_->TimeInMilliseconds(); DataSize prior_in_flight = GetOutstandingData(); OnTransportFeedback(feedback); std::vector<PacketFeedback> feedback_vector = last_packet_feedback_vector_; if (feedback_vector.empty()) return absl::nullopt; SortPacketFeedbackVector(&feedback_vector); TransportPacketsFeedback msg; msg.packet_feedbacks = PacketResultsFromRtpFeedbackVector(feedback_vector); msg.feedback_time = Timestamp::ms(feedback_time_ms); msg.prior_in_flight = prior_in_flight; msg.data_in_flight = GetOutstandingData(); return msg; } void TransportFeedbackAdapter::SetNetworkIds(uint16_t local_id, uint16_t remote_id) { rtc::CritScope cs(&lock_); local_net_id_ = local_id; remote_net_id_ = remote_id; } DataSize TransportFeedbackAdapter::GetOutstandingData() const { rtc::CritScope cs(&lock_); return send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_); } std::vector<PacketFeedback> TransportFeedbackAdapter::GetPacketFeedbackVector( const rtcp::TransportFeedback& feedback) { int64_t timestamp_us = feedback.GetBaseTimeUs(); int64_t now_ms = clock_->TimeInMilliseconds(); // Add timestamp deltas to a local time base selected on first packet arrival. // This won't be the true time base, but makes it easier to manually inspect // time stamps. if (last_timestamp_us_ == kNoTimestamp) { current_offset_ms_ = now_ms; } else { int64_t delta = timestamp_us - last_timestamp_us_; // Detect and compensate for wrap-arounds in base time. if (std::abs(delta - kBaseTimestampRangeSizeUs) < std::abs(delta)) { delta -= kBaseTimestampRangeSizeUs; // Wrap backwards. } else if (std::abs(delta + kBaseTimestampRangeSizeUs) < std::abs(delta)) { delta += kBaseTimestampRangeSizeUs; // Wrap forwards. } current_offset_ms_ += delta / 1000; } last_timestamp_us_ = timestamp_us; std::vector<PacketFeedback> packet_feedback_vector; if (feedback.GetPacketStatusCount() == 0) { RTC_LOG(LS_INFO) << "Empty transport feedback packet received."; return packet_feedback_vector; } packet_feedback_vector.reserve(feedback.GetPacketStatusCount()); { rtc::CritScope cs(&lock_); size_t failed_lookups = 0; int64_t offset_us = 0; int64_t timestamp_ms = 0; uint16_t seq_num = feedback.GetBaseSequence(); for (const auto& packet : feedback.GetReceivedPackets()) { // Insert into the vector those unreceived packets which precede this // iteration's received packet. for (; seq_num != packet.sequence_number(); ++seq_num) { PacketFeedback packet_feedback(PacketFeedback::kNotReceived, seq_num); // Note: Element not removed from history because it might be reported // as received by another feedback. if (!send_time_history_.GetFeedback(&packet_feedback, false)) ++failed_lookups; if (packet_feedback.local_net_id == local_net_id_ && packet_feedback.remote_net_id == remote_net_id_) { packet_feedback_vector.push_back(packet_feedback); } } // Handle this iteration's received packet. offset_us += packet.delta_us(); timestamp_ms = current_offset_ms_ + (offset_us / 1000); PacketFeedback packet_feedback(timestamp_ms, packet.sequence_number()); if (!send_time_history_.GetFeedback(&packet_feedback, true)) ++failed_lookups; if (packet_feedback.local_net_id == local_net_id_ && packet_feedback.remote_net_id == remote_net_id_) { packet_feedback_vector.push_back(packet_feedback); } ++seq_num; } if (failed_lookups > 0) { RTC_LOG(LS_WARNING) << "Failed to lookup send time for " << failed_lookups << " packet" << (failed_lookups > 1 ? "s" : "") << ". Send time history too small?"; } } return packet_feedback_vector; } void TransportFeedbackAdapter::OnTransportFeedback( const rtcp::TransportFeedback& feedback) { last_packet_feedback_vector_ = GetPacketFeedbackVector(feedback); { rtc::CritScope cs(&observers_lock_); for (auto* observer : observers_) { observer->OnPacketFeedbackVector(last_packet_feedback_vector_); } } } std::vector<PacketFeedback> TransportFeedbackAdapter::GetTransportFeedbackVector() const { return last_packet_feedback_vector_; } } // namespace webrtc <commit_msg>Routing unacknowledged data in TransportFeedbackAdapter.<commit_after>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/congestion_controller/rtp/transport_feedback_adapter.h" #include <algorithm> #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/mod_ops.h" namespace webrtc { namespace { void SortPacketFeedbackVector(std::vector<webrtc::PacketFeedback>* input) { std::sort(input->begin(), input->end(), PacketFeedbackComparator()); } PacketResult NetworkPacketFeedbackFromRtpPacketFeedback( const webrtc::PacketFeedback& pf) { PacketResult feedback; if (pf.arrival_time_ms == webrtc::PacketFeedback::kNotReceived) feedback.receive_time = Timestamp::PlusInfinity(); else feedback.receive_time = Timestamp::ms(pf.arrival_time_ms); if (pf.send_time_ms != webrtc::PacketFeedback::kNoSendTime) { feedback.sent_packet = SentPacket(); feedback.sent_packet->sequence_number = pf.long_sequence_number; feedback.sent_packet->send_time = Timestamp::ms(pf.send_time_ms); feedback.sent_packet->size = DataSize::bytes(pf.payload_size); feedback.sent_packet->pacing_info = pf.pacing_info; feedback.sent_packet->prior_unacked_data = DataSize::bytes(pf.unacknowledged_data); } return feedback; } std::vector<PacketResult> PacketResultsFromRtpFeedbackVector( const std::vector<PacketFeedback>& feedback_vector) { RTC_DCHECK(std::is_sorted(feedback_vector.begin(), feedback_vector.end(), PacketFeedbackComparator())); std::vector<PacketResult> packet_feedbacks; packet_feedbacks.reserve(feedback_vector.size()); for (const PacketFeedback& rtp_feedback : feedback_vector) { auto feedback = NetworkPacketFeedbackFromRtpPacketFeedback(rtp_feedback); packet_feedbacks.push_back(feedback); } return packet_feedbacks; } } // namespace const int64_t kNoTimestamp = -1; const int64_t kSendTimeHistoryWindowMs = 60000; const int64_t kBaseTimestampScaleFactor = rtcp::TransportFeedback::kDeltaScaleFactor * (1 << 8); const int64_t kBaseTimestampRangeSizeUs = kBaseTimestampScaleFactor * (1 << 24); TransportFeedbackAdapter::TransportFeedbackAdapter(const Clock* clock) : send_time_history_(clock, kSendTimeHistoryWindowMs), clock_(clock), current_offset_ms_(kNoTimestamp), last_timestamp_us_(kNoTimestamp), local_net_id_(0), remote_net_id_(0) {} TransportFeedbackAdapter::~TransportFeedbackAdapter() { RTC_DCHECK(observers_.empty()); } void TransportFeedbackAdapter::RegisterPacketFeedbackObserver( PacketFeedbackObserver* observer) { rtc::CritScope cs(&observers_lock_); RTC_DCHECK(observer); RTC_DCHECK(std::find(observers_.begin(), observers_.end(), observer) == observers_.end()); observers_.push_back(observer); } void TransportFeedbackAdapter::DeRegisterPacketFeedbackObserver( PacketFeedbackObserver* observer) { rtc::CritScope cs(&observers_lock_); RTC_DCHECK(observer); const auto it = std::find(observers_.begin(), observers_.end(), observer); RTC_DCHECK(it != observers_.end()); observers_.erase(it); } void TransportFeedbackAdapter::AddPacket(uint32_t ssrc, uint16_t sequence_number, size_t length, const PacedPacketInfo& pacing_info) { { rtc::CritScope cs(&lock_); const int64_t creation_time_ms = clock_->TimeInMilliseconds(); send_time_history_.AddAndRemoveOld( PacketFeedback(creation_time_ms, sequence_number, length, local_net_id_, remote_net_id_, pacing_info)); } { rtc::CritScope cs(&observers_lock_); for (auto* observer : observers_) { observer->OnPacketAdded(ssrc, sequence_number); } } } absl::optional<SentPacket> TransportFeedbackAdapter::ProcessSentPacket( const rtc::SentPacket& sent_packet) { rtc::CritScope cs(&lock_); // TODO(srte): Only use one way to indicate that packet feedback is used. if (sent_packet.info.included_in_feedback || sent_packet.packet_id != -1) { send_time_history_.OnSentPacket(sent_packet.packet_id, sent_packet.send_time_ms); absl::optional<PacketFeedback> packet = send_time_history_.GetPacket(sent_packet.packet_id); if (packet) { SentPacket msg; msg.size = DataSize::bytes(packet->payload_size); msg.send_time = Timestamp::ms(packet->send_time_ms); msg.sequence_number = packet->long_sequence_number; msg.prior_unacked_data = DataSize::bytes(packet->unacknowledged_data); msg.data_in_flight = send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_); return msg; } } else if (sent_packet.info.included_in_allocation) { send_time_history_.AddUntracked(sent_packet.info.packet_size_bytes, sent_packet.send_time_ms); } return absl::nullopt; } absl::optional<TransportPacketsFeedback> TransportFeedbackAdapter::ProcessTransportFeedback( const rtcp::TransportFeedback& feedback) { int64_t feedback_time_ms = clock_->TimeInMilliseconds(); DataSize prior_in_flight = GetOutstandingData(); OnTransportFeedback(feedback); std::vector<PacketFeedback> feedback_vector = last_packet_feedback_vector_; if (feedback_vector.empty()) return absl::nullopt; SortPacketFeedbackVector(&feedback_vector); TransportPacketsFeedback msg; msg.packet_feedbacks = PacketResultsFromRtpFeedbackVector(feedback_vector); msg.feedback_time = Timestamp::ms(feedback_time_ms); msg.prior_in_flight = prior_in_flight; msg.data_in_flight = GetOutstandingData(); return msg; } void TransportFeedbackAdapter::SetNetworkIds(uint16_t local_id, uint16_t remote_id) { rtc::CritScope cs(&lock_); local_net_id_ = local_id; remote_net_id_ = remote_id; } DataSize TransportFeedbackAdapter::GetOutstandingData() const { rtc::CritScope cs(&lock_); return send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_); } std::vector<PacketFeedback> TransportFeedbackAdapter::GetPacketFeedbackVector( const rtcp::TransportFeedback& feedback) { int64_t timestamp_us = feedback.GetBaseTimeUs(); int64_t now_ms = clock_->TimeInMilliseconds(); // Add timestamp deltas to a local time base selected on first packet arrival. // This won't be the true time base, but makes it easier to manually inspect // time stamps. if (last_timestamp_us_ == kNoTimestamp) { current_offset_ms_ = now_ms; } else { int64_t delta = timestamp_us - last_timestamp_us_; // Detect and compensate for wrap-arounds in base time. if (std::abs(delta - kBaseTimestampRangeSizeUs) < std::abs(delta)) { delta -= kBaseTimestampRangeSizeUs; // Wrap backwards. } else if (std::abs(delta + kBaseTimestampRangeSizeUs) < std::abs(delta)) { delta += kBaseTimestampRangeSizeUs; // Wrap forwards. } current_offset_ms_ += delta / 1000; } last_timestamp_us_ = timestamp_us; std::vector<PacketFeedback> packet_feedback_vector; if (feedback.GetPacketStatusCount() == 0) { RTC_LOG(LS_INFO) << "Empty transport feedback packet received."; return packet_feedback_vector; } packet_feedback_vector.reserve(feedback.GetPacketStatusCount()); { rtc::CritScope cs(&lock_); size_t failed_lookups = 0; int64_t offset_us = 0; int64_t timestamp_ms = 0; uint16_t seq_num = feedback.GetBaseSequence(); for (const auto& packet : feedback.GetReceivedPackets()) { // Insert into the vector those unreceived packets which precede this // iteration's received packet. for (; seq_num != packet.sequence_number(); ++seq_num) { PacketFeedback packet_feedback(PacketFeedback::kNotReceived, seq_num); // Note: Element not removed from history because it might be reported // as received by another feedback. if (!send_time_history_.GetFeedback(&packet_feedback, false)) ++failed_lookups; if (packet_feedback.local_net_id == local_net_id_ && packet_feedback.remote_net_id == remote_net_id_) { packet_feedback_vector.push_back(packet_feedback); } } // Handle this iteration's received packet. offset_us += packet.delta_us(); timestamp_ms = current_offset_ms_ + (offset_us / 1000); PacketFeedback packet_feedback(timestamp_ms, packet.sequence_number()); if (!send_time_history_.GetFeedback(&packet_feedback, true)) ++failed_lookups; if (packet_feedback.local_net_id == local_net_id_ && packet_feedback.remote_net_id == remote_net_id_) { packet_feedback_vector.push_back(packet_feedback); } ++seq_num; } if (failed_lookups > 0) { RTC_LOG(LS_WARNING) << "Failed to lookup send time for " << failed_lookups << " packet" << (failed_lookups > 1 ? "s" : "") << ". Send time history too small?"; } } return packet_feedback_vector; } void TransportFeedbackAdapter::OnTransportFeedback( const rtcp::TransportFeedback& feedback) { last_packet_feedback_vector_ = GetPacketFeedbackVector(feedback); { rtc::CritScope cs(&observers_lock_); for (auto* observer : observers_) { observer->OnPacketFeedbackVector(last_packet_feedback_vector_); } } } std::vector<PacketFeedback> TransportFeedbackAdapter::GetTransportFeedbackVector() const { return last_packet_feedback_vector_; } } // namespace webrtc <|endoftext|>
<commit_before>/* libs/graphics/images/SkImageDecoder.cpp ** ** Copyright 2006, The Android Open Source Project ** ** 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 "SkImageDecoder.h" #include "SkBitmap.h" #include "SkPixelRef.h" #include "SkStream.h" #include "SkTemplates.h" static SkBitmap::Config gDeviceConfig = SkBitmap::kNo_Config; SkBitmap::Config SkImageDecoder::GetDeviceConfig() { return gDeviceConfig; } void SkImageDecoder::SetDeviceConfig(SkBitmap::Config config) { gDeviceConfig = config; } /////////////////////////////////////////////////////////////////////////////// SkImageDecoder::SkImageDecoder() : fPeeker(NULL), fChooser(NULL), fAllocator(NULL), fSampleSize(1), fDitherImage(true) { } SkImageDecoder::~SkImageDecoder() { fPeeker->safeUnref(); fChooser->safeUnref(); fAllocator->safeUnref(); } SkImageDecoder::Format SkImageDecoder::getFormat() const { return kUnknown_Format; } SkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker* peeker) { SkRefCnt_SafeAssign(fPeeker, peeker); return peeker; } SkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser* chooser) { SkRefCnt_SafeAssign(fChooser, chooser); return chooser; } SkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator* alloc) { SkRefCnt_SafeAssign(fAllocator, alloc); return alloc; } void SkImageDecoder::setSampleSize(int size) { if (size < 1) { size = 1; } fSampleSize = size; } bool SkImageDecoder::chooseFromOneChoice(SkBitmap::Config config, int width, int height) const { Chooser* chooser = fChooser; if (NULL == chooser) { // no chooser, we just say YES to decoding :) return true; } chooser->begin(1); chooser->inspect(0, config, width, height); return chooser->choose() == 0; } bool SkImageDecoder::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) const { return bitmap->allocPixels(fAllocator, ctable); } /////////////////////////////////////////////////////////////////////////////// /* Technically, this should be 342, since that is the cutoff point between an index and 32bit bitmap (they take equal ram), but since 32bit is almost always faster, I bump up the value a bit. */ #define MIN_SIZE_FOR_INDEX (512) /* Return the "optimal" config for this bitmap. In this case, we just look to promote index bitmaps to full-color, since those are a little faster to draw (fewer memory lookups). Seems like we could expose this to the caller through some exising or new proxy object, allowing them to decide (after sniffing some aspect of the original bitmap) what config they really want. */ static SkBitmap::Config optimal_config(const SkBitmap& bm, SkBitmap::Config pref) { if (bm.config() != pref) { if (bm.config() == SkBitmap::kIndex8_Config) { Sk64 size64 = bm.getSize64(); if (size64.is32()) { int32_t size = size64.get32(); if (size < MIN_SIZE_FOR_INDEX) { return SkBitmap::kARGB_8888_Config; } } } } return bm.config(); } bool SkImageDecoder::decode(SkStream* stream, SkBitmap* bm, SkBitmap::Config pref, Mode mode) { // pass a temporary bitmap, so that if we return false, we are assured of // leaving the caller's bitmap untouched. SkBitmap tmp; // we reset this to false before calling onDecode fShouldCancelDecode = false; if (!this->onDecode(stream, &tmp, pref, mode)) { return false; } SkBitmap::Config c = optimal_config(tmp, pref); if (c != tmp.config()) { if (mode == kDecodeBounds_Mode) { tmp.setConfig(c, tmp.width(), tmp.height()); } else { SkBitmap tmp2; if (tmp.copyTo(&tmp2, c, this->getAllocator())) { tmp.swap(tmp2); } } } bm->swap(tmp); return true; } /////////////////////////////////////////////////////////////////////////////// bool SkImageDecoder::DecodeFile(const char file[], SkBitmap* bm, SkBitmap::Config pref, Mode mode) { SkASSERT(file); SkASSERT(bm); SkFILEStream stream(file); if (stream.isValid()) { if (SkImageDecoder::DecodeStream(&stream, bm, pref, mode)) { bm->pixelRef()->setURI(file); } return true; } return false; } bool SkImageDecoder::DecodeMemory(const void* buffer, size_t size, SkBitmap* bm, SkBitmap::Config pref, Mode mode) { if (0 == size) { return false; } SkASSERT(buffer); SkMemoryStream stream(buffer, size); return SkImageDecoder::DecodeStream(&stream, bm, pref, mode); } bool SkImageDecoder::DecodeStream(SkStream* stream, SkBitmap* bm, SkBitmap::Config pref, Mode mode) { SkASSERT(stream); SkASSERT(bm); bool success = false; SkImageDecoder* codec = SkImageDecoder::Factory(stream); if (NULL != codec) { success = codec->decode(stream, bm, pref, mode); delete codec; } return success; } <commit_msg>Do not merge check if we can promote to the preferred config<commit_after>/* libs/graphics/images/SkImageDecoder.cpp ** ** Copyright 2006, The Android Open Source Project ** ** 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 "SkImageDecoder.h" #include "SkBitmap.h" #include "SkPixelRef.h" #include "SkStream.h" #include "SkTemplates.h" static SkBitmap::Config gDeviceConfig = SkBitmap::kNo_Config; SkBitmap::Config SkImageDecoder::GetDeviceConfig() { return gDeviceConfig; } void SkImageDecoder::SetDeviceConfig(SkBitmap::Config config) { gDeviceConfig = config; } /////////////////////////////////////////////////////////////////////////////// SkImageDecoder::SkImageDecoder() : fPeeker(NULL), fChooser(NULL), fAllocator(NULL), fSampleSize(1), fDitherImage(true) { } SkImageDecoder::~SkImageDecoder() { fPeeker->safeUnref(); fChooser->safeUnref(); fAllocator->safeUnref(); } SkImageDecoder::Format SkImageDecoder::getFormat() const { return kUnknown_Format; } SkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker* peeker) { SkRefCnt_SafeAssign(fPeeker, peeker); return peeker; } SkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser* chooser) { SkRefCnt_SafeAssign(fChooser, chooser); return chooser; } SkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator* alloc) { SkRefCnt_SafeAssign(fAllocator, alloc); return alloc; } void SkImageDecoder::setSampleSize(int size) { if (size < 1) { size = 1; } fSampleSize = size; } bool SkImageDecoder::chooseFromOneChoice(SkBitmap::Config config, int width, int height) const { Chooser* chooser = fChooser; if (NULL == chooser) { // no chooser, we just say YES to decoding :) return true; } chooser->begin(1); chooser->inspect(0, config, width, height); return chooser->choose() == 0; } bool SkImageDecoder::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) const { return bitmap->allocPixels(fAllocator, ctable); } /////////////////////////////////////////////////////////////////////////////// static bool canCopyTo(SkBitmap::Config src, SkBitmap::Config dst) { if (src == SkBitmap::kNo_Config) { return false; } bool sameConfigs = (src == dst); switch (dst) { case SkBitmap::kA8_Config: case SkBitmap::kARGB_4444_Config: case SkBitmap::kRGB_565_Config: case SkBitmap::kARGB_8888_Config: break; case SkBitmap::kA1_Config: case SkBitmap::kIndex8_Config: if (!sameConfigs) { return false; } break; default: return false; } // do not copy src if srcConfig == kA1_Config while dstConfig != kA1_Config if (src == SkBitmap::kA1_Config && !sameConfigs) { return false; } return true; } bool SkImageDecoder::decode(SkStream* stream, SkBitmap* bm, SkBitmap::Config pref, Mode mode) { // pass a temporary bitmap, so that if we return false, we are assured of // leaving the caller's bitmap untouched. SkBitmap tmp; // we reset this to false before calling onDecode fShouldCancelDecode = false; if (!this->onDecode(stream, &tmp, pref, mode)) { return false; } if (tmp.config() != pref && canCopyTo(tmp.config(), pref)) { if (mode == kDecodeBounds_Mode) { tmp.setConfig(pref, tmp.width(), tmp.height()); } else if (mode == kDecodePixels_Mode) { SkBitmap tmp2; if (tmp.copyTo(&tmp2, pref, this->getAllocator())) { tmp.swap(tmp2); } } } bm->swap(tmp); return true; } /////////////////////////////////////////////////////////////////////////////// bool SkImageDecoder::DecodeFile(const char file[], SkBitmap* bm, SkBitmap::Config pref, Mode mode) { SkASSERT(file); SkASSERT(bm); SkFILEStream stream(file); if (stream.isValid()) { if (SkImageDecoder::DecodeStream(&stream, bm, pref, mode)) { bm->pixelRef()->setURI(file); } return true; } return false; } bool SkImageDecoder::DecodeMemory(const void* buffer, size_t size, SkBitmap* bm, SkBitmap::Config pref, Mode mode) { if (0 == size) { return false; } SkASSERT(buffer); SkMemoryStream stream(buffer, size); return SkImageDecoder::DecodeStream(&stream, bm, pref, mode); } bool SkImageDecoder::DecodeStream(SkStream* stream, SkBitmap* bm, SkBitmap::Config pref, Mode mode) { SkASSERT(stream); SkASSERT(bm); bool success = false; SkImageDecoder* codec = SkImageDecoder::Factory(stream); if (NULL != codec) { success = codec->decode(stream, bm, pref, mode); delete codec; } return success; } <|endoftext|>
<commit_before>//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "LightningLayer.h" #include "LightningTree.h" #include "../sliceDataStorage.h" #include "../utils/linearAlg2D.h" #include "../utils/SVG.h" #include "../utils/SparsePointGridInclusive.h" using namespace cura; coord_t LightningLayer::getWeightedDistance(const Point& boundary_loc, const Point& unsupported_loc) { return vSize(boundary_loc - unsupported_loc); } PolygonLightningDistanceField::PolygonLightningDistanceField ( const coord_t& radius, const Polygons& current_outline, const Polygons& current_overhang, const std::vector<std::shared_ptr<LightningTreeNode>>& initial_trees ) { supporting_radius = radius; Polygons supporting_polylines = current_outline; for (PolygonRef poly : supporting_polylines) { if (!poly.empty()) { poly.add(poly[0]); // add start so that the polyline is closed } } const LightningTreeNode::branch_visitor_func_t add_offset_branch_func = [&](const Point& parent, const Point& child) { supporting_polylines.addLine(parent, child); }; for (const auto& tree : initial_trees) { tree->visitBranches(add_offset_branch_func); } supported = supporting_polylines.offsetPolyLine(supporting_radius); unsupported = current_overhang.difference(supported); } bool PolygonLightningDistanceField::tryGetNextPoint(Point* p, coord_t supporting_radius) const { if (unsupported.area() < 25) { return false; } coord_t total_length = unsupported[0].polygonLength(); coord_t dist_to_point_on_boundary = std::rand() % total_length; ClosestPolygonPoint cpp = PolygonUtils::walk(ClosestPolygonPoint(unsupported[0][0], 0, unsupported[0]), dist_to_point_on_boundary); *p = PolygonUtils::moveInside(cpp, supporting_radius); if (!unsupported.inside(*p)) { PolygonUtils::moveInside(unsupported, *p, supporting_radius / 2); } // NOTE: it's okay for the rare case where a point ends up outside; it's just an inefficient tree branch. return true; } void PolygonLightningDistanceField::update(const Point& to_node, const Point& added_leaf) { Polygons line; line.addLine(to_node, added_leaf); Polygons offsetted = line.offsetPolyLine(supporting_radius, ClipperLib::jtRound); supported = supported.unionPolygons(offsetted); unsupported = unsupported.difference(supported); } // -- -- -- -- -- -- // -- -- -- -- -- -- LightningDistanceField::LightningDistanceField ( const coord_t& radius, const Polygons& current_outline, const Polygons& current_overhang, const std::vector<std::shared_ptr<LightningTreeNode>>& initial_trees ) : grid(cell_size) , supporting_radius(radius) , current_outline(current_outline) , current_overhang(current_overhang) { std::vector<Point> regular_dots = PolygonUtils::spreadDotsArea(current_overhang, cell_size); for (Point p : regular_dots) { const ClosestPolygonPoint cpp = PolygonUtils::findClosest(p, current_outline); const coord_t dist_to_boundary = vSize(p - cpp.p()); unsupported_points.emplace_back(p, dist_to_boundary); } unsupported_points.sort([](const UnsupCell& a, const UnsupCell& b) { return a.dist_to_boundary < b.dist_to_boundary; }); for (auto it = unsupported_points.begin(); it != unsupported_points.end(); ++it) { UnsupCell& cell = *it; unsupported_points_grid.emplace(grid.toGridPoint(cell.loc), it); } } bool LightningDistanceField::tryGetNextPoint(Point* p, coord_t supporting_radius) const { if (unsupported_points.empty()) return false; *p = unsupported_points.front().loc; return true; } void LightningDistanceField::update(const Point& to_node, const Point& added_leaf) { grid.processNearby(added_leaf, supporting_radius, [added_leaf, this](const SquareGrid::GridPoint& grid_loc) { auto it = unsupported_points_grid.find(grid_loc); if (it != unsupported_points_grid.end()) { std::list<UnsupCell>::iterator& list_it = it->second; UnsupCell& cell = *list_it; if (shorterThen(cell.loc - added_leaf, supporting_radius)) { unsupported_points.erase(list_it); unsupported_points_grid.erase(it); } } return true; }); } // -- -- -- -- -- -- // -- -- -- -- -- -- Point GroundingLocation::p() const { if (tree_node != nullptr) { return tree_node->getLocation(); } else { assert(boundary_location); return boundary_location->p(); } } LightningTreeNode::node_visitor_func_t getAddToLocatorFunc(SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator) { return [&tree_node_locator](std::shared_ptr<LightningTreeNode> node) { tree_node_locator.insert(node->getLocation(), node); }; } void LightningLayer::fillLocator(SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator) { const LightningTreeNode::node_visitor_func_t add_node_to_locator_func = getAddToLocatorFunc(tree_node_locator); for (auto& tree : tree_roots) { tree->visitNodes(add_node_to_locator_func); } } void LightningLayer::generateNewTrees(const Polygons& current_overhang, Polygons& current_outlines, coord_t supporting_radius) { LightningDistanceField distance_field(supporting_radius, current_outlines, current_overhang, tree_roots); constexpr coord_t locator_cell_size = 2000; SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>> tree_node_locator(locator_cell_size); const auto add_to_locator_func = getAddToLocatorFunc(tree_node_locator); fillLocator(tree_node_locator); constexpr size_t debug_max_iterations = 9999; // TODO: remove size_t i_debug = 0; // Until no more points need to be added to support all: // Determine next point from tree/outline areas via distance-field Point unsupported_location; while (distance_field.tryGetNextPoint(&unsupported_location, supporting_radius) && i_debug < debug_max_iterations) { ++i_debug; GroundingLocation grounding_loc = getBestGroundingLocation(unsupported_location, current_outlines, supporting_radius, tree_node_locator); // TODO: update unsupported_location to lie closer to grounding_loc attach(unsupported_location, grounding_loc)->visitNodes(add_to_locator_func); // update distance field distance_field.update(grounding_loc.p(), unsupported_location); } } GroundingLocation LightningLayer::getBestGroundingLocation(const Point& unsupported_location, const Polygons& current_outlines, const coord_t supporting_radius, const SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator, const std::shared_ptr<LightningTreeNode>& exclude_tree) { ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines); Point node_location = cpp.p(); std::shared_ptr<LightningTreeNode> sub_tree(nullptr); coord_t current_dist = getWeightedDistance(node_location, unsupported_location); auto candidate_trees = tree_node_locator.getNearbyVals(unsupported_location, std::min(current_dist, supporting_radius)); for (auto& candidate_wptr : candidate_trees) { auto candidate_sub_tree = candidate_wptr.lock(); if (candidate_sub_tree && candidate_sub_tree != exclude_tree && !(exclude_tree && exclude_tree->hasOffspring(candidate_sub_tree))) { const coord_t candidate_dist = candidate_sub_tree->getWeightedDistance(unsupported_location, supporting_radius); if (candidate_dist < current_dist) { current_dist = candidate_dist; sub_tree = candidate_sub_tree; } } } if (!sub_tree) { return GroundingLocation{ nullptr, cpp }; } else { return GroundingLocation{ sub_tree, std::optional<ClosestPolygonPoint>() }; } } std::shared_ptr<LightningTreeNode> LightningLayer::attach(const Point& unsupported_location, const GroundingLocation& grounding_loc) { // Update trees & distance fields. if (grounding_loc.boundary_location) { tree_roots.push_back(LightningTreeNode::create(grounding_loc.p(), unsupported_location)); return tree_roots.back(); } else { return grounding_loc.tree_node->addChild(unsupported_location); } } void LightningLayer::reconnectRoots(std::vector<std::shared_ptr<LightningTreeNode>>& to_be_reconnected_tree_roots, const Polygons& current_outlines, const coord_t supporting_radius) { constexpr coord_t locator_cell_size = 2000; SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>> tree_node_locator(locator_cell_size); fillLocator(tree_node_locator); const LightningTreeNode::node_visitor_func_t add_node_to_locator_func = getAddToLocatorFunc(tree_node_locator); for (auto root_ptr : to_be_reconnected_tree_roots) { auto old_root_it = std::find(tree_roots.begin(), tree_roots.end(), root_ptr); GroundingLocation ground = getBestGroundingLocation(root_ptr->getLocation(), current_outlines, supporting_radius, tree_node_locator, root_ptr); if (ground.boundary_location) { if (ground.boundary_location.value().p() == root_ptr->getLocation()) { continue; // Already on the boundary. } auto new_root = LightningTreeNode::create(ground.p()); new_root->addChild(root_ptr); tree_node_locator.insert(new_root->getLocation(), new_root); *old_root_it = std::move(new_root); // replace old root with new root } else { assert(ground.tree_node); assert(ground.tree_node != root_ptr); assert(!root_ptr->hasOffspring(ground.tree_node)); assert(!ground.tree_node->hasOffspring(root_ptr)); ground.tree_node->addChild(root_ptr); // remove old root *old_root_it = std::move(tree_roots.back()); tree_roots.pop_back(); } } } // Returns 'added someting'. Polygons LightningLayer::convertToLines() const { Polygons result_lines; if (tree_roots.empty()) { return result_lines; } // TODO: The convert trees to lines 'algorithm' is way too simple right now (unless they're already going to be connected later). LightningTreeNode::branch_visitor_func_t convert_trees_to_lines = [&result_lines](const Point& node, const Point& leaf) { result_lines.addLine(node, leaf); }; for (const auto& tree : tree_roots) { tree->visitBranches(convert_trees_to_lines); } return result_lines; } <commit_msg>No need for closure outside of fillLocator.<commit_after>//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "LightningLayer.h" #include "LightningTree.h" #include "../sliceDataStorage.h" #include "../utils/linearAlg2D.h" #include "../utils/SVG.h" #include "../utils/SparsePointGridInclusive.h" using namespace cura; coord_t LightningLayer::getWeightedDistance(const Point& boundary_loc, const Point& unsupported_loc) { return vSize(boundary_loc - unsupported_loc); } PolygonLightningDistanceField::PolygonLightningDistanceField ( const coord_t& radius, const Polygons& current_outline, const Polygons& current_overhang, const std::vector<std::shared_ptr<LightningTreeNode>>& initial_trees ) { supporting_radius = radius; Polygons supporting_polylines = current_outline; for (PolygonRef poly : supporting_polylines) { if (!poly.empty()) { poly.add(poly[0]); // add start so that the polyline is closed } } const LightningTreeNode::branch_visitor_func_t add_offset_branch_func = [&](const Point& parent, const Point& child) { supporting_polylines.addLine(parent, child); }; for (const auto& tree : initial_trees) { tree->visitBranches(add_offset_branch_func); } supported = supporting_polylines.offsetPolyLine(supporting_radius); unsupported = current_overhang.difference(supported); } bool PolygonLightningDistanceField::tryGetNextPoint(Point* p, coord_t supporting_radius) const { if (unsupported.area() < 25) { return false; } coord_t total_length = unsupported[0].polygonLength(); coord_t dist_to_point_on_boundary = std::rand() % total_length; ClosestPolygonPoint cpp = PolygonUtils::walk(ClosestPolygonPoint(unsupported[0][0], 0, unsupported[0]), dist_to_point_on_boundary); *p = PolygonUtils::moveInside(cpp, supporting_radius); if (!unsupported.inside(*p)) { PolygonUtils::moveInside(unsupported, *p, supporting_radius / 2); } // NOTE: it's okay for the rare case where a point ends up outside; it's just an inefficient tree branch. return true; } void PolygonLightningDistanceField::update(const Point& to_node, const Point& added_leaf) { Polygons line; line.addLine(to_node, added_leaf); Polygons offsetted = line.offsetPolyLine(supporting_radius, ClipperLib::jtRound); supported = supported.unionPolygons(offsetted); unsupported = unsupported.difference(supported); } // -- -- -- -- -- -- // -- -- -- -- -- -- LightningDistanceField::LightningDistanceField ( const coord_t& radius, const Polygons& current_outline, const Polygons& current_overhang, const std::vector<std::shared_ptr<LightningTreeNode>>& initial_trees ) : grid(cell_size) , supporting_radius(radius) , current_outline(current_outline) , current_overhang(current_overhang) { std::vector<Point> regular_dots = PolygonUtils::spreadDotsArea(current_overhang, cell_size); for (Point p : regular_dots) { const ClosestPolygonPoint cpp = PolygonUtils::findClosest(p, current_outline); const coord_t dist_to_boundary = vSize(p - cpp.p()); unsupported_points.emplace_back(p, dist_to_boundary); } unsupported_points.sort([](const UnsupCell& a, const UnsupCell& b) { return a.dist_to_boundary < b.dist_to_boundary; }); for (auto it = unsupported_points.begin(); it != unsupported_points.end(); ++it) { UnsupCell& cell = *it; unsupported_points_grid.emplace(grid.toGridPoint(cell.loc), it); } } bool LightningDistanceField::tryGetNextPoint(Point* p, coord_t supporting_radius) const { if (unsupported_points.empty()) return false; *p = unsupported_points.front().loc; return true; } void LightningDistanceField::update(const Point& to_node, const Point& added_leaf) { grid.processNearby(added_leaf, supporting_radius, [added_leaf, this](const SquareGrid::GridPoint& grid_loc) { auto it = unsupported_points_grid.find(grid_loc); if (it != unsupported_points_grid.end()) { std::list<UnsupCell>::iterator& list_it = it->second; UnsupCell& cell = *list_it; if (shorterThen(cell.loc - added_leaf, supporting_radius)) { unsupported_points.erase(list_it); unsupported_points_grid.erase(it); } } return true; }); } // -- -- -- -- -- -- // -- -- -- -- -- -- Point GroundingLocation::p() const { if (tree_node != nullptr) { return tree_node->getLocation(); } else { assert(boundary_location); return boundary_location->p(); } } void LightningLayer::fillLocator(SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator) { const LightningTreeNode::node_visitor_func_t add_node_to_locator_func = [&tree_node_locator](std::shared_ptr<LightningTreeNode> node) { tree_node_locator.insert(node->getLocation(), node); }; for (auto& tree : tree_roots) { tree->visitNodes(add_node_to_locator_func); } } void LightningLayer::generateNewTrees(const Polygons& current_overhang, Polygons& current_outlines, coord_t supporting_radius) { LightningDistanceField distance_field(supporting_radius, current_outlines, current_overhang, tree_roots); constexpr coord_t locator_cell_size = 2000; SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>> tree_node_locator(locator_cell_size); fillLocator(tree_node_locator); constexpr size_t debug_max_iterations = 9999; // TODO: remove size_t i_debug = 0; // Until no more points need to be added to support all: // Determine next point from tree/outline areas via distance-field Point unsupported_location; while (distance_field.tryGetNextPoint(&unsupported_location, supporting_radius) && i_debug < debug_max_iterations) { ++i_debug; GroundingLocation grounding_loc = getBestGroundingLocation(unsupported_location, current_outlines, supporting_radius, tree_node_locator); // TODO: update unsupported_location to lie closer to grounding_loc auto tree_node = attach(unsupported_location, grounding_loc); tree_node_locator.insert(tree_node->getLocation(), tree_node); // update distance field distance_field.update(grounding_loc.p(), unsupported_location); } } GroundingLocation LightningLayer::getBestGroundingLocation(const Point& unsupported_location, const Polygons& current_outlines, const coord_t supporting_radius, const SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator, const std::shared_ptr<LightningTreeNode>& exclude_tree) { ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines); Point node_location = cpp.p(); std::shared_ptr<LightningTreeNode> sub_tree(nullptr); coord_t current_dist = getWeightedDistance(node_location, unsupported_location); auto candidate_trees = tree_node_locator.getNearbyVals(unsupported_location, std::min(current_dist, supporting_radius)); for (auto& candidate_wptr : candidate_trees) { auto candidate_sub_tree = candidate_wptr.lock(); if (candidate_sub_tree && candidate_sub_tree != exclude_tree && !(exclude_tree && exclude_tree->hasOffspring(candidate_sub_tree))) { const coord_t candidate_dist = candidate_sub_tree->getWeightedDistance(unsupported_location, supporting_radius); if (candidate_dist < current_dist) { current_dist = candidate_dist; sub_tree = candidate_sub_tree; } } } if (!sub_tree) { return GroundingLocation{ nullptr, cpp }; } else { return GroundingLocation{ sub_tree, std::optional<ClosestPolygonPoint>() }; } } std::shared_ptr<LightningTreeNode> LightningLayer::attach(const Point& unsupported_location, const GroundingLocation& grounding_loc) { // Update trees & distance fields. if (grounding_loc.boundary_location) { tree_roots.push_back(LightningTreeNode::create(grounding_loc.p(), unsupported_location)); return tree_roots.back(); } else { return grounding_loc.tree_node->addChild(unsupported_location); } } void LightningLayer::reconnectRoots(std::vector<std::shared_ptr<LightningTreeNode>>& to_be_reconnected_tree_roots, const Polygons& current_outlines, const coord_t supporting_radius) { constexpr coord_t locator_cell_size = 2000; SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>> tree_node_locator(locator_cell_size); fillLocator(tree_node_locator); for (auto root_ptr : to_be_reconnected_tree_roots) { auto old_root_it = std::find(tree_roots.begin(), tree_roots.end(), root_ptr); GroundingLocation ground = getBestGroundingLocation(root_ptr->getLocation(), current_outlines, supporting_radius, tree_node_locator, root_ptr); if (ground.boundary_location) { if (ground.boundary_location.value().p() == root_ptr->getLocation()) { continue; // Already on the boundary. } auto new_root = LightningTreeNode::create(ground.p()); new_root->addChild(root_ptr); tree_node_locator.insert(new_root->getLocation(), new_root); *old_root_it = std::move(new_root); // replace old root with new root } else { assert(ground.tree_node); assert(ground.tree_node != root_ptr); assert(!root_ptr->hasOffspring(ground.tree_node)); assert(!ground.tree_node->hasOffspring(root_ptr)); ground.tree_node->addChild(root_ptr); // remove old root *old_root_it = std::move(tree_roots.back()); tree_roots.pop_back(); } } } // Returns 'added someting'. Polygons LightningLayer::convertToLines() const { Polygons result_lines; if (tree_roots.empty()) { return result_lines; } // TODO: The convert trees to lines 'algorithm' is way too simple right now (unless they're already going to be connected later). LightningTreeNode::branch_visitor_func_t convert_trees_to_lines = [&result_lines](const Point& node, const Point& leaf) { result_lines.addLine(node, leaf); }; for (const auto& tree : tree_roots) { tree->visitBranches(convert_trees_to_lines); } return result_lines; } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the LiveSupport project. http://livesupport.campware.org/ To report bugs, send an e-mail to bugs@campware.org LiveSupport is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. LiveSupport is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with LiveSupport; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author: fgerlits $ Version : $Revision: 1.21 $ Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/products/gLiveSupport/src/MasterPanelWindow.cxx,v $ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #include <iostream> #include <unicode/msgfmt.h> #include <gtkmm/label.h> #include <gtkmm/main.h> #include "LiveSupport/Core/TimeConversion.h" #include "MasterPanelWindow.h" using namespace LiveSupport; using namespace LiveSupport::GLiveSupport; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Constructor. *----------------------------------------------------------------------------*/ MasterPanelWindow :: MasterPanelWindow (Ptr<GLiveSupport>::Ref gLiveSupport, Ptr<ResourceBundle>::Ref bundle) throw () : LocalizedObject(bundle) { this->gLiveSupport = gLiveSupport; Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance(); // TODO: remove hard-coded station logo path reference radioLogoWidget = Gtk::manage(new Gtk::Image("var/stationLogo.png")); radioLogoWidget->set_size_request(158, 104); // set up the layout, which is a button box layout = Gtk::manage(new Gtk::Table()); // set up the time label timeWidget = Gtk::manage(new Gtk::Label("time")); timeBin = Gtk::manage(widgetFactory->createBlueBin()); timeBin->add(*timeWidget); timeBin->set_size_request(153, 104); // set up the now playing widget nowPlayingWidget = Gtk::manage(new Gtk::Label("now playing")); nowPlayingBin = Gtk::manage(widgetFactory->createDarkBlueBin()); nowPlayingBin->add(*nowPlayingWidget); timeBin->set_size_request(-1, 104); // set up the VU meter widget vuMeterWidget = Gtk::manage(new Gtk::Label("VU meter")); vuMeterBin = Gtk::manage(widgetFactory->createBlueBin()); vuMeterBin->add(*vuMeterWidget); vuMeterBin->set_size_request(400, 40); // set up the next playing widget nextPlayingWidget = Gtk::manage(new Gtk::Label("next playing")); nextPlayingBin = Gtk::manage(widgetFactory->createBlueBin()); nextPlayingBin->add(*nextPlayingWidget); nextPlayingBin->set_size_request(400, 59); // create the bottom bar bottomBar = Gtk::manage(new Gtk::Table()); bottomBar->set_size_request(-1, 30); buttonBar = Gtk::manage(new Gtk::Table()); buttonBarAlignment = Gtk::manage(new Gtk::Alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, 0, 0)); buttonBarAlignment->add(*buttonBar); userInfoWidget = Gtk::manage(new MasterPanelUserInfoWidget(gLiveSupport, bundle)); userInfoAlignment = Gtk::manage(new Gtk::Alignment(Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER, 0, 0)); userInfoAlignment->add(*userInfoWidget); bottomBar->attach(*buttonBarAlignment, 0, 1, 0, 1, Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); bottomBar->attach(*userInfoAlignment, 1, 2, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); // set up the main window, and show everything // all the localized widgets were set up in changeLanguage() set_border_width(10); layout->attach(*timeBin, 0, 1, 0, 2, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 0, 0); layout->attach(*nowPlayingBin, 1, 2, 0, 2, Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); layout->attach(*vuMeterBin, 2, 3, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 0, 0); layout->attach(*nextPlayingBin, 2, 3, 1, 2, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 0, 0); layout->attach(*radioLogoWidget, 3, 4, 0, 2, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); layout->attach(*bottomBar, 0, 4, 2, 3, Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 0, 0); add(*layout); // set the background to white bgColor = Colors::getColor(Colors::White); modify_bg(Gtk::STATE_NORMAL, bgColor); // set the size and location of the window, according to the screen size Glib::RefPtr<Gdk::Screen> screen = get_screen(); int width; int height; get_size(width, height); width = screen->get_width(); set_default_size(width, height); move(0, 0); set_decorated(false); // set the localized resources changeLanguage(bundle); // show what's there to see showAnonymousUI(); // set the timer, that will update timeWidget setTimer(); } /*------------------------------------------------------------------------------ * Destructor. *----------------------------------------------------------------------------*/ MasterPanelWindow :: ~MasterPanelWindow (void) throw () { resetTimer(); gLiveSupport->stopAudio(); } /*------------------------------------------------------------------------------ * Change the language of the panel *----------------------------------------------------------------------------*/ void MasterPanelWindow :: changeLanguage(Ptr<ResourceBundle>::Ref bundle) throw () { setBundle(bundle); try { set_title(*getResourceUstring("windowTitle")); Ptr<WidgetFactory>::Ref wf = WidgetFactory::getInstance(); uploadFileButton = wf->createButton( *getResourceUstring("uploadFileButtonLabel")); scratchpadButton = wf->createButton( *getResourceUstring("scratchpadButtonLabel")); simplePlaylistMgmtButton = wf->createButton( *getResourceUstring("simplePlaylistMgmtButtonLabel")); schedulerButton = wf->createButton( *getResourceUstring("schedulerButtonLabel")); searchButton = wf->createButton( *getResourceUstring("searchButtonLabel")); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; std::exit(1); } userInfoWidget->changeLanguage(bundle); // re-attach the localized widgets to the layout buttonBar->attach(*uploadFileButton, 0, 1, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); buttonBar->attach(*scratchpadButton, 1, 2, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); buttonBar->attach(*simplePlaylistMgmtButton, 2, 3, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); buttonBar->attach(*schedulerButton, 3, 4, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); buttonBar->attach(*searchButton, 4, 5, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); // re-bind events to the buttons uploadFileButton->signal_clicked().connect(sigc::mem_fun(*this, &MasterPanelWindow::onUploadFileButtonClicked)); scratchpadButton->signal_clicked().connect(sigc::mem_fun(*this, &MasterPanelWindow::onScratchpadButtonClicked)); simplePlaylistMgmtButton->signal_clicked().connect( sigc::mem_fun(*this, &MasterPanelWindow::onSimplePlaylistMgmtButtonClicked)); schedulerButton->signal_clicked().connect(sigc::mem_fun(*this, &MasterPanelWindow::onSchedulerButtonClicked)); searchButton->signal_clicked().connect(sigc::mem_fun(*this, &MasterPanelWindow::onSearchButtonClicked)); } /*------------------------------------------------------------------------------ * Set the timer *----------------------------------------------------------------------------*/ void MasterPanelWindow :: setTimer(void) throw () { sigc::slot<bool> slot = sigc::bind(sigc::mem_fun(*this, &MasterPanelWindow::onUpdateTime), 0); // set the timer to active once a second timer.reset(new sigc::connection( Glib::signal_timeout().connect(slot, 1000))); } /*------------------------------------------------------------------------------ * Clear the timer *----------------------------------------------------------------------------*/ void MasterPanelWindow :: resetTimer(void) throw () { timer->disconnect(); timer.reset(); } /*------------------------------------------------------------------------------ * Update the timeWidget display, with the current time *----------------------------------------------------------------------------*/ bool MasterPanelWindow :: onUpdateTime(int dummy) throw () { Ptr<const ptime>::Ref now; try { now = gLiveSupport->getScheduler()->getSchedulerTime(); } catch (XmlRpcException &e) { // TODO: handle error } if (now.get()) { time_duration dayTime = now->time_of_day(); // get the time of day, only up to a second precision time_duration dayTimeSec(dayTime.hours(), dayTime.minutes(), dayTime.seconds(), 0); timeWidget->set_text(to_simple_string(dayTimeSec)); } return true; } /*------------------------------------------------------------------------------ * The event when the upload file button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onUploadFileButtonClicked(void) throw () { if (!scratchpadWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("uploadFileWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } uploadFileWindow.reset(new UploadFileWindow(gLiveSupport, bundle)); } if (!uploadFileWindow->is_visible()) { uploadFileWindow->show(); } } /*------------------------------------------------------------------------------ * The event when the Scratchpad button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onScratchpadButtonClicked(void) throw () { if (!scratchpadWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("scratchpadWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } scratchpadWindow.reset(new ScratchpadWindow(gLiveSupport, bundle)); } if (!scratchpadWindow->is_visible()) { scratchpadWindow->show(); } scratchpadWindow->showContents(); } /*------------------------------------------------------------------------------ * The event when the Simple Playlist Management button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onSimplePlaylistMgmtButtonClicked(void) throw () { if (!simplePlaylistMgmtWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("simplePlaylistManagementWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } simplePlaylistMgmtWindow.reset( new SimplePlaylistManagementWindow(gLiveSupport, bundle)); } if (!simplePlaylistMgmtWindow->is_visible()) { simplePlaylistMgmtWindow->show(); } } /*------------------------------------------------------------------------------ * The event when the Scheduler button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onSchedulerButtonClicked(void) throw () { if (!schedulerWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("schedulerWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } schedulerWindow.reset(new SchedulerWindow(gLiveSupport, bundle)); } if (!schedulerWindow->is_visible()) { schedulerWindow->show(); } } /*------------------------------------------------------------------------------ * The event when the Search button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onSearchButtonClicked(void) throw () { if (!searchWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("searchWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } searchWindow.reset(new SearchWindow(gLiveSupport, bundle)); } if (!searchWindow->is_visible()) { searchWindow->show(); } } /*------------------------------------------------------------------------------ * Show only the UI components that are visible when no one is logged in *----------------------------------------------------------------------------*/ void MasterPanelWindow :: showAnonymousUI(void) throw () { show_all(); buttonBar->hide(); uploadFileButton->hide(); scratchpadButton->hide(); simplePlaylistMgmtButton->hide(); schedulerButton->hide(); searchButton->hide(); if (uploadFileWindow) { uploadFileWindow->hide(); } if (scratchpadWindow) { scratchpadWindow->hide(); } if (simplePlaylistMgmtWindow) { simplePlaylistMgmtWindow->hide(); } if (schedulerWindow) { schedulerWindow->hide(); } if (searchWindow) { searchWindow->hide(); } } /*------------------------------------------------------------------------------ * Show the UI components that are visible to a specific user. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: showLoggedInUI(void) throw () { show_all(); } <commit_msg>all windows but the master panel are destroyed at logout fix for issue #878, see http://bugs.campware.org/view.php?id=878<commit_after>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the LiveSupport project. http://livesupport.campware.org/ To report bugs, send an e-mail to bugs@campware.org LiveSupport is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. LiveSupport is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with LiveSupport; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author: maroy $ Version : $Revision: 1.22 $ Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/products/gLiveSupport/src/MasterPanelWindow.cxx,v $ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #include <iostream> #include <unicode/msgfmt.h> #include <gtkmm/label.h> #include <gtkmm/main.h> #include "LiveSupport/Core/TimeConversion.h" #include "MasterPanelWindow.h" using namespace LiveSupport; using namespace LiveSupport::GLiveSupport; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Constructor. *----------------------------------------------------------------------------*/ MasterPanelWindow :: MasterPanelWindow (Ptr<GLiveSupport>::Ref gLiveSupport, Ptr<ResourceBundle>::Ref bundle) throw () : LocalizedObject(bundle) { this->gLiveSupport = gLiveSupport; Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance(); // TODO: remove hard-coded station logo path reference radioLogoWidget = Gtk::manage(new Gtk::Image("var/stationLogo.png")); radioLogoWidget->set_size_request(158, 104); // set up the layout, which is a button box layout = Gtk::manage(new Gtk::Table()); // set up the time label timeWidget = Gtk::manage(new Gtk::Label("time")); timeBin = Gtk::manage(widgetFactory->createBlueBin()); timeBin->add(*timeWidget); timeBin->set_size_request(153, 104); // set up the now playing widget nowPlayingWidget = Gtk::manage(new Gtk::Label("now playing")); nowPlayingBin = Gtk::manage(widgetFactory->createDarkBlueBin()); nowPlayingBin->add(*nowPlayingWidget); timeBin->set_size_request(-1, 104); // set up the VU meter widget vuMeterWidget = Gtk::manage(new Gtk::Label("VU meter")); vuMeterBin = Gtk::manage(widgetFactory->createBlueBin()); vuMeterBin->add(*vuMeterWidget); vuMeterBin->set_size_request(400, 40); // set up the next playing widget nextPlayingWidget = Gtk::manage(new Gtk::Label("next playing")); nextPlayingBin = Gtk::manage(widgetFactory->createBlueBin()); nextPlayingBin->add(*nextPlayingWidget); nextPlayingBin->set_size_request(400, 59); // create the bottom bar bottomBar = Gtk::manage(new Gtk::Table()); bottomBar->set_size_request(-1, 30); buttonBar = Gtk::manage(new Gtk::Table()); buttonBarAlignment = Gtk::manage(new Gtk::Alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, 0, 0)); buttonBarAlignment->add(*buttonBar); userInfoWidget = Gtk::manage(new MasterPanelUserInfoWidget(gLiveSupport, bundle)); userInfoAlignment = Gtk::manage(new Gtk::Alignment(Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER, 0, 0)); userInfoAlignment->add(*userInfoWidget); bottomBar->attach(*buttonBarAlignment, 0, 1, 0, 1, Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); bottomBar->attach(*userInfoAlignment, 1, 2, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); // set up the main window, and show everything // all the localized widgets were set up in changeLanguage() set_border_width(10); layout->attach(*timeBin, 0, 1, 0, 2, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 0, 0); layout->attach(*nowPlayingBin, 1, 2, 0, 2, Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); layout->attach(*vuMeterBin, 2, 3, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 0, 0); layout->attach(*nextPlayingBin, 2, 3, 1, 2, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 0, 0); layout->attach(*radioLogoWidget, 3, 4, 0, 2, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); layout->attach(*bottomBar, 0, 4, 2, 3, Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 0, 0); add(*layout); // set the background to white bgColor = Colors::getColor(Colors::White); modify_bg(Gtk::STATE_NORMAL, bgColor); // set the size and location of the window, according to the screen size Glib::RefPtr<Gdk::Screen> screen = get_screen(); int width; int height; get_size(width, height); width = screen->get_width(); set_default_size(width, height); move(0, 0); set_decorated(false); // set the localized resources changeLanguage(bundle); // show what's there to see showAnonymousUI(); // set the timer, that will update timeWidget setTimer(); } /*------------------------------------------------------------------------------ * Destructor. *----------------------------------------------------------------------------*/ MasterPanelWindow :: ~MasterPanelWindow (void) throw () { resetTimer(); gLiveSupport->stopAudio(); } /*------------------------------------------------------------------------------ * Change the language of the panel *----------------------------------------------------------------------------*/ void MasterPanelWindow :: changeLanguage(Ptr<ResourceBundle>::Ref bundle) throw () { setBundle(bundle); try { set_title(*getResourceUstring("windowTitle")); Ptr<WidgetFactory>::Ref wf = WidgetFactory::getInstance(); uploadFileButton = wf->createButton( *getResourceUstring("uploadFileButtonLabel")); scratchpadButton = wf->createButton( *getResourceUstring("scratchpadButtonLabel")); simplePlaylistMgmtButton = wf->createButton( *getResourceUstring("simplePlaylistMgmtButtonLabel")); schedulerButton = wf->createButton( *getResourceUstring("schedulerButtonLabel")); searchButton = wf->createButton( *getResourceUstring("searchButtonLabel")); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; std::exit(1); } userInfoWidget->changeLanguage(bundle); // re-attach the localized widgets to the layout buttonBar->attach(*uploadFileButton, 0, 1, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); buttonBar->attach(*scratchpadButton, 1, 2, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); buttonBar->attach(*simplePlaylistMgmtButton, 2, 3, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); buttonBar->attach(*schedulerButton, 3, 4, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); buttonBar->attach(*searchButton, 4, 5, 0, 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 5, 0); // re-bind events to the buttons uploadFileButton->signal_clicked().connect(sigc::mem_fun(*this, &MasterPanelWindow::onUploadFileButtonClicked)); scratchpadButton->signal_clicked().connect(sigc::mem_fun(*this, &MasterPanelWindow::onScratchpadButtonClicked)); simplePlaylistMgmtButton->signal_clicked().connect( sigc::mem_fun(*this, &MasterPanelWindow::onSimplePlaylistMgmtButtonClicked)); schedulerButton->signal_clicked().connect(sigc::mem_fun(*this, &MasterPanelWindow::onSchedulerButtonClicked)); searchButton->signal_clicked().connect(sigc::mem_fun(*this, &MasterPanelWindow::onSearchButtonClicked)); } /*------------------------------------------------------------------------------ * Set the timer *----------------------------------------------------------------------------*/ void MasterPanelWindow :: setTimer(void) throw () { sigc::slot<bool> slot = sigc::bind(sigc::mem_fun(*this, &MasterPanelWindow::onUpdateTime), 0); // set the timer to active once a second timer.reset(new sigc::connection( Glib::signal_timeout().connect(slot, 1000))); } /*------------------------------------------------------------------------------ * Clear the timer *----------------------------------------------------------------------------*/ void MasterPanelWindow :: resetTimer(void) throw () { timer->disconnect(); timer.reset(); } /*------------------------------------------------------------------------------ * Update the timeWidget display, with the current time *----------------------------------------------------------------------------*/ bool MasterPanelWindow :: onUpdateTime(int dummy) throw () { Ptr<const ptime>::Ref now; try { now = gLiveSupport->getScheduler()->getSchedulerTime(); } catch (XmlRpcException &e) { // TODO: handle error } if (now.get()) { time_duration dayTime = now->time_of_day(); // get the time of day, only up to a second precision time_duration dayTimeSec(dayTime.hours(), dayTime.minutes(), dayTime.seconds(), 0); timeWidget->set_text(to_simple_string(dayTimeSec)); } return true; } /*------------------------------------------------------------------------------ * The event when the upload file button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onUploadFileButtonClicked(void) throw () { if (!uploadFileWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("uploadFileWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } uploadFileWindow.reset(new UploadFileWindow(gLiveSupport, bundle)); } if (!uploadFileWindow->is_visible()) { uploadFileWindow->show(); } } /*------------------------------------------------------------------------------ * The event when the Scratchpad button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onScratchpadButtonClicked(void) throw () { if (!scratchpadWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("scratchpadWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } scratchpadWindow.reset(new ScratchpadWindow(gLiveSupport, bundle)); } if (!scratchpadWindow->is_visible()) { scratchpadWindow->show(); } scratchpadWindow->showContents(); } /*------------------------------------------------------------------------------ * The event when the Simple Playlist Management button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onSimplePlaylistMgmtButtonClicked(void) throw () { if (!simplePlaylistMgmtWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("simplePlaylistManagementWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } simplePlaylistMgmtWindow.reset( new SimplePlaylistManagementWindow(gLiveSupport, bundle)); } if (!simplePlaylistMgmtWindow->is_visible()) { simplePlaylistMgmtWindow->show(); } } /*------------------------------------------------------------------------------ * The event when the Scheduler button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onSchedulerButtonClicked(void) throw () { if (!schedulerWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("schedulerWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } schedulerWindow.reset(new SchedulerWindow(gLiveSupport, bundle)); } if (!schedulerWindow->is_visible()) { schedulerWindow->show(); } } /*------------------------------------------------------------------------------ * The event when the Search button has been clicked. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: onSearchButtonClicked(void) throw () { if (!searchWindow.get()) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("searchWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } searchWindow.reset(new SearchWindow(gLiveSupport, bundle)); } if (!searchWindow->is_visible()) { searchWindow->show(); } } /*------------------------------------------------------------------------------ * Show only the UI components that are visible when no one is logged in *----------------------------------------------------------------------------*/ void MasterPanelWindow :: showAnonymousUI(void) throw () { show_all(); buttonBar->hide(); uploadFileButton->hide(); scratchpadButton->hide(); simplePlaylistMgmtButton->hide(); schedulerButton->hide(); searchButton->hide(); if (uploadFileWindow.get()) { uploadFileWindow->hide(); uploadFileWindow.reset(); } if (scratchpadWindow.get()) { scratchpadWindow->hide(); scratchpadWindow.reset(); } if (simplePlaylistMgmtWindow.get()) { simplePlaylistMgmtWindow->hide(); simplePlaylistMgmtWindow.reset(); } if (schedulerWindow.get()) { schedulerWindow->hide(); schedulerWindow.reset(); } if (searchWindow.get()) { searchWindow->hide(); searchWindow.reset(); } } /*------------------------------------------------------------------------------ * Show the UI components that are visible to a specific user. *----------------------------------------------------------------------------*/ void MasterPanelWindow :: showLoggedInUI(void) throw () { show_all(); } <|endoftext|>
<commit_before>/********************************************************************** * Copyright (c) 2013-2014 Red Hat, Inc. * * Developed by Daynix Computing LTD. * * Authors: * Dmitry Fleytman <dmitry@daynix.com> * Pavel Gurvich <pavel@daynix.com> * * 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 "stdafx.h" #include "WdfDevice.h" #include "trace.h" #include "WdfDevice.tmh" CDeviceInit::~CDeviceInit() { if (m_Attached) { Free(); } } void CDeviceInit::Attach(PWDFDEVICE_INIT DevInit) { m_Attached = true; CPreAllocatedDeviceInit::Attach(DevInit); } PWDFDEVICE_INIT CDeviceInit::Detach() { m_Attached = false; return CPreAllocatedDeviceInit::Detach(); } NTSTATUS CPreAllocatedDeviceInit::SetName(const UNICODE_STRING &Name) { auto status = WdfDeviceInitAssignName(m_DeviceInit, &Name); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } return status; } void CPreAllocatedDeviceInit::Free() { WdfDeviceInitFree(m_DeviceInit); } void CPreAllocatedDeviceInit::SetPowerCallbacks(PFN_WDF_DEVICE_SELF_MANAGED_IO_INIT SelfManagedIoFunc) { WDF_PNPPOWER_EVENT_CALLBACKS Callbacks; WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&Callbacks); Callbacks.EvtDeviceSelfManagedIoInit = SelfManagedIoFunc; WdfDeviceInitSetPnpPowerEventCallbacks(m_DeviceInit, &Callbacks); } void CPreAllocatedDeviceInit::Attach(PWDFDEVICE_INIT DeviceInit) { m_DeviceInit = DeviceInit; } PWDFDEVICE_INIT CPreAllocatedDeviceInit::Detach() { auto DevInit = m_DeviceInit; m_DeviceInit = nullptr; return DevInit; } NTSTATUS CPreAllocatedDeviceInit::SetPreprocessCallback(PFN_WDFDEVICE_WDM_IRP_PREPROCESS Callback, UCHAR MajorFunction, const PUCHAR MinorFunctions, ULONG NumMinorFunctions) { auto status = WdfDeviceInitAssignWdmIrpPreprocessCallback(m_DeviceInit, Callback, MajorFunction, MinorFunctions, NumMinorFunctions); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! status: %!STATUS!", status); } return status; } NTSTATUS CWdfDevice::CreateSymLink(const UNICODE_STRING &Name) { auto status = WdfDeviceCreateSymbolicLink(m_Device, &Name); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } return status; } NTSTATUS CWdfDevice::Create(CPreAllocatedDeviceInit &DeviceInit, WDF_OBJECT_ATTRIBUTES &DeviceAttr) { auto DevInitObj = DeviceInit.Detach(); auto status = WdfDeviceCreate(&DevInitObj, &DeviceAttr, &m_Device); if (!NT_SUCCESS(status)) { DeviceInit.Attach(DevInitObj); TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } status = CacheDeviceName(); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! Device name caching failed %!STATUS!", status); } return status; } NTSTATUS CWdfQueue::Create(CWdfDevice &Device) { WDF_IO_QUEUE_CONFIG QueueConfig; WDF_OBJECT_ATTRIBUTES Attributes; InitConfig(QueueConfig); SetCallbacks(QueueConfig); WDF_OBJECT_ATTRIBUTES_INIT(&Attributes); Attributes.ExecutionLevel = WdfExecutionLevelPassive; auto status = Device.AddQueue(QueueConfig, Attributes, m_Queue); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } return status; } NTSTATUS CWdfDevice::AddQueue(WDF_IO_QUEUE_CONFIG &Config, WDF_OBJECT_ATTRIBUTES &Attributes, WDFQUEUE &Queue) { auto status = WdfIoQueueCreate(m_Device, &Config, &Attributes, &Queue); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } return status; } void CWdfDefaultQueue::InitConfig(WDF_IO_QUEUE_CONFIG &QueueConfig) { WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&QueueConfig, m_DispatchType); } void CWdfSpecificQueue::InitConfig(WDF_IO_QUEUE_CONFIG &QueueConfig) { WDF_IO_QUEUE_CONFIG_INIT(&QueueConfig, m_DispatchType); } NTSTATUS CWdfDevice::CacheDeviceName() { WDFSTRING deviceName; auto status = WdfStringCreate(NULL, WDF_NO_OBJECT_ATTRIBUTES, &deviceName); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! WdfStringCreate failed. %!STATUS!", status); return status; } status = WdfDeviceRetrieveDeviceName(m_Device, deviceName); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! WdfDeviceRetrieveDeviceName failed. %!STATUS!", status); WdfObjectDelete(deviceName); return status; } UNICODE_STRING UnicodeDeviceName; WdfStringGetUnicodeString(deviceName, &UnicodeDeviceName); status = m_CachedName.Create(&UnicodeDeviceName); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! CString creation failed. %!STATUS!", status); WdfObjectDelete(deviceName); return status; } TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! Newly created device name is %wZ", &UnicodeDeviceName); WdfObjectDelete(deviceName); return STATUS_SUCCESS; } NTSTATUS CWdfDevice::CreateUserModeHandle(HANDLE RequestorProcess, PHANDLE ObjectHandle) { IO_STATUS_BLOCK IoStatusBlock; PCUNICODE_STRING UniName = m_CachedName; OBJECT_ATTRIBUTES ObjectAttributes; InitializeObjectAttributes(&ObjectAttributes, const_cast<PUNICODE_STRING>(UniName), OBJ_KERNEL_HANDLE, nullptr, nullptr); HANDLE KernelHandle; auto status = ZwOpenFile(&KernelHandle, GENERIC_READ | GENERIC_WRITE, &ObjectAttributes, &IoStatusBlock, 0, FILE_NON_DIRECTORY_FILE | FILE_RANDOM_ACCESS); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! ZwOpenFile failed. %!STATUS!", status); return status; } status = ZwDuplicateObject(ZwCurrentProcess(), KernelHandle, RequestorProcess, ObjectHandle, 0, 0, DUPLICATE_SAME_ACCESS | DUPLICATE_SAME_ATTRIBUTES | DUPLICATE_CLOSE_SOURCE); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! ZwDuplicateObject failed. %!STATUS!", status); ZwClose(KernelHandle); } return status; } <commit_msg>CWdfDevice: Pacify excessive traces<commit_after>/********************************************************************** * Copyright (c) 2013-2014 Red Hat, Inc. * * Developed by Daynix Computing LTD. * * Authors: * Dmitry Fleytman <dmitry@daynix.com> * Pavel Gurvich <pavel@daynix.com> * * 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 "stdafx.h" #include "WdfDevice.h" #include "trace.h" #include "WdfDevice.tmh" CDeviceInit::~CDeviceInit() { if (m_Attached) { Free(); } } void CDeviceInit::Attach(PWDFDEVICE_INIT DevInit) { m_Attached = true; CPreAllocatedDeviceInit::Attach(DevInit); } PWDFDEVICE_INIT CDeviceInit::Detach() { m_Attached = false; return CPreAllocatedDeviceInit::Detach(); } NTSTATUS CPreAllocatedDeviceInit::SetName(const UNICODE_STRING &Name) { auto status = WdfDeviceInitAssignName(m_DeviceInit, &Name); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } return status; } void CPreAllocatedDeviceInit::Free() { WdfDeviceInitFree(m_DeviceInit); } void CPreAllocatedDeviceInit::SetPowerCallbacks(PFN_WDF_DEVICE_SELF_MANAGED_IO_INIT SelfManagedIoFunc) { WDF_PNPPOWER_EVENT_CALLBACKS Callbacks; WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&Callbacks); Callbacks.EvtDeviceSelfManagedIoInit = SelfManagedIoFunc; WdfDeviceInitSetPnpPowerEventCallbacks(m_DeviceInit, &Callbacks); } void CPreAllocatedDeviceInit::Attach(PWDFDEVICE_INIT DeviceInit) { m_DeviceInit = DeviceInit; } PWDFDEVICE_INIT CPreAllocatedDeviceInit::Detach() { auto DevInit = m_DeviceInit; m_DeviceInit = nullptr; return DevInit; } NTSTATUS CPreAllocatedDeviceInit::SetPreprocessCallback(PFN_WDFDEVICE_WDM_IRP_PREPROCESS Callback, UCHAR MajorFunction, const PUCHAR MinorFunctions, ULONG NumMinorFunctions) { auto status = WdfDeviceInitAssignWdmIrpPreprocessCallback(m_DeviceInit, Callback, MajorFunction, MinorFunctions, NumMinorFunctions); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! status: %!STATUS!", status); } return status; } NTSTATUS CWdfDevice::CreateSymLink(const UNICODE_STRING &Name) { auto status = WdfDeviceCreateSymbolicLink(m_Device, &Name); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } return status; } NTSTATUS CWdfDevice::Create(CPreAllocatedDeviceInit &DeviceInit, WDF_OBJECT_ATTRIBUTES &DeviceAttr) { auto DevInitObj = DeviceInit.Detach(); auto status = WdfDeviceCreate(&DevInitObj, &DeviceAttr, &m_Device); if (!NT_SUCCESS(status)) { DeviceInit.Attach(DevInitObj); TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } status = CacheDeviceName(); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! Device name caching failed %!STATUS!", status); } return status; } NTSTATUS CWdfQueue::Create(CWdfDevice &Device) { WDF_IO_QUEUE_CONFIG QueueConfig; WDF_OBJECT_ATTRIBUTES Attributes; InitConfig(QueueConfig); SetCallbacks(QueueConfig); WDF_OBJECT_ATTRIBUTES_INIT(&Attributes); Attributes.ExecutionLevel = WdfExecutionLevelPassive; auto status = Device.AddQueue(QueueConfig, Attributes, m_Queue); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } return status; } NTSTATUS CWdfDevice::AddQueue(WDF_IO_QUEUE_CONFIG &Config, WDF_OBJECT_ATTRIBUTES &Attributes, WDFQUEUE &Queue) { auto status = WdfIoQueueCreate(m_Device, &Config, &Attributes, &Queue); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! failed %!STATUS!", status); } return status; } void CWdfDefaultQueue::InitConfig(WDF_IO_QUEUE_CONFIG &QueueConfig) { WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&QueueConfig, m_DispatchType); } void CWdfSpecificQueue::InitConfig(WDF_IO_QUEUE_CONFIG &QueueConfig) { WDF_IO_QUEUE_CONFIG_INIT(&QueueConfig, m_DispatchType); } NTSTATUS CWdfDevice::CacheDeviceName() { WDFSTRING deviceName; auto status = WdfStringCreate(NULL, WDF_NO_OBJECT_ATTRIBUTES, &deviceName); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! WdfStringCreate failed. %!STATUS!", status); return status; } status = WdfDeviceRetrieveDeviceName(m_Device, deviceName); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! WdfDeviceRetrieveDeviceName failed. %!STATUS!", status); WdfObjectDelete(deviceName); return status; } UNICODE_STRING UnicodeDeviceName; WdfStringGetUnicodeString(deviceName, &UnicodeDeviceName); status = m_CachedName.Create(&UnicodeDeviceName); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! CString creation failed. %!STATUS!", status); WdfObjectDelete(deviceName); return status; } TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! Newly created device name is %wZ", &UnicodeDeviceName); WdfObjectDelete(deviceName); return STATUS_SUCCESS; } NTSTATUS CWdfDevice::CreateUserModeHandle(HANDLE RequestorProcess, PHANDLE ObjectHandle) { IO_STATUS_BLOCK IoStatusBlock; PCUNICODE_STRING UniName = m_CachedName; OBJECT_ATTRIBUTES ObjectAttributes; InitializeObjectAttributes(&ObjectAttributes, const_cast<PUNICODE_STRING>(UniName), OBJ_KERNEL_HANDLE, nullptr, nullptr); HANDLE KernelHandle; auto status = ZwOpenFile(&KernelHandle, GENERIC_READ | GENERIC_WRITE, &ObjectAttributes, &IoStatusBlock, 0, FILE_NON_DIRECTORY_FILE | FILE_RANDOM_ACCESS); if (!NT_SUCCESS(status)) { return status; } status = ZwDuplicateObject(ZwCurrentProcess(), KernelHandle, RequestorProcess, ObjectHandle, 0, 0, DUPLICATE_SAME_ACCESS | DUPLICATE_SAME_ATTRIBUTES | DUPLICATE_CLOSE_SOURCE); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, "%!FUNC! ZwDuplicateObject failed. %!STATUS!", status); ZwClose(KernelHandle); } return status; } <|endoftext|>
<commit_before>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/io/BufferedPipe.h> namespace stingray { BufferedPipe::BufferedPipe(const IPipePtr& pipe, size_t bufferSize) : _pipe(pipe), _buffer(bufferSize), _bufferOffset(), _bufferSize() { } u64 BufferedPipe::Read(ByteData data, const ICancellationToken& token) { if (_bufferOffset == _bufferSize) { const size_t size = _pipe->Read(_buffer.GetByteData(), token); if (size == 0) return 0; _bufferOffset = 0; _bufferSize = size; } const size_t size = std::min(_bufferSize - _bufferOffset, data.size()); std::copy(_buffer.begin() + _bufferOffset, _buffer.begin() + _bufferOffset + size, data.begin()); _bufferOffset += size; return size; } } <commit_msg>use data/size methods of ByteData instead of begin/end<commit_after>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/io/BufferedPipe.h> namespace stingray { BufferedPipe::BufferedPipe(const IPipePtr& pipe, size_t bufferSize) : _pipe(pipe), _buffer(bufferSize), _bufferOffset(), _bufferSize() { } u64 BufferedPipe::Read(ByteData data, const ICancellationToken& token) { if (_bufferOffset == _bufferSize) { const size_t size = _pipe->Read(_buffer.GetByteData(), token); if (size == 0) return 0; _bufferOffset = 0; _bufferSize = size; } const size_t size = std::min(_bufferSize - _bufferOffset, data.size()); std::copy(_buffer.data() + _bufferOffset, _buffer.data() + _bufferOffset + size, data.data()); _bufferOffset += size; return size; } } <|endoftext|>
<commit_before>// // Copyright (c) 2014 Christoph Malek // See LICENSE for more information. // #ifndef TWSM_SERVER_BROWSER #define TWSM_SERVER_BROWSER #include "ui_main_window.h" #include <mlk/log/log.h> #include <mlk/time/simple_timer.h> #include <twl/network/network.hpp> #include <QObject> #include <QTableWidgetItem> namespace Ui {class main_window;} namespace twsm { class server_browser : public QObject { Q_OBJECT Ui::main_window& m_ui; twl::master_server m_masters; twl::game_server m_servers; mlk::tm::simple_timer m_stopwatch{0}; bool m_refreshing_masters{false}, m_refreshing{false}; public: server_browser(Ui::main_window& ui) : m_ui{ui} { } void update() { m_masters.update(); m_servers.update(); } void init() { mlk::lout("server_browser", true) << "init. settings default masters. setting up events."; // setup default masters m_masters.add_master({"master1.teeworlds.com:8300"}); m_masters.add_master({"master2.teeworlds.com:8300"}); m_masters.add_master({"master3.teeworlds.com:8300"}); m_masters.add_master({"master4.teeworlds.com:8300"}); // setup events m_masters.on_finish = [this]{this->masters_finished();}; m_servers.on_finish = [this]{this->servers_finished();}; // ui events QObject::connect(m_ui.m_pb_srvb_refresh, SIGNAL(clicked()), this, SLOT(refresh())); } public slots: void refresh() { // reset ui m_ui.m_tw_srvb_list->clearContents(); m_ui.m_tw_srvb_list->setRowCount(0); m_ui.m_lb_srvb_status->setText("Refreshing masters..."); // request masterlist m_refreshing_masters = true; m_masters.request_list(); } private: void masters_finished() { // master refresh finished m_refreshing_masters = false; m_refreshing = true; auto ips(m_masters.get_list()); mlk::lout("server_browser") << "refreshed masters. got " << ips.size() << " ips."; m_ui.m_lb_srvb_status->setText(QString{"Refreshed masters, processing %1 servers..."}.arg(ips.size())); if(ips.empty()) return; // make ready for server refreshing m_servers.reset(); m_servers.add_masterlist(ips); m_servers.request_info(); m_stopwatch.restart(); } void servers_finished() { // server refresh finished m_refreshing = false; auto tm(m_stopwatch.elapsed_time()); mlk::lout("server_browser") << "refreshed servers. (twl) processed " << m_servers.get_infos().size() << " servers in " << tm << "ms."; m_ui.m_tw_srvb_list->setSortingEnabled(false); for(auto& a : m_servers.get_infos()) { m_ui.m_tw_srvb_list->insertRow(m_ui.m_tw_srvb_list->rowCount()); auto* name(new QTableWidgetItem{a.name().c_str()}); auto* type(new QTableWidgetItem{a.gametype().c_str()}); auto* map(new QTableWidgetItem{a.mapname().c_str()}); auto* players(new QTableWidgetItem{QString{"%1/%2"}.arg(a.numclients()).arg(a.maxclients())}); auto* ping(new QTableWidgetItem{QString{"%1"}.arg(a.ping())}); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 0, name); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 1, type); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 2, map); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 3, players); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 4, ping); } m_ui.m_tw_srvb_list->setSortingEnabled(true); m_ui.m_lb_srvb_status->setText("Servers refreshed."); mlk::lout("server_browser") << "ui took " << m_stopwatch.elapsed_time() - tm << " ms."; } }; } #endif // TWSM_SERVER_BROWSER <commit_msg>serverbrowser: changed text on 0 servers<commit_after>// // Copyright (c) 2014 Christoph Malek // See LICENSE for more information. // #ifndef TWSM_SERVER_BROWSER #define TWSM_SERVER_BROWSER #include "ui_main_window.h" #include <mlk/log/log.h> #include <mlk/time/simple_timer.h> #include <twl/network/network.hpp> #include <QObject> #include <QTableWidgetItem> namespace Ui {class main_window;} namespace twsm { class server_browser : public QObject { Q_OBJECT Ui::main_window& m_ui; twl::master_server m_masters; twl::game_server m_servers; mlk::tm::simple_timer m_stopwatch{0}; bool m_refreshing_masters{false}, m_refreshing{false}; public: server_browser(Ui::main_window& ui) : m_ui{ui} { } void update() { m_masters.update(); m_servers.update(); } void init() { mlk::lout("server_browser", true) << "init. settings default masters. setting up events."; // setup default masters m_masters.add_master({"master1.teeworlds.com:8300"}); m_masters.add_master({"master2.teeworlds.com:8300"}); m_masters.add_master({"master3.teeworlds.com:8300"}); m_masters.add_master({"master4.teeworlds.com:8300"}); // setup events m_masters.on_finish = [this]{this->masters_finished();}; m_servers.on_finish = [this]{this->servers_finished();}; // ui events QObject::connect(m_ui.m_pb_srvb_refresh, SIGNAL(clicked()), this, SLOT(refresh())); } public slots: void refresh() { // reset ui m_ui.m_tw_srvb_list->clearContents(); m_ui.m_tw_srvb_list->setRowCount(0); m_ui.m_lb_srvb_status->setText("Refreshing masters..."); // request masterlist m_refreshing_masters = true; m_masters.request_list(); } private: void masters_finished() { // master refresh finished m_refreshing_masters = false; m_refreshing = true; auto ips(m_masters.get_list()); mlk::lout("server_browser") << "refreshed masters. got " << ips.size() << " ips."; if(ips.empty()) { m_ui.m_lb_srvb_status->setText("Got no servers from masters. Stopping refreshing."); return; } m_ui.m_lb_srvb_status->setText(QString{"Refreshed masters, processing %1 servers..."}.arg(ips.size())); // make ready for server refreshing m_servers.reset(); m_servers.add_masterlist(ips); m_servers.request_info(); m_stopwatch.restart(); } void servers_finished() { // server refresh finished m_refreshing = false; auto tm(m_stopwatch.elapsed_time()); mlk::lout("server_browser") << "refreshed servers. (twl) processed " << m_servers.get_infos().size() << " servers in " << tm << "ms."; m_ui.m_tw_srvb_list->setSortingEnabled(false); for(auto& a : m_servers.get_infos()) { m_ui.m_tw_srvb_list->insertRow(m_ui.m_tw_srvb_list->rowCount()); auto* name(new QTableWidgetItem{a.name().c_str()}); auto* type(new QTableWidgetItem{a.gametype().c_str()}); auto* map(new QTableWidgetItem{a.mapname().c_str()}); auto* players(new QTableWidgetItem{QString{"%1/%2"}.arg(a.numclients()).arg(a.maxclients())}); auto* ping(new QTableWidgetItem{QString{"%1"}.arg(a.ping())}); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 0, name); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 1, type); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 2, map); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 3, players); m_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 4, ping); } m_ui.m_tw_srvb_list->setSortingEnabled(true); m_ui.m_lb_srvb_status->setText("Servers refreshed."); mlk::lout("server_browser") << "ui took " << m_stopwatch.elapsed_time() - tm << " ms."; } }; } #endif // TWSM_SERVER_BROWSER <|endoftext|>
<commit_before>#ifndef ENTT_ENTITY_COMPONENT_HPP #define ENTT_ENTITY_COMPONENT_HPP #include <type_traits> #include "../config/config.h" namespace entt { /*! @brief Commonly used default traits for all types. */ struct basic_component_traits { /*! @brief Pointer stability, default is `std::false_type`. */ using in_place_delete = std::false_type; /*! @brief Empty type optimization, default is `ENTT_IGNORE_IF_EMPTY`. */ using ignore_if_empty = ENTT_IGNORE_IF_EMPTY; }; /** * @brief Common way to access various properties of components. * @tparam Type Type of component. */ template<typename Type, typename = void> struct component_traits: basic_component_traits { static_assert(std::is_same_v<std::decay_t<Type>, Type>, "Unsupported type"); }; } #endif <commit_msg>component: added in_place_delete_v and ignore_if_empty_v<commit_after>#ifndef ENTT_ENTITY_COMPONENT_HPP #define ENTT_ENTITY_COMPONENT_HPP #include <type_traits> #include "../config/config.h" namespace entt { /*! @brief Commonly used default traits for all types. */ struct basic_component_traits { /*! @brief Pointer stability, default is `std::false_type`. */ using in_place_delete = std::false_type; /*! @brief Empty type optimization, default is `ENTT_IGNORE_IF_EMPTY`. */ using ignore_if_empty = ENTT_IGNORE_IF_EMPTY; }; /** * @brief Common way to access various properties of components. * @tparam Type Type of component. */ template<typename Type, typename = void> struct component_traits: basic_component_traits { static_assert(std::is_same_v<std::decay_t<Type>, Type>, "Unsupported type"); }; /** * @brief Helper variable template. * @tparam Type Type of component. */ template<class Type> inline constexpr bool in_place_delete_v = component_traits<Type>::in_place_delete::value; /** * @brief Helper variable template. * @tparam Type Type of component. */ template<class Type> inline constexpr bool ignore_if_empty_v = component_traits<Type>::ignore_if_empty::value; } #endif <|endoftext|>
<commit_before>#ifndef SILICIUM_REACTIVE_COROUTINE_HPP #define SILICIUM_REACTIVE_COROUTINE_HPP #include <silicium/exchange.hpp> #include <silicium/yield_context.hpp> #include <silicium/fast_variant.hpp> #include <boost/coroutine/all.hpp> namespace Si { namespace detail { template <class Element> struct result { Element value; result() { } explicit result(Element value) : value(std::move(value)) { } #ifdef _MSC_VER result(result &&other) : value(std::move(other.value)) { } result &operator = (result &&other) { value = std::move(other.value); return *this; } result(result const &other) : value(other.value) { } result &operator = (result const &other) { value = other.value; return *this; } #endif }; struct yield { Si::observable<nothing> *target; }; template <class Element> struct make_command { typedef Si::fast_variant<result<Element>, yield> type; }; template <class Element> struct coroutine_yield_context_impl : detail::yield_context_impl<Element> { typedef typename boost::coroutines::coroutine<typename detail::make_command<Element>::type>::push_type consumer_type; explicit coroutine_yield_context_impl(consumer_type &consumer) : consumer(&consumer) { } virtual void push_result(Element result) SILICIUM_OVERRIDE { (*consumer)(detail::result<Element>(std::move(result))); } virtual void get_one(observable<nothing> &target) SILICIUM_OVERRIDE { (*consumer)(detail::yield{&target}); } private: consumer_type *consumer = nullptr; }; } template <class Element> struct coroutine_observable : private Si::observer<nothing> , public boost::static_visitor<> //TODO make private { typedef Element element_type; coroutine_observable() { } coroutine_observable(coroutine_observable &&other) { *this = std::move(other); } coroutine_observable &operator = (coroutine_observable &&other) { coro_ = std::move(other.coro_); action = std::move(other.action); receiver_ = std::move(other.receiver_); return *this; } template <class Action> explicit coroutine_observable(Action &&action) : action(std::forward<Action>(action)) { } void async_get_one(Si::observer<element_type> &receiver) { receiver_ = &receiver; next(); } //TODO make private void operator()(detail::result<element_type> command) { return Si::exchange(receiver_, nullptr)->got_element(std::move(command.value)); } //TODO make private void operator()(detail::yield command) { command.target->async_get_one(*this); } private: typedef typename detail::make_command<element_type>::type command_type; typedef typename boost::coroutines::coroutine<command_type>::pull_type coroutine_type; using coroutine_holder = #ifdef _MSC_VER std::shared_ptr<coroutine_type> #else coroutine_type #endif ; coroutine_holder coro_; std::function<void (yield_context<Element> &)> action; Si::observer<Element> *receiver_ = nullptr; coroutine_type &coro() { return #ifdef _MSC_VER * #endif coro_; } virtual void got_element(nothing) SILICIUM_OVERRIDE { next(); } virtual void ended() SILICIUM_OVERRIDE { Si::exchange(receiver_, nullptr)->ended(); } void next() { if (action) { auto bound_action = action; coro_ = #ifdef _MSC_VER std::make_shared<coroutine_type> #else coroutine_type #endif ([bound_action](typename boost::coroutines::coroutine<command_type>::push_type &push) { detail::coroutine_yield_context_impl<Element> yield_impl(push); yield_context<Element> yield(yield_impl); //TODO: save this indirection return bound_action(yield); }); action = nullptr; } else if (coro()) { coro()(); } if (coro()) { command_type command = coro().get(); return Si::apply_visitor(*this, command); } else { Si::exchange(receiver_, nullptr)->ended(); } } }; template <class Element, class Action> auto make_coroutine(Action &&action) -> coroutine_observable<Element> { return coroutine_observable<Element>(std::forward<Action>(action)); } } #endif <commit_msg>fix mistake in coroutine when the observable given to get_one ended<commit_after>#ifndef SILICIUM_REACTIVE_COROUTINE_HPP #define SILICIUM_REACTIVE_COROUTINE_HPP #include <silicium/exchange.hpp> #include <silicium/yield_context.hpp> #include <silicium/fast_variant.hpp> #include <boost/coroutine/all.hpp> namespace Si { namespace detail { template <class Element> struct result { Element value; result() { } explicit result(Element value) : value(std::move(value)) { } #ifdef _MSC_VER result(result &&other) : value(std::move(other.value)) { } result &operator = (result &&other) { value = std::move(other.value); return *this; } result(result const &other) : value(other.value) { } result &operator = (result const &other) { value = other.value; return *this; } #endif }; struct yield { Si::observable<nothing> *target; }; template <class Element> struct make_command { typedef Si::fast_variant<result<Element>, yield> type; }; template <class Element> struct coroutine_yield_context_impl : detail::yield_context_impl<Element> { typedef typename boost::coroutines::coroutine<typename detail::make_command<Element>::type>::push_type consumer_type; explicit coroutine_yield_context_impl(consumer_type &consumer) : consumer(&consumer) { } virtual void push_result(Element result) SILICIUM_OVERRIDE { (*consumer)(detail::result<Element>(std::move(result))); } virtual void get_one(observable<nothing> &target) SILICIUM_OVERRIDE { (*consumer)(detail::yield{&target}); } private: consumer_type *consumer = nullptr; }; } template <class Element> struct coroutine_observable : private Si::observer<nothing> , public boost::static_visitor<> //TODO make private { typedef Element element_type; coroutine_observable() { } coroutine_observable(coroutine_observable &&other) { *this = std::move(other); } coroutine_observable &operator = (coroutine_observable &&other) { coro_ = std::move(other.coro_); action = std::move(other.action); receiver_ = std::move(other.receiver_); return *this; } template <class Action> explicit coroutine_observable(Action &&action) : action(std::forward<Action>(action)) { } void async_get_one(Si::observer<element_type> &receiver) { receiver_ = &receiver; next(); } //TODO make private void operator()(detail::result<element_type> command) { return Si::exchange(receiver_, nullptr)->got_element(std::move(command.value)); } //TODO make private void operator()(detail::yield command) { command.target->async_get_one(*this); } private: typedef typename detail::make_command<element_type>::type command_type; typedef typename boost::coroutines::coroutine<command_type>::pull_type coroutine_type; using coroutine_holder = #ifdef _MSC_VER std::shared_ptr<coroutine_type> #else coroutine_type #endif ; coroutine_holder coro_; std::function<void (yield_context<Element> &)> action; Si::observer<Element> *receiver_ = nullptr; coroutine_type &coro() { return #ifdef _MSC_VER * #endif coro_; } virtual void got_element(nothing) SILICIUM_OVERRIDE { next(); } virtual void ended() SILICIUM_OVERRIDE { next(); } void next() { if (action) { auto bound_action = action; coro_ = #ifdef _MSC_VER std::make_shared<coroutine_type> #else coroutine_type #endif ([bound_action](typename boost::coroutines::coroutine<command_type>::push_type &push) { detail::coroutine_yield_context_impl<Element> yield_impl(push); yield_context<Element> yield(yield_impl); //TODO: save this indirection return bound_action(yield); }); action = nullptr; } else if (coro()) { coro()(); } if (coro()) { command_type command = coro().get(); return Si::apply_visitor(*this, command); } else { Si::exchange(receiver_, nullptr)->ended(); } } }; template <class Element, class Action> auto make_coroutine(Action &&action) -> coroutine_observable<Element> { return coroutine_observable<Element>(std::forward<Action>(action)); } } #endif <|endoftext|>
<commit_before>/** * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io> * Authors: * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <poll.h> #include <thread> #include "eventql/eventql.h" #include "eventql/util/application.h" #include "eventql/util/logging.h" #include "eventql/util/UnixTime.h" #include "eventql/util/return_code.h" #include "eventql/util/cli/CLI.h" #include "eventql/util/io/inputstream.h" #include "eventql/util/cli/term.h" #include "eventql/util/cli/flagparser.h" #include "eventql/util/thread/threadpool.h" #include "eventql/cli/cli_config.h" ReturnCode sendQuery( const String& query, const String& qry_db, evql_client_t* client) { uint64_t qry_flags = 0; if (!qry_db.empty()) { qry_flags |= EVQL_QUERY_SWITCHDB; } int rc = evql_query(client, query.c_str(), qry_db.c_str(), qry_flags); size_t result_ncols; if (rc == 0) { rc = evql_num_columns(client, &result_ncols); } while (rc >= 0) { const char** fields; size_t* field_lens; rc = evql_fetch_row(client, &fields, &field_lens); if (rc < 1) { break; } } evql_client_releasebuffers(client); if (rc == -1) { return ReturnCode::error("EIOERROR", evql_client_geterror(client)); } else { return ReturnCode::success(); } } void print( size_t num_errors, size_t num_succes, UnixTime start, OutputStream* stdout_os) { UnixTime now; auto duration = now - start; stdout_os->write(StringUtil::format( "total successful error milliseconds\n" " $0 $1 $2 $3\n\n", num_errors + num_succes, num_succes, num_errors, duration.milliseconds() )); } static constexpr auto kMaxErrors = 10; struct TimeWindow { static constexpr auto kMillisPerWindow = 1 * kMillisPerSecond; void clear() { num_requests = 0; UnixTime now; start = now; } int64_t getRemainingMillis() { UnixTime now; auto duration = now - start; return kMillisPerWindow - duration.milliseconds(); } size_t num_requests; UnixTime start; }; int main(int argc, const char** argv) { cli::FlagParser flags; flags.defineFlag( "help", cli::FlagParser::T_SWITCH, false, "?", NULL, "help", "<help>"); flags.defineFlag( "version", cli::FlagParser::T_SWITCH, false, "v", NULL, "print version", "<switch>"); flags.defineFlag( "host", cli::FlagParser::T_STRING, false, "h", NULL, "eventql server hostname", "<host>"); flags.defineFlag( "port", cli::FlagParser::T_INTEGER, false, "p", NULL, "eventql server port", "<port>"); flags.defineFlag( "database", cli::FlagParser::T_STRING, false, "d", NULL, "database", "<db>"); flags.defineFlag( "query", cli::FlagParser::T_STRING, true, "q", NULL, "query str", "<query>"); flags.defineFlag( "threads", cli::FlagParser::T_INTEGER, false, "t", "10", "number of threads", "<threads>"); flags.defineFlag( "rate", cli::FlagParser::T_INTEGER, false, "r", "1", "number of requests per second", "<rate>"); flags.defineFlag( "max", cli::FlagParser::T_INTEGER, false, "n", NULL, "number of requests per second", "<rate>"); flags.defineFlag( "loglevel", cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Vector<String> cmd_argv = flags.getArgv(); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); Application::init(); Application::logToStderr("evqlbenchmark"); auto stdin_is = InputStream::getStdin(); auto stdout_os = OutputStream::getStdout(); auto stderr_os = OutputStream::getStderr(); bool print_help = flags.isSet("help"); bool print_version = flags.isSet("version"); if (print_version || print_help) { auto stdout_os = OutputStream::getStdout(); stdout_os->write( StringUtil::format( "EventQL $0 ($1)\n" "Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n", eventql::kVersionString, eventql::kBuildID)); } if (print_version) { return 1; } if (print_help) { stdout_os->write( "Usage: $ evqlbenchmark [OPTIONS] <command> [<args>]\n\n" " -D, --database <db> Select a database\n" " -h, --host <hostname> Set the EventQL server hostname\n" " -p, --port <port> Set the EventQL server port\n" " -?, --help <topic> Display a command's help text and exit\n" " -v, --version Display the version of this binary and exit\n\n" "evqlbenchmark commands:\n" ); return 1; } logInfo("evqlbenchmark", "starting benchmark"); /* options */ eventql::ProcessConfigBuilder cfg_builder; { auto status = cfg_builder.loadDefaultConfigFile("evql"); if (!status.isSuccess()) { logFatal("evqlbenchmark", "error while loading config file %s", status.message()); return 0; } } if (flags.isSet("host")) { cfg_builder.setProperty("evql", "host", flags.getString("host")); } if (flags.isSet("port")) { cfg_builder.setProperty( "evql", "port", StringUtil::toString(flags.getInt("port"))); } if (flags.isSet("database")) { cfg_builder.setProperty("evql", "database", flags.getString("database")); } eventql::cli::CLIConfig cfg(cfg_builder.getConfig()); String qry_db; if (flags.isSet("database")) { qry_db = flags.getString("database"); } auto qry_str = flags.getString("query"); auto rate = flags.getInt("rate"); auto num_threads = flags.getInt("threads"); size_t max_requests; bool has_max = false; if (flags.isSet("max")) { max_requests = flags.getInt("max"); has_max = true; } const UnixTime global_start; std::mutex m; TimeWindow twindow; auto errors = 0; auto requests_sent = 0; Vector<std::thread> threads; for (size_t i = 0; i < num_threads; ++i) { threads.emplace_back(std::thread([&] () { /* connect to eventql client */ auto client = evql_client_init(); if (!client) { logFatal("evqlbenchmark", "can't initialize eventql client"); return 0; } { auto rc = evql_client_connect( client, cfg.getHost().c_str(), cfg.getPort(), 0); if (rc < 0) { logFatal("evqlbenchmark", "can't connect to eventql client: $0", evql_client_geterror(client)); return 0; } } for (;;) { /* check remaining time in current timewindow */ m.lock(); /* start a new timewindow */ if (twindow.getRemainingMillis() <= 0) { twindow.clear(); m.unlock(); continue; } m.unlock(); /* send query */ auto rc = sendQuery(qry_str, qry_db, client); m.lock(); if (!rc.isSuccess()) { logFatal("evqlbenchmark", "executing query failed: $0", rc.getMessage()); ++errors; } else { ++requests_sent; } m.unlock(); print(errors, requests_sent, global_start, stdout_os.get()); if (errors > kMaxErrors || (has_max && requests_sent >= max_requests)) { break; } } evql_client_close(client); })); } for (auto& t : threads) { t.join(); } print(errors, requests_sent, global_start, stdout_os.get()); return 0; } <commit_msg>benchmark: cleanup<commit_after>/** * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io> * Authors: * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <poll.h> #include <thread> #include "eventql/eventql.h" #include "eventql/util/application.h" #include "eventql/util/logging.h" #include "eventql/util/UnixTime.h" #include "eventql/util/return_code.h" #include "eventql/util/cli/CLI.h" #include "eventql/util/io/inputstream.h" #include "eventql/util/cli/term.h" #include "eventql/util/cli/flagparser.h" #include "eventql/util/thread/threadpool.h" #include "eventql/cli/cli_config.h" struct TimeWindow { static constexpr auto kMillisPerWindow = 1 * kMillisPerSecond; TimeWindow() : num_requests_(0) {} void addRequest() { ++num_requests_; } int64_t getRemainingMillis() { UnixTime now; auto duration = now - start_; return kMillisPerWindow - duration.milliseconds(); } void clear() { num_requests_ = 0; UnixTime now; start_ = now; } protected: size_t num_requests_; UnixTime start_; }; struct RequestStats { static constexpr auto kMaxErrors = 10; RequestStats() : failed_requests_(0), successful_requests_(0), max_requests_(0), has_max_(false) {} void addFailedRequest() { ++failed_requests_; } void addSuccessfulRequest() { ++successful_requests_; } uint64_t getFailedRequests() { return failed_requests_; } uint64_t getSuccessfulRequest() { return successful_requests_; } uint64_t getTotal() { return successful_requests_ + failed_requests_; } void setMaximumRequests(uint64_t max_requests) { max_requests_ = max_requests; has_max_ = true; } bool stop() { if (failed_requests_ >= kMaxErrors) if (!has_max_) { return false; } return getTotal() >= max_requests_; } protected: uint64_t failed_requests_; uint64_t successful_requests_; uint64_t max_requests_; bool has_max_; }; ReturnCode sendQuery( const String& query, const String& qry_db, evql_client_t* client) { uint64_t qry_flags = 0; if (!qry_db.empty()) { qry_flags |= EVQL_QUERY_SWITCHDB; } int rc = evql_query(client, query.c_str(), qry_db.c_str(), qry_flags); size_t result_ncols; if (rc == 0) { rc = evql_num_columns(client, &result_ncols); } while (rc >= 0) { const char** fields; size_t* field_lens; rc = evql_fetch_row(client, &fields, &field_lens); if (rc < 1) { break; } } evql_client_releasebuffers(client); if (rc == -1) { return ReturnCode::error("EIOERROR", evql_client_geterror(client)); } else { return ReturnCode::success(); } } void print( size_t num_errors, size_t num_succes, UnixTime start, OutputStream* stdout_os) { UnixTime now; auto duration = now - start; stdout_os->write(StringUtil::format( "total successful error milliseconds\n" " $0 $1 $2 $3\n\n", num_errors + num_succes, num_succes, num_errors, duration.milliseconds() )); } int main(int argc, const char** argv) { cli::FlagParser flags; flags.defineFlag( "help", cli::FlagParser::T_SWITCH, false, "?", NULL, "help", "<help>"); flags.defineFlag( "version", cli::FlagParser::T_SWITCH, false, "v", NULL, "print version", "<switch>"); flags.defineFlag( "host", cli::FlagParser::T_STRING, false, "h", NULL, "eventql server hostname", "<host>"); flags.defineFlag( "port", cli::FlagParser::T_INTEGER, false, "p", NULL, "eventql server port", "<port>"); flags.defineFlag( "database", cli::FlagParser::T_STRING, false, "d", NULL, "database", "<db>"); flags.defineFlag( "query", cli::FlagParser::T_STRING, true, "q", NULL, "query str", "<query>"); flags.defineFlag( "threads", cli::FlagParser::T_INTEGER, false, "t", "10", "number of threads", "<threads>"); flags.defineFlag( "rate", cli::FlagParser::T_INTEGER, false, "r", "1", "number of requests per second", "<rate>"); flags.defineFlag( "max", cli::FlagParser::T_INTEGER, false, "n", NULL, "number of requests per second", "<rate>"); flags.defineFlag( "loglevel", cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Vector<String> cmd_argv = flags.getArgv(); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); Application::init(); Application::logToStderr("evqlbenchmark"); auto stdin_is = InputStream::getStdin(); auto stdout_os = OutputStream::getStdout(); auto stderr_os = OutputStream::getStderr(); bool print_help = flags.isSet("help"); bool print_version = flags.isSet("version"); if (print_version || print_help) { auto stdout_os = OutputStream::getStdout(); stdout_os->write( StringUtil::format( "EventQL $0 ($1)\n" "Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n", eventql::kVersionString, eventql::kBuildID)); } if (print_version) { return 1; } if (print_help) { stdout_os->write( "Usage: $ evqlbenchmark [OPTIONS] <command> [<args>]\n\n" " -D, --database <db> Select a database\n" " -h, --host <hostname> Set the EventQL server hostname\n" " -p, --port <port> Set the EventQL server port\n" " -?, --help <topic> Display a command's help text and exit\n" " -v, --version Display the version of this binary and exit\n\n" "evqlbenchmark commands:\n" ); return 1; } logInfo("evqlbenchmark", "starting benchmark"); /* options */ eventql::ProcessConfigBuilder cfg_builder; { auto status = cfg_builder.loadDefaultConfigFile("evql"); if (!status.isSuccess()) { logFatal("evqlbenchmark", "error while loading config file %s", status.message()); return 0; } } if (flags.isSet("host")) { cfg_builder.setProperty("evql", "host", flags.getString("host")); } if (flags.isSet("port")) { cfg_builder.setProperty( "evql", "port", StringUtil::toString(flags.getInt("port"))); } if (flags.isSet("database")) { cfg_builder.setProperty("evql", "database", flags.getString("database")); } eventql::cli::CLIConfig cfg(cfg_builder.getConfig()); String qry_db; if (flags.isSet("database")) { qry_db = flags.getString("database"); } auto qry_str = flags.getString("query"); auto rate = flags.getInt("rate"); const UnixTime global_start; std::mutex m; TimeWindow twindow; RequestStats rstats; if (flags.isSet("max")) { rstats.setMaximumRequests(flags.getInt("max")); } auto num_threads = flags.getInt("threads"); Vector<std::thread> threads; for (size_t i = 0; i < num_threads; ++i) { threads.emplace_back(std::thread([&] () { /* connect to eventql client */ auto client = evql_client_init(); if (!client) { logFatal("evqlbenchmark", "can't initialize eventql client"); return 0; } { auto rc = evql_client_connect( client, cfg.getHost().c_str(), cfg.getPort(), 0); if (rc < 0) { logFatal("evqlbenchmark", "can't connect to eventql client: $0", evql_client_geterror(client)); return 0; } } for (;;) { m.lock(); /* check remaining time in current timewindow */ if (twindow.getRemainingMillis() <= 0) { /* start a new timewindow */ twindow.clear(); m.unlock(); continue; } m.unlock(); /* send query */ auto rc = sendQuery(qry_str, qry_db, client); m.lock(); if (!rc.isSuccess()) { logFatal("evqlbenchmark", "executing query failed: $0", rc.getMessage()); rstats.addFailedRequest(); } else { rstats.addSuccessfulRequest(); } m.unlock(); //print(errors, requests_sent, global_start, stdout_os.get()); if (rstats.stop()) { break; } } evql_client_close(client); })); } for (auto& t : threads) { t.join(); } //print(errors, requests_sent, global_start, stdout_os.get()); return 0; } <|endoftext|>
<commit_before>/* * OCB Mode * (C) 2013 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/ocb.h> #include <botan/cmac.h> #include <botan/internal/xor_buf.h> #include <botan/internal/bit_ops.h> #include <algorithm> #include <botan/hex.h> #include <iostream> namespace Botan { // Has to be in Botan namespace so unique_ptr can reference it class L_computer { public: L_computer(const BlockCipher& cipher) { m_L_star.resize(cipher.block_size()); cipher.encrypt(m_L_star); m_L_dollar = poly_double(star()); m_L.push_back(poly_double(dollar())); } const secure_vector<byte>& star() const { return m_L_star; } const secure_vector<byte>& dollar() const { return m_L_dollar; } const secure_vector<byte>& operator()(size_t i) const { return get(i); } const secure_vector<byte>& get(size_t i) const { while(m_L.size() <= i) m_L.push_back(poly_double(m_L.back())); return m_L.at(i); } private: secure_vector<byte> poly_double(const secure_vector<byte>& in) const { return CMAC::poly_double(in, 0x87); } secure_vector<byte> m_L_dollar, m_L_star; mutable std::vector<secure_vector<byte>> m_L; }; #if 0 class Nonce_State { public: secure_vector<byte> update_nonce(const byte nonce[], size_t nonce_len); bool fresh_nonce() { bool b = false; std::swap(b, m_fresh); return b; } private: secure_vector<byte> m_stretch; bool m_fresh = false; }; #endif namespace { /* * OCB's HASH */ secure_vector<byte> ocb_hash(const L_computer& L, const BlockCipher& cipher, const byte ad[], size_t ad_len) { const size_t BS = cipher.block_size(); secure_vector<byte> sum(BS); secure_vector<byte> offset(BS); secure_vector<byte> buf(BS); const size_t ad_blocks = (ad_len / BS); const size_t ad_remainder = (ad_len % BS); for(size_t i = 0; i != ad_blocks; ++i) { // this loop could run in parallel offset ^= L(ctz(i+1)); buf = offset; xor_buf(&buf[0], &ad[BS*i], BS); cipher.encrypt(buf); sum ^= buf; } if(ad_remainder) { offset ^= L.star(); buf = offset; xor_buf(&buf[0], &ad[BS*ad_blocks], ad_remainder); buf[ad_len % BS] ^= 0x80; cipher.encrypt(buf); sum ^= buf; } return sum; } } OCB_Mode::OCB_Mode(BlockCipher* cipher, size_t tag_size, bool decrypting) : Buffered_Filter(cipher->parallel_bytes(), decrypting ? tag_size : 0), m_cipher(cipher), m_tag_size(tag_size), m_ad_hash(BS), m_offset(BS), m_checksum(BS) { if(m_cipher->block_size() != BS) throw std::invalid_argument("OCB requires a 128 bit cipher so cannot be used with " + m_cipher->name()); if(m_tag_size != 16) // 64, 96 bits also supported throw std::invalid_argument("OCB cannot produce a " + std::to_string(m_tag_size) + " byte tag"); } OCB_Mode::~OCB_Mode() { /* for unique_ptr destructor */ } bool OCB_Mode::valid_keylength(size_t n) const { return m_cipher->valid_keylength(n); } std::string OCB_Mode::name() const { return m_cipher->name() + "/OCB"; // include tag size } void OCB_Mode::set_key(const SymmetricKey& key) { m_cipher->set_key(key); m_L.reset(new L_computer(*m_cipher)); } void OCB_Mode::set_nonce(const byte nonce[], size_t nonce_len) { if(!valid_iv_length(nonce_len)) throw Invalid_IV_Length(name(), nonce_len); byte bottom; secure_vector<byte> stretch; if(1) // need to recompute stretch (save iv to compare) { secure_vector<byte> buf(BS); const size_t offset = BS - nonce_len; copy_mem(&buf[offset], nonce, nonce_len); buf[offset-1] = 1; bottom = buf[15] & 0x3F; buf[15] &= 0xC0; m_cipher->encrypt(buf); for(size_t i = 0; i != 8; ++i) buf.push_back(buf[i] ^ buf[i+1]); stretch = buf; } // now set the offset from stretch and bottom const size_t shift_bytes = bottom / 8; const size_t shift_bits = bottom % 8; for(size_t i = 0; i != BS; ++i) { m_offset[i] = (stretch[i+shift_bytes] << shift_bits); m_offset[i] |= (stretch[i+shift_bytes+1] >> (8-shift_bits)); } } void OCB_Mode::start_msg() { //BOTAN_ASSERT(m_nonce_state.fresh_nonce(), "Nonce state is fresh"); } void OCB_Mode::set_associated_data(const byte ad[], size_t ad_len) { m_ad_hash = ocb_hash(*m_L, *m_cipher, &ad[0], ad_len); } void OCB_Mode::write(const byte input[], size_t length) { Buffered_Filter::write(input, length); } void OCB_Mode::end_msg() { Buffered_Filter::end_msg(); } void OCB_Encryption::buffered_block(const byte input[], size_t input_length) { BOTAN_ASSERT(input_length % BS == 0, "Input length is an even number of blocks"); const size_t blocks = input_length / BS; const size_t par_bytes = m_cipher->parallel_bytes(); BOTAN_ASSERT(par_bytes % BS == 0, "Cipher is parallel in full blocks"); const size_t par_blocks = par_bytes / BS; const L_computer& L = *m_L; // convenient name secure_vector<byte> ctext_buf(par_bytes); secure_vector<byte> csum_accum(par_bytes); secure_vector<byte> offsets(par_bytes); size_t blocks_left = blocks; while(blocks_left) { const size_t to_proc = std::min(blocks_left, par_blocks); const size_t proc_bytes = to_proc * BS; xor_buf(&csum_accum[0], &input[0], proc_bytes); for(size_t i = 0; i != to_proc; ++i) { m_offset ^= L(ctz(++m_block_index)); copy_mem(&offsets[BS*i], &m_offset[0], BS); } copy_mem(&ctext_buf[0], &input[0], proc_bytes); ctext_buf ^= offsets; m_cipher->encrypt(ctext_buf); ctext_buf ^= offsets; send(ctext_buf, proc_bytes); input += proc_bytes; blocks_left -= to_proc; } // fold into checksum for(size_t i = 0; i != csum_accum.size(); ++i) m_checksum[i % BS] ^= csum_accum[i]; } void OCB_Encryption::buffered_final(const byte input[], size_t input_length) { if(input_length >= BS) { const size_t final_blocks = input_length / BS; const size_t final_bytes = final_blocks * BS; buffered_block(input, final_bytes); input += final_bytes; input_length -= final_bytes; } if(input_length) { BOTAN_ASSERT(input_length < BS, "Only a partial block left"); xor_buf(&m_checksum[0], &input[0], input_length); m_checksum[input_length] ^= 0x80; m_offset ^= m_L->star(); // Offset_* secure_vector<byte> buf(BS); m_cipher->encrypt(m_offset, buf); xor_buf(&buf[0], &input[0], input_length); send(buf, input_length); // final ciphertext } // now compute the tag secure_vector<byte> mac = m_offset; mac ^= m_checksum; mac ^= m_L->dollar(); m_cipher->encrypt(mac); mac ^= m_ad_hash; send(mac); zeroise(m_checksum); zeroise(m_offset); m_block_index = 0; } void OCB_Decryption::buffered_block(const byte input[], size_t input_length) { BOTAN_ASSERT(input_length % BS == 0, "Input length is an even number of blocks"); const size_t blocks = input_length / BS; const L_computer& L = *m_L; secure_vector<byte> ptext_buf(BS); for(size_t i = 0; i != blocks; ++i) { // could run in parallel m_offset ^= L(ctz(++m_block_index)); ptext_buf = m_offset; xor_buf(&ptext_buf[0], &input[BS*i], BS); m_cipher->decrypt(ptext_buf); ptext_buf ^= m_offset; send(ptext_buf); m_checksum ^= ptext_buf; } } void OCB_Decryption::buffered_final(const byte input[], size_t input_length) { BOTAN_ASSERT(input_length >= m_tag_size, "We have the tag"); const byte* included_tag = &input[input_length-m_tag_size]; input_length -= m_tag_size; if(input_length >= BS) { const size_t final_blocks = input_length / BS; const size_t final_bytes = final_blocks * BS; buffered_block(input, final_bytes); input += final_bytes; input_length -= final_bytes; } if(input_length) { BOTAN_ASSERT(input_length < BS, "Only a partial block left"); m_offset ^= m_L->star(); // Offset_* secure_vector<byte> buf(BS); m_cipher->encrypt(m_offset, buf); // P_* xor_buf(&buf[0], &input[0], input_length); xor_buf(&m_checksum[0], &buf[0], input_length); m_checksum[input_length] ^= 0x80; send(buf, input_length); // final plaintext } // now compute the tag secure_vector<byte> mac = m_offset; mac ^= m_checksum; mac ^= m_L->dollar(); m_cipher->encrypt(mac); mac ^= m_ad_hash; zeroise(m_checksum); zeroise(m_offset); m_block_index = 0; if(!same_mem(&mac[0], included_tag, m_tag_size)) throw Integrity_Failure("OCB tag check failed"); } } <commit_msg>Parallel OCB decryption<commit_after>/* * OCB Mode * (C) 2013 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/ocb.h> #include <botan/cmac.h> #include <botan/internal/xor_buf.h> #include <botan/internal/bit_ops.h> #include <algorithm> #include <botan/hex.h> #include <iostream> namespace Botan { // Has to be in Botan namespace so unique_ptr can reference it class L_computer { public: L_computer(const BlockCipher& cipher) { m_L_star.resize(cipher.block_size()); cipher.encrypt(m_L_star); m_L_dollar = poly_double(star()); m_L.push_back(poly_double(dollar())); } const secure_vector<byte>& star() const { return m_L_star; } const secure_vector<byte>& dollar() const { return m_L_dollar; } const secure_vector<byte>& operator()(size_t i) const { return get(i); } const secure_vector<byte>& get(size_t i) const { while(m_L.size() <= i) m_L.push_back(poly_double(m_L.back())); return m_L.at(i); } private: secure_vector<byte> poly_double(const secure_vector<byte>& in) const { return CMAC::poly_double(in, 0x87); } secure_vector<byte> m_L_dollar, m_L_star; mutable std::vector<secure_vector<byte>> m_L; }; #if 0 class Nonce_State { public: secure_vector<byte> update_nonce(const byte nonce[], size_t nonce_len); bool fresh_nonce() { bool b = false; std::swap(b, m_fresh); return b; } private: secure_vector<byte> m_stretch; bool m_fresh = false; }; #endif namespace { /* * OCB's HASH */ secure_vector<byte> ocb_hash(const L_computer& L, const BlockCipher& cipher, const byte ad[], size_t ad_len) { const size_t BS = cipher.block_size(); secure_vector<byte> sum(BS); secure_vector<byte> offset(BS); secure_vector<byte> buf(BS); const size_t ad_blocks = (ad_len / BS); const size_t ad_remainder = (ad_len % BS); for(size_t i = 0; i != ad_blocks; ++i) { // this loop could run in parallel offset ^= L(ctz(i+1)); buf = offset; xor_buf(&buf[0], &ad[BS*i], BS); cipher.encrypt(buf); sum ^= buf; } if(ad_remainder) { offset ^= L.star(); buf = offset; xor_buf(&buf[0], &ad[BS*ad_blocks], ad_remainder); buf[ad_len % BS] ^= 0x80; cipher.encrypt(buf); sum ^= buf; } return sum; } } OCB_Mode::OCB_Mode(BlockCipher* cipher, size_t tag_size, bool decrypting) : Buffered_Filter(cipher->parallel_bytes(), decrypting ? tag_size : 0), m_cipher(cipher), m_tag_size(tag_size), m_ad_hash(BS), m_offset(BS), m_checksum(BS) { if(m_cipher->block_size() != BS) throw std::invalid_argument("OCB requires a 128 bit cipher so cannot be used with " + m_cipher->name()); if(m_tag_size != 16) // 64, 96 bits also supported throw std::invalid_argument("OCB cannot produce a " + std::to_string(m_tag_size) + " byte tag"); } OCB_Mode::~OCB_Mode() { /* for unique_ptr destructor */ } bool OCB_Mode::valid_keylength(size_t n) const { return m_cipher->valid_keylength(n); } std::string OCB_Mode::name() const { return m_cipher->name() + "/OCB"; // include tag size } void OCB_Mode::set_key(const SymmetricKey& key) { m_cipher->set_key(key); m_L.reset(new L_computer(*m_cipher)); } void OCB_Mode::set_nonce(const byte nonce[], size_t nonce_len) { if(!valid_iv_length(nonce_len)) throw Invalid_IV_Length(name(), nonce_len); byte bottom; secure_vector<byte> stretch; if(1) // need to recompute stretch (save iv to compare) { secure_vector<byte> buf(BS); const size_t offset = BS - nonce_len; copy_mem(&buf[offset], nonce, nonce_len); buf[offset-1] = 1; bottom = buf[15] & 0x3F; buf[15] &= 0xC0; m_cipher->encrypt(buf); for(size_t i = 0; i != 8; ++i) buf.push_back(buf[i] ^ buf[i+1]); stretch = buf; } // now set the offset from stretch and bottom const size_t shift_bytes = bottom / 8; const size_t shift_bits = bottom % 8; for(size_t i = 0; i != BS; ++i) { m_offset[i] = (stretch[i+shift_bytes] << shift_bits); m_offset[i] |= (stretch[i+shift_bytes+1] >> (8-shift_bits)); } } void OCB_Mode::start_msg() { //BOTAN_ASSERT(m_nonce_state.fresh_nonce(), "Nonce state is fresh"); } void OCB_Mode::set_associated_data(const byte ad[], size_t ad_len) { m_ad_hash = ocb_hash(*m_L, *m_cipher, &ad[0], ad_len); } void OCB_Mode::write(const byte input[], size_t length) { Buffered_Filter::write(input, length); } void OCB_Mode::end_msg() { Buffered_Filter::end_msg(); } void OCB_Encryption::buffered_block(const byte input[], size_t input_length) { BOTAN_ASSERT(input_length % BS == 0, "Input length is an even number of blocks"); const size_t blocks = input_length / BS; const size_t par_bytes = m_cipher->parallel_bytes(); BOTAN_ASSERT(par_bytes % BS == 0, "Cipher is parallel in full blocks"); const size_t par_blocks = par_bytes / BS; const L_computer& L = *m_L; // convenient name secure_vector<byte> ctext_buf(par_bytes); secure_vector<byte> csum_accum(par_bytes); secure_vector<byte> offsets(par_bytes); size_t blocks_left = blocks; while(blocks_left) { const size_t to_proc = std::min(blocks_left, par_blocks); const size_t proc_bytes = to_proc * BS; xor_buf(&csum_accum[0], &input[0], proc_bytes); for(size_t i = 0; i != to_proc; ++i) { m_offset ^= L(ctz(++m_block_index)); copy_mem(&offsets[BS*i], &m_offset[0], BS); } copy_mem(&ctext_buf[0], &input[0], proc_bytes); ctext_buf ^= offsets; m_cipher->encrypt(ctext_buf); ctext_buf ^= offsets; send(ctext_buf, proc_bytes); input += proc_bytes; blocks_left -= to_proc; } // fold into checksum for(size_t i = 0; i != csum_accum.size(); ++i) m_checksum[i % BS] ^= csum_accum[i]; } void OCB_Encryption::buffered_final(const byte input[], size_t input_length) { if(input_length >= BS) { const size_t final_blocks = input_length / BS; const size_t final_bytes = final_blocks * BS; buffered_block(input, final_bytes); input += final_bytes; input_length -= final_bytes; } if(input_length) { BOTAN_ASSERT(input_length < BS, "Only a partial block left"); xor_buf(&m_checksum[0], &input[0], input_length); m_checksum[input_length] ^= 0x80; m_offset ^= m_L->star(); // Offset_* secure_vector<byte> buf(BS); m_cipher->encrypt(m_offset, buf); xor_buf(&buf[0], &input[0], input_length); send(buf, input_length); // final ciphertext } // now compute the tag secure_vector<byte> mac = m_offset; mac ^= m_checksum; mac ^= m_L->dollar(); m_cipher->encrypt(mac); mac ^= m_ad_hash; send(mac); zeroise(m_checksum); zeroise(m_offset); m_block_index = 0; } void OCB_Decryption::buffered_block(const byte input[], size_t input_length) { BOTAN_ASSERT(input_length % BS == 0, "Input length is an even number of blocks"); const size_t blocks = input_length / BS; const size_t par_bytes = m_cipher->parallel_bytes(); BOTAN_ASSERT(par_bytes % BS == 0, "Cipher is parallel in full blocks"); const size_t par_blocks = par_bytes / BS; const L_computer& L = *m_L; // convenient name secure_vector<byte> ptext_buf(par_bytes); secure_vector<byte> csum_accum(par_bytes); secure_vector<byte> offsets(par_bytes); size_t blocks_left = blocks; while(blocks_left) { const size_t to_proc = std::min(blocks_left, par_blocks); const size_t proc_bytes = to_proc * BS; for(size_t i = 0; i != to_proc; ++i) { m_offset ^= L(ctz(++m_block_index)); copy_mem(&offsets[BS*i], &m_offset[0], BS); } copy_mem(&ptext_buf[0], &input[0], proc_bytes); ptext_buf ^= offsets; m_cipher->decrypt(ptext_buf); ptext_buf ^= offsets; xor_buf(&csum_accum[0], &ptext_buf[0], proc_bytes); send(ptext_buf, proc_bytes); input += proc_bytes; blocks_left -= to_proc; } // fold into checksum for(size_t i = 0; i != csum_accum.size(); ++i) m_checksum[i % BS] ^= csum_accum[i]; } void OCB_Decryption::buffered_final(const byte input[], size_t input_length) { BOTAN_ASSERT(input_length >= m_tag_size, "We have the tag"); const byte* included_tag = &input[input_length-m_tag_size]; input_length -= m_tag_size; if(input_length >= BS) { const size_t final_blocks = input_length / BS; const size_t final_bytes = final_blocks * BS; buffered_block(input, final_bytes); input += final_bytes; input_length -= final_bytes; } if(input_length) { BOTAN_ASSERT(input_length < BS, "Only a partial block left"); m_offset ^= m_L->star(); // Offset_* secure_vector<byte> buf(BS); m_cipher->encrypt(m_offset, buf); // P_* xor_buf(&buf[0], &input[0], input_length); xor_buf(&m_checksum[0], &buf[0], input_length); m_checksum[input_length] ^= 0x80; send(buf, input_length); // final plaintext } // now compute the tag secure_vector<byte> mac = m_offset; mac ^= m_checksum; mac ^= m_L->dollar(); m_cipher->encrypt(mac); mac ^= m_ad_hash; zeroise(m_checksum); zeroise(m_offset); m_block_index = 0; if(!same_mem(&mac[0], included_tag, m_tag_size)) throw Integrity_Failure("OCB tag check failed"); } } <|endoftext|>
<commit_before>/****************************************************************/ /* PIKA - Phase field snow micro-structure model */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "PhaseTransition.h" #include "AirProperties.h" template<> InputParameters validParams<PhaseTransition>() { InputParameters params = validParams<ACBulk>(); params += validParams<CoefficientKernelInterface>(); params.addRequiredCoupledVar("chemical_potential", "The chemical potential variable to couple"); params.addParam<std::string>("lambda", "lambda", "The name of the material property containing the definition of lambda"); params.addParam<std::string>("equilibrium_concentration", "equilibrium_concentration", "The name of the material property containing the equilibrium concentration"); return params; } PhaseTransition::PhaseTransition(const std::string & name, InputParameters parameters) : ACBulk(name, parameters), PropertyUserObjectInterface(name, parameters), CoefficientKernelInterface(name, parameters), _s(coupledValue("chemical_potential")), _lambda(getMaterialProperty<Real>(getParam<std::string>("lambda"))), _s_eq(getMaterialProperty<Real>(getParam<std::string>("equilibrium_concentration"))) { } Real PhaseTransition::computeDFDOP(PFFunctionType type) { switch (type) { case Residual: return - coefficient(_qp) * (_lambda[_qp]) * (_s[_qp] - _s_eq[_qp]) * (1.0 - _u[_qp]*_u[_qp])*(1.0 - _u[_qp]*_u[_qp]); case Jacobian: return coefficient(_qp) * 4.0 * _lambda[_qp] * _u[_qp] * (-_u[_qp] * _u[_qp]+1.0) * (_s[_qp] - _s_eq[_qp]) * _phi[_j][_qp]; } } <commit_msg>Always have return value<commit_after>/****************************************************************/ /* PIKA - Phase field snow micro-structure model */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "PhaseTransition.h" #include "AirProperties.h" template<> InputParameters validParams<PhaseTransition>() { InputParameters params = validParams<ACBulk>(); params += validParams<CoefficientKernelInterface>(); params.addRequiredCoupledVar("chemical_potential", "The chemical potential variable to couple"); params.addParam<std::string>("lambda", "lambda", "The name of the material property containing the definition of lambda"); params.addParam<std::string>("equilibrium_concentration", "equilibrium_concentration", "The name of the material property containing the equilibrium concentration"); return params; } PhaseTransition::PhaseTransition(const std::string & name, InputParameters parameters) : ACBulk(name, parameters), PropertyUserObjectInterface(name, parameters), CoefficientKernelInterface(name, parameters), _s(coupledValue("chemical_potential")), _lambda(getMaterialProperty<Real>(getParam<std::string>("lambda"))), _s_eq(getMaterialProperty<Real>(getParam<std::string>("equilibrium_concentration"))) { } Real PhaseTransition::computeDFDOP(PFFunctionType type) { switch (type) { case Residual: return - coefficient(_qp) * (_lambda[_qp]) * (_s[_qp] - _s_eq[_qp]) * (1.0 - _u[_qp]*_u[_qp])*(1.0 - _u[_qp]*_u[_qp]); case Jacobian: return coefficient(_qp) * 4.0 * _lambda[_qp] * _u[_qp] * (-_u[_qp] * _u[_qp]+1.0) * (_s[_qp] - _s_eq[_qp]) * _phi[_j][_qp]; } return 0.0; } <|endoftext|>
<commit_before>#include "gboost.h" #include "solver.h" #include "core/tpool.h" #include "core/logger.h" #include "gboost_stump.h" #include "core/ibstream.h" #include "core/obstream.h" using namespace nano; static auto measure(const task_t& task, const fold_t& fold, const tensor4d_t& outputs, const loss_t& loss) { const auto& tpool = tpool_t::instance(); std::vector<stats_t> errors(tpool.workers()); std::vector<stats_t> values(tpool.workers()); loopit(task.size(fold), [&] (const size_t i, const size_t t) { assert(t < tpool.workers()); const auto input = task.input(fold, i); const auto target = task.target(fold, i); const auto output = outputs.tensor(i); errors[t](loss.error(target, output)); values[t](loss.value(target, output)); }); for (size_t t = 1; t < tpool.workers(); ++ t) { errors[0](errors[t]); values[0](values[t]); } return std::make_pair(errors[0], values[0]); } static void update(const task_t& task, const fold_t& fold, tensor4d_t& outputs, const stump_t& stump) { loopi(task.size(fold), [&] (const size_t i) { const auto input = task.input(fold, i); const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1; outputs.array(i) += stump.m_outputs.array(oindex); }); } // todo: break the computation in smaller functions (move them to gboost.h) // todo: better comment tensor/tensor.h void gboost_stump_t::to_json(json_t& json) const { nano::to_json(json, "rounds", m_rounds, "patience", m_patience, "stump", m_stype, "stumps", join(enum_values<stump>()), "solver", m_solver, "solvers", join(get_solvers().ids()), "regularization", m_rtype, "regularizations", join(enum_values<regularization>())); } void gboost_stump_t::from_json(const json_t& json) { nano::from_json(json, "rounds", m_rounds, "patience", m_patience, "stump", m_stype, "solver", m_solver, "regularization", m_rtype); } trainer_result_t gboost_stump_t::train(const task_t& task, const size_t fold, const loss_t& loss) { // check if the solver is properly set rsolver_t solver; critical(solver = get_solvers().get(m_solver), strcat("invalid solver (", m_solver, ")")); m_idims = task.idims(); m_odims = task.odims(); m_stumps.clear(); trainer_result_t result("<config>"); timer_t timer; const auto fold_train = fold_t{fold, protocol::train}; const auto fold_valid = fold_t{fold, protocol::valid}; const auto fold_test = fold_t{fold, protocol::test}; tensor4d_t outputs_train(cat_dims(task.size(fold_train), m_odims)); tensor4d_t outputs_valid(cat_dims(task.size(fold_valid), m_odims)); tensor4d_t outputs_test(cat_dims(task.size(fold_test), m_odims)); outputs_train.zero(); outputs_valid.zero(); outputs_test.zero(); stats_t errors_train, errors_valid, errors_test; stats_t values_train, values_valid, values_test; std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss); std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss); std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss); result.update(trainer_state_t{timer.milliseconds(), 0, {values_train.avg(), errors_train.avg()}, {values_valid.avg(), errors_valid.avg()}, {values_test.avg(), errors_test.avg()}}, m_patience); log_info() << result; tensor4d_t residuals_train(cat_dims(task.size(fold_train), m_odims)); tensor3d_t residuals_pos1(m_odims), residuals_pos2(m_odims); tensor3d_t residuals_neg1(m_odims), residuals_neg2(m_odims); stump_t stump; tensor4d_t stump_outputs_train(cat_dims(task.size(fold_train), m_odims)); tensor4d_t targets(cat_dims(task.size(fold_train), m_odims)); for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto target = task.target(fold_train, i); targets.tensor(i) = target.tensor(); } gboost_lsearch_function_t func(targets, outputs_train, stump_outputs_train, loss); for (auto round = 0; round < m_rounds && !result.is_done(); ++ round) { for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto input = task.input(fold_train, i); const auto target = task.target(fold_train, i); const auto output = outputs_train.tensor(i); const auto vgrad = loss.vgrad(target, output); residuals_train.vector(i) = -vgrad.vector(); } scalar_t best_value = std::numeric_limits<scalar_t>::max(); // todo: generalize this - e.g. to use features that are products of two input features for (auto feature = 0; feature < nano::size(m_idims); ++ feature) { scalars_t fvalues(task.size(fold_train)); for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto input = task.input(fold_train, i); fvalues[i] = input(feature); } auto thresholds = fvalues; std::sort(thresholds.begin(), thresholds.end()); thresholds.erase(std::unique(thresholds.begin(), thresholds.end()), thresholds.end()); for (size_t t = 0; t + 1 < thresholds.size(); ++ t) { const auto threshold = (thresholds[t + 0] + thresholds[t + 1]) / 2; residuals_pos1.zero(), residuals_pos2.zero(); residuals_neg1.zero(), residuals_neg2.zero(); int cnt_pos = 0, cnt_neg = 0; for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto residual = residuals_train.tensor(i).array(); if (fvalues[i] < threshold) { cnt_neg ++; residuals_neg1.array() += residual; residuals_neg2.array() += residual * residual; } else { cnt_pos ++; residuals_pos1.array() += residual; residuals_pos2.array() += residual * residual; } } const auto value = (residuals_pos2.array().sum() - residuals_pos1.array().square().sum() / cnt_pos) + (residuals_neg2.array().sum() - residuals_neg1.array().square().sum() / cnt_neg); //log_info() << "feature = " << feature // << ", threshold = " << threshold // << ", value = " << value // << ", count = " << cnt_neg << "+" << cnt_pos << "=" << task.size(fold_train); if (value < best_value) { best_value = value; stump.m_feature = feature; stump.m_threshold = threshold; stump.m_outputs.resize(cat_dims(2, m_odims)); stump.m_outputs.vector(0) = residuals_neg1.vector() / cnt_neg; stump.m_outputs.vector(1) = residuals_pos1.vector() / cnt_pos; } // todo: fit both real and discrete stumps } } // line-search for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto input = task.input(fold_train, i); const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1; stump_outputs_train.tensor(i) = stump.m_outputs.tensor(oindex); } const auto state = solver->minimize(100, epsilon2<scalar_t>(), func, vector_t::Constant(1, 0)); const auto step = state.x(0); stump.m_outputs.vector() *= step; m_stumps.push_back(stump); // update current outputs update(task, fold_train, outputs_train, stump); update(task, fold_valid, outputs_valid, stump); update(task, fold_test, outputs_test, stump); std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss); std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss); std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss); result.update(trainer_state_t{timer.milliseconds(), round + 1, {values_train.avg(), errors_train.avg()}, {values_valid.avg(), errors_valid.avg()}, {values_test.avg(), errors_test.avg()}}, m_patience); log_info() << result << ",feature=" << stump.m_feature << ",gamma=" << step << ",solver=" << state.m_status << "|i=" << state.m_iterations << "|f=" << state.f << "|g=" << state.convergence_criteria() << "."; } // keep only the stumps up to optimum epoch (on the validation dataset) m_stumps.erase( m_stumps.begin() + result.optimum().m_epoch, m_stumps.end()); return result; } tensor3d_t gboost_stump_t::output(const tensor3d_t& input) const { assert(input.dims() == m_idims); tensor3d_t output(m_odims); output.zero(); const auto idata = input.array(); auto odata = output.array(); for (const auto& stump : m_stumps) { const auto oindex = idata(stump.m_feature) < stump.m_threshold ? 0 : 1; odata.array() += stump.m_outputs.array(oindex); } return output; } bool gboost_stump_t::save(obstream_t& stream) const { if ( !stream.write(m_idims) || !stream.write(m_odims) || !stream.write(m_rounds) || !stream.write(m_stype) || !stream.write(m_rtype) || !stream.write(m_stumps.size())) { return false; } for (const auto& stump : m_stumps) { assert(stump.m_feature >= 0 && stump.m_feature < nano::size(m_idims)); assert(stump.m_outputs.dims() == cat_dims(2, m_odims)); if ( !stream.write(stump.m_feature) || !stream.write(stump.m_threshold) || !stream.write_tensor(stump.m_outputs)) { return false; } } return true; } bool gboost_stump_t::load(ibstream_t& stream) { size_t n_stumps = 0; if ( !stream.read(m_idims) || !stream.read(m_odims) || !stream.read(m_rounds) || !stream.read(m_stype) || !stream.read(m_rtype) || !stream.read(n_stumps)) { return false; } m_stumps.resize(n_stumps); for (auto& stump : m_stumps) { if ( !stream.read(stump.m_feature) || !stream.read(stump.m_threshold) || !stream.read_tensor(stump.m_outputs) || stump.m_feature < 0 || stump.m_feature >= nano::size(m_idims) || stump.m_outputs.dims() != cat_dims(2, m_odims)) { return false; } } // todo: more verbose loading (#stumps, feature or coefficient statistics, idims...) return true; } probes_t gboost_stump_t::probes() const { // todo: add probes here to measure the training and the evaluation time probes_t probes; return probes; } <commit_msg>improve logging for gboost stump<commit_after>#include "gboost.h" #include "solver.h" #include "core/tpool.h" #include "core/logger.h" #include "gboost_stump.h" #include "core/ibstream.h" #include "core/obstream.h" using namespace nano; static auto measure(const task_t& task, const fold_t& fold, const tensor4d_t& outputs, const loss_t& loss) { const auto& tpool = tpool_t::instance(); std::vector<stats_t> errors(tpool.workers()); std::vector<stats_t> values(tpool.workers()); loopit(task.size(fold), [&] (const size_t i, const size_t t) { assert(t < tpool.workers()); const auto input = task.input(fold, i); const auto target = task.target(fold, i); const auto output = outputs.tensor(i); errors[t](loss.error(target, output)); values[t](loss.value(target, output)); }); for (size_t t = 1; t < tpool.workers(); ++ t) { errors[0](errors[t]); values[0](values[t]); } return std::make_pair(errors[0], values[0]); } static void update(const task_t& task, const fold_t& fold, tensor4d_t& outputs, const stump_t& stump) { loopi(task.size(fold), [&] (const size_t i) { const auto input = task.input(fold, i); const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1; outputs.array(i) += stump.m_outputs.array(oindex); }); } // todo: break the computation in smaller functions (move them to gboost.h) // todo: better comment tensor/tensor.h void gboost_stump_t::to_json(json_t& json) const { nano::to_json(json, "rounds", m_rounds, "patience", m_patience, "stump", m_stype, "stumps", join(enum_values<stump>()), "solver", m_solver, "solvers", join(get_solvers().ids()), "regularization", m_rtype, "regularizations", join(enum_values<regularization>())); } void gboost_stump_t::from_json(const json_t& json) { nano::from_json(json, "rounds", m_rounds, "patience", m_patience, "stump", m_stype, "solver", m_solver, "regularization", m_rtype); } trainer_result_t gboost_stump_t::train(const task_t& task, const size_t fold, const loss_t& loss) { // check if the solver is properly set rsolver_t solver; critical(solver = get_solvers().get(m_solver), strcat("search solver (", m_solver, ").")); m_idims = task.idims(); m_odims = task.odims(); m_stumps.clear(); trainer_result_t result("<config>"); timer_t timer; const auto fold_train = fold_t{fold, protocol::train}; const auto fold_valid = fold_t{fold, protocol::valid}; const auto fold_test = fold_t{fold, protocol::test}; tensor4d_t outputs_train(cat_dims(task.size(fold_train), m_odims)); tensor4d_t outputs_valid(cat_dims(task.size(fold_valid), m_odims)); tensor4d_t outputs_test(cat_dims(task.size(fold_test), m_odims)); outputs_train.zero(); outputs_valid.zero(); outputs_test.zero(); stats_t errors_train, errors_valid, errors_test; stats_t values_train, values_valid, values_test; std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss); std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss); std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss); result.update(trainer_state_t{timer.milliseconds(), 0, {values_train.avg(), errors_train.avg()}, {values_valid.avg(), errors_valid.avg()}, {values_test.avg(), errors_test.avg()}}, m_patience); log_info() << result << "."; tensor4d_t residuals_train(cat_dims(task.size(fold_train), m_odims)); tensor3d_t residuals_pos1(m_odims), residuals_pos2(m_odims); tensor3d_t residuals_neg1(m_odims), residuals_neg2(m_odims); stump_t stump; tensor4d_t stump_outputs_train(cat_dims(task.size(fold_train), m_odims)); tensor4d_t targets(cat_dims(task.size(fold_train), m_odims)); for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto target = task.target(fold_train, i); targets.tensor(i) = target.tensor(); } gboost_lsearch_function_t func(targets, outputs_train, stump_outputs_train, loss); for (auto round = 0; round < m_rounds && !result.is_done(); ++ round) { for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto input = task.input(fold_train, i); const auto target = task.target(fold_train, i); const auto output = outputs_train.tensor(i); const auto vgrad = loss.vgrad(target, output); residuals_train.vector(i) = -vgrad.vector(); } scalar_t best_value = std::numeric_limits<scalar_t>::max(); // todo: generalize this - e.g. to use features that are products of two input features for (auto feature = 0; feature < nano::size(m_idims); ++ feature) { scalars_t fvalues(task.size(fold_train)); for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto input = task.input(fold_train, i); fvalues[i] = input(feature); } auto thresholds = fvalues; std::sort(thresholds.begin(), thresholds.end()); thresholds.erase(std::unique(thresholds.begin(), thresholds.end()), thresholds.end()); for (size_t t = 0; t + 1 < thresholds.size(); ++ t) { const auto threshold = (thresholds[t + 0] + thresholds[t + 1]) / 2; residuals_pos1.zero(), residuals_pos2.zero(); residuals_neg1.zero(), residuals_neg2.zero(); int cnt_pos = 0, cnt_neg = 0; for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto residual = residuals_train.tensor(i).array(); if (fvalues[i] < threshold) { cnt_neg ++; residuals_neg1.array() += residual; residuals_neg2.array() += residual * residual; } else { cnt_pos ++; residuals_pos1.array() += residual; residuals_pos2.array() += residual * residual; } } const auto value = (residuals_pos2.array().sum() - residuals_pos1.array().square().sum() / cnt_pos) + (residuals_neg2.array().sum() - residuals_neg1.array().square().sum() / cnt_neg); //log_info() << "feature = " << feature // << ", threshold = " << threshold // << ", value = " << value // << ", count = " << cnt_neg << "+" << cnt_pos << "=" << task.size(fold_train); if (value < best_value) { best_value = value; stump.m_feature = feature; stump.m_threshold = threshold; stump.m_outputs.resize(cat_dims(2, m_odims)); stump.m_outputs.vector(0) = residuals_neg1.vector() / cnt_neg; stump.m_outputs.vector(1) = residuals_pos1.vector() / cnt_pos; } // todo: fit both real and discrete stumps } } // line-search for (size_t i = 0, size = task.size(fold_train); i < size; ++ i) { const auto input = task.input(fold_train, i); const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1; stump_outputs_train.tensor(i) = stump.m_outputs.tensor(oindex); } const auto state = solver->minimize(100, epsilon2<scalar_t>(), func, vector_t::Constant(1, 0)); const auto step = state.x(0); stump.m_outputs.vector() *= step; m_stumps.push_back(stump); // update current outputs update(task, fold_train, outputs_train, stump); update(task, fold_valid, outputs_valid, stump); update(task, fold_test, outputs_test, stump); std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss); std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss); std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss); result.update(trainer_state_t{timer.milliseconds(), round + 1, {values_train.avg(), errors_train.avg()}, {values_valid.avg(), errors_valid.avg()}, {values_test.avg(), errors_test.avg()}}, m_patience); log_info() << result << ",feature=" << stump.m_feature << ",solver=(" << state.m_status << ",i=" << state.m_iterations << ",x=" << state.x(0) << ",f=" << state.f << ",g=" << state.convergence_criteria() << ")."; } // keep only the stumps up to optimum epoch (on the validation dataset) m_stumps.erase( m_stumps.begin() + result.optimum().m_epoch, m_stumps.end()); return result; } tensor3d_t gboost_stump_t::output(const tensor3d_t& input) const { assert(input.dims() == m_idims); tensor3d_t output(m_odims); output.zero(); const auto idata = input.array(); auto odata = output.array(); for (const auto& stump : m_stumps) { const auto oindex = idata(stump.m_feature) < stump.m_threshold ? 0 : 1; odata.array() += stump.m_outputs.array(oindex); } return output; } bool gboost_stump_t::save(obstream_t& stream) const { if ( !stream.write(m_idims) || !stream.write(m_odims) || !stream.write(m_rounds) || !stream.write(m_stype) || !stream.write(m_rtype) || !stream.write(m_stumps.size())) { return false; } for (const auto& stump : m_stumps) { assert(stump.m_feature >= 0 && stump.m_feature < nano::size(m_idims)); assert(stump.m_outputs.dims() == cat_dims(2, m_odims)); if ( !stream.write(stump.m_feature) || !stream.write(stump.m_threshold) || !stream.write_tensor(stump.m_outputs)) { return false; } } return true; } bool gboost_stump_t::load(ibstream_t& stream) { size_t n_stumps = 0; if ( !stream.read(m_idims) || !stream.read(m_odims) || !stream.read(m_rounds) || !stream.read(m_stype) || !stream.read(m_rtype) || !stream.read(n_stumps)) { return false; } m_stumps.resize(n_stumps); for (auto& stump : m_stumps) { if ( !stream.read(stump.m_feature) || !stream.read(stump.m_threshold) || !stream.read_tensor(stump.m_outputs) || stump.m_feature < 0 || stump.m_feature >= nano::size(m_idims) || stump.m_outputs.dims() != cat_dims(2, m_odims)) { return false; } } // todo: more verbose loading (#stumps, feature or coefficient statistics, idims...) return true; } probes_t gboost_stump_t::probes() const { // todo: add probes here to measure the training and the evaluation time probes_t probes; return probes; } <|endoftext|>
<commit_before>#include "Transports/AddressFactory.hpp" #include "Utils/Logging.hpp" #include "Settings.hpp" using Dissent::Utils::Logging; namespace Dissent { namespace Applications { Settings::Settings(const QString &file, bool actions) : _use_file(true), _settings(new QSettings(file, QSettings::IniFormat)) { Init(actions); } Settings::Settings() : _use_file(false), _settings(new QSettings()) { Init(); } Settings::Settings(const QSharedPointer<QSettings> &settings, bool file, bool actions) : _use_file(file), _settings(settings) { Init(actions); } void Settings::Init(bool actions) { if(_settings->value(Param<Params::Help>(), false).toBool()) { Help = true; return; } Help = false; QVariant remote = _settings->value(Param<Params::RemoteEndPoints>()); RemoteEndPoints = ParseAddressList("RemoteEndPoints", remote); QVariant local = _settings->value(Param<Params::LocalEndPoints>()); LocalEndPoints = ParseAddressList("EndPoint", local); Auth = _settings->value(Param<Params::Auth>(), true).toBool(); LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>(), 1).toInt(); Console = _settings->value(Param<Params::Console>(), false).toBool(); ExitTunnel = _settings->value(Param<Params::ExitTunnel>(), false).toBool(); Multithreading = _settings->value(Param<Params::Multithreading>(), false).toBool(); WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), "http"); WebServer = WebServerUrl != QUrl(); EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), "tcp"); EntryTunnel = EntryTunnelUrl != QUrl(); ExitTunnelProxyUrl = TryParseUrl(_settings->value(Param<Params::ExitTunnelProxyUrl>()).toString(), "tcp"); ExitTunnel = (ExitTunnelProxyUrl != QUrl()) || ExitTunnel; if(_settings->contains(Param<Params::RoundType>())) { QString stype = _settings->value(Param<Params::RoundType>()).toString(); RoundType = Anonymity::RoundFactory::GetRoundType(stype); } else { RoundType = Anonymity::RoundFactory::NULL_ROUND; } Log = _settings->value(Param<Params::Log>(), "null").toString(); QString log_lower = Log.toLower(); if(actions) { if(log_lower == "stderr") { Logging::UseStderr(); } else if(log_lower == "stdout") { Logging::UseStdout(); } else if(log_lower == "null" || log_lower.isEmpty()) { Logging::Disable(); } else { Logging::UseFile(Log); } } if(_settings->contains(Param<Params::LocalId>())) { LocalId = ParseIdList(_settings->value(Param<Params::LocalId>())); } if(_settings->contains(Param<Params::ServerIds>())) { ServerIds = ParseIdList(_settings->value(Param<Params::ServerIds>())); } PublicKeys = _settings->value(Param<Params::PublicKeys>()).toString(); PrivateKeys = _settings->value(Param<Params::PrivateKeys>()).toString(); } bool Settings::IsValid() { if(_use_file && (_settings->status() != QSettings::NoError)) { _reason = "File error"; return false; } if(!LocalEndPoints.count()) { _reason = "No local end points"; return false; } if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) { _reason = "Invalid WebServerUrl: " + WebServerUrl.toString(); return false; } if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) { _reason = "Invalid EntryTunnelUrl: " + EntryTunnelUrl.toString(); return false; } if(!ServerIds.count()) { _reason = "No server Ids"; return false; } if(Auth && (LocalId.count() != LocalNodeCount)) { _reason = QString("Insufficient local ids, found %1, expected %2."). arg(LocalId.count()).arg(LocalNodeCount); return false; } if(RoundType == Anonymity::RoundFactory::INVALID) { _reason = "Invalid round type: " + _settings->value(Param<Params::RoundType>()).toString(); return false; } return true; } QString Settings::GetError() { IsValid(); return _reason; } QList<Transports::Address> Settings::ParseAddressList(const QString &name, const QVariant &values) { QList<Transports::Address> list; if(values.isNull()) { return list; } QVariantList varlist = values.toList(); if(!varlist.empty()) { foreach(QVariant value, varlist) { list.append(Transports::AddressFactory::GetInstance(). CreateAddress(ParseUrl(name, value))); } } else { list.append(Transports::AddressFactory::GetInstance(). CreateAddress(ParseUrl(name, values))); } return list; } QUrl Settings::ParseUrl(const QString &name, const QVariant &value) { QUrl url(value.toString()); if(!url.isValid()) { qFatal("Invalid %s: %s", name.toLatin1().data(), value.toString().toLatin1().data()); } return url; } QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme) { QUrl url = QUrl(string_rep); if(url.toString() != string_rep) { return QUrl(); } if(url.scheme() != scheme) { return QUrl(); } return url; } QList<Connections::Id> Settings::ParseIdList(const QVariant &qids) { QList<Connections::Id> id_list; QVariantList ids = qids.toList(); if(!ids.empty()) { foreach(const QVariant &id, ids) { id_list.append(Connections::Id(id.toString())); } } else { id_list.append(Connections::Id(qids.toString())); } return id_list; } void Settings::Save() { if(!_use_file) { return; } QStringList peers; foreach(const Transports::Address &addr, RemoteEndPoints) { peers << addr.ToString(); } if(!peers.empty()) { _settings->setValue(Param<Params::RemoteEndPoints>(), peers); } QStringList endpoints; foreach(const Transports::Address &addr, LocalEndPoints) { endpoints << addr.ToString(); } if(!endpoints.empty()) { _settings->setValue(Param<Params::LocalEndPoints>(), endpoints); } _settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount); _settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl); _settings->setValue(Param<Params::Console>(), Console); _settings->setValue(Param<Params::Auth>(), Auth); _settings->setValue(Param<Params::Log>(), Log); _settings->setValue(Param<Params::Multithreading>(), Multithreading); QVariantList local_ids; foreach(const Connections::Id &id, LocalId) { local_ids.append(id.ToString()); } _settings->setValue(Param<Params::LocalId>(), local_ids); QVariantList server_ids; foreach(const Connections::Id &id, ServerIds) { server_ids.append(id.ToString()); } _settings->setValue(Param<Params::ServerIds>(), server_ids); } Settings Settings::CommandLineParse(const QStringList &params, bool actions) { QSharedPointer<QxtCommandOptions> options = GetOptions(); options->parse(params); QSharedPointer<QSettings> settings; bool file = (options->positional().count() > 0); if(file) { settings = QSharedPointer<QSettings>( new QSettings(options->positional()[0], QSettings::IniFormat)); } else { settings = QSharedPointer<QSettings>(new QSettings()); // Bug in other platforms?? I do not know... settings->clear(); if(params.size() == 1) { settings->setValue(Param<Params::Help>(), true); } } QMultiHash<QString, QVariant> kv_params = options->parameters(); if(kv_params.value(Param<Params::Help>(), false).toBool() && file) { file = false; settings = QSharedPointer<QSettings>(new QSettings()); } foreach(const QString &key, kv_params.uniqueKeys()) { if(options->value(key).type() == QVariant::String && options->value(key).toString().isEmpty()) { settings->setValue(key, true); } else { settings->setValue(key, options->value(key)); } } return Settings(settings, file, actions); } QSharedPointer<QxtCommandOptions> Settings::GetOptions() { QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions()); options->add(Param<Params::Help>(), "help (this screen)", QxtCommandOptions::NoValue); options->add(Param<Params::RemoteEndPoints>(), "list of remote end points", QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple); options->add(Param<Params::LocalEndPoints>(), "list of local end points", QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple); options->add(Param<Params::LocalNodeCount>(), "number of virtual nodes to start", QxtCommandOptions::ValueRequired); options->add(Param<Params::Auth>(), "bool, enable or disable authentication", QxtCommandOptions::ValueRequired); options->add(Param<Params::RoundType>(), "the type of round", QxtCommandOptions::ValueRequired); options->add(Param<Params::Log>(), "logging mechanism: stderr, stdout, or a file path", QxtCommandOptions::ValueRequired); options->add(Param<Params::Console>(), "enable console", QxtCommandOptions::NoValue); options->add(Param<Params::WebServerUrl>(), "web server url (enables web server)", QxtCommandOptions::ValueRequired); options->add(Param<Params::EntryTunnelUrl>(), "entry tunnel url (enables entry tunnel)", QxtCommandOptions::ValueRequired); options->add(Param<Params::ExitTunnel>(), "enables exit tunnel", QxtCommandOptions::NoValue); options->add(Param<Params::ExitTunnelProxyUrl>(), "enables redirecting to a proxy at the end of an exit tunnel", QxtCommandOptions::ValueRequired); options->add(Param<Params::Multithreading>(), "enables multithreading", QxtCommandOptions::NoValue); options->add(Param<Params::LocalId>(), "one or more 160-bit base64 local id", QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple); options->add(Param<Params::ServerIds>(), "one or more 160-bit base64 server id", QxtCommandOptions::ValueRequired); options->add(Param<Params::PrivateKeys>(), "a path to a directory containing private keys", QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple); options->add(Param<Params::PublicKeys>(), "a path to a directory containing public keys (public keys end in \".pub\"", QxtCommandOptions::ValueRequired); return options; } } } <commit_msg>[Applications] For some reason this has help set to true by default<commit_after>#include "Transports/AddressFactory.hpp" #include "Utils/Logging.hpp" #include "Settings.hpp" using Dissent::Utils::Logging; namespace Dissent { namespace Applications { Settings::Settings(const QString &file, bool actions) : _use_file(true), _settings(new QSettings(file, QSettings::IniFormat)) { Init(actions); } Settings::Settings() : _use_file(false), _settings(new QSettings()) { _settings->clear(); Init(); } Settings::Settings(const QSharedPointer<QSettings> &settings, bool file, bool actions) : _use_file(file), _settings(settings) { Init(actions); } void Settings::Init(bool actions) { if(_settings->value(Param<Params::Help>(), false).toBool()) { Help = true; return; } Help = false; QVariant remote = _settings->value(Param<Params::RemoteEndPoints>()); RemoteEndPoints = ParseAddressList("RemoteEndPoints", remote); QVariant local = _settings->value(Param<Params::LocalEndPoints>()); LocalEndPoints = ParseAddressList("EndPoint", local); Auth = _settings->value(Param<Params::Auth>(), true).toBool(); LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>(), 1).toInt(); Console = _settings->value(Param<Params::Console>(), false).toBool(); ExitTunnel = _settings->value(Param<Params::ExitTunnel>(), false).toBool(); Multithreading = _settings->value(Param<Params::Multithreading>(), false).toBool(); WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), "http"); WebServer = WebServerUrl != QUrl(); EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), "tcp"); EntryTunnel = EntryTunnelUrl != QUrl(); ExitTunnelProxyUrl = TryParseUrl(_settings->value(Param<Params::ExitTunnelProxyUrl>()).toString(), "tcp"); ExitTunnel = (ExitTunnelProxyUrl != QUrl()) || ExitTunnel; if(_settings->contains(Param<Params::RoundType>())) { QString stype = _settings->value(Param<Params::RoundType>()).toString(); RoundType = Anonymity::RoundFactory::GetRoundType(stype); } else { RoundType = Anonymity::RoundFactory::NULL_ROUND; } Log = _settings->value(Param<Params::Log>(), "null").toString(); QString log_lower = Log.toLower(); if(actions) { if(log_lower == "stderr") { Logging::UseStderr(); } else if(log_lower == "stdout") { Logging::UseStdout(); } else if(log_lower == "null" || log_lower.isEmpty()) { Logging::Disable(); } else { Logging::UseFile(Log); } } if(_settings->contains(Param<Params::LocalId>())) { LocalId = ParseIdList(_settings->value(Param<Params::LocalId>())); } if(_settings->contains(Param<Params::ServerIds>())) { ServerIds = ParseIdList(_settings->value(Param<Params::ServerIds>())); } PublicKeys = _settings->value(Param<Params::PublicKeys>()).toString(); PrivateKeys = _settings->value(Param<Params::PrivateKeys>()).toString(); } bool Settings::IsValid() { if(_use_file && (_settings->status() != QSettings::NoError)) { _reason = "File error"; return false; } if(!LocalEndPoints.count()) { _reason = "No local end points"; return false; } if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) { _reason = "Invalid WebServerUrl: " + WebServerUrl.toString(); return false; } if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) { _reason = "Invalid EntryTunnelUrl: " + EntryTunnelUrl.toString(); return false; } if(!ServerIds.count()) { _reason = "No server Ids"; return false; } if(Auth && (LocalId.count() != LocalNodeCount)) { _reason = QString("Insufficient local ids, found %1, expected %2."). arg(LocalId.count()).arg(LocalNodeCount); return false; } if(RoundType == Anonymity::RoundFactory::INVALID) { _reason = "Invalid round type: " + _settings->value(Param<Params::RoundType>()).toString(); return false; } return true; } QString Settings::GetError() { IsValid(); return _reason; } QList<Transports::Address> Settings::ParseAddressList(const QString &name, const QVariant &values) { QList<Transports::Address> list; if(values.isNull()) { return list; } QVariantList varlist = values.toList(); if(!varlist.empty()) { foreach(QVariant value, varlist) { list.append(Transports::AddressFactory::GetInstance(). CreateAddress(ParseUrl(name, value))); } } else { list.append(Transports::AddressFactory::GetInstance(). CreateAddress(ParseUrl(name, values))); } return list; } QUrl Settings::ParseUrl(const QString &name, const QVariant &value) { QUrl url(value.toString()); if(!url.isValid()) { qFatal("Invalid %s: %s", name.toLatin1().data(), value.toString().toLatin1().data()); } return url; } QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme) { QUrl url = QUrl(string_rep); if(url.toString() != string_rep) { return QUrl(); } if(url.scheme() != scheme) { return QUrl(); } return url; } QList<Connections::Id> Settings::ParseIdList(const QVariant &qids) { QList<Connections::Id> id_list; QVariantList ids = qids.toList(); if(!ids.empty()) { foreach(const QVariant &id, ids) { id_list.append(Connections::Id(id.toString())); } } else { id_list.append(Connections::Id(qids.toString())); } return id_list; } void Settings::Save() { if(!_use_file) { return; } QStringList peers; foreach(const Transports::Address &addr, RemoteEndPoints) { peers << addr.ToString(); } if(!peers.empty()) { _settings->setValue(Param<Params::RemoteEndPoints>(), peers); } QStringList endpoints; foreach(const Transports::Address &addr, LocalEndPoints) { endpoints << addr.ToString(); } if(!endpoints.empty()) { _settings->setValue(Param<Params::LocalEndPoints>(), endpoints); } _settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount); _settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl); _settings->setValue(Param<Params::Console>(), Console); _settings->setValue(Param<Params::Auth>(), Auth); _settings->setValue(Param<Params::Log>(), Log); _settings->setValue(Param<Params::Multithreading>(), Multithreading); QVariantList local_ids; foreach(const Connections::Id &id, LocalId) { local_ids.append(id.ToString()); } _settings->setValue(Param<Params::LocalId>(), local_ids); QVariantList server_ids; foreach(const Connections::Id &id, ServerIds) { server_ids.append(id.ToString()); } _settings->setValue(Param<Params::ServerIds>(), server_ids); } Settings Settings::CommandLineParse(const QStringList &params, bool actions) { QSharedPointer<QxtCommandOptions> options = GetOptions(); options->parse(params); QSharedPointer<QSettings> settings; bool file = (options->positional().count() > 0); if(file) { settings = QSharedPointer<QSettings>( new QSettings(options->positional()[0], QSettings::IniFormat)); } else { settings = QSharedPointer<QSettings>(new QSettings()); // Bug in other platforms?? I do not know... settings->clear(); if(params.size() == 1) { settings->setValue(Param<Params::Help>(), true); } } QMultiHash<QString, QVariant> kv_params = options->parameters(); if(kv_params.value(Param<Params::Help>(), false).toBool() && file) { file = false; settings = QSharedPointer<QSettings>(new QSettings()); } foreach(const QString &key, kv_params.uniqueKeys()) { if(options->value(key).type() == QVariant::String && options->value(key).toString().isEmpty()) { settings->setValue(key, true); } else { settings->setValue(key, options->value(key)); } } return Settings(settings, file, actions); } QSharedPointer<QxtCommandOptions> Settings::GetOptions() { QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions()); options->add(Param<Params::Help>(), "help (this screen)", QxtCommandOptions::NoValue); options->add(Param<Params::RemoteEndPoints>(), "list of remote end points", QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple); options->add(Param<Params::LocalEndPoints>(), "list of local end points", QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple); options->add(Param<Params::LocalNodeCount>(), "number of virtual nodes to start", QxtCommandOptions::ValueRequired); options->add(Param<Params::Auth>(), "bool, enable or disable authentication", QxtCommandOptions::ValueRequired); options->add(Param<Params::RoundType>(), "the type of round", QxtCommandOptions::ValueRequired); options->add(Param<Params::Log>(), "logging mechanism: stderr, stdout, or a file path", QxtCommandOptions::ValueRequired); options->add(Param<Params::Console>(), "enable console", QxtCommandOptions::NoValue); options->add(Param<Params::WebServerUrl>(), "web server url (enables web server)", QxtCommandOptions::ValueRequired); options->add(Param<Params::EntryTunnelUrl>(), "entry tunnel url (enables entry tunnel)", QxtCommandOptions::ValueRequired); options->add(Param<Params::ExitTunnel>(), "enables exit tunnel", QxtCommandOptions::NoValue); options->add(Param<Params::ExitTunnelProxyUrl>(), "enables redirecting to a proxy at the end of an exit tunnel", QxtCommandOptions::ValueRequired); options->add(Param<Params::Multithreading>(), "enables multithreading", QxtCommandOptions::NoValue); options->add(Param<Params::LocalId>(), "one or more 160-bit base64 local id", QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple); options->add(Param<Params::ServerIds>(), "one or more 160-bit base64 server id", QxtCommandOptions::ValueRequired); options->add(Param<Params::PrivateKeys>(), "a path to a directory containing private keys", QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple); options->add(Param<Params::PublicKeys>(), "a path to a directory containing public keys (public keys end in \".pub\"", QxtCommandOptions::ValueRequired); return options; } } } <|endoftext|>
<commit_before>/// /// @file /// @copyright Copyright (C) 2017, Jonathan Bryan Schmalhofer /// /// @brief Node to cyclically publish buffered PNG images /// #include <string> #include <ros/ros.h> #include <image_transport/image_transport.h> sensor_msgs::Image airsim_image_left_msg, airsim_image_right_msg; int main(int argc, char **argv) { ros::init(argc, argv, "airsim_to_ros_image_publisher_node"); ros::NodeHandle node_handle; ROS_INFO("Starting node"); image_transport::ImageTransport image_transport(node_handle); image_transport::Publisher left_stereoimage_chatter = image_transport.advertise("/airsim/left/image_raw", 1); image_transport::Publisher right_stereoimage_chatter = image_transport.advertise("/airsim/right/image_raw", 1); std::uint32_t last_sequence_sent = 0; while (ros::ok()) { ROS_INFO("Waiting for data"); int8_t received_return_value = 0; if (1 == received_return_value) { switch (airsim_to_ros.GetImageType()) { case 0: // Unknown break; case 1: // Left ROS_INFO("Left image received"); // Header airsim_image_left_msg.header.seq = airsim_to_ros.GetImageHeaderSeq(); airsim_image_left_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec(); airsim_image_left_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec(); airsim_image_left_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid(); // Image airsim_image_left_msg.height = airsim_to_ros.GetImageHeight(); airsim_image_left_msg.width = airsim_to_ros.GetImageWidth(); airsim_image_left_msg.encoding = airsim_to_ros.GetImageEncoding(); airsim_image_left_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian(); airsim_image_left_msg.step = airsim_to_ros.GetImageStep(); airsim_image_left_msg.data.resize(airsim_to_ros.GetImageDataSize()); memcpy((char*)(&airsim_image_left_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize()); break; case 2: // Right ROS_INFO("Right image received"); // Header airsim_image_right_msg.header.seq = airsim_to_ros.GetImageHeaderSeq(); airsim_image_right_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec(); airsim_image_right_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec(); airsim_image_right_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid(); // Image airsim_image_right_msg.height = airsim_to_ros.GetImageHeight(); airsim_image_right_msg.width = airsim_to_ros.GetImageWidth(); airsim_image_right_msg.encoding = airsim_to_ros.GetImageEncoding(); airsim_image_right_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian(); airsim_image_right_msg.step = airsim_to_ros.GetImageStep(); airsim_image_right_msg.data.resize(airsim_to_ros.GetImageDataSize()); memcpy((char*)(&airsim_image_right_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize()); break; default: break; } // TODO: Introduce Debug Mode ROS_INFO("Image received"); ROS_INFO(" Image.header.seq %d", airsim_to_ros.GetImageHeaderSeq()); ROS_INFO(" Image.header.stamp.sec %d", airsim_to_ros.GetImageHeaderStampSec()); ROS_INFO(" Image.header.stamp.nsec %d", airsim_to_ros.GetImageHeaderStampNsec()); ROS_INFO(" Image.header.frame_id %s", airsim_to_ros.GetImageHeaderFrameid()); ROS_INFO(" Image.height %d", airsim_to_ros.GetImageHeight()); ROS_INFO(" Image.width %d", airsim_to_ros.GetImageWidth()); ROS_INFO(" Image.encoding %s", airsim_to_ros.GetImageEncoding()); ROS_INFO(" Image.is_bigendian %d", airsim_to_ros.GetImageIsBigendian()); ROS_INFO(" Image.step %d", airsim_to_ros.GetImageStep()); ROS_INFO(" size(Image.data) %d", airsim_to_ros.GetImageDataSize()); if ( airsim_image_left_msg.header.seq == airsim_image_right_msg.header.seq && airsim_image_left_msg.header.seq > last_sequence_sent ) { ROS_INFO("Images forwarded"); left_stereoimage_chatter.publish(airsim_image_left_msg); right_stereoimage_chatter.publish(airsim_image_right_msg); } } else if (-1 == received_return_value) { ROS_INFO("Invalid Image received - did not forward"); } } return 0; } <commit_msg>bugfix for stub<commit_after>/// /// @file /// @copyright Copyright (C) 2017, Jonathan Bryan Schmalhofer /// /// @brief Node to cyclically publish buffered PNG images /// #include <string> #include <ros/ros.h> #include <image_transport/image_transport.h> sensor_msgs::Image airsim_image_left_msg, airsim_image_right_msg; int main(int argc, char **argv) { ros::init(argc, argv, "airsim_to_ros_image_publisher_node"); ros::NodeHandle node_handle; ROS_INFO("Starting node"); image_transport::ImageTransport image_transport(node_handle); image_transport::Publisher left_stereoimage_chatter = image_transport.advertise("/airsim/left/image_raw", 1); image_transport::Publisher right_stereoimage_chatter = image_transport.advertise("/airsim/right/image_raw", 1); std::uint32_t last_sequence_sent = 0; while (ros::ok()) { ROS_INFO("Waiting for data"); int8_t received_return_value = 0; if (1 == received_return_value) { /* switch (airsim_to_ros.GetImageType()) { case 0: // Unknown break; case 1: // Left ROS_INFO("Left image received"); // Header airsim_image_left_msg.header.seq = airsim_to_ros.GetImageHeaderSeq(); airsim_image_left_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec(); airsim_image_left_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec(); airsim_image_left_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid(); // Image airsim_image_left_msg.height = airsim_to_ros.GetImageHeight(); airsim_image_left_msg.width = airsim_to_ros.GetImageWidth(); airsim_image_left_msg.encoding = airsim_to_ros.GetImageEncoding(); airsim_image_left_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian(); airsim_image_left_msg.step = airsim_to_ros.GetImageStep(); airsim_image_left_msg.data.resize(airsim_to_ros.GetImageDataSize()); memcpy((char*)(&airsim_image_left_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize()); break; case 2: // Right ROS_INFO("Right image received"); // Header airsim_image_right_msg.header.seq = airsim_to_ros.GetImageHeaderSeq(); airsim_image_right_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec(); airsim_image_right_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec(); airsim_image_right_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid(); // Image airsim_image_right_msg.height = airsim_to_ros.GetImageHeight(); airsim_image_right_msg.width = airsim_to_ros.GetImageWidth(); airsim_image_right_msg.encoding = airsim_to_ros.GetImageEncoding(); airsim_image_right_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian(); airsim_image_right_msg.step = airsim_to_ros.GetImageStep(); airsim_image_right_msg.data.resize(airsim_to_ros.GetImageDataSize()); memcpy((char*)(&airsim_image_right_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize()); break; default: break; } // TODO: Introduce Debug Mode ROS_INFO("Image received"); ROS_INFO(" Image.header.seq %d", airsim_to_ros.GetImageHeaderSeq()); ROS_INFO(" Image.header.stamp.sec %d", airsim_to_ros.GetImageHeaderStampSec()); ROS_INFO(" Image.header.stamp.nsec %d", airsim_to_ros.GetImageHeaderStampNsec()); ROS_INFO(" Image.header.frame_id %s", airsim_to_ros.GetImageHeaderFrameid()); ROS_INFO(" Image.height %d", airsim_to_ros.GetImageHeight()); ROS_INFO(" Image.width %d", airsim_to_ros.GetImageWidth()); ROS_INFO(" Image.encoding %s", airsim_to_ros.GetImageEncoding()); ROS_INFO(" Image.is_bigendian %d", airsim_to_ros.GetImageIsBigendian()); ROS_INFO(" Image.step %d", airsim_to_ros.GetImageStep()); ROS_INFO(" size(Image.data) %d", airsim_to_ros.GetImageDataSize()); */ if ( airsim_image_left_msg.header.seq == airsim_image_right_msg.header.seq && airsim_image_left_msg.header.seq > last_sequence_sent ) { ROS_INFO("Images forwarded"); left_stereoimage_chatter.publish(airsim_image_left_msg); right_stereoimage_chatter.publish(airsim_image_right_msg); } } else if (-1 == received_return_value) { ROS_INFO("Invalid Image received - did not forward"); } } return 0; } <|endoftext|>
<commit_before>#include "Common.h" #include "CacheAdapters/LevelDB.h" #include "SSEConfig.h" #include "SSEEvent.h" using namespace std; /** Constructor. @param config SSEChannelConfig. **/ LevelDB::LevelDB(const ChannelConfig& config) : _config(config) { const string cachefile = _config.server->GetValue("leveldb.storageDir") + "/" + config.id + ".db"; LOG(INFO) << "LevelDB storage file: " << cachefile; InitDB(cachefile); } /** Destructor. */ LevelDB::~LevelDB() { leveldb_options_destroy(_options); leveldb_writeoptions_destroy(_woptions); leveldb_readoptions_destroy(_roptions); leveldb_close(_db); } /** @param dbfile Path where we should create or load the database. **/ void LevelDB::InitDB(const string& dbfile) { char* err = NULL; _options = leveldb_options_create(); _roptions = leveldb_readoptions_create(); _woptions = leveldb_writeoptions_create(); leveldb_options_set_create_if_missing(_options, 1); _db = leveldb_open(_options, dbfile.c_str(), &err); if (err != NULL) { LOG(FATAL) << "Failed to open leveldb storage file: " << err; leveldb_free(err); err = NULL; } LOG(INFO) << "LevelDB::InitDB finished for " << _config.id; } /** Add event to cache. @patam event Pointer to SSEEvent to cache. **/ void LevelDB::CacheEvent(SSEEvent* event) { char* err = NULL; leveldb_put(_db, _woptions, event->getid().c_str(), event->getid().length(), event->get().c_str(), event->get().length(), &err); if (err != NULL) { LOG(ERROR) << "Failed to cache event with id " << event->getid() << ": " << err; leveldb_free(err); return; } if (GetSizeOfCachedEvents() > _config.cacheLength) { size_t klen; char *err = NULL; leveldb_iterator_t* it = leveldb_create_iterator(_db, _roptions); leveldb_iter_seek_to_first(it); const string key = leveldb_iter_key(it, &klen); leveldb_delete(_db, _woptions, key.c_str(), klen, &err); if (err != NULL) { LOG(ERROR) << "Failed to delete key " << key << ": " << err; leveldb_free(err); } else { DLOG(INFO) << "Deleted key " << key; } leveldb_iter_destroy(it); } } /** Get a list of all events since a givend ID. @param lastId ID of first event. **/ deque<string> LevelDB::GetEventsSinceId(string lastId) { deque<string> events; leveldb_iterator_t* it; leveldb_readoptions_t* readopts; const leveldb_snapshot_t* snapshot; snapshot = leveldb_create_snapshot(_db); readopts = leveldb_readoptions_create(); leveldb_readoptions_set_snapshot(readopts, snapshot); it = leveldb_create_iterator(_db, readopts); for (leveldb_iter_seek(it, lastId.c_str(), lastId.length()); leveldb_iter_valid(it); leveldb_iter_next(it)) { size_t vlen; const char* val = leveldb_iter_value(it, &vlen); events.push_back(val); } leveldb_iter_destroy(it); leveldb_release_snapshot(_db, snapshot); leveldb_readoptions_destroy(readopts); return events; } /** Get a list of all events stored in the cache. **/ deque<string> LevelDB::GetAllEvents() { deque<string> events; leveldb_iterator_t* it; leveldb_readoptions_t* readopts; const leveldb_snapshot_t* snapshot; snapshot = leveldb_create_snapshot(_db); readopts = leveldb_readoptions_create(); leveldb_readoptions_set_snapshot(readopts, snapshot); it = leveldb_create_iterator(_db, readopts); for (leveldb_iter_seek_to_first(it); leveldb_iter_valid(it); leveldb_iter_next(it)) { size_t vlen; const char* val = leveldb_iter_value(it, &vlen); events.push_back(val); } leveldb_iter_destroy(it); leveldb_release_snapshot(_db, snapshot); leveldb_readoptions_destroy(readopts); return events; } /** Get number of events currently stored in the cache. **/ int LevelDB::GetSizeOfCachedEvents() { leveldb_iterator_t* it; leveldb_readoptions_t* readopts; const leveldb_snapshot_t* snapshot; int n_keys; snapshot = leveldb_create_snapshot(_db); readopts = leveldb_readoptions_create(); it = leveldb_create_iterator(_db, readopts); leveldb_iter_seek_to_first(it); for(n_keys = 0; leveldb_iter_valid(it); leveldb_iter_next(it)) { n_keys++; } leveldb_iter_destroy(it); leveldb_release_snapshot(_db, snapshot); leveldb_readoptions_destroy(readopts); return n_keys; } <commit_msg>Make room for the null terminator when storing events in the LevelDB cache.<commit_after>#include "Common.h" #include "CacheAdapters/LevelDB.h" #include "SSEConfig.h" #include "SSEEvent.h" using namespace std; /** Constructor. @param config SSEChannelConfig. **/ LevelDB::LevelDB(const ChannelConfig& config) : _config(config) { const string cachefile = _config.server->GetValue("leveldb.storageDir") + "/" + config.id + ".db"; LOG(INFO) << "LevelDB storage file: " << cachefile; InitDB(cachefile); } /** Destructor. */ LevelDB::~LevelDB() { leveldb_options_destroy(_options); leveldb_writeoptions_destroy(_woptions); leveldb_readoptions_destroy(_roptions); leveldb_close(_db); } /** @param dbfile Path where we should create or load the database. **/ void LevelDB::InitDB(const string& dbfile) { char* err = NULL; _options = leveldb_options_create(); _roptions = leveldb_readoptions_create(); _woptions = leveldb_writeoptions_create(); leveldb_options_set_create_if_missing(_options, 1); _db = leveldb_open(_options, dbfile.c_str(), &err); if (err != NULL) { LOG(FATAL) << "Failed to open leveldb storage file: " << err; leveldb_free(err); err = NULL; } LOG(INFO) << "LevelDB::InitDB finished for " << _config.id; } /** Add event to cache. @patam event Pointer to SSEEvent to cache. **/ void LevelDB::CacheEvent(SSEEvent* event) { char* err = NULL; leveldb_put(_db, _woptions, event->getid().c_str(), event->getid().length()+1, event->get().c_str(), event->get().length()+1, &err); if (err != NULL) { LOG(ERROR) << "Failed to cache event with id " << event->getid() << ": " << err; leveldb_free(err); return; } if (GetSizeOfCachedEvents() > _config.cacheLength) { size_t klen; char *err = NULL; leveldb_iterator_t* it = leveldb_create_iterator(_db, _roptions); leveldb_iter_seek_to_first(it); const string key = leveldb_iter_key(it, &klen); leveldb_delete(_db, _woptions, key.c_str(), klen, &err); if (err != NULL) { LOG(ERROR) << "Failed to delete key " << key << ": " << err; leveldb_free(err); } else { DLOG(INFO) << "Deleted key " << key; } leveldb_iter_destroy(it); } } /** Get a list of all events since a givend ID. @param lastId ID of first event. **/ deque<string> LevelDB::GetEventsSinceId(string lastId) { deque<string> events; leveldb_iterator_t* it; leveldb_readoptions_t* readopts; const leveldb_snapshot_t* snapshot; snapshot = leveldb_create_snapshot(_db); readopts = leveldb_readoptions_create(); leveldb_readoptions_set_snapshot(readopts, snapshot); it = leveldb_create_iterator(_db, readopts); for (leveldb_iter_seek(it, lastId.c_str(), lastId.length()); leveldb_iter_valid(it); leveldb_iter_next(it)) { size_t vlen; const char* val = leveldb_iter_value(it, &vlen); events.push_back(val); } leveldb_iter_destroy(it); leveldb_release_snapshot(_db, snapshot); leveldb_readoptions_destroy(readopts); return events; } /** Get a list of all events stored in the cache. **/ deque<string> LevelDB::GetAllEvents() { deque<string> events; leveldb_iterator_t* it; leveldb_readoptions_t* readopts; const leveldb_snapshot_t* snapshot; snapshot = leveldb_create_snapshot(_db); readopts = leveldb_readoptions_create(); leveldb_readoptions_set_snapshot(readopts, snapshot); it = leveldb_create_iterator(_db, readopts); for (leveldb_iter_seek_to_first(it); leveldb_iter_valid(it); leveldb_iter_next(it)) { size_t vlen; const char* val = leveldb_iter_value(it, &vlen); events.push_back(val); } leveldb_iter_destroy(it); leveldb_release_snapshot(_db, snapshot); leveldb_readoptions_destroy(readopts); return events; } /** Get number of events currently stored in the cache. **/ int LevelDB::GetSizeOfCachedEvents() { leveldb_iterator_t* it; leveldb_readoptions_t* readopts; const leveldb_snapshot_t* snapshot; int n_keys; snapshot = leveldb_create_snapshot(_db); readopts = leveldb_readoptions_create(); it = leveldb_create_iterator(_db, readopts); leveldb_iter_seek_to_first(it); for(n_keys = 0; leveldb_iter_valid(it); leveldb_iter_next(it)) { n_keys++; } leveldb_iter_destroy(it); leveldb_release_snapshot(_db, snapshot); leveldb_readoptions_destroy(readopts); return n_keys; } <|endoftext|>
<commit_before>#include "slider.h" #include "qdebug.h" Slider::Slider(QWidget * parent) : QSlider(parent) { setStyleSheet(QString( "QSlider::groove {" "border: 1px solid #bbb;" "border-radius: 2px;" "}" "QSlider::groove:horizontal {" "height: 18px;" "}" "QSlider::groove:vertical {" "width: 18px;" "}" "QSlider::sub-page:horizontal {" "background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #000, stop: 1 #777);" "background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 1, stop: 0 #777, stop: 1 #fff);" "border: 1px solid #777;" "border-radius: 2px;" "}" "QSlider::add-page:horizontal {" "background: #fff;" "border: 1px solid #777;" "border-radius: 2px;" "}" "QSlider::sub-page:vertical {" "background: #fff;" "border: 1px solid #777;" "border-radius: 2px;" "}" "QSlider::add-page:vertical {" "background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #000, stop: 1 #777);" "background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 1, stop: 0 #777, stop: 1 #fff);" "border: 1px solid #777;" "border-radius: 2px;" "}" "QSlider::handle {" "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #eee, stop:1 #ccc);" "border: 1px solid #777;" "margin: 0 -1px;" "border-radius: 2px;" "}" "QSlider::handle:horizontal {" "width: 12px;" "}" "QSlider::handle:vertical {" "height: 12px;" "}" "QSlider::handle:hover {" "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #fff, stop:1 #ddd);" "border: 1px solid #444;" "border-radius: 2px;" "}" "QSlider::sub-page:disabled {" "background: #bbb;" "border-color: #999;" "}" "QSlider::add-page:disabled {" "background: #eee;" "border-color: #999;" "}" "QSlider::handle:disabled {" "background: #eee;" "border: 1px solid #aaa;" "border-radius: 2px;" "}" )); } void Slider::paintEvent(QPaintEvent * event) { QSlider::paintEvent(event); QPainter p(this); p.save(); p.setPen(QColor::fromRgb(0, 0, 0)); QRect rect = geometry(); float limit, temp = 0, step = ((float)maximum()) / tickInterval(); int multiplyer = 0; if (orientation() == Qt::Horizontal) { while(temp < 20) { multiplyer++; temp = ((float)rect.width()) / (step / multiplyer); } step = temp; limit = (rect.width() / step) == 0 ? rect.width() - step : rect.width(); for(float pos = step; pos < limit; pos += step) { p.drawLine(pos, rect.top() + 4, pos, rect.bottom() - 7); } if (multiplyer > 1) p.drawText(4, rect.top() + 18, "x " + QString::number(multiplyer)); } else { while(temp < 20) { multiplyer++; temp = ((float)rect.height()) / (step / multiplyer); } step = temp; limit = (rect.height() / step) == 0 ? rect.height() - step : rect.height(); for(float pos = step; pos < limit; pos += step) { p.drawLine(rect.left() + 4, pos, rect.right() - 7, pos); } if (multiplyer > 1) { p.drawText(rect.left() + 4 + (multiplyer < 10 ? 3 : 0), (int)(limit - step / 2) + 2, "x" + QString::number(multiplyer)); } } p.restore(); } <commit_msg>minor improve<commit_after>#include "slider.h" #include "qdebug.h" Slider::Slider(QWidget * parent) : QSlider(parent) { setStyleSheet(QString( "QSlider::groove {" "border: 1px solid #bbb;" "border-radius: 2px;" "}" "QSlider::groove:horizontal {" "height: 18px;" "}" "QSlider::groove:vertical {" "width: 18px;" "}" "QSlider::sub-page:horizontal {" "background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #000, stop: 1 #777);" "background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 1, stop: 0 #777, stop: 1 #fff);" "border: 1px solid #777;" "border-radius: 2px;" "}" "QSlider::add-page:horizontal {" "background: #fff;" "border: 1px solid #777;" "border-radius: 2px;" "}" "QSlider::sub-page:vertical {" "background: #fff;" "border: 1px solid #777;" "border-radius: 2px;" "}" "QSlider::add-page:vertical {" "background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #000, stop: 1 #777);" "background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 1, stop: 0 #777, stop: 1 #fff);" "border: 1px solid #777;" "border-radius: 2px;" "}" "QSlider::handle {" "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #eee, stop:1 #ccc);" "border: 1px solid #777;" "margin: 0 -1px;" "border-radius: 2px;" "}" "QSlider::handle:horizontal {" "width: 12px;" "}" "QSlider::handle:vertical {" "height: 12px;" "}" "QSlider::handle:hover {" "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #fff, stop:1 #ddd);" "border: 1px solid #444;" "border-radius: 2px;" "}" "QSlider::sub-page:disabled {" "background: #bbb;" "border-color: #999;" "}" "QSlider::add-page:disabled {" "background: #eee;" "border-color: #999;" "}" "QSlider::handle:disabled {" "background: #eee;" "border: 1px solid #aaa;" "border-radius: 2px;" "}" )); } void Slider::paintEvent(QPaintEvent * event) { QSlider::paintEvent(event); QPainter p(this); p.save(); p.setPen(QColor::fromRgb(0, 0, 0)); QRect rect = geometry(); float limit, temp = 0, step = ((float)maximum()) / tickInterval(); int multiplyer = 0; if (orientation() == Qt::Horizontal) { while(temp < 16) { multiplyer++; temp = ((float)rect.width()) / (step / multiplyer); } step = temp; limit = (rect.width() / step) == 0 ? rect.width() - step : rect.width(); for(float pos = step; pos < limit; pos += step) { p.drawLine(pos, rect.top() + 4, pos, rect.bottom() - 7); } if (multiplyer > 1) p.drawText(4, rect.top() + 18, "x " + QString::number(multiplyer)); } else { while(temp < 20) { multiplyer++; temp = ((float)rect.height()) / (step / multiplyer); } step = temp; limit = (rect.height() / step) == 0 ? rect.height() - step : rect.height(); for(float pos = step; pos < limit; pos += step) { p.drawLine(rect.left() + 4, pos, rect.right() - 7, pos); } if (multiplyer > 1) { p.drawText(rect.left() + 4 + (multiplyer < 10 ? 3 : 0), (int)(limit - step / 2) + 2, "x" + QString::number(multiplyer)); } } p.restore(); } <|endoftext|>
<commit_before>#include "overlap.h" using namespace annis; Overlap::Overlap(DB &db, AnnotationIterator &left, AnnotationIterator &right) : left(left), rightAnnotation(right.getAnnotation()), db(db), edbLeft(db.getEdgeDB(ComponentType::LEFT_TOKEN, annis_ns, "")), edbRight(db.getEdgeDB(ComponentType::RIGHT_TOKEN, annis_ns, "")), edbOrder(db.getEdgeDB(ComponentType::ORDERING, annis_ns, "")), lhsLeftTokenIt(LeftMostTokenForNodeIterator(left, db)), tokenRightFromLHSIt(db, edbOrder, lhsLeftTokenIt, initAnnotation(db.getNodeNameStringID(), 0, db.getNamespaceStringID()), 0, uintmax) { reset(); } BinaryMatch Overlap::next() { BinaryMatch result; result.found = false; // TODO: implement overlap BinaryMatch rightTokenMatch; if(currentMatches.empty()) { rightTokenMatch = tokenRightFromLHSIt.next(); } else { rightTokenMatch.found = false; } while(currentMatches.empty() && rightTokenMatch.found) { result.lhs = lhsLeftTokenIt.currentNodeMatch(); // get the node that has a right border with the token std::vector<nodeid_t> overlapCandidates = edbRight->getOutgoingEdges(rightTokenMatch.rhs.node); // also add the token itself overlapCandidates.insert(overlapCandidates.begin(), rightTokenMatch.rhs.node); // check each candidate if it's left side comes before the right side of the lhs node for(unsigned int i=0; i < overlapCandidates.size(); i++) { nodeid_t candidateID = overlapCandidates[i]; // the first candidate is always the token itself, otherwise get the aligned token nodeid_t leftTokenForCandidate = i == 0 ? candidateID : edbLeft->getOutgoingEdges(candidateID)[0]; if(edbOrder->isConnected(initEdge(leftTokenForCandidate, rightTokenMatch.rhs.node), 0, uintmax)) { Match m; m.node = candidateID; for(const Annotation& anno : db.getNodeAnnotationsByID(candidateID)) { if(checkAnnotationEqual(rightAnnotation, anno)) { m.anno = anno; currentMatches.push_back(m); } } } } rightTokenMatch = tokenRightFromLHSIt.next(); } // end while while(!currentMatches.empty()) { result.found = true; result.rhs = currentMatches.front(); currentMatches.pop_front(); } return result; } void Overlap::reset() { uniqueMatches.clear(); left.reset(); currentMatches.clear(); lhsLeftTokenIt.reset(); tokenRightFromLHSIt.reset(); } Overlap::~Overlap() { } <commit_msg>use left-hand-side<commit_after>#include "overlap.h" using namespace annis; Overlap::Overlap(DB &db, AnnotationIterator &left, AnnotationIterator &right) : left(left), rightAnnotation(right.getAnnotation()), db(db), edbLeft(db.getEdgeDB(ComponentType::LEFT_TOKEN, annis_ns, "")), edbRight(db.getEdgeDB(ComponentType::RIGHT_TOKEN, annis_ns, "")), edbOrder(db.getEdgeDB(ComponentType::ORDERING, annis_ns, "")), lhsLeftTokenIt(left, db), tokenRightFromLHSIt(db, edbOrder, lhsLeftTokenIt, initAnnotation(db.getNodeNameStringID(), 0, db.getNamespaceStringID()), 0, uintmax) { reset(); } BinaryMatch Overlap::next() { BinaryMatch result; result.found = false; BinaryMatch rightTokenMatch; if(currentMatches.empty()) { rightTokenMatch = tokenRightFromLHSIt.next(); } else { rightTokenMatch.found = false; } while(currentMatches.empty() && rightTokenMatch.found) { result.lhs = lhsLeftTokenIt.currentNodeMatch(); // get the node that has a right border with the token std::vector<nodeid_t> overlapCandidates = edbRight->getOutgoingEdges(rightTokenMatch.rhs.node); // also add the token itself overlapCandidates.insert(overlapCandidates.begin(), rightTokenMatch.rhs.node); // check each candidate if it's left side comes before the right side of the lhs node for(unsigned int i=0; i < overlapCandidates.size(); i++) { nodeid_t candidateID = overlapCandidates[i]; // the first candidate is always the token itself, otherwise get the aligned token nodeid_t leftTokenForCandidate = i == 0 ? candidateID : edbLeft->getOutgoingEdges(candidateID)[0]; if(edbOrder->isConnected(initEdge(leftTokenForCandidate, rightTokenMatch.lhs.node), 0, uintmax)) { Match m; m.node = candidateID; for(const Annotation& anno : db.getNodeAnnotationsByID(candidateID)) { if(checkAnnotationEqual(rightAnnotation, anno)) { m.anno = anno; currentMatches.push_back(m); } } } } rightTokenMatch = tokenRightFromLHSIt.next(); } // end while while(!currentMatches.empty()) { result.found = true; result.rhs = currentMatches.front(); currentMatches.pop_front(); } return result; } void Overlap::reset() { uniqueMatches.clear(); left.reset(); currentMatches.clear(); lhsLeftTokenIt.reset(); tokenRightFromLHSIt.reset(); } Overlap::~Overlap() { } <|endoftext|>
<commit_before>// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/StaticMethodInfo> #include <osgIntrospection/Attributes> #include <osg/Array> #include <osgUtil/OperationArrayFunctor> // Must undefine IN and OUT macros defined in Windows headers #ifdef IN #undef IN #endif #ifdef OUT #undef OUT #endif BEGIN_VALUE_REFLECTOR(osgUtil::AddRangeOperator) I_DeclaringFile("osgUtil/OperationArrayFunctor"); I_Constructor0(____AddRangeOperator, "", ""); I_PublicMemberProperty(unsigned int, _begin); I_PublicMemberProperty(unsigned int, _count); I_PublicMemberProperty(osg::Vec3, _vector); END_REFLECTOR BEGIN_VALUE_REFLECTOR(osgUtil::MultiplyRangeOperator) I_DeclaringFile("osgUtil/OperationArrayFunctor"); I_Constructor0(____MultiplyRangeOperator, "", ""); I_PublicMemberProperty(unsigned int, _begin); I_PublicMemberProperty(unsigned int, _count); I_PublicMemberProperty(osg::Vec3, _vector); END_REFLECTOR TYPE_NAME_ALIAS(osgUtil::OperationArrayFunctor< osgUtil::AddRangeOperator >, osgUtil::AddRangeFunctor) TYPE_NAME_ALIAS(osgUtil::OperationArrayFunctor< osgUtil::MultiplyRangeOperator >, osgUtil::MultiplyRangeFunctor) BEGIN_OBJECT_REFLECTOR(osgUtil::OperationArrayFunctor< osgUtil::AddRangeOperator >) I_DeclaringFile("osgUtil/OperationArrayFunctor"); I_BaseType(osg::ArrayVisitor); I_Constructor0(____AddRangeOperator >, "", ""); I_Method1(void, apply, IN, osg::Array &, x, Properties::VIRTUAL, __void__apply__osg_Array_R1, "", ""); I_Method1(void, apply, IN, osg::Vec2Array &, array, Properties::VIRTUAL, __void__apply__osg_Vec2Array_R1, "", ""); I_Method1(void, apply, IN, osg::Vec3Array &, array, Properties::VIRTUAL, __void__apply__osg_Vec3Array_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4Array &, array, Properties::VIRTUAL, __void__apply__osg_Vec4Array_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4ubArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec4ubArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec2bArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec2bArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec3bArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec3bArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4bArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec4bArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec2sArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec2sArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec3sArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec3sArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4sArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec4sArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec2dArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec2dArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec3dArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec3dArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4dArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec4dArray_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgUtil::OperationArrayFunctor< osgUtil::MultiplyRangeOperator >) I_DeclaringFile("osgUtil/OperationArrayFunctor"); I_BaseType(osg::ArrayVisitor); I_Constructor0(____MultiplyRangeOperator >, "", ""); I_Method1(void, apply, IN, osg::Array &, x, Properties::VIRTUAL, __void__apply__osg_Array_R1, "", ""); I_Method1(void, apply, IN, osg::Vec2Array &, array, Properties::VIRTUAL, __void__apply__osg_Vec2Array_R1, "", ""); I_Method1(void, apply, IN, osg::Vec3Array &, array, Properties::VIRTUAL, __void__apply__osg_Vec3Array_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4Array &, array, Properties::VIRTUAL, __void__apply__osg_Vec4Array_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4ubArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec4ubArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec2bArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec2bArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec3bArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec3bArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4bArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec4bArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec2sArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec2sArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec3sArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec3sArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4sArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec4sArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec2dArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec2dArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec3dArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec3dArray_R1, "", ""); I_Method1(void, apply, IN, osg::Vec4dArray &, array, Properties::VIRTUAL, __void__apply__osg_Vec4dArray_R1, "", ""); END_REFLECTOR <commit_msg>Removed OperationArrayFunctor for wrappers to avoid compile errors assocaited with them<commit_after><|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). Copyright (C) 2008 Matthias Kretz <kretz@kde.org> This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "common.h" #include "audiooutput.h" #include "backend.h" #include "mediaobject.h" #include "gsthelper.h" #include <phonon/audiooutput.h> QT_BEGIN_NAMESPACE namespace Phonon { namespace Gstreamer { AudioOutput::AudioOutput(Backend *backend, QObject *parent) : QObject(parent) , MediaNode(backend, AudioSink) , m_volumeLevel(1.0) , m_device(0) // ### get from backend , m_volumeElement(0) , m_audioBin(0) , m_audioSink(0) , m_conv(0) { static int count = 0; m_name = "AudioOutput" + QString::number(count++); if (m_backend->isValid()) { m_audioBin = gst_bin_new (NULL); gst_object_ref (GST_OBJECT (m_audioBin)); gst_object_sink (GST_OBJECT (m_audioBin)); m_conv = gst_element_factory_make ("audioconvert", NULL); // Get category from parent Phonon::Category category = Phonon::NoCategory; if (Phonon::AudioOutput *audioOutput = qobject_cast<Phonon::AudioOutput *>(parent)) category = audioOutput->category(); m_audioSink = m_backend->deviceManager()->createAudioSink(category); m_volumeElement = gst_element_factory_make ("volume", NULL); GstElement *queue = gst_element_factory_make ("queue", NULL); GstElement *audioresample = gst_element_factory_make ("audioresample", NULL); if (queue && m_audioBin && m_conv && audioresample && m_audioSink && m_volumeElement) { gst_bin_add_many (GST_BIN (m_audioBin), queue, m_conv, audioresample, m_volumeElement, m_audioSink, (const char*)NULL); if (gst_element_link_many (queue, m_conv, audioresample, m_volumeElement, m_audioSink, (const char*)NULL)) { // Add ghost sink for audiobin GstPad *audiopad = gst_element_get_pad (queue, "sink"); gst_element_add_pad (m_audioBin, gst_ghost_pad_new ("sink", audiopad)); gst_object_unref (audiopad); m_isValid = true; // Initialization ok, accept input } } } } void AudioOutput::mediaNodeEvent(const MediaNodeEvent *event) { if (!m_audioBin) return; switch (event->type()) { default: break; } } AudioOutput::~AudioOutput() { if (m_audioBin) { gst_element_set_state (m_audioBin, GST_STATE_NULL); gst_object_unref (m_audioBin); } } qreal AudioOutput::volume() const { return m_volumeLevel; } int AudioOutput::outputDevice() const { return m_device; } void AudioOutput::setVolume(qreal newVolume) { if (newVolume > 2.0 ) newVolume = 2.0; else if (newVolume < 0.0) newVolume = 0.0; if (newVolume == m_volumeLevel) return; m_volumeLevel = newVolume; if (m_volumeElement) { g_object_set(G_OBJECT(m_volumeElement), "volume", newVolume, (const char*)NULL); } emit volumeChanged(newVolume); } bool AudioOutput::setOutputDevice(int newDevice) { m_backend->logMessage(Q_FUNC_INFO + QString::number(newDevice), Backend::Info, this); if (newDevice == m_device) return true; if (root()) { root()->saveState(); if (gst_element_set_state(root()->pipeline(), GST_STATE_READY) == GST_STATE_CHANGE_FAILURE) return false; } bool success = false; const QList<AudioDevice> deviceList = m_backend->deviceManager()->audioOutputDevices(); if (m_audioSink && newDevice >= 0 && newDevice < deviceList.size()) { // Save previous state GstState oldState = GST_STATE(m_audioSink); const QByteArray oldDeviceValue = GstHelper::property(m_audioSink, "device"); const QByteArray deviceId = deviceList.at(newDevice).gstId; m_device = newDevice; // We test if the device can be opened by checking if it can go from NULL to READY state gst_element_set_state(m_audioSink, GST_STATE_NULL); success = GstHelper::setProperty(m_audioSink, "device", deviceId); if (success) { success = (gst_element_set_state(m_audioSink, oldState) == GST_STATE_CHANGE_SUCCESS); } if (!success) { // Revert state m_backend->logMessage(Q_FUNC_INFO + QLatin1String(" Failed to change device ") + deviceId, Backend::Info, this); GstHelper::setProperty(m_audioSink, "device", oldDeviceValue); gst_element_set_state(m_audioSink, oldState); } else { m_backend->logMessage(Q_FUNC_INFO + QLatin1String(" Successfully changed device ") + deviceId, Backend::Info, this); } // Note the stopped state should not really be neccessary, but seems to be required to // properly reset after changing the audio state if (root()) { QMetaObject::invokeMethod(root(), "setState", Qt::QueuedConnection, Q_ARG(State, StoppedState)); root()->resumeState(); } } return success; } #if (PHONON_VERSION >= PHONON_VERSION_CHECK(4, 2, 0)) bool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice) { m_backend->logMessage(Q_FUNC_INFO, Backend::Info, this); if (!m_audioSink || !newDevice.isValid()) { return false; } const QVariant driver = newDevice.property("driver"); if (!driver.isValid()) { return setOutputDevice(newDevice.index()); } if (newDevice.index() == m_device) { return true; } if (root()) { root()->saveState(); if (gst_element_set_state(root()->pipeline(), GST_STATE_READY) == GST_STATE_CHANGE_FAILURE) return false; } // Save previous state const GstState oldState = GST_STATE(m_audioSink); const QByteArray oldDeviceValue = GstHelper::property(m_audioSink, "device"); const QByteArray sinkName = GstHelper::property(m_audioSink, "name"); if (sinkName == "alsasink" || sinkName == "alsasink2") { if (driver.toByteArray() != "alsa") { return false; } } const QVariant deviceIdsProperty = newDevice.property("deviceIds"); QStringList deviceIds; if (deviceIdsProperty.type() == QVariant::StringList) { deviceIds = deviceIdsProperty.toStringList(); } else if (deviceIdsProperty.type() == QVariant::String) { deviceIds += deviceIdsProperty.toString(); } // We test if the device can be opened by checking if it can go from NULL to READY state foreach (const QString &deviceId, deviceIds) { gst_element_set_state(m_audioSink, GST_STATE_NULL); if (GstHelper::setProperty(m_audioSink, "device", deviceId.toUtf8())) { m_backend->logMessage(Q_FUNC_INFO + QLatin1String("setProperty(device,") + deviceId + QLatin1String(") succeeded"), Backend::Info, this); if (gst_element_set_state(m_audioSink, oldState) == GST_STATE_CHANGE_SUCCESS) { m_backend->logMessage(Q_FUNC_INFO + QLatin1String("go to old state on device") + deviceId + QLatin1String(" succeeded"), Backend::Info, this); m_device = newDevice.index(); if (root()) { QMetaObject::invokeMethod(root(), "setState", Qt::QueuedConnection, Q_ARG(State, StoppedState)); root()->resumeState(); } return true; } else { m_backend->logMessage(Q_FUNC_INFO + QLatin1String("go to old state on device") + deviceId + QLatin1String(" failed"), Backend::Info, this); } } else { m_backend->logMessage(Q_FUNC_INFO + QLatin1String("setProperty(device,") + deviceId + QLatin1String(") failed"), Backend::Info, this); } } // Revert state GstHelper::setProperty(m_audioSink, "device", oldDeviceValue); gst_element_set_state(m_audioSink, oldState); if (root()) { QMetaObject::invokeMethod(root(), "setState", Qt::QueuedConnection, Q_ARG(State, StoppedState)); root()->resumeState(); } return false; } #endif } } //namespace Phonon::Gstreamer QT_END_NAMESPACE #include "moc_audiooutput.cpp" <commit_msg>Set the glib appname for gstreamer. This will allow sound servers such as pulseaudio to show the application name with a volume slider.<commit_after>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). Copyright (C) 2008 Matthias Kretz <kretz@kde.org> This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "common.h" #include "audiooutput.h" #include "backend.h" #include "mediaobject.h" #include "gsthelper.h" #include <phonon/audiooutput.h> QT_BEGIN_NAMESPACE namespace Phonon { namespace Gstreamer { AudioOutput::AudioOutput(Backend *backend, QObject *parent) : QObject(parent) , MediaNode(backend, AudioSink) , m_volumeLevel(1.0) , m_device(0) // ### get from backend , m_volumeElement(0) , m_audioBin(0) , m_audioSink(0) , m_conv(0) { static int count = 0; m_name = "AudioOutput" + QString::number(count++); if (m_backend->isValid()) { g_set_application_name(qApp->applicationName().toUtf8()); m_audioBin = gst_bin_new (NULL); gst_object_ref (GST_OBJECT (m_audioBin)); gst_object_sink (GST_OBJECT (m_audioBin)); m_conv = gst_element_factory_make ("audioconvert", NULL); // Get category from parent Phonon::Category category = Phonon::NoCategory; if (Phonon::AudioOutput *audioOutput = qobject_cast<Phonon::AudioOutput *>(parent)) category = audioOutput->category(); m_audioSink = m_backend->deviceManager()->createAudioSink(category); m_volumeElement = gst_element_factory_make ("volume", NULL); GstElement *queue = gst_element_factory_make ("queue", NULL); GstElement *audioresample = gst_element_factory_make ("audioresample", NULL); if (queue && m_audioBin && m_conv && audioresample && m_audioSink && m_volumeElement) { gst_bin_add_many (GST_BIN (m_audioBin), queue, m_conv, audioresample, m_volumeElement, m_audioSink, (const char*)NULL); if (gst_element_link_many (queue, m_conv, audioresample, m_volumeElement, m_audioSink, (const char*)NULL)) { // Add ghost sink for audiobin GstPad *audiopad = gst_element_get_pad (queue, "sink"); gst_element_add_pad (m_audioBin, gst_ghost_pad_new ("sink", audiopad)); gst_object_unref (audiopad); m_isValid = true; // Initialization ok, accept input } } } } void AudioOutput::mediaNodeEvent(const MediaNodeEvent *event) { if (!m_audioBin) return; switch (event->type()) { default: break; } } AudioOutput::~AudioOutput() { if (m_audioBin) { gst_element_set_state (m_audioBin, GST_STATE_NULL); gst_object_unref (m_audioBin); } } qreal AudioOutput::volume() const { return m_volumeLevel; } int AudioOutput::outputDevice() const { return m_device; } void AudioOutput::setVolume(qreal newVolume) { if (newVolume > 2.0 ) newVolume = 2.0; else if (newVolume < 0.0) newVolume = 0.0; if (newVolume == m_volumeLevel) return; m_volumeLevel = newVolume; if (m_volumeElement) { g_object_set(G_OBJECT(m_volumeElement), "volume", newVolume, (const char*)NULL); } emit volumeChanged(newVolume); } bool AudioOutput::setOutputDevice(int newDevice) { m_backend->logMessage(Q_FUNC_INFO + QString::number(newDevice), Backend::Info, this); if (newDevice == m_device) return true; if (root()) { root()->saveState(); if (gst_element_set_state(root()->pipeline(), GST_STATE_READY) == GST_STATE_CHANGE_FAILURE) return false; } bool success = false; const QList<AudioDevice> deviceList = m_backend->deviceManager()->audioOutputDevices(); if (m_audioSink && newDevice >= 0 && newDevice < deviceList.size()) { // Save previous state GstState oldState = GST_STATE(m_audioSink); const QByteArray oldDeviceValue = GstHelper::property(m_audioSink, "device"); const QByteArray deviceId = deviceList.at(newDevice).gstId; m_device = newDevice; // We test if the device can be opened by checking if it can go from NULL to READY state gst_element_set_state(m_audioSink, GST_STATE_NULL); success = GstHelper::setProperty(m_audioSink, "device", deviceId); if (success) { success = (gst_element_set_state(m_audioSink, oldState) == GST_STATE_CHANGE_SUCCESS); } if (!success) { // Revert state m_backend->logMessage(Q_FUNC_INFO + QLatin1String(" Failed to change device ") + deviceId, Backend::Info, this); GstHelper::setProperty(m_audioSink, "device", oldDeviceValue); gst_element_set_state(m_audioSink, oldState); } else { m_backend->logMessage(Q_FUNC_INFO + QLatin1String(" Successfully changed device ") + deviceId, Backend::Info, this); } // Note the stopped state should not really be neccessary, but seems to be required to // properly reset after changing the audio state if (root()) { QMetaObject::invokeMethod(root(), "setState", Qt::QueuedConnection, Q_ARG(State, StoppedState)); root()->resumeState(); } } return success; } #if (PHONON_VERSION >= PHONON_VERSION_CHECK(4, 2, 0)) bool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice) { m_backend->logMessage(Q_FUNC_INFO, Backend::Info, this); if (!m_audioSink || !newDevice.isValid()) { return false; } const QVariant driver = newDevice.property("driver"); if (!driver.isValid()) { return setOutputDevice(newDevice.index()); } if (newDevice.index() == m_device) { return true; } if (root()) { root()->saveState(); if (gst_element_set_state(root()->pipeline(), GST_STATE_READY) == GST_STATE_CHANGE_FAILURE) return false; } // Save previous state const GstState oldState = GST_STATE(m_audioSink); const QByteArray oldDeviceValue = GstHelper::property(m_audioSink, "device"); const QByteArray sinkName = GstHelper::property(m_audioSink, "name"); if (sinkName == "alsasink" || sinkName == "alsasink2") { if (driver.toByteArray() != "alsa") { return false; } } const QVariant deviceIdsProperty = newDevice.property("deviceIds"); QStringList deviceIds; if (deviceIdsProperty.type() == QVariant::StringList) { deviceIds = deviceIdsProperty.toStringList(); } else if (deviceIdsProperty.type() == QVariant::String) { deviceIds += deviceIdsProperty.toString(); } // We test if the device can be opened by checking if it can go from NULL to READY state foreach (const QString &deviceId, deviceIds) { gst_element_set_state(m_audioSink, GST_STATE_NULL); if (GstHelper::setProperty(m_audioSink, "device", deviceId.toUtf8())) { m_backend->logMessage(Q_FUNC_INFO + QLatin1String("setProperty(device,") + deviceId + QLatin1String(") succeeded"), Backend::Info, this); if (gst_element_set_state(m_audioSink, oldState) == GST_STATE_CHANGE_SUCCESS) { m_backend->logMessage(Q_FUNC_INFO + QLatin1String("go to old state on device") + deviceId + QLatin1String(" succeeded"), Backend::Info, this); m_device = newDevice.index(); if (root()) { QMetaObject::invokeMethod(root(), "setState", Qt::QueuedConnection, Q_ARG(State, StoppedState)); root()->resumeState(); } return true; } else { m_backend->logMessage(Q_FUNC_INFO + QLatin1String("go to old state on device") + deviceId + QLatin1String(" failed"), Backend::Info, this); } } else { m_backend->logMessage(Q_FUNC_INFO + QLatin1String("setProperty(device,") + deviceId + QLatin1String(") failed"), Backend::Info, this); } } // Revert state GstHelper::setProperty(m_audioSink, "device", oldDeviceValue); gst_element_set_state(m_audioSink, oldState); if (root()) { QMetaObject::invokeMethod(root(), "setState", Qt::QueuedConnection, Q_ARG(State, StoppedState)); root()->resumeState(); } return false; } #endif } } //namespace Phonon::Gstreamer QT_END_NAMESPACE #include "moc_audiooutput.cpp" <|endoftext|>
<commit_before>/* * * Copyright (c) 2021 Project CHIP Authors * * 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. */ /** * @file * Provides an implementation of the DiagnosticDataProvider object * for ESP32 platform. */ #include <platform/internal/CHIPDeviceLayerInternal.h> #include <app-common/zap-generated/enums.h> #include <crypto/CHIPCryptoPAL.h> #include <platform/DiagnosticDataProvider.h> #include <platform/ESP32/DiagnosticDataProviderImpl.h> #include <platform/ESP32/ESP32Utils.h> #include "esp_event.h" #include "esp_heap_caps_init.h" #include "esp_log.h" #include "esp_netif.h" #include "esp_spi_flash.h" #include "esp_system.h" #include "esp_wifi.h" using namespace ::chip; using namespace ::chip::TLV; using namespace ::chip::DeviceLayer; using namespace ::chip::DeviceLayer::Internal; using namespace ::chip::app::Clusters::GeneralDiagnostics; namespace { InterfaceType GetInterfaceType(const char * if_desc) { if (strncmp(if_desc, "ap", strnlen(if_desc, 2)) == 0 || strncmp(if_desc, "sta", strnlen(if_desc, 3)) == 0) return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_WI_FI; if (strncmp(if_desc, "openthread", strnlen(if_desc, 10)) == 0) return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_THREAD; if (strncmp(if_desc, "eth", strnlen(if_desc, 3)) == 0) return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_ETHERNET; return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_UNSPECIFIED; } #if CHIP_DEVICE_CONFIG_ENABLE_WIFI uint8_t MapAuthModeToSecurityType(wifi_auth_mode_t authmode) { switch (authmode) { case WIFI_AUTH_OPEN: return 1; case WIFI_AUTH_WEP: return 2; case WIFI_AUTH_WPA_PSK: return 3; case WIFI_AUTH_WPA2_PSK: return 4; case WIFI_AUTH_WPA3_PSK: return 5; default: return 0; } } uint8_t GetWiFiVersionFromAPRecord(wifi_ap_record_t ap_info) { if (ap_info.phy_11n) return 3; else if (ap_info.phy_11g) return 2; else if (ap_info.phy_11b) return 1; else return 0; } #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI } // namespace namespace chip { namespace DeviceLayer { DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() { static DiagnosticDataProviderImpl sInstance; return sInstance; } CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) { currentHeapFree = esp_get_free_heap_size(); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) { currentHeapUsed = heap_caps_get_total_size(MALLOC_CAP_DEFAULT) - esp_get_free_heap_size(); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) { currentHeapHighWatermark = heap_caps_get_total_size(MALLOC_CAP_DEFAULT) - esp_get_minimum_free_heap_size(); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetRebootCount(uint16_t & rebootCount) { uint32_t count = 0; CHIP_ERROR err = ConfigurationMgr().GetRebootCount(count); if (err == CHIP_NO_ERROR) { VerifyOrReturnError(count <= UINT16_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); rebootCount = static_cast<uint16_t>(count); } return err; } CHIP_ERROR DiagnosticDataProviderImpl::GetUpTime(uint64_t & upTime) { System::Clock::Timestamp currentTime = System::SystemClock().GetMonotonicTimestamp(); System::Clock::Timestamp startTime = PlatformMgrImpl().GetStartTime(); if (currentTime >= startTime) { upTime = std::chrono::duration_cast<System::Clock::Seconds64>(currentTime - startTime).count(); return CHIP_NO_ERROR; } return CHIP_ERROR_INVALID_TIME; } CHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) { uint64_t upTime = 0; if (GetUpTime(upTime) == CHIP_NO_ERROR) { uint32_t totalHours = 0; if (ConfigurationMgr().GetTotalOperationalHours(totalHours) == CHIP_NO_ERROR) { VerifyOrReturnError(upTime / 3600 <= UINT32_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); totalOperationalHours = totalHours + static_cast<uint32_t>(upTime / 3600); return CHIP_NO_ERROR; } } return CHIP_ERROR_INVALID_TIME; } CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason) { bootReason = BootReasonType::kUnspecified; uint8_t reason; reason = static_cast<uint8_t>(esp_reset_reason()); if (reason == ESP_RST_UNKNOWN) { bootReason = BootReasonType::kUnspecified; } else if (reason == ESP_RST_POWERON) { bootReason = BootReasonType::kPowerOnReboot; } else if (reason == ESP_RST_BROWNOUT) { bootReason = BootReasonType::kBrownOutReset; } else if (reason == ESP_RST_SW) { bootReason = BootReasonType::kSoftwareReset; } else if (reason == ESP_RST_INT_WDT) { bootReason = BootReasonType::kSoftwareWatchdogReset; /* Reboot can be due to hardware or software watchdog*/ } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** netifpp) { esp_netif_t * netif = esp_netif_next(NULL); NetworkInterface * head = NULL; if (netif == NULL) { ChipLogError(DeviceLayer, "Failed to get network interfaces"); } else { for (esp_netif_t * ifa = netif; ifa != NULL; ifa = esp_netif_next(ifa)) { NetworkInterface * ifp = new NetworkInterface(); strncpy(ifp->Name, esp_netif_get_ifkey(ifa), Inet::InterfaceId::kMaxIfNameLength); ifp->Name[Inet::InterfaceId::kMaxIfNameLength - 1] = '\0'; ifp->name = CharSpan::fromCharString(ifp->Name); ifp->isOperational = true; ifp->type = GetInterfaceType(esp_netif_get_desc(ifa)); ifp->offPremiseServicesReachableIPv4.SetNull(); ifp->offPremiseServicesReachableIPv6.SetNull(); if (esp_netif_get_mac(ifa, ifp->MacAddress) != ESP_OK) { ChipLogError(DeviceLayer, "Failed to get network hardware address"); } else { ifp->hardwareAddress = ByteSpan(ifp->MacAddress, 6); } ifp->Next = head; head = ifp; } } *netifpp = head; return CHIP_NO_ERROR; } void DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * netifp) { while (netifp) { NetworkInterface * del = netifp; netifp = netifp->Next; delete del; } } #if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(ByteSpan & BssId) { wifi_ap_record_t ap_info; esp_err_t err; static uint8_t macAddress[kMaxHardwareAddrSize]; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { memcpy(macAddress, ap_info.bssid, 6); } BssId = ByteSpan(macAddress, 6); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(uint8_t & securityType) { securityType = 0; wifi_ap_record_t ap_info; esp_err_t err; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { securityType = MapAuthModeToSecurityType(ap_info.authmode); } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion) { wifiVersion = 0; wifi_ap_record_t ap_info; esp_err_t err; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { wifiVersion = GetWiFiVersionFromAPRecord(ap_info); } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) { channelNumber = 0; wifi_ap_record_t ap_info; esp_err_t err; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { channelNumber = ap_info.primary; } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) { rssi = 0; wifi_ap_record_t ap_info; esp_err_t err; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { rssi = ap_info.rssi; } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastRxCount(uint32_t & packetMulticastRxCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastTxCount(uint32_t & packetMulticastTxCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastRxCount(uint32_t & packetUnicastRxCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiOverrunCount(uint64_t & overrunCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts() { return CHIP_NO_ERROR; } #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI DiagnosticDataProvider & GetDiagnosticDataProviderImpl() { return DiagnosticDataProviderImpl::GetDefaultInstance(); } } // namespace DeviceLayer } // namespace chip <commit_msg>ESP32: Add IPAddresses for the network interfaces in generaldiagnostic cluster (#21271)<commit_after>/* * * Copyright (c) 2021 Project CHIP Authors * * 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. */ /** * @file * Provides an implementation of the DiagnosticDataProvider object * for ESP32 platform. */ #include <platform/internal/CHIPDeviceLayerInternal.h> #include <app-common/zap-generated/enums.h> #include <crypto/CHIPCryptoPAL.h> #include <platform/DiagnosticDataProvider.h> #include <platform/ESP32/DiagnosticDataProviderImpl.h> #include <platform/ESP32/ESP32Utils.h> #include "esp_event.h" #include "esp_heap_caps_init.h" #include "esp_log.h" #include "esp_netif.h" #include "esp_spi_flash.h" #include "esp_system.h" #include "esp_wifi.h" using namespace ::chip; using namespace ::chip::TLV; using namespace ::chip::DeviceLayer; using namespace ::chip::DeviceLayer::Internal; using namespace ::chip::app::Clusters::GeneralDiagnostics; namespace { InterfaceType GetInterfaceType(const char * if_desc) { if (strncmp(if_desc, "ap", strnlen(if_desc, 2)) == 0 || strncmp(if_desc, "sta", strnlen(if_desc, 3)) == 0) return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_WI_FI; if (strncmp(if_desc, "openthread", strnlen(if_desc, 10)) == 0) return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_THREAD; if (strncmp(if_desc, "eth", strnlen(if_desc, 3)) == 0) return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_ETHERNET; return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_UNSPECIFIED; } #if CHIP_DEVICE_CONFIG_ENABLE_WIFI uint8_t MapAuthModeToSecurityType(wifi_auth_mode_t authmode) { switch (authmode) { case WIFI_AUTH_OPEN: return 1; case WIFI_AUTH_WEP: return 2; case WIFI_AUTH_WPA_PSK: return 3; case WIFI_AUTH_WPA2_PSK: return 4; case WIFI_AUTH_WPA3_PSK: return 5; default: return 0; } } uint8_t GetWiFiVersionFromAPRecord(wifi_ap_record_t ap_info) { if (ap_info.phy_11n) return 3; else if (ap_info.phy_11g) return 2; else if (ap_info.phy_11b) return 1; else return 0; } #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI } // namespace namespace chip { namespace DeviceLayer { DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() { static DiagnosticDataProviderImpl sInstance; return sInstance; } CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) { currentHeapFree = esp_get_free_heap_size(); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) { currentHeapUsed = heap_caps_get_total_size(MALLOC_CAP_DEFAULT) - esp_get_free_heap_size(); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) { currentHeapHighWatermark = heap_caps_get_total_size(MALLOC_CAP_DEFAULT) - esp_get_minimum_free_heap_size(); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetRebootCount(uint16_t & rebootCount) { uint32_t count = 0; CHIP_ERROR err = ConfigurationMgr().GetRebootCount(count); if (err == CHIP_NO_ERROR) { VerifyOrReturnError(count <= UINT16_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); rebootCount = static_cast<uint16_t>(count); } return err; } CHIP_ERROR DiagnosticDataProviderImpl::GetUpTime(uint64_t & upTime) { System::Clock::Timestamp currentTime = System::SystemClock().GetMonotonicTimestamp(); System::Clock::Timestamp startTime = PlatformMgrImpl().GetStartTime(); if (currentTime >= startTime) { upTime = std::chrono::duration_cast<System::Clock::Seconds64>(currentTime - startTime).count(); return CHIP_NO_ERROR; } return CHIP_ERROR_INVALID_TIME; } CHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) { uint64_t upTime = 0; if (GetUpTime(upTime) == CHIP_NO_ERROR) { uint32_t totalHours = 0; if (ConfigurationMgr().GetTotalOperationalHours(totalHours) == CHIP_NO_ERROR) { VerifyOrReturnError(upTime / 3600 <= UINT32_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); totalOperationalHours = totalHours + static_cast<uint32_t>(upTime / 3600); return CHIP_NO_ERROR; } } return CHIP_ERROR_INVALID_TIME; } CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason) { bootReason = BootReasonType::kUnspecified; uint8_t reason; reason = static_cast<uint8_t>(esp_reset_reason()); if (reason == ESP_RST_UNKNOWN) { bootReason = BootReasonType::kUnspecified; } else if (reason == ESP_RST_POWERON) { bootReason = BootReasonType::kPowerOnReboot; } else if (reason == ESP_RST_BROWNOUT) { bootReason = BootReasonType::kBrownOutReset; } else if (reason == ESP_RST_SW) { bootReason = BootReasonType::kSoftwareReset; } else if (reason == ESP_RST_INT_WDT) { bootReason = BootReasonType::kSoftwareWatchdogReset; /* Reboot can be due to hardware or software watchdog*/ } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** netifpp) { esp_netif_t * netif = esp_netif_next(NULL); NetworkInterface * head = NULL; uint8_t ipv6_addr_count = 0; esp_ip6_addr_t ip6_addr[kMaxIPv6AddrCount]; if (netif == NULL) { ChipLogError(DeviceLayer, "Failed to get network interfaces"); } else { for (esp_netif_t * ifa = netif; ifa != NULL; ifa = esp_netif_next(ifa)) { NetworkInterface * ifp = new NetworkInterface(); esp_netif_ip_info_t ipv4_info; strncpy(ifp->Name, esp_netif_get_ifkey(ifa), Inet::InterfaceId::kMaxIfNameLength); ifp->Name[Inet::InterfaceId::kMaxIfNameLength - 1] = '\0'; ifp->name = CharSpan::fromCharString(ifp->Name); ifp->isOperational = true; ifp->type = GetInterfaceType(esp_netif_get_desc(ifa)); ifp->offPremiseServicesReachableIPv4.SetNull(); ifp->offPremiseServicesReachableIPv6.SetNull(); if (esp_netif_get_mac(ifa, ifp->MacAddress) != ESP_OK) { ChipLogError(DeviceLayer, "Failed to get network hardware address"); } else { ifp->hardwareAddress = ByteSpan(ifp->MacAddress, 6); } if (esp_netif_get_ip_info(ifa, &ipv4_info) == ESP_OK) { memcpy(ifp->Ipv4AddressesBuffer[0], &(ipv4_info.ip.addr), kMaxIPv4AddrSize); ifp->Ipv4AddressSpans[0] = ByteSpan(ifp->Ipv4AddressesBuffer[0], kMaxIPv4AddrSize); ifp->IPv4Addresses = chip::app::DataModel::List<chip::ByteSpan>(ifp->Ipv4AddressSpans, 1); } ipv6_addr_count = esp_netif_get_all_ip6(ifa, ip6_addr); for (uint8_t idx = 0; idx < ipv6_addr_count; ++idx) { memcpy(ifp->Ipv6AddressesBuffer[idx], ip6_addr[idx].addr, kMaxIPv6AddrSize); ifp->Ipv6AddressSpans[idx] = ByteSpan(ifp->Ipv6AddressesBuffer[idx], kMaxIPv6AddrSize); } ifp->IPv6Addresses = chip::app::DataModel::List<chip::ByteSpan>(ifp->Ipv6AddressSpans, ipv6_addr_count); ifp->Next = head; head = ifp; } } *netifpp = head; return CHIP_NO_ERROR; } void DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * netifp) { while (netifp) { NetworkInterface * del = netifp; netifp = netifp->Next; delete del; } } #if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(ByteSpan & BssId) { wifi_ap_record_t ap_info; esp_err_t err; static uint8_t macAddress[kMaxHardwareAddrSize]; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { memcpy(macAddress, ap_info.bssid, 6); } BssId = ByteSpan(macAddress, 6); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(uint8_t & securityType) { securityType = 0; wifi_ap_record_t ap_info; esp_err_t err; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { securityType = MapAuthModeToSecurityType(ap_info.authmode); } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion) { wifiVersion = 0; wifi_ap_record_t ap_info; esp_err_t err; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { wifiVersion = GetWiFiVersionFromAPRecord(ap_info); } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) { channelNumber = 0; wifi_ap_record_t ap_info; esp_err_t err; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { channelNumber = ap_info.primary; } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) { rssi = 0; wifi_ap_record_t ap_info; esp_err_t err; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { rssi = ap_info.rssi; } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastRxCount(uint32_t & packetMulticastRxCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastTxCount(uint32_t & packetMulticastTxCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastRxCount(uint32_t & packetUnicastRxCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiOverrunCount(uint64_t & overrunCount) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts() { return CHIP_NO_ERROR; } #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI DiagnosticDataProvider & GetDiagnosticDataProviderImpl() { return DiagnosticDataProviderImpl::GetDefaultInstance(); } } // namespace DeviceLayer } // namespace chip <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2007 Trolltech ASA. All rights reserved. This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "videowidget.h" #include <QtCore/QEvent> #include <QtGui/QResizeEvent> #include <QtGui/QPalette> #include <QtGui/QImage> #include <QtGui/QPainter> #include <QtGui/QBoxLayout> #include <QApplication> #include <gst/gst.h> #include <gst/interfaces/propertyprobe.h> #include "mediaobject.h" #include "message.h" #include "common.h" #include "glrenderer.h" #include "widgetrenderer.h" #include "x11renderer.h" QT_BEGIN_NAMESPACE namespace Phonon { namespace Gstreamer { VideoWidget::VideoWidget(Backend *backend, QWidget *parent) : QWidget(parent), MediaNode(backend, VideoSink), m_videoBin(0), m_renderer(0), m_aspectRatio(Phonon::VideoWidget::AspectRatioAuto), m_brightness(0.0), m_hue(0.0), m_contrast(0.0), m_saturation(0.0), m_videoBalance(0), m_colorspace(0), m_videoplug(0) { setupVideoBin(); } VideoWidget::~VideoWidget() { if (m_videoBin) { gst_element_set_state (m_videoBin, GST_STATE_NULL); gst_object_unref (m_videoBin); } if (m_renderer) delete m_renderer; } void VideoWidget::setupVideoBin() { m_renderer = m_backend->deviceManager()->createVideoRenderer(this); GstElement *videoSink = m_renderer->videoSink(); m_videoBin = gst_bin_new (NULL); Q_ASSERT(m_videoBin); gst_object_ref (GST_OBJECT (m_videoBin)); //Take ownership gst_object_sink (GST_OBJECT (m_videoBin)); //The videoplug element is the final element before the pluggable videosink m_videoplug = gst_element_factory_make ("identity", NULL); //Colorspace ensures that the output of the stream matches the input format accepted by our video sink m_colorspace = gst_element_factory_make ("ffmpegcolorspace", NULL); //Video scale is used to prepare the correct aspect ratio and scale. GstElement *videoScale = gst_element_factory_make ("videoscale", NULL); //We need a queue to support the tee from parent node GstElement *queue = gst_element_factory_make ("queue", NULL); if (queue && m_videoBin && videoScale && m_colorspace && videoSink && m_videoplug) { //Ensure that the bare essentials are prepared gst_bin_add_many (GST_BIN (m_videoBin), queue, m_colorspace, m_videoplug, videoScale, videoSink, NULL); bool success = false; //Video balance controls color/sat/hue in the YUV colorspace m_videoBalance = gst_element_factory_make ("videobalance", NULL); if (m_videoBalance) { // For video balance to work we have to first ensure that the video is in YUV colorspace, // then hand it off to the videobalance filter before finally converting it back to RGB. // Hence we nede a videoFilter to convert the colorspace before and after videobalance GstElement *m_colorspace2 = gst_element_factory_make ("ffmpegcolorspace", NULL); gst_bin_add_many(GST_BIN(m_videoBin), m_videoBalance, m_colorspace2, NULL); success = gst_element_link_many(queue, m_colorspace, m_videoBalance, m_colorspace2, videoScale, m_videoplug, videoSink, NULL); } else { //If video balance is not available, just connect to sink directly success = gst_element_link_many(queue, m_colorspace, videoScale, m_videoplug, videoSink, NULL); } if (success) { GstPad *videopad = gst_element_get_pad (queue, "sink"); gst_element_add_pad (m_videoBin, gst_ghost_pad_new ("sink", videopad)); gst_object_unref (videopad); QWidget *parentWidget = qobject_cast<QWidget*>(parent()); if (parentWidget) parentWidget->winId(); // Due to some existing issues with alien in 4.4, // we must currently force the creation of a parent widget. m_isValid = true; //initialization ok, accept input } } } void VideoWidget::paintEvent(QPaintEvent *event) { Q_ASSERT(m_renderer); m_renderer->handlePaint(event); } void VideoWidget::setVisible(bool val) { Q_ASSERT(m_renderer); // Disable overlays for graphics view if (root() && window() && window()->testAttribute(Qt::WA_DontShowOnScreen) && !m_renderer->paintsOnWidget()) { m_backend->logMessage(QString("Widget rendering forced"), Backend::Info, this); GstElement *videoSink = m_renderer->videoSink(); Q_ASSERT(videoSink); gst_element_set_state (videoSink, GST_STATE_NULL); gst_bin_remove(GST_BIN(m_videoBin), videoSink); delete m_renderer; m_renderer = 0; // Use widgetRenderer as a fallback m_renderer = new WidgetRenderer(this); videoSink = m_renderer->videoSink(); gst_bin_add(GST_BIN(m_videoBin), videoSink); gst_element_link(m_videoplug, videoSink); gst_element_set_state (videoSink, GST_STATE_PAUSED); // Request return to current state root()->invalidateGraph(); root()->setState(root()->state()); } QWidget::setVisible(val); } bool VideoWidget::event(QEvent *event) { if (m_renderer && m_renderer->eventFilter(event)) return true; return QWidget::event(event); } Phonon::VideoWidget::AspectRatio VideoWidget::aspectRatio() const { return m_aspectRatio; } QSize VideoWidget::sizeHint() const { if (!m_movieSize.isEmpty()) return m_movieSize; else return QSize(640, 480); } void VideoWidget::setAspectRatio(Phonon::VideoWidget::AspectRatio aspectRatio) { m_aspectRatio = aspectRatio; if (m_renderer) m_renderer->aspectRatioChanged(aspectRatio); } Phonon::VideoWidget::ScaleMode VideoWidget::scaleMode() const { return m_scaleMode; } QRect VideoWidget::scaleToAspect(QRect srcRect, int w, int h) const { float width = srcRect.width(); float height = srcRect.width() * (float(h) / float(w)); if (height > srcRect.height()) { height = srcRect.height(); width = srcRect.height() * (float(w) / float(h)); } return QRect(0, 0, (int)width, (int)height); } /*** * Calculates the actual rectangle the movie will be presented with * * ### This function does currently asume a 1:1 pixel aspect **/ QRect VideoWidget::calculateDrawFrameRect() const { QRect widgetRect = rect(); QRect drawFrameRect; // Set m_drawFrameRect to be the size of the smallest possible // rect conforming to the aspect and containing the whole frame: switch (aspectRatio()) { case Phonon::VideoWidget::AspectRatioWidget: drawFrameRect = widgetRect; // No more calculations needed. return drawFrameRect; case Phonon::VideoWidget::AspectRatio4_3: drawFrameRect = scaleToAspect(widgetRect, 4, 3); break; case Phonon::VideoWidget::AspectRatio16_9: drawFrameRect = scaleToAspect(widgetRect, 16, 9); break; case Phonon::VideoWidget::AspectRatioAuto: default: drawFrameRect = QRect(0, 0, movieSize().width(), movieSize().height()); break; } // Scale m_drawFrameRect to fill the widget // without breaking aspect: float widgetWidth = widgetRect.width(); float widgetHeight = widgetRect.height(); float frameWidth = widgetWidth; float frameHeight = drawFrameRect.height() * float(widgetWidth) / float(drawFrameRect.width()); switch (scaleMode()) { case Phonon::VideoWidget::ScaleAndCrop: if (frameHeight < widgetHeight) { frameWidth *= float(widgetHeight) / float(frameHeight); frameHeight = widgetHeight; } break; case Phonon::VideoWidget::FitInView: default: if (frameHeight > widgetHeight) { frameWidth *= float(widgetHeight) / float(frameHeight); frameHeight = widgetHeight; } break; } drawFrameRect.setSize(QSize(int(frameWidth), int(frameHeight))); drawFrameRect.moveTo(int((widgetWidth - frameWidth) / 2.0f), int((widgetHeight - frameHeight) / 2.0f)); return drawFrameRect; } void VideoWidget::setScaleMode(Phonon::VideoWidget::ScaleMode scaleMode) { m_scaleMode = scaleMode; if (m_renderer) m_renderer->scaleModeChanged(scaleMode); } qreal VideoWidget::brightness() const { return m_brightness; } qreal clampedValue(qreal val) { if (val > 1.0 ) return 1.0; else if (val < -1.0) return -1.0; else return val; } void VideoWidget::setBrightness(qreal newValue) { newValue = clampedValue(newValue); if (newValue == m_brightness) return; m_brightness = newValue; if (m_videoBalance) g_object_set(G_OBJECT(m_videoBalance), "brightness", newValue, NULL); //gstreamer range is [-1, 1] } qreal VideoWidget::contrast() const { return m_contrast; } void VideoWidget::setContrast(qreal newValue) { newValue = clampedValue(newValue); if (newValue == m_contrast) return; m_contrast = newValue; if (m_videoBalance) g_object_set(G_OBJECT(m_videoBalance), "contrast", (newValue + 1.0), NULL); //gstreamer range is [0-2] } qreal VideoWidget::hue() const { return m_hue; } void VideoWidget::setHue(qreal newValue) { if (newValue == m_hue) return; newValue = clampedValue(newValue); m_hue = newValue; if (m_videoBalance) g_object_set(G_OBJECT(m_videoBalance), "hue", newValue, NULL); //gstreamer range is [-1, 1] } qreal VideoWidget::saturation() const { return m_saturation; } void VideoWidget::setSaturation(qreal newValue) { newValue = clampedValue(newValue); if (newValue == m_saturation) return; m_saturation = newValue; if (m_videoBalance) g_object_set(G_OBJECT(m_videoBalance), "saturation", newValue + 1.0, NULL); //gstreamer range is [0, 2] } void VideoWidget::setMovieSize(const QSize &size) { m_backend->logMessage(QString("New video size %0 x %1").arg(size.width()).arg(size.height()), Backend::Info); if (size == m_movieSize) return; m_movieSize = size; widget()->updateGeometry(); widget()->update(); } void VideoWidget::mediaNodeEvent(const MediaNodeEvent *event) { switch (event->type()) { case MediaNodeEvent::VideoSizeChanged: { const QSize *size = static_cast<const QSize*>(event->data()); setMovieSize(*size); } break; default: break; } // Forward events to renderer if (m_renderer) m_renderer->handleMediaNodeEvent(event); } } } //namespace Phonon::Gstreamer QT_END_NAMESPACE #include "moc_videowidget.cpp" <commit_msg>silence a valgrind warning - this initialization is not really necessary, though<commit_after>/* This file is part of the KDE project. Copyright (C) 2007 Trolltech ASA. All rights reserved. This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "videowidget.h" #include <QtCore/QEvent> #include <QtGui/QResizeEvent> #include <QtGui/QPalette> #include <QtGui/QImage> #include <QtGui/QPainter> #include <QtGui/QBoxLayout> #include <QApplication> #include <gst/gst.h> #include <gst/interfaces/propertyprobe.h> #include "mediaobject.h" #include "message.h" #include "common.h" #include "glrenderer.h" #include "widgetrenderer.h" #include "x11renderer.h" QT_BEGIN_NAMESPACE namespace Phonon { namespace Gstreamer { VideoWidget::VideoWidget(Backend *backend, QWidget *parent) : QWidget(parent), MediaNode(backend, VideoSink), m_videoBin(0), m_renderer(0), m_aspectRatio(Phonon::VideoWidget::AspectRatioAuto), m_brightness(0.0), m_hue(0.0), m_contrast(0.0), m_saturation(0.0), m_scaleMode(Phonon::VideoWidget::FitInView), m_videoBalance(0), m_colorspace(0), m_videoplug(0) { setupVideoBin(); } VideoWidget::~VideoWidget() { if (m_videoBin) { gst_element_set_state (m_videoBin, GST_STATE_NULL); gst_object_unref (m_videoBin); } if (m_renderer) delete m_renderer; } void VideoWidget::setupVideoBin() { m_renderer = m_backend->deviceManager()->createVideoRenderer(this); GstElement *videoSink = m_renderer->videoSink(); m_videoBin = gst_bin_new (NULL); Q_ASSERT(m_videoBin); gst_object_ref (GST_OBJECT (m_videoBin)); //Take ownership gst_object_sink (GST_OBJECT (m_videoBin)); //The videoplug element is the final element before the pluggable videosink m_videoplug = gst_element_factory_make ("identity", NULL); //Colorspace ensures that the output of the stream matches the input format accepted by our video sink m_colorspace = gst_element_factory_make ("ffmpegcolorspace", NULL); //Video scale is used to prepare the correct aspect ratio and scale. GstElement *videoScale = gst_element_factory_make ("videoscale", NULL); //We need a queue to support the tee from parent node GstElement *queue = gst_element_factory_make ("queue", NULL); if (queue && m_videoBin && videoScale && m_colorspace && videoSink && m_videoplug) { //Ensure that the bare essentials are prepared gst_bin_add_many (GST_BIN (m_videoBin), queue, m_colorspace, m_videoplug, videoScale, videoSink, NULL); bool success = false; //Video balance controls color/sat/hue in the YUV colorspace m_videoBalance = gst_element_factory_make ("videobalance", NULL); if (m_videoBalance) { // For video balance to work we have to first ensure that the video is in YUV colorspace, // then hand it off to the videobalance filter before finally converting it back to RGB. // Hence we nede a videoFilter to convert the colorspace before and after videobalance GstElement *m_colorspace2 = gst_element_factory_make ("ffmpegcolorspace", NULL); gst_bin_add_many(GST_BIN(m_videoBin), m_videoBalance, m_colorspace2, NULL); success = gst_element_link_many(queue, m_colorspace, m_videoBalance, m_colorspace2, videoScale, m_videoplug, videoSink, NULL); } else { //If video balance is not available, just connect to sink directly success = gst_element_link_many(queue, m_colorspace, videoScale, m_videoplug, videoSink, NULL); } if (success) { GstPad *videopad = gst_element_get_pad (queue, "sink"); gst_element_add_pad (m_videoBin, gst_ghost_pad_new ("sink", videopad)); gst_object_unref (videopad); QWidget *parentWidget = qobject_cast<QWidget*>(parent()); if (parentWidget) parentWidget->winId(); // Due to some existing issues with alien in 4.4, // we must currently force the creation of a parent widget. m_isValid = true; //initialization ok, accept input } } } void VideoWidget::paintEvent(QPaintEvent *event) { Q_ASSERT(m_renderer); m_renderer->handlePaint(event); } void VideoWidget::setVisible(bool val) { Q_ASSERT(m_renderer); // Disable overlays for graphics view if (root() && window() && window()->testAttribute(Qt::WA_DontShowOnScreen) && !m_renderer->paintsOnWidget()) { m_backend->logMessage(QString("Widget rendering forced"), Backend::Info, this); GstElement *videoSink = m_renderer->videoSink(); Q_ASSERT(videoSink); gst_element_set_state (videoSink, GST_STATE_NULL); gst_bin_remove(GST_BIN(m_videoBin), videoSink); delete m_renderer; m_renderer = 0; // Use widgetRenderer as a fallback m_renderer = new WidgetRenderer(this); videoSink = m_renderer->videoSink(); gst_bin_add(GST_BIN(m_videoBin), videoSink); gst_element_link(m_videoplug, videoSink); gst_element_set_state (videoSink, GST_STATE_PAUSED); // Request return to current state root()->invalidateGraph(); root()->setState(root()->state()); } QWidget::setVisible(val); } bool VideoWidget::event(QEvent *event) { if (m_renderer && m_renderer->eventFilter(event)) return true; return QWidget::event(event); } Phonon::VideoWidget::AspectRatio VideoWidget::aspectRatio() const { return m_aspectRatio; } QSize VideoWidget::sizeHint() const { if (!m_movieSize.isEmpty()) return m_movieSize; else return QSize(640, 480); } void VideoWidget::setAspectRatio(Phonon::VideoWidget::AspectRatio aspectRatio) { m_aspectRatio = aspectRatio; if (m_renderer) m_renderer->aspectRatioChanged(aspectRatio); } Phonon::VideoWidget::ScaleMode VideoWidget::scaleMode() const { return m_scaleMode; } QRect VideoWidget::scaleToAspect(QRect srcRect, int w, int h) const { float width = srcRect.width(); float height = srcRect.width() * (float(h) / float(w)); if (height > srcRect.height()) { height = srcRect.height(); width = srcRect.height() * (float(w) / float(h)); } return QRect(0, 0, (int)width, (int)height); } /*** * Calculates the actual rectangle the movie will be presented with * * ### This function does currently asume a 1:1 pixel aspect **/ QRect VideoWidget::calculateDrawFrameRect() const { QRect widgetRect = rect(); QRect drawFrameRect; // Set m_drawFrameRect to be the size of the smallest possible // rect conforming to the aspect and containing the whole frame: switch (aspectRatio()) { case Phonon::VideoWidget::AspectRatioWidget: drawFrameRect = widgetRect; // No more calculations needed. return drawFrameRect; case Phonon::VideoWidget::AspectRatio4_3: drawFrameRect = scaleToAspect(widgetRect, 4, 3); break; case Phonon::VideoWidget::AspectRatio16_9: drawFrameRect = scaleToAspect(widgetRect, 16, 9); break; case Phonon::VideoWidget::AspectRatioAuto: default: drawFrameRect = QRect(0, 0, movieSize().width(), movieSize().height()); break; } // Scale m_drawFrameRect to fill the widget // without breaking aspect: float widgetWidth = widgetRect.width(); float widgetHeight = widgetRect.height(); float frameWidth = widgetWidth; float frameHeight = drawFrameRect.height() * float(widgetWidth) / float(drawFrameRect.width()); switch (scaleMode()) { case Phonon::VideoWidget::ScaleAndCrop: if (frameHeight < widgetHeight) { frameWidth *= float(widgetHeight) / float(frameHeight); frameHeight = widgetHeight; } break; case Phonon::VideoWidget::FitInView: default: if (frameHeight > widgetHeight) { frameWidth *= float(widgetHeight) / float(frameHeight); frameHeight = widgetHeight; } break; } drawFrameRect.setSize(QSize(int(frameWidth), int(frameHeight))); drawFrameRect.moveTo(int((widgetWidth - frameWidth) / 2.0f), int((widgetHeight - frameHeight) / 2.0f)); return drawFrameRect; } void VideoWidget::setScaleMode(Phonon::VideoWidget::ScaleMode scaleMode) { m_scaleMode = scaleMode; if (m_renderer) m_renderer->scaleModeChanged(scaleMode); } qreal VideoWidget::brightness() const { return m_brightness; } qreal clampedValue(qreal val) { if (val > 1.0 ) return 1.0; else if (val < -1.0) return -1.0; else return val; } void VideoWidget::setBrightness(qreal newValue) { newValue = clampedValue(newValue); if (newValue == m_brightness) return; m_brightness = newValue; if (m_videoBalance) g_object_set(G_OBJECT(m_videoBalance), "brightness", newValue, NULL); //gstreamer range is [-1, 1] } qreal VideoWidget::contrast() const { return m_contrast; } void VideoWidget::setContrast(qreal newValue) { newValue = clampedValue(newValue); if (newValue == m_contrast) return; m_contrast = newValue; if (m_videoBalance) g_object_set(G_OBJECT(m_videoBalance), "contrast", (newValue + 1.0), NULL); //gstreamer range is [0-2] } qreal VideoWidget::hue() const { return m_hue; } void VideoWidget::setHue(qreal newValue) { if (newValue == m_hue) return; newValue = clampedValue(newValue); m_hue = newValue; if (m_videoBalance) g_object_set(G_OBJECT(m_videoBalance), "hue", newValue, NULL); //gstreamer range is [-1, 1] } qreal VideoWidget::saturation() const { return m_saturation; } void VideoWidget::setSaturation(qreal newValue) { newValue = clampedValue(newValue); if (newValue == m_saturation) return; m_saturation = newValue; if (m_videoBalance) g_object_set(G_OBJECT(m_videoBalance), "saturation", newValue + 1.0, NULL); //gstreamer range is [0, 2] } void VideoWidget::setMovieSize(const QSize &size) { m_backend->logMessage(QString("New video size %0 x %1").arg(size.width()).arg(size.height()), Backend::Info); if (size == m_movieSize) return; m_movieSize = size; widget()->updateGeometry(); widget()->update(); } void VideoWidget::mediaNodeEvent(const MediaNodeEvent *event) { switch (event->type()) { case MediaNodeEvent::VideoSizeChanged: { const QSize *size = static_cast<const QSize*>(event->data()); setMovieSize(*size); } break; default: break; } // Forward events to renderer if (m_renderer) m_renderer->handleMediaNodeEvent(event); } } } //namespace Phonon::Gstreamer QT_END_NAMESPACE #include "moc_videowidget.cpp" <|endoftext|>
<commit_before>/************************************************************************** ** ** Copyright (C) 2015 Denis Mingulov ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "classviewparsertreeitem.h" #include "classviewsymbollocation.h" #include "classviewsymbolinformation.h" #include "classviewconstants.h" #include "classviewutils.h" #include <QHash> #include <QPair> #include <QIcon> #include <QStandardItem> #include <QMutex> #include <QDebug> enum { debug = false }; namespace ClassView { namespace Internal { ///////////////////////////////// ParserTreeItemPrivate ////////////////////////////////// /*! \class ParserTreeItemPrivate \brief The ParserTreeItemPrivate class defines private class data for the ParserTreeItem class. \sa ParserTreeItem */ class ParserTreeItemPrivate { public: //! symbol locations QSet<SymbolLocation> symbolLocations; //! symbol information QHash<SymbolInformation, ParserTreeItem::Ptr> symbolInformations; //! An icon QIcon icon; }; ///////////////////////////////// ParserTreeItem ////////////////////////////////// /*! \class ParserTreeItem \brief The ParserTreeItem class is an item for the internal Class View tree. Not virtual - to speed up its work. */ ParserTreeItem::ParserTreeItem() : d(new ParserTreeItemPrivate()) { } ParserTreeItem::~ParserTreeItem() { delete d; } ParserTreeItem &ParserTreeItem::operator=(const ParserTreeItem &other) { d->symbolLocations = other.d->symbolLocations; d->icon = other.d->icon; d->symbolInformations.clear(); return *this; } /*! Copies a parser tree item from the location specified by \a from to this item. */ void ParserTreeItem::copy(const ParserTreeItem::ConstPtr &from) { if (from.isNull()) return; d->symbolLocations = from->d->symbolLocations; d->icon = from->d->icon; d->symbolInformations = from->d->symbolInformations; } /*! \fn void copyTree(const ParserTreeItem::ConstPtr &from) Copies a parser tree item with children from the location specified by \a from to this item. */ void ParserTreeItem::copyTree(const ParserTreeItem::ConstPtr &target) { if (target.isNull()) return; // copy content d->symbolLocations = target->d->symbolLocations; d->icon = target->d->icon; d->symbolInformations.clear(); // reserve memory // int amount = qMin(100 , target->d_ptr->symbolInformations.count() * 2); // d_ptr->symbolInformations.reserve(amount); // every child CitSymbolInformations cur = target->d->symbolInformations.constBegin(); CitSymbolInformations end = target->d->symbolInformations.constEnd(); for (; cur != end; ++cur) { ParserTreeItem::Ptr item(new ParserTreeItem()); item->copyTree(cur.value()); appendChild(item, cur.key()); } } /*! Adds information about symbol location from a \location. \sa SymbolLocation, removeSymbolLocation, symbolLocations */ void ParserTreeItem::addSymbolLocation(const SymbolLocation &location) { d->symbolLocations.insert(location); } /*! Adds information about symbol locations from \a locations. \sa SymbolLocation, removeSymbolLocation, symbolLocations */ void ParserTreeItem::addSymbolLocation(const QSet<SymbolLocation> &locations) { d->symbolLocations.unite(locations); } /*! Removes information about \a location. \sa SymbolLocation, addSymbolLocation, symbolLocations */ void ParserTreeItem::removeSymbolLocation(const SymbolLocation &location) { d->symbolLocations.remove(location); } /*! Removes information about \a locations. \sa SymbolLocation, addSymbolLocation, symbolLocations */ void ParserTreeItem::removeSymbolLocations(const QSet<SymbolLocation> &locations) { d->symbolLocations.subtract(locations); } /*! Gets information about symbol positions. \sa SymbolLocation, addSymbolLocation, removeSymbolLocation */ QSet<SymbolLocation> ParserTreeItem::symbolLocations() const { return d->symbolLocations; } /*! Appends the child item \a item to \a inf symbol information. */ void ParserTreeItem::appendChild(const ParserTreeItem::Ptr &item, const SymbolInformation &inf) { // removeChild must be used to remove an item if (item.isNull()) return; d->symbolInformations[inf] = item; } /*! Removes the \a inf symbol information. */ void ParserTreeItem::removeChild(const SymbolInformation &inf) { d->symbolInformations.remove(inf); } /*! Returns the child item specified by \a inf symbol information. */ ParserTreeItem::Ptr ParserTreeItem::child(const SymbolInformation &inf) const { return d->symbolInformations.value(inf); } /*! Returns the amount of children of the tree item. */ int ParserTreeItem::childCount() const { return d->symbolInformations.count(); } /*! \property QIcon::icon \brief the icon assigned to the tree item */ QIcon ParserTreeItem::icon() const { return d->icon; } /*! Sets the \a icon for the tree item. */ void ParserTreeItem::setIcon(const QIcon &icon) { d->icon = icon; } /*! Adds an internal state with \a target, which contains the correct current state. */ void ParserTreeItem::add(const ParserTreeItem::ConstPtr &target) { if (target.isNull()) return; // add locations d->symbolLocations = d->symbolLocations.unite(target->d->symbolLocations); // add children // every target child CitSymbolInformations cur = target->d->symbolInformations.constBegin(); CitSymbolInformations end = target->d->symbolInformations.constEnd(); while (cur != end) { const SymbolInformation &inf = cur.key(); const ParserTreeItem::Ptr &targetChild = cur.value(); ParserTreeItem::Ptr child = d->symbolInformations.value(inf); if (!child.isNull()) { child->add(targetChild); } else { ParserTreeItem::Ptr add(new ParserTreeItem()); add->copyTree(targetChild); d->symbolInformations[inf] = add; } // next item ++cur; } } /*! Appends this item to the QStandardIten item \a item. */ void ParserTreeItem::convertTo(QStandardItem *item) const { if (!item) return; QMap<SymbolInformation, ParserTreeItem::Ptr> map; // convert to map - to sort it CitSymbolInformations curHash = d->symbolInformations.constBegin(); CitSymbolInformations endHash = d->symbolInformations.constEnd(); while (curHash != endHash) { map.insert(curHash.key(), curHash.value()); ++curHash; } typedef QMap<SymbolInformation, ParserTreeItem::Ptr>::const_iterator MapCitSymbolInformations; // add to item MapCitSymbolInformations cur = map.constBegin(); MapCitSymbolInformations end = map.constEnd(); while (cur != end) { const SymbolInformation &inf = cur.key(); ParserTreeItem::Ptr ptr = cur.value(); QStandardItem *add = new QStandardItem(); Utils::setSymbolInformationToItem(inf, add); if (!ptr.isNull()) { // icon add->setIcon(ptr->icon()); // draggable if (!ptr->symbolLocations().isEmpty()) add->setFlags(add->flags() | Qt::ItemIsDragEnabled); // locations add->setData(Utils::locationsToRole(ptr->symbolLocations()), Constants::SymbolLocationsRole); } item->appendRow(add); ++cur; } } /*! Checks \a item in a QStandardItemModel for lazy data population. */ bool ParserTreeItem::canFetchMore(QStandardItem *item) const { if (!item) return false; int storedChildren = item->rowCount(); int internalChildren = d->symbolInformations.count(); if (storedChildren < internalChildren) return true; return false; } /*! Performs lazy data population for \a item in a QStandardItemModel if needed. */ void ParserTreeItem::fetchMore(QStandardItem *item) const { if (!item) return; convertTo(item); } /*! Debug dump. */ void ParserTreeItem::debugDump(int ident) const { CitSymbolInformations curHash = d->symbolInformations.constBegin(); CitSymbolInformations endHash = d->symbolInformations.constEnd(); while (curHash != endHash) { const SymbolInformation &inf = curHash.key(); qDebug() << QString(2*ident, QLatin1Char(' ')) << inf.iconType() << inf.name() << inf.type() << curHash.value().isNull(); if (!curHash.value().isNull()) curHash.value()->debugDump(ident + 1); ++curHash; } } } // namespace Internal } // namespace ClassView <commit_msg>ClassView: removed dead code<commit_after>/************************************************************************** ** ** Copyright (C) 2015 Denis Mingulov ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "classviewparsertreeitem.h" #include "classviewsymbollocation.h" #include "classviewsymbolinformation.h" #include "classviewconstants.h" #include "classviewutils.h" #include <QHash> #include <QPair> #include <QIcon> #include <QStandardItem> #include <QMutex> #include <QDebug> namespace ClassView { namespace Internal { ///////////////////////////////// ParserTreeItemPrivate ////////////////////////////////// /*! \class ParserTreeItemPrivate \brief The ParserTreeItemPrivate class defines private class data for the ParserTreeItem class. \sa ParserTreeItem */ class ParserTreeItemPrivate { public: //! symbol locations QSet<SymbolLocation> symbolLocations; //! symbol information QHash<SymbolInformation, ParserTreeItem::Ptr> symbolInformations; //! An icon QIcon icon; }; ///////////////////////////////// ParserTreeItem ////////////////////////////////// /*! \class ParserTreeItem \brief The ParserTreeItem class is an item for the internal Class View tree. Not virtual - to speed up its work. */ ParserTreeItem::ParserTreeItem() : d(new ParserTreeItemPrivate()) { } ParserTreeItem::~ParserTreeItem() { delete d; } ParserTreeItem &ParserTreeItem::operator=(const ParserTreeItem &other) { d->symbolLocations = other.d->symbolLocations; d->icon = other.d->icon; d->symbolInformations.clear(); return *this; } /*! Copies a parser tree item from the location specified by \a from to this item. */ void ParserTreeItem::copy(const ParserTreeItem::ConstPtr &from) { if (from.isNull()) return; d->symbolLocations = from->d->symbolLocations; d->icon = from->d->icon; d->symbolInformations = from->d->symbolInformations; } /*! \fn void copyTree(const ParserTreeItem::ConstPtr &from) Copies a parser tree item with children from the location specified by \a from to this item. */ void ParserTreeItem::copyTree(const ParserTreeItem::ConstPtr &target) { if (target.isNull()) return; // copy content d->symbolLocations = target->d->symbolLocations; d->icon = target->d->icon; d->symbolInformations.clear(); // reserve memory // int amount = qMin(100 , target->d_ptr->symbolInformations.count() * 2); // d_ptr->symbolInformations.reserve(amount); // every child CitSymbolInformations cur = target->d->symbolInformations.constBegin(); CitSymbolInformations end = target->d->symbolInformations.constEnd(); for (; cur != end; ++cur) { ParserTreeItem::Ptr item(new ParserTreeItem()); item->copyTree(cur.value()); appendChild(item, cur.key()); } } /*! Adds information about symbol location from a \location. \sa SymbolLocation, removeSymbolLocation, symbolLocations */ void ParserTreeItem::addSymbolLocation(const SymbolLocation &location) { d->symbolLocations.insert(location); } /*! Adds information about symbol locations from \a locations. \sa SymbolLocation, removeSymbolLocation, symbolLocations */ void ParserTreeItem::addSymbolLocation(const QSet<SymbolLocation> &locations) { d->symbolLocations.unite(locations); } /*! Removes information about \a location. \sa SymbolLocation, addSymbolLocation, symbolLocations */ void ParserTreeItem::removeSymbolLocation(const SymbolLocation &location) { d->symbolLocations.remove(location); } /*! Removes information about \a locations. \sa SymbolLocation, addSymbolLocation, symbolLocations */ void ParserTreeItem::removeSymbolLocations(const QSet<SymbolLocation> &locations) { d->symbolLocations.subtract(locations); } /*! Gets information about symbol positions. \sa SymbolLocation, addSymbolLocation, removeSymbolLocation */ QSet<SymbolLocation> ParserTreeItem::symbolLocations() const { return d->symbolLocations; } /*! Appends the child item \a item to \a inf symbol information. */ void ParserTreeItem::appendChild(const ParserTreeItem::Ptr &item, const SymbolInformation &inf) { // removeChild must be used to remove an item if (item.isNull()) return; d->symbolInformations[inf] = item; } /*! Removes the \a inf symbol information. */ void ParserTreeItem::removeChild(const SymbolInformation &inf) { d->symbolInformations.remove(inf); } /*! Returns the child item specified by \a inf symbol information. */ ParserTreeItem::Ptr ParserTreeItem::child(const SymbolInformation &inf) const { return d->symbolInformations.value(inf); } /*! Returns the amount of children of the tree item. */ int ParserTreeItem::childCount() const { return d->symbolInformations.count(); } /*! \property QIcon::icon \brief the icon assigned to the tree item */ QIcon ParserTreeItem::icon() const { return d->icon; } /*! Sets the \a icon for the tree item. */ void ParserTreeItem::setIcon(const QIcon &icon) { d->icon = icon; } /*! Adds an internal state with \a target, which contains the correct current state. */ void ParserTreeItem::add(const ParserTreeItem::ConstPtr &target) { if (target.isNull()) return; // add locations d->symbolLocations = d->symbolLocations.unite(target->d->symbolLocations); // add children // every target child CitSymbolInformations cur = target->d->symbolInformations.constBegin(); CitSymbolInformations end = target->d->symbolInformations.constEnd(); while (cur != end) { const SymbolInformation &inf = cur.key(); const ParserTreeItem::Ptr &targetChild = cur.value(); ParserTreeItem::Ptr child = d->symbolInformations.value(inf); if (!child.isNull()) { child->add(targetChild); } else { ParserTreeItem::Ptr add(new ParserTreeItem()); add->copyTree(targetChild); d->symbolInformations[inf] = add; } // next item ++cur; } } /*! Appends this item to the QStandardIten item \a item. */ void ParserTreeItem::convertTo(QStandardItem *item) const { if (!item) return; QMap<SymbolInformation, ParserTreeItem::Ptr> map; // convert to map - to sort it CitSymbolInformations curHash = d->symbolInformations.constBegin(); CitSymbolInformations endHash = d->symbolInformations.constEnd(); while (curHash != endHash) { map.insert(curHash.key(), curHash.value()); ++curHash; } typedef QMap<SymbolInformation, ParserTreeItem::Ptr>::const_iterator MapCitSymbolInformations; // add to item MapCitSymbolInformations cur = map.constBegin(); MapCitSymbolInformations end = map.constEnd(); while (cur != end) { const SymbolInformation &inf = cur.key(); ParserTreeItem::Ptr ptr = cur.value(); QStandardItem *add = new QStandardItem(); Utils::setSymbolInformationToItem(inf, add); if (!ptr.isNull()) { // icon add->setIcon(ptr->icon()); // draggable if (!ptr->symbolLocations().isEmpty()) add->setFlags(add->flags() | Qt::ItemIsDragEnabled); // locations add->setData(Utils::locationsToRole(ptr->symbolLocations()), Constants::SymbolLocationsRole); } item->appendRow(add); ++cur; } } /*! Checks \a item in a QStandardItemModel for lazy data population. */ bool ParserTreeItem::canFetchMore(QStandardItem *item) const { if (!item) return false; int storedChildren = item->rowCount(); int internalChildren = d->symbolInformations.count(); if (storedChildren < internalChildren) return true; return false; } /*! Performs lazy data population for \a item in a QStandardItemModel if needed. */ void ParserTreeItem::fetchMore(QStandardItem *item) const { if (!item) return; convertTo(item); } /*! Debug dump. */ void ParserTreeItem::debugDump(int ident) const { CitSymbolInformations curHash = d->symbolInformations.constBegin(); CitSymbolInformations endHash = d->symbolInformations.constEnd(); while (curHash != endHash) { const SymbolInformation &inf = curHash.key(); qDebug() << QString(2*ident, QLatin1Char(' ')) << inf.iconType() << inf.name() << inf.type() << curHash.value().isNull(); if (!curHash.value().isNull()) curHash.value()->debugDump(ident + 1); ++curHash; } } } // namespace Internal } // namespace ClassView <|endoftext|>
<commit_before>/* * Copyright (C) 2019 The Android Open Source Project * * 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 <stddef.h> #include <stdint.h> #include "perfetto/base/file_utils.h" #include "perfetto/base/temp_file.h" #include "src/profiling/memory/shared_ring_buffer.h" namespace perfetto { namespace profiling { namespace { struct MetadataHeader { alignas(uint64_t) std::atomic<bool> spinlock; uint64_t read_pos; uint64_t write_pos; }; size_t RoundToPow2(size_t v) { uint64_t x = static_cast<size_t>(v); if (x < 2) return 2; x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x |= x >> 32; x++; return static_cast<size_t>(x); } int FuzzRingBuffer(const uint8_t* data, size_t size) { if (size <= sizeof(MetadataHeader)) return 0; auto fd = base::TempFile::CreateUnlinked().ReleaseFD(); PERFETTO_CHECK(fd); // Put the remaining fuzzer input into the data portion of the ring buffer. size_t payload_size = size - sizeof(MetadataHeader); const uint8_t* payload = data + sizeof(MetadataHeader); size_t payload_size_pages = (payload_size + base::kPageSize - 1) / base::kPageSize; // Upsize test buffer to be 2^n data pages (precondition of the impl) + 1 page // for the metadata. size_t total_size_pages = 1 + RoundToPow2(payload_size_pages); PERFETTO_CHECK(ftruncate(*fd, total_size_pages * base::kPageSize) == 0); PERFETTO_CHECK(base::WriteAll(*fd, data, sizeof(MetadataHeader)) != -1); PERFETTO_CHECK(lseek(*fd, base::kPageSize, SEEK_SET) != -1); PERFETTO_CHECK(base::WriteAll(*fd, payload, payload_size) != -1); auto buf = SharedRingBuffer::Attach(std::move(fd)); PERFETTO_CHECK(!!buf); bool did_read; do { auto read_buf = buf->BeginRead(); did_read = bool(read_buf); if (did_read) { volatile uint8_t* v_data = read_buf.data; // Assert we get a reference to valid memory. for (size_t i = 0; i < read_buf.size; ++i) v_data[i] = v_data[i]; } buf->EndRead(std::move(read_buf)); } while (did_read); return 0; } } // namespace } // namespace profiling } // namespace perfetto extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { return perfetto::profiling::FuzzRingBuffer(data, size); } <commit_msg>Fix typo in fuzzer (functionally equivalent). am: 0e7d41f09a am: 6322f83417<commit_after>/* * Copyright (C) 2019 The Android Open Source Project * * 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 <stddef.h> #include <stdint.h> #include "perfetto/base/file_utils.h" #include "perfetto/base/temp_file.h" #include "src/profiling/memory/shared_ring_buffer.h" namespace perfetto { namespace profiling { namespace { struct MetadataHeader { alignas(uint64_t) std::atomic<bool> spinlock; uint64_t read_pos; uint64_t write_pos; }; size_t RoundToPow2(size_t v) { uint64_t x = static_cast<uint64_t>(v); if (x < 2) return 2; x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x |= x >> 32; x++; return static_cast<size_t>(x); } int FuzzRingBuffer(const uint8_t* data, size_t size) { if (size <= sizeof(MetadataHeader)) return 0; auto fd = base::TempFile::CreateUnlinked().ReleaseFD(); PERFETTO_CHECK(fd); // Put the remaining fuzzer input into the data portion of the ring buffer. size_t payload_size = size - sizeof(MetadataHeader); const uint8_t* payload = data + sizeof(MetadataHeader); size_t payload_size_pages = (payload_size + base::kPageSize - 1) / base::kPageSize; // Upsize test buffer to be 2^n data pages (precondition of the impl) + 1 page // for the metadata. size_t total_size_pages = 1 + RoundToPow2(payload_size_pages); PERFETTO_CHECK(ftruncate(*fd, total_size_pages * base::kPageSize) == 0); PERFETTO_CHECK(base::WriteAll(*fd, data, sizeof(MetadataHeader)) != -1); PERFETTO_CHECK(lseek(*fd, base::kPageSize, SEEK_SET) != -1); PERFETTO_CHECK(base::WriteAll(*fd, payload, payload_size) != -1); auto buf = SharedRingBuffer::Attach(std::move(fd)); PERFETTO_CHECK(!!buf); bool did_read; do { auto read_buf = buf->BeginRead(); did_read = bool(read_buf); if (did_read) { volatile uint8_t* v_data = read_buf.data; // Assert we get a reference to valid memory. for (size_t i = 0; i < read_buf.size; ++i) v_data[i] = v_data[i]; } buf->EndRead(std::move(read_buf)); } while (did_read); return 0; } } // namespace } // namespace profiling } // namespace perfetto extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { return perfetto::profiling::FuzzRingBuffer(data, size); } <|endoftext|>
<commit_before>#include <cstdlib> #include <cassert> #include "api-loader.h" #include "pointers.h" #include <string> #include <vector> #include <stdexcept> #ifdef USE_DETOURS #include "detours/detours.h" #endif #ifdef USE_MHOOK #include "mhook/mhook-lib/mhook.h" #endif #include "gl-wrappers.h" #include <DGLCommon/os.h> #ifndef _WIN32 #include <dlfcn.h> #endif //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation //use DIRECT_CALL(name) to call one of these pointers LoadedPointer g_DirectPointers[Entrypoints_NUM] = { #define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library}, #define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library) #include "codegen/functionList.inl" #undef FUNC_LIST_ELEM_SUPPORTED #undef FUNC_LIST_ELEM_NOT_SUPPORTED }; APILoader::APILoader():m_GlueLibrary(LIBRARY_NONE), m_LoadedApiLibraries(LIBRARY_NONE) {} void* APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) { #ifdef _WIN32 return GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp)); #else return dlsym(library, GetEntryPointName(entryp)); #endif } void* APILoader::loadExtPointer(Entrypoint entryp) { if (!g_DirectPointers[entryp].ptr) { if (!m_GlueLibrary) { throw std::runtime_error("Trying to call *GetProcAdress, but no glue library loaded"); } void * ptr = NULL; switch (m_GlueLibrary) { #ifdef _WIN32 case LIBRARY_WGL: ptr = DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)); break; #endif case LIBRARY_EGL: ptr = (void*)DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp)); break; default: assert(!"unknown glue library"); } g_DirectPointers[entryp].ptr = ptr; } return g_DirectPointers[entryp].ptr; } std::string APILoader::getLibraryName(ApiLibrary apiLibrary) { switch (apiLibrary) { case LIBRARY_EGL: #ifdef _WIN32 return "libEGL.dll"; #else return "libEGL.so.1"; #endif case LIBRARY_GL: case LIBRARY_WGL: #ifdef _WIN32 return "opengl32.dll"; #else return "libGL.so.1"; #endif case LIBRARY_ES2: case LIBRARY_ES3: #ifdef _WIN32 return "libGLESv2.dll"; #else return "libGLESv2.so.1"; #endif default: assert(!"unknown library"); throw std::runtime_error("Unknown GL library name"); } } void APILoader::loadLibrary(ApiLibrary apiLibrary) { std::string libraryName = getLibraryName(apiLibrary); if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) { std::vector<std::string> libSearchPath; LoadedLib openGLLibraryHandle = NULL; #ifdef _WIN32 char buffer[1000]; #ifndef _WIN64 if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) { //we are running 32bit app on 64 bit windows libSearchPath.push_back(buffer); } #endif if (!openGLLibraryHandle) { if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) { //we are running on native system (32 on 32 or 64 on 64) libSearchPath.push_back(buffer); } } #ifndef _WIN64 libSearchPath.push_back("C:\\Windows\\SysWOW64\\"); #endif libSearchPath.push_back("C:\\Windows\\System32\\"); libSearchPath.push_back("."); #endif libSearchPath.push_back(""); for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) { #ifdef _WIN32 openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str()); #else openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW); #endif } if (!openGLLibraryHandle) { std::string msg = std::string("Cannot load ") + libraryName + " system library"; Os::fatal(msg); } else { m_LoadedLibraries[libraryName] = openGLLibraryHandle; } } LoadedLib library = m_LoadedLibraries[libraryName]; //we use MS Detours only on win32, on x64 mHook is used #ifdef USE_DETOURS DetourRestoreAfterWith(); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); #endif //g_DirectPointers is now filled with opengl32.dll pointers // we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but //application will always call us. for (int i = 0; i < Entrypoints_NUM; i++) { if (!(g_DirectPointers[i].libraryMask & apiLibrary)) { //Do not load - entrypoint does not belong to currently loaded API continue; } if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) { //Do not load - entrypoint belongs to already loaded API continue; } g_DirectPointers[i].ptr = loadGLPointer(library, i); if (g_DirectPointers[i].ptr) { //this entrypoint was loaded from OpenGL32.dll, detour it! void * hookPtr = getWrapperPointer(i); #ifdef USE_DETOURS DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr); #endif #ifdef USE_MHOOK if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) { std::string error = "Cannot load OpenGL32.dll funcion "; error += GetEntryPointName(i); error += "()."; Os::fatal(error); } #endif } } #ifdef USE_DETOURS DetourTransactionCommit(); #endif if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL) m_GlueLibrary = apiLibrary; m_LoadedApiLibraries |= apiLibrary; } void* APILoader::ensurePointer(Entrypoint entryp) { if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) { return g_DirectPointers[entryp].ptr; } else { std::string error = "Operation aborted, because the "; error += GetEntryPointName(entryp); error += " function is not available on current context. Try updating GPU drivers."; throw std::runtime_error(error); } } APILoader g_ApiLoader; <commit_msg>Change order of paths in dll search: first search without path. This will definitely kill loading DGLWrapper.dll by changing name to opengl32.dll, but fixes problem when library is both in . and in %SYSTEM%.<commit_after>#include <cstdlib> #include <cassert> #include "api-loader.h" #include "pointers.h" #include <string> #include <vector> #include <stdexcept> #ifdef USE_DETOURS #include "detours/detours.h" #endif #ifdef USE_MHOOK #include "mhook/mhook-lib/mhook.h" #endif #include "gl-wrappers.h" #include <DGLCommon/os.h> #ifndef _WIN32 #include <dlfcn.h> #endif //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation //use DIRECT_CALL(name) to call one of these pointers LoadedPointer g_DirectPointers[Entrypoints_NUM] = { #define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library}, #define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library) #include "codegen/functionList.inl" #undef FUNC_LIST_ELEM_SUPPORTED #undef FUNC_LIST_ELEM_NOT_SUPPORTED }; APILoader::APILoader():m_GlueLibrary(LIBRARY_NONE), m_LoadedApiLibraries(LIBRARY_NONE) {} void* APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) { #ifdef _WIN32 return GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp)); #else return dlsym(library, GetEntryPointName(entryp)); #endif } void* APILoader::loadExtPointer(Entrypoint entryp) { if (!g_DirectPointers[entryp].ptr) { if (!m_GlueLibrary) { throw std::runtime_error("Trying to call *GetProcAdress, but no glue library loaded"); } void * ptr = NULL; switch (m_GlueLibrary) { #ifdef _WIN32 case LIBRARY_WGL: ptr = DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)); break; #endif case LIBRARY_EGL: ptr = (void*)DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp)); break; default: assert(!"unknown glue library"); } g_DirectPointers[entryp].ptr = ptr; } return g_DirectPointers[entryp].ptr; } std::string APILoader::getLibraryName(ApiLibrary apiLibrary) { switch (apiLibrary) { case LIBRARY_EGL: #ifdef _WIN32 return "libEGL.dll"; #else return "libEGL.so.1"; #endif case LIBRARY_GL: case LIBRARY_WGL: #ifdef _WIN32 return "opengl32.dll"; #else return "libGL.so.1"; #endif case LIBRARY_ES2: case LIBRARY_ES3: #ifdef _WIN32 return "libGLESv2.dll"; #else return "libGLESv2.so.1"; #endif default: assert(!"unknown library"); throw std::runtime_error("Unknown GL library name"); } } void APILoader::loadLibrary(ApiLibrary apiLibrary) { std::string libraryName = getLibraryName(apiLibrary); if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) { std::vector<std::string> libSearchPath; LoadedLib openGLLibraryHandle = NULL; libSearchPath.push_back(""); #ifdef _WIN32 char buffer[1000]; #ifndef _WIN64 if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) { //we are running 32bit app on 64 bit windows libSearchPath.push_back(buffer + std::string("\\")); } #endif if (!openGLLibraryHandle) { if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) { //we are running on native system (32 on 32 or 64 on 64) libSearchPath.push_back(buffer + std::string("\\")); } } #ifndef _WIN64 libSearchPath.push_back("C:\\Windows\\SysWOW64\\"); #endif libSearchPath.push_back("C:\\Windows\\System32\\"); libSearchPath.push_back("."); #endif for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) { #ifdef _WIN32 openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str()); #else openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW); #endif } if (!openGLLibraryHandle) { std::string msg = std::string("Cannot load ") + libraryName + " system library"; Os::fatal(msg); } else { m_LoadedLibraries[libraryName] = openGLLibraryHandle; } } LoadedLib library = m_LoadedLibraries[libraryName]; //we use MS Detours only on win32, on x64 mHook is used #ifdef USE_DETOURS DetourRestoreAfterWith(); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); #endif //g_DirectPointers is now filled with opengl32.dll pointers // we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but //application will always call us. for (int i = 0; i < Entrypoints_NUM; i++) { if (!(g_DirectPointers[i].libraryMask & apiLibrary)) { //Do not load - entrypoint does not belong to currently loaded API continue; } if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) { //Do not load - entrypoint belongs to already loaded API continue; } g_DirectPointers[i].ptr = loadGLPointer(library, i); if (g_DirectPointers[i].ptr) { //this entrypoint was loaded from OpenGL32.dll, detour it! void * hookPtr = getWrapperPointer(i); #ifdef USE_DETOURS DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr); #endif #ifdef USE_MHOOK if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) { std::string error = "Cannot load OpenGL32.dll funcion "; error += GetEntryPointName(i); error += "()."; Os::fatal(error); } #endif } } #ifdef USE_DETOURS DetourTransactionCommit(); #endif if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL) m_GlueLibrary = apiLibrary; m_LoadedApiLibraries |= apiLibrary; } void* APILoader::ensurePointer(Entrypoint entryp) { if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) { return g_DirectPointers[entryp].ptr; } else { std::string error = "Operation aborted, because the "; error += GetEntryPointName(entryp); error += " function is not available on current context. Try updating GPU drivers."; throw std::runtime_error(error); } } APILoader g_ApiLoader; <|endoftext|>
<commit_before>/* Copyright (c) 2009-2011 Sony Pictures Imageworks Inc., et al. 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 Sony Pictures Imageworks 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. */ #include <vector> #include <string> #include <cstdio> #include <cstdlib> #include <ctype.h> #include <boost/unordered_map.hpp> #include <boost/algorithm/string.hpp> #include <OpenImageIO/dassert.h> #include <OpenImageIO/pugixml.hpp> #include "oslexec_pvt.h" #ifdef OSL_NAMESPACE namespace OSL_NAMESPACE { #endif namespace OSL { namespace pvt { // OSL::pvt namespace pugi = OIIO_NAMESPACE::pugi; // Helper class to manage the dictionaries. // // Shaders are written as if they parse arbitrary things from whole // cloth on every call: from potentially loading XML from disk, parsing // it, doing queries, and converting the string data to other types. // // But that is expensive, so we really cache all this stuff at several // levels. // // We have parsed xml (as pugi::xml_document *'s) cached in a hash table, // looked up by the xml and/or dictionary name. Either will do, if it // looks like a filename, it will read the XML from the file, otherwise it // will interpret it as xml directly. // // Also, individual queries are cached in a hash table. The key is a // tuple of (nodeID, query_string, type_requested), so that asking for a // particular query to return a string is a totally different cache // entry than asking for it to be converted to a matrix, say. // class Dictionary { public: Dictionary (ShadingSystemImpl &ss) : m_shadingsys(ss) { // Create placeholder element 0 == 'not found' m_nodes.push_back (Node(0, pugi::xml_node())); } ~Dictionary () { // Free all the documents. for (size_t i = 0, e = m_documents.size(); i < e; ++i) delete m_documents[i]; } int dict_find (ustring dictionaryname, ustring query); int dict_find (int nodeID, ustring query); int dict_next (int nodeID); int dict_value (int nodeID, ustring attribname, TypeDesc type, void *data); private: // We cache individual queries with a key that is a tuple of the // (nodeID, query_string, type_requested). struct Query { int document; // which dictionary document int node; // root node for the search ustring name; // name for the the search TypeDesc type; // UNKNOWN signifies a node, versus an attribute value Query (int doc_, int node_, ustring name_, TypeDesc type_=TypeDesc::UNKNOWN) : document(doc_), node(node_), name(name_), type(type_) { } bool operator== (const Query &q) const { return document == q.document && node == q.node && name == q.name && type == q.type; } }; // Must define a hash operation to build the unordered_map. struct QueryHash { size_t operator() (const Query &key) const { return key.name.hash() + 17*key.node + 79*key.document; } }; // The cached query result is mostly just a 'valueoffset', which is // the index into floatdata/intdata/stringdata (depending on the type // being asked for) at which the decoded data live, or a node ID // if the query was for a node rather than for an attribute. struct QueryResult { int valueoffset; // Offset into one of the 'data' vectors, or nodeID bool is_valid; // true: query found QueryResult (bool valid=true) : valueoffset(0), is_valid(valid) { } QueryResult (bool isnode, int value) : valueoffset(value), is_valid(true) { } }; // Nodes we've looked up. Includes a 'next' index of the matching node // for the query that generated this one. struct Node { int document; // which document the node belongs to pugi::xml_node node; // which node within the dictionary int next; // next node for the same query Node (int d, const pugi::xml_node &n) : document(d), node(n), next(0) { } }; typedef boost::unordered_map <Query, QueryResult, QueryHash> QueryMap; typedef boost::unordered_map<ustring, int, ustringHash> DocMap; ShadingSystemImpl &m_shadingsys; // back-pointer to shading sys // List of XML documents we've read in. std::vector<pugi::xml_document *> m_documents; // Map xml strings and/or filename to indices in m_documents. DocMap m_document_map; // Cache of fully resolved queries. Dictionary::QueryMap m_cache; // query cache // List of all the nodes we've found by queries. std::vector<Dictionary::Node> m_nodes; // m_floatdata, m_intdata, and m_stringdata hold the decoded data // results (including type conversion) of cached queries. std::vector<float> m_floatdata; std::vector<int> m_intdata; std::vector<ustring> m_stringdata; // Helper function: return the document index given dictionary name. int get_document_index (ustring dictionaryname); }; int Dictionary::get_document_index (ustring dictionaryname) { DocMap::iterator dm = m_document_map.find(dictionaryname); int dindex; if (dm == m_document_map.end()) { dindex = m_documents.size(); m_document_map[dictionaryname] = dindex; pugi::xml_document *doc = new pugi::xml_document; m_documents.push_back (doc); pugi::xml_parse_result parse_result; if (boost::ends_with (dictionaryname.string(), ".xml")) { // xml file -- read it parse_result = doc->load_file (dictionaryname.c_str()); } else { // load xml directly from the string parse_result = doc->load_buffer (dictionaryname.c_str(), dictionaryname.length()); } if (! parse_result) { m_shadingsys.error ("XML parsed with errors: %s, at offset %d", parse_result.description(), parse_result.offset); return 0; } } else { dindex = dm->second; } DASSERT (dindex >= 0 && dindex < (int)m_documents.size()); return dindex; } int Dictionary::dict_find (ustring dictionaryname, ustring query) { int dindex = get_document_index (dictionaryname); ASSERT (dindex >= 0 && dindex < (int)m_documents.size()); Query q (dindex, 0, query); QueryMap::iterator qfound = m_cache.find (q); if (qfound != m_cache.end()) { return qfound->second.valueoffset; } pugi::xml_document *doc = m_documents[dindex]; // Query was not found. Do the expensive lookup and cache it pugi::xpath_node_set matches; try { matches = doc->select_nodes (query.c_str()); } catch (const pugi::xpath_exception& e) { m_shadingsys.error ("Invalid dict_find query '%s': %s", query.c_str(), e.what()); return 0; } if (matches.empty()) { m_cache[q] = QueryResult (false); // mark invalid return 0; // Not found } int firstmatch = (int) m_nodes.size(); int last = -1; for (int i = 0, e = (int)matches.size(); i < e; ++i) { m_nodes.push_back (Node (dindex, matches[i].node())); int nodeid = (int) m_nodes.size()-1; if (last < 0) { // If this is the first match, add a cache entry for it m_cache[q] = QueryResult (true /* it's a node */, nodeid); } else { // If this is a subsequent match, set the last match's 'next' m_nodes[last].next = nodeid; } last = nodeid; } return firstmatch; } int Dictionary::dict_find (int nodeID, ustring query) { if (nodeID <= 0 || nodeID >= (int)m_nodes.size()) return 0; // invalid node ID const Dictionary::Node &node (m_nodes[nodeID]); Query q (node.document, nodeID, query); QueryMap::iterator qfound = m_cache.find (q); if (qfound != m_cache.end()) { return qfound->second.valueoffset; } // Query was not found. Do the expensive lookup and cache it pugi::xpath_node_set matches; try { matches = node.node.select_nodes (query.c_str()); } catch (const pugi::xpath_exception& e) { m_shadingsys.error ("Invalid dict_find query '%s': %s", query.c_str(), e.what()); return 0; } if (matches.empty()) { m_cache[q] = QueryResult (false); // mark invalid return 0; // Not found } int firstmatch = (int) m_nodes.size(); int last = -1; for (int i = 0, e = (int)matches.size(); i < e; ++i) { m_nodes.push_back (Node (node.document, matches[i].node())); int nodeid = (int) m_nodes.size()-1; if (last < 0) { // If this is the first match, add a cache entry for it m_cache[q] = QueryResult (true /* it's a node */, nodeid); } else { // If this is a subsequent match, set the last match's 'next' m_nodes[last].next = nodeid; } last = nodeid; } return firstmatch; } int Dictionary::dict_next (int nodeID) { if (nodeID <= 0 || nodeID >= (int)m_nodes.size()) return 0; // invalid node ID return m_nodes[nodeID].next; } int Dictionary::dict_value (int nodeID, ustring attribname, TypeDesc type, void *data) { if (nodeID <= 0 || nodeID >= (int)m_nodes.size()) return 0; // invalid node ID const Dictionary::Node &node (m_nodes[nodeID]); Dictionary::Query q (node.document, nodeID, attribname, type); Dictionary::QueryMap::iterator qfound = m_cache.find (q); if (qfound != m_cache.end()) { // previously found int offset = qfound->second.valueoffset; int n = type.numelements() * type.aggregate; if (type.basetype == TypeDesc::STRING) { ASSERT (n == 1 && "no string arrays in XML"); ((ustring *)data)[0] = m_stringdata[offset]; } if (type.basetype == TypeDesc::INT) { for (int i = 0; i < n; ++i) ((int *)data)[i] = m_intdata[offset++]; return 1; } if (type.basetype == TypeDesc::FLOAT) { for (int i = 0; i < n; ++i) ((float *)data)[i] = m_floatdata[offset++]; return 1; } return 0; // Unknown type } // OK, the entry wasn't in the cache, we need to decode it and cache it. const char *val = NULL; if (attribname.empty()) { val = node.node.value(); } else { for (pugi::xml_attribute_iterator ait = node.node.attributes_begin(); ait != node.node.attributes_end(); ++ait) { if (ait->name() == attribname) { val = ait->value(); break; } } } if (val == NULL) return 0; // not found Dictionary::QueryResult r (false, 0); int n = type.numelements() * type.aggregate; if (type.basetype == TypeDesc::STRING && n == 1) { r.valueoffset = (int) m_stringdata.size(); ustring s (val); m_stringdata.push_back (s); ((ustring *)data)[0] = s; m_cache[q] = r; return 1; } if (type.basetype == TypeDesc::INT) { r.valueoffset = (int) m_intdata.size(); for (int i = 0; i < n; ++i) { int v = (int) strtol (val, (char **)&val, 10); while (isspace(*val) || *val == ',') ++val; m_intdata.push_back (v); ((int *)data)[i] = v; } m_cache[q] = r; return 1; } if (type.basetype == TypeDesc::FLOAT) { r.valueoffset = (int) m_floatdata.size(); for (int i = 0; i < n; ++i) { float v = (int) strtof (val, (char **)&val); while (isspace(*val) || *val == ',') ++val; m_floatdata.push_back (v); ((float *)data)[i] = v; } m_cache[q] = r; return 1; } // Anything that's left is an unsupported type return 0; } int ShadingContext::dict_find (ustring dictionaryname, ustring query) { if (! m_dictionary) { m_dictionary = new Dictionary (shadingsys()); } return m_dictionary->dict_find (dictionaryname, query); } int ShadingContext::dict_find (int nodeID, ustring query) { if (! m_dictionary) { m_dictionary = new Dictionary (shadingsys()); } return m_dictionary->dict_find (nodeID, query); } int ShadingContext::dict_next (int nodeID) { if (! m_dictionary) return 0; return m_dictionary->dict_next (nodeID); } int ShadingContext::dict_value (int nodeID, ustring attribname, TypeDesc type, void *data) { if (! m_dictionary) return 0; return m_dictionary->dict_value (nodeID, attribname, type, data); } void ShadingContext::free_dict_resources () { delete m_dictionary; } }; // namespace pvt }; // namespace OSL #ifdef OSL_NAMESPACE }; // end namespace OSL_NAMESPACE #endif <commit_msg>Fix XML buglet: not returning the 'success' error code when retrieving cached XML data of type string.<commit_after>/* Copyright (c) 2009-2011 Sony Pictures Imageworks Inc., et al. 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 Sony Pictures Imageworks 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. */ #include <vector> #include <string> #include <cstdio> #include <cstdlib> #include <ctype.h> #include <boost/unordered_map.hpp> #include <boost/algorithm/string.hpp> #include <OpenImageIO/dassert.h> #include <OpenImageIO/pugixml.hpp> #include "oslexec_pvt.h" #ifdef OSL_NAMESPACE namespace OSL_NAMESPACE { #endif namespace OSL { namespace pvt { // OSL::pvt namespace pugi = OIIO_NAMESPACE::pugi; // Helper class to manage the dictionaries. // // Shaders are written as if they parse arbitrary things from whole // cloth on every call: from potentially loading XML from disk, parsing // it, doing queries, and converting the string data to other types. // // But that is expensive, so we really cache all this stuff at several // levels. // // We have parsed xml (as pugi::xml_document *'s) cached in a hash table, // looked up by the xml and/or dictionary name. Either will do, if it // looks like a filename, it will read the XML from the file, otherwise it // will interpret it as xml directly. // // Also, individual queries are cached in a hash table. The key is a // tuple of (nodeID, query_string, type_requested), so that asking for a // particular query to return a string is a totally different cache // entry than asking for it to be converted to a matrix, say. // class Dictionary { public: Dictionary (ShadingSystemImpl &ss) : m_shadingsys(ss) { // Create placeholder element 0 == 'not found' m_nodes.push_back (Node(0, pugi::xml_node())); } ~Dictionary () { // Free all the documents. for (size_t i = 0, e = m_documents.size(); i < e; ++i) delete m_documents[i]; } int dict_find (ustring dictionaryname, ustring query); int dict_find (int nodeID, ustring query); int dict_next (int nodeID); int dict_value (int nodeID, ustring attribname, TypeDesc type, void *data); private: // We cache individual queries with a key that is a tuple of the // (nodeID, query_string, type_requested). struct Query { int document; // which dictionary document int node; // root node for the search ustring name; // name for the the search TypeDesc type; // UNKNOWN signifies a node, versus an attribute value Query (int doc_, int node_, ustring name_, TypeDesc type_=TypeDesc::UNKNOWN) : document(doc_), node(node_), name(name_), type(type_) { } bool operator== (const Query &q) const { return document == q.document && node == q.node && name == q.name && type == q.type; } }; // Must define a hash operation to build the unordered_map. struct QueryHash { size_t operator() (const Query &key) const { return key.name.hash() + 17*key.node + 79*key.document; } }; // The cached query result is mostly just a 'valueoffset', which is // the index into floatdata/intdata/stringdata (depending on the type // being asked for) at which the decoded data live, or a node ID // if the query was for a node rather than for an attribute. struct QueryResult { int valueoffset; // Offset into one of the 'data' vectors, or nodeID bool is_valid; // true: query found QueryResult (bool valid=true) : valueoffset(0), is_valid(valid) { } QueryResult (bool isnode, int value) : valueoffset(value), is_valid(true) { } }; // Nodes we've looked up. Includes a 'next' index of the matching node // for the query that generated this one. struct Node { int document; // which document the node belongs to pugi::xml_node node; // which node within the dictionary int next; // next node for the same query Node (int d, const pugi::xml_node &n) : document(d), node(n), next(0) { } }; typedef boost::unordered_map <Query, QueryResult, QueryHash> QueryMap; typedef boost::unordered_map<ustring, int, ustringHash> DocMap; ShadingSystemImpl &m_shadingsys; // back-pointer to shading sys // List of XML documents we've read in. std::vector<pugi::xml_document *> m_documents; // Map xml strings and/or filename to indices in m_documents. DocMap m_document_map; // Cache of fully resolved queries. Dictionary::QueryMap m_cache; // query cache // List of all the nodes we've found by queries. std::vector<Dictionary::Node> m_nodes; // m_floatdata, m_intdata, and m_stringdata hold the decoded data // results (including type conversion) of cached queries. std::vector<float> m_floatdata; std::vector<int> m_intdata; std::vector<ustring> m_stringdata; // Helper function: return the document index given dictionary name. int get_document_index (ustring dictionaryname); }; int Dictionary::get_document_index (ustring dictionaryname) { DocMap::iterator dm = m_document_map.find(dictionaryname); int dindex; if (dm == m_document_map.end()) { dindex = m_documents.size(); m_document_map[dictionaryname] = dindex; pugi::xml_document *doc = new pugi::xml_document; m_documents.push_back (doc); pugi::xml_parse_result parse_result; if (boost::ends_with (dictionaryname.string(), ".xml")) { // xml file -- read it parse_result = doc->load_file (dictionaryname.c_str()); } else { // load xml directly from the string parse_result = doc->load_buffer (dictionaryname.c_str(), dictionaryname.length()); } if (! parse_result) { m_shadingsys.error ("XML parsed with errors: %s, at offset %d", parse_result.description(), parse_result.offset); return 0; } } else { dindex = dm->second; } DASSERT (dindex >= 0 && dindex < (int)m_documents.size()); return dindex; } int Dictionary::dict_find (ustring dictionaryname, ustring query) { int dindex = get_document_index (dictionaryname); ASSERT (dindex >= 0 && dindex < (int)m_documents.size()); Query q (dindex, 0, query); QueryMap::iterator qfound = m_cache.find (q); if (qfound != m_cache.end()) { return qfound->second.valueoffset; } pugi::xml_document *doc = m_documents[dindex]; // Query was not found. Do the expensive lookup and cache it pugi::xpath_node_set matches; try { matches = doc->select_nodes (query.c_str()); } catch (const pugi::xpath_exception& e) { m_shadingsys.error ("Invalid dict_find query '%s': %s", query.c_str(), e.what()); return 0; } if (matches.empty()) { m_cache[q] = QueryResult (false); // mark invalid return 0; // Not found } int firstmatch = (int) m_nodes.size(); int last = -1; for (int i = 0, e = (int)matches.size(); i < e; ++i) { m_nodes.push_back (Node (dindex, matches[i].node())); int nodeid = (int) m_nodes.size()-1; if (last < 0) { // If this is the first match, add a cache entry for it m_cache[q] = QueryResult (true /* it's a node */, nodeid); } else { // If this is a subsequent match, set the last match's 'next' m_nodes[last].next = nodeid; } last = nodeid; } return firstmatch; } int Dictionary::dict_find (int nodeID, ustring query) { if (nodeID <= 0 || nodeID >= (int)m_nodes.size()) return 0; // invalid node ID const Dictionary::Node &node (m_nodes[nodeID]); Query q (node.document, nodeID, query); QueryMap::iterator qfound = m_cache.find (q); if (qfound != m_cache.end()) { return qfound->second.valueoffset; } // Query was not found. Do the expensive lookup and cache it pugi::xpath_node_set matches; try { matches = node.node.select_nodes (query.c_str()); } catch (const pugi::xpath_exception& e) { m_shadingsys.error ("Invalid dict_find query '%s': %s", query.c_str(), e.what()); return 0; } if (matches.empty()) { m_cache[q] = QueryResult (false); // mark invalid return 0; // Not found } int firstmatch = (int) m_nodes.size(); int last = -1; for (int i = 0, e = (int)matches.size(); i < e; ++i) { m_nodes.push_back (Node (node.document, matches[i].node())); int nodeid = (int) m_nodes.size()-1; if (last < 0) { // If this is the first match, add a cache entry for it m_cache[q] = QueryResult (true /* it's a node */, nodeid); } else { // If this is a subsequent match, set the last match's 'next' m_nodes[last].next = nodeid; } last = nodeid; } return firstmatch; } int Dictionary::dict_next (int nodeID) { if (nodeID <= 0 || nodeID >= (int)m_nodes.size()) return 0; // invalid node ID return m_nodes[nodeID].next; } int Dictionary::dict_value (int nodeID, ustring attribname, TypeDesc type, void *data) { if (nodeID <= 0 || nodeID >= (int)m_nodes.size()) return 0; // invalid node ID const Dictionary::Node &node (m_nodes[nodeID]); Dictionary::Query q (node.document, nodeID, attribname, type); Dictionary::QueryMap::iterator qfound = m_cache.find (q); if (qfound != m_cache.end()) { // previously found int offset = qfound->second.valueoffset; int n = type.numelements() * type.aggregate; if (type.basetype == TypeDesc::STRING) { ASSERT (n == 1 && "no string arrays in XML"); ((ustring *)data)[0] = m_stringdata[offset]; return 1; } if (type.basetype == TypeDesc::INT) { for (int i = 0; i < n; ++i) ((int *)data)[i] = m_intdata[offset++]; return 1; } if (type.basetype == TypeDesc::FLOAT) { for (int i = 0; i < n; ++i) ((float *)data)[i] = m_floatdata[offset++]; return 1; } return 0; // Unknown type } // OK, the entry wasn't in the cache, we need to decode it and cache it. const char *val = NULL; if (attribname.empty()) { val = node.node.value(); } else { for (pugi::xml_attribute_iterator ait = node.node.attributes_begin(); ait != node.node.attributes_end(); ++ait) { if (ait->name() == attribname) { val = ait->value(); break; } } } if (val == NULL) return 0; // not found Dictionary::QueryResult r (false, 0); int n = type.numelements() * type.aggregate; if (type.basetype == TypeDesc::STRING && n == 1) { r.valueoffset = (int) m_stringdata.size(); ustring s (val); m_stringdata.push_back (s); ((ustring *)data)[0] = s; m_cache[q] = r; return 1; } if (type.basetype == TypeDesc::INT) { r.valueoffset = (int) m_intdata.size(); for (int i = 0; i < n; ++i) { int v = (int) strtol (val, (char **)&val, 10); while (isspace(*val) || *val == ',') ++val; m_intdata.push_back (v); ((int *)data)[i] = v; } m_cache[q] = r; return 1; } if (type.basetype == TypeDesc::FLOAT) { r.valueoffset = (int) m_floatdata.size(); for (int i = 0; i < n; ++i) { float v = (int) strtof (val, (char **)&val); while (isspace(*val) || *val == ',') ++val; m_floatdata.push_back (v); ((float *)data)[i] = v; } m_cache[q] = r; return 1; } // Anything that's left is an unsupported type return 0; } int ShadingContext::dict_find (ustring dictionaryname, ustring query) { if (! m_dictionary) { m_dictionary = new Dictionary (shadingsys()); } return m_dictionary->dict_find (dictionaryname, query); } int ShadingContext::dict_find (int nodeID, ustring query) { if (! m_dictionary) { m_dictionary = new Dictionary (shadingsys()); } return m_dictionary->dict_find (nodeID, query); } int ShadingContext::dict_next (int nodeID) { if (! m_dictionary) return 0; return m_dictionary->dict_next (nodeID); } int ShadingContext::dict_value (int nodeID, ustring attribname, TypeDesc type, void *data) { if (! m_dictionary) return 0; return m_dictionary->dict_value (nodeID, attribname, type, data); } void ShadingContext::free_dict_resources () { delete m_dictionary; } }; // namespace pvt }; // namespace OSL #ifdef OSL_NAMESPACE }; // end namespace OSL_NAMESPACE #endif <|endoftext|>
<commit_before>#include <list> #include <sstream> #include <stdexcept> #include <string> #include <typeinfo> #include <dbxml/DbXml.hpp> #include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/IterImpl.hh> #include "DbCorpusReaderPrivate.hh" #include "util/url.hh" namespace db = DbXml; namespace alpinocorpus { /* begin() */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlContainer &container) { try { r = container.getAllDocuments( db::DBXML_LAZY_DOCS | db::DBXML_WELL_FORMED_ONLY ); } catch (db::XmlException const &e) { throw Error(e.what()); } } /* query */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlResults const &r_) : r(r_) { } /* end() */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlManager &mgr) : r(mgr.createResults()) // builds empty XmlResults { } IterImpl *DbCorpusReaderPrivate::DbIter::copy() const { // XXX - Copy constructor of XmlResults copies handle but not body. // The copyResults() method returns an XmlResults instance that // is eagerly evaluated. Is there a way to copy XmlResults, // retain the iterator position, and have it lazy? // No pointer members return new DbIter(*this); } bool DbCorpusReaderPrivate::DbIter::hasNext() { try { return r.hasNext(); } catch (db::XmlException const &e) { if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED) throw IterationInterrupted(); else throw Error(e.what()); } } /* operator++ */ Entry DbCorpusReaderPrivate::DbIter::next(CorpusReader const &) { db::XmlValue v; try { r.next(v); } catch (db::XmlException const &e) { if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED) throw IterationInterrupted(); else throw Error(e.what()); } std::string name; std::string value; if (v.isNode()) { db::XmlDocument doc = v.asDocument(); value = v.getNodeValue(); name = doc.getName(); } else if (v.isString()) value = v.asString(); Entry e = {name, value}; return e; } DbCorpusReaderPrivate::QueryIter::QueryIter(db::XmlResults const &r, db::XmlQueryContext const &ctx) : DbIter(r), context(ctx) { } void DbCorpusReaderPrivate::QueryIter::interrupt() { context.interruptQuery(); } IterImpl *DbCorpusReaderPrivate::QueryIter::copy() const { // XXX - See DbIter::copy() return new QueryIter(*this); } DbCorpusReaderPrivate::DbCorpusReaderPrivate(std::string const &path) : mgr(), container() { try { db::XmlContainerConfig config; config.setReadOnly(true); container = mgr.openContainer(path, config); // Nasty: using a hard-coded alias to work use in the xpath queries. container.addAlias("corpus"); setNameAndCollection(path); } catch (db::XmlException const &e) { throw OpenError(path, e.what()); } } DbCorpusReaderPrivate::~DbCorpusReaderPrivate() { } CorpusReader::EntryIterator DbCorpusReaderPrivate::getEntries() const { return EntryIterator(new DbIter(container)); } std::string DbCorpusReaderPrivate::getName() const { return container.getName(); } bool DbCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const { try { db::XmlQueryContext ctx = mgr.createQueryContext(); mgr.prepare(query, ctx); } catch (db::XmlException const &e) { return false; } return true; } std::string DbCorpusReaderPrivate::readEntry(std::string const &filename) const { try { db::XmlDocument doc(container.getDocument(filename, db::DBXML_LAZY_DOCS)); std::string content; return doc.getContent(content); } catch (db::XmlException const &e) { std::ostringstream msg; msg << "entry \"" << filename << "\" cannot be read from \"" << container.getName() << "\" (" << e.what() << ")"; throw Error(msg.str()); } } CorpusReader::EntryIterator DbCorpusReaderPrivate::runXPath(std::string const &query) const { return runXQuery(std::string("collection('corpus')" + query)); } CorpusReader::EntryIterator DbCorpusReaderPrivate::runXQuery(std::string const &query) const { // XXX use DBXML_DOCUMENT_PROJECTION and return to whole-doc containers? try { db::XmlQueryContext ctx = mgr.createQueryContext(db::XmlQueryContext::LiveValues, db::XmlQueryContext::Lazy); ctx.setDefaultCollection(collection); db::XmlResults r(mgr.query(query, ctx, db::DBXML_LAZY_DOCS | db::DBXML_WELL_FORMED_ONLY )); return EntryIterator(new QueryIter(r, ctx)); } catch (db::XmlException const &e) { throw Error(e.what()); } } /* * Set corpus name to container name; set collection to a usable collection * name. * * The collection name is used for querying. We set it to the absolute path * so we can still run queries after a chdir(). * For some reason, DB XML strips off a leading slash in the filename, * so we prepend an extra one. */ void DbCorpusReaderPrivate::setNameAndCollection(std::string const &path) { std::string uri = "/" + name(); collection = util::toPercentEncoding(uri); } } <commit_msg>XQuery: a node is not necessarily from a document.<commit_after>#include <list> #include <sstream> #include <stdexcept> #include <string> #include <typeinfo> #include <dbxml/DbXml.hpp> #include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/IterImpl.hh> #include "DbCorpusReaderPrivate.hh" #include "util/url.hh" namespace db = DbXml; namespace alpinocorpus { /* begin() */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlContainer &container) { try { r = container.getAllDocuments( db::DBXML_LAZY_DOCS | db::DBXML_WELL_FORMED_ONLY ); } catch (db::XmlException const &e) { throw Error(e.what()); } } /* query */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlResults const &r_) : r(r_) { } /* end() */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlManager &mgr) : r(mgr.createResults()) // builds empty XmlResults { } IterImpl *DbCorpusReaderPrivate::DbIter::copy() const { // XXX - Copy constructor of XmlResults copies handle but not body. // The copyResults() method returns an XmlResults instance that // is eagerly evaluated. Is there a way to copy XmlResults, // retain the iterator position, and have it lazy? // No pointer members return new DbIter(*this); } bool DbCorpusReaderPrivate::DbIter::hasNext() { try { return r.hasNext(); } catch (db::XmlException const &e) { if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED) throw IterationInterrupted(); else throw Error(e.what()); } } /* operator++ */ Entry DbCorpusReaderPrivate::DbIter::next(CorpusReader const &) { db::XmlValue v; try { r.next(v); } catch (db::XmlException const &e) { if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED) throw IterationInterrupted(); else throw Error(e.what()); } std::string name; std::string value; if (v.isNode()) { value = v.getNodeValue(); try { db::XmlDocument doc = v.asDocument(); name = doc.getName(); } catch (db::XmlException &) { // Could not use node as a document. Why is there no isDocument() // method? } } else if (v.isString()) value = v.asString(); Entry e = {name, value}; return e; } DbCorpusReaderPrivate::QueryIter::QueryIter(db::XmlResults const &r, db::XmlQueryContext const &ctx) : DbIter(r), context(ctx) { } void DbCorpusReaderPrivate::QueryIter::interrupt() { context.interruptQuery(); } IterImpl *DbCorpusReaderPrivate::QueryIter::copy() const { // XXX - See DbIter::copy() return new QueryIter(*this); } DbCorpusReaderPrivate::DbCorpusReaderPrivate(std::string const &path) : mgr(), container() { try { db::XmlContainerConfig config; config.setReadOnly(true); container = mgr.openContainer(path, config); // Nasty: using a hard-coded alias to work use in the xpath queries. container.addAlias("corpus"); setNameAndCollection(path); } catch (db::XmlException const &e) { throw OpenError(path, e.what()); } } DbCorpusReaderPrivate::~DbCorpusReaderPrivate() { } CorpusReader::EntryIterator DbCorpusReaderPrivate::getEntries() const { return EntryIterator(new DbIter(container)); } std::string DbCorpusReaderPrivate::getName() const { return container.getName(); } bool DbCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const { try { db::XmlQueryContext ctx = mgr.createQueryContext(); mgr.prepare(query, ctx); } catch (db::XmlException const &e) { return false; } return true; } std::string DbCorpusReaderPrivate::readEntry(std::string const &filename) const { try { db::XmlDocument doc(container.getDocument(filename, db::DBXML_LAZY_DOCS)); std::string content; return doc.getContent(content); } catch (db::XmlException const &e) { std::ostringstream msg; msg << "entry \"" << filename << "\" cannot be read from \"" << container.getName() << "\" (" << e.what() << ")"; throw Error(msg.str()); } } CorpusReader::EntryIterator DbCorpusReaderPrivate::runXPath(std::string const &query) const { return runXQuery(std::string("collection('corpus')" + query)); } CorpusReader::EntryIterator DbCorpusReaderPrivate::runXQuery(std::string const &query) const { // XXX use DBXML_DOCUMENT_PROJECTION and return to whole-doc containers? try { db::XmlQueryContext ctx = mgr.createQueryContext(db::XmlQueryContext::LiveValues, db::XmlQueryContext::Lazy); ctx.setDefaultCollection(collection); db::XmlResults r(mgr.query(query, ctx, db::DBXML_LAZY_DOCS | db::DBXML_WELL_FORMED_ONLY )); return EntryIterator(new QueryIter(r, ctx)); } catch (db::XmlException const &e) { throw Error(e.what()); } } /* * Set corpus name to container name; set collection to a usable collection * name. * * The collection name is used for querying. We set it to the absolute path * so we can still run queries after a chdir(). * For some reason, DB XML strips off a leading slash in the filename, * so we prepend an extra one. */ void DbCorpusReaderPrivate::setNameAndCollection(std::string const &path) { std::string uri = "/" + name(); collection = util::toPercentEncoding(uri); } } <|endoftext|>
<commit_before> // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/sfm/sfm.hpp" #include "openMVG/image/image.hpp" #include "openMVG/system/timer.hpp" using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::sfm; #include "third_party/cmdLine/cmdLine.h" #include "third_party/progress/progress.hpp" #include <stdlib.h> #ifdef OPENMVG_USE_OPENMP #include <omp.h> #endif int main(int argc, char *argv[]) { CmdLine cmd; std::string sSfM_Data_Filename; std::string sOutDir = ""; bool bExportOnlyReconstructedViews = false; #ifdef OPENMVG_USE_OPENMP int iNumThreads = 0; #endif cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") ); cmd.add( make_option('o', sOutDir, "outdir") ); cmd.add( make_option('r', bExportOnlyReconstructedViews, "exportOnlyReconstructed") ); #ifdef OPENMVG_USE_OPENMP cmd.add( make_option('n', iNumThreads, "numThreads") ); #endif try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Export undistorted images related to a sfm_data file.\n" << "Usage: " << argv[0] << '\n' << "[-i|--sfmdata] filename, the SfM_Data file to convert\n" << "[-o|--outdir] path\n" << "[-r|--exportOnlyReconstructed] path\n" #ifdef OPENMVG_USE_OPENMP << "[-n|--numThreads] number of parallel computations\n" #endif << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } // Create output dir if (!stlplus::folder_exists(sOutDir)) stlplus::folder_create( sOutDir ); SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS))) { std::cerr << std::endl << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } bool bOk = true; { system::Timer timer; // Export views as undistorted images (those with valid Intrinsics) Image<RGBColor> image, image_ud; C_Progress_display my_progress_bar( sfm_data.GetViews().size(), std::cout, "\n- EXTRACT UNDISTORTED IMAGES -\n" ); #ifdef OPENMVG_USE_OPENMP const unsigned int nb_max_thread = omp_get_max_threads(); #endif #ifdef OPENMVG_USE_OPENMP omp_set_num_threads(iNumThreads); #pragma omp parallel for schedule(dynamic) if(iNumThreads > 0) private(image,image_ud) #endif for(int i = 0; i < sfm_data.views.size(); ++i) { #ifdef OPENMVG_USE_OPENMP if(iNumThreads == 0) omp_set_num_threads(nb_max_thread); #endif Views::const_iterator iterViews = sfm_data.views.begin(); std::advance(iterViews, i); const View * view = iterViews->second.get(); // Check if the view is in reconstruction if(bExportOnlyReconstructedViews && !sfm_data.IsPoseAndIntrinsicDefined(view)) continue; bool bIntrinsicDefined = view->id_intrinsic != UndefinedIndexT && sfm_data.GetIntrinsics().find(view->id_intrinsic) != sfm_data.GetIntrinsics().end(); Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path); const std::string dstImage = stlplus::create_filespec( sOutDir, stlplus::filename_part(srcImage)); const IntrinsicBase * cam = iterIntrinsic->second.get(); if (cam->have_disto()) { // undistort the image and save it if (ReadImage( srcImage.c_str(), &image)) { UndistortImage(image, cam, image_ud, BLACK); bOk &= WriteImage(dstImage.c_str(), image_ud); } } else // (no distortion) { // copy the image since there is no distortion stlplus::file_copy(srcImage, dstImage); } #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif ++my_progress_bar; } std::cout << "Task done in (s): " << timer.elapsed() << std::endl; } // Exit program if (bOk) return( EXIT_SUCCESS ); else return( EXIT_FAILURE ); } <commit_msg>Corrected loading of SfM data to also load the extrinsics<commit_after> // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/sfm/sfm.hpp" #include "openMVG/image/image.hpp" #include "openMVG/system/timer.hpp" using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::sfm; #include "third_party/cmdLine/cmdLine.h" #include "third_party/progress/progress.hpp" #include <stdlib.h> #ifdef OPENMVG_USE_OPENMP #include <omp.h> #endif int main(int argc, char *argv[]) { CmdLine cmd; std::string sSfM_Data_Filename; std::string sOutDir = ""; bool bExportOnlyReconstructedViews = false; #ifdef OPENMVG_USE_OPENMP int iNumThreads = 0; #endif cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") ); cmd.add( make_option('o', sOutDir, "outdir") ); cmd.add( make_option('r', bExportOnlyReconstructedViews, "exportOnlyReconstructed") ); #ifdef OPENMVG_USE_OPENMP cmd.add( make_option('n', iNumThreads, "numThreads") ); #endif try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Export undistorted images related to a sfm_data file.\n" << "Usage: " << argv[0] << '\n' << "[-i|--sfmdata] filename, the SfM_Data file to convert\n" << "[-o|--outdir] path\n" << "[-r|--exportOnlyReconstructed] path\n" #ifdef OPENMVG_USE_OPENMP << "[-n|--numThreads] number of parallel computations\n" #endif << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } // Create output dir if (!stlplus::folder_exists(sOutDir)) stlplus::folder_create( sOutDir ); SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS))) { std::cerr << std::endl << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } bool bOk = true; { system::Timer timer; // Export views as undistorted images (those with valid Intrinsics) Image<RGBColor> image, image_ud; C_Progress_display my_progress_bar( sfm_data.GetViews().size(), std::cout, "\n- EXTRACT UNDISTORTED IMAGES -\n" ); #ifdef OPENMVG_USE_OPENMP const unsigned int nb_max_thread = omp_get_max_threads(); #endif #ifdef OPENMVG_USE_OPENMP omp_set_num_threads(iNumThreads); #pragma omp parallel for schedule(dynamic) if(iNumThreads > 0) private(image,image_ud) #endif for(int i = 0; i < sfm_data.views.size(); ++i) { #ifdef OPENMVG_USE_OPENMP if(iNumThreads == 0) omp_set_num_threads(nb_max_thread); #endif Views::const_iterator iterViews = sfm_data.views.begin(); std::advance(iterViews, i); const View * view = iterViews->second.get(); // Check if the view is in reconstruction if(bExportOnlyReconstructedViews && !sfm_data.IsPoseAndIntrinsicDefined(view)) continue; bool bIntrinsicDefined = view->id_intrinsic != UndefinedIndexT && sfm_data.GetIntrinsics().find(view->id_intrinsic) != sfm_data.GetIntrinsics().end(); Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path); const std::string dstImage = stlplus::create_filespec( sOutDir, stlplus::filename_part(srcImage)); const IntrinsicBase * cam = iterIntrinsic->second.get(); if (cam->have_disto()) { // undistort the image and save it if (ReadImage( srcImage.c_str(), &image)) { UndistortImage(image, cam, image_ud, BLACK); bOk &= WriteImage(dstImage.c_str(), image_ud); } } else // (no distortion) { // copy the image since there is no distortion stlplus::file_copy(srcImage, dstImage); } #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif ++my_progress_bar; } std::cout << "Task done in (s): " << timer.elapsed() << std::endl; } // Exit program if (bOk) return( EXIT_SUCCESS ); else return( EXIT_FAILURE ); } <|endoftext|>
<commit_before>#include "BootConfig.hpp" using namespace HomieInternals; BootConfig::BootConfig() : Boot("config") , _http(80) , _ssid_count(0) , _last_wifi_scan(0) , _last_wifi_scan_ended(true) , _flagged_for_reboot(false) , _flagged_for_reboot_at(0) { } BootConfig::~BootConfig() { } void BootConfig::setup() { Boot::setup(); char device_id[8 + 1]; sprintf(device_id, "%08x", ESP.getChipId()); Logger.log("Device ID is "); Logger.logln(device_id); String tmp_hostname = String("Homie-"); tmp_hostname += device_id; WiFi.hostname(tmp_hostname); digitalWrite(BUILTIN_LED, LOW); WiFi.mode(WIFI_AP); IPAddress apIP(192, 168, 1, 1); WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); WiFi.softAP(tmp_hostname.c_str(), device_id); Logger.log("AP started as "); Logger.logln(tmp_hostname); // Trigger sync Wi-Fi scan (don't do before AP init or doesn't work) this->_ssid_count = WiFi.scanNetworks(); this->_last_wifi_scan = millis(); this->_json_wifi_networks = this->_generateNetworksJson(); this->_dns.setTTL(300); this->_dns.setErrorReplyCode(DNSReplyCode::ServerFailure); this->_dns.start(53, "homie.config", apIP); this->_http.on("/heart", HTTP_GET, [this]() { Logger.logln("Received heart request"); this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), "{\"heart\":\"beat\"}"); }); this->_http.on("/networks", HTTP_GET, std::bind(&BootConfig::_onNetworksRequest, this)); this->_http.on("/config", HTTP_PUT, std::bind(&BootConfig::_onConfigRequest, this)); this->_http.on("/config", HTTP_OPTIONS, [this]() { // CORS this->_http.sendContent(FPSTR(PROGMEM_CONFIG_CORS)); }); this->_http.begin(); } String BootConfig::_generateNetworksJson() { DynamicJsonBuffer generatedJsonBuffer; JsonObject& json = generatedJsonBuffer.createObject(); JsonArray& networks = json.createNestedArray("networks"); for (int network = 0; network < this->_ssid_count; network++) { JsonObject& json_network = generatedJsonBuffer.createObject(); json_network["ssid"] = WiFi.SSID(network); json_network["rssi"] = WiFi.RSSI(network); switch (WiFi.encryptionType(network)) { case ENC_TYPE_WEP: json_network["encryption"] = "wep"; break; case ENC_TYPE_TKIP: json_network["encryption"] = "wpa"; break; case ENC_TYPE_CCMP: json_network["encryption"] = "wpa2"; break; case ENC_TYPE_NONE: json_network["encryption"] = "none"; break; case ENC_TYPE_AUTO: json_network["encryption"] = "auto"; break; } networks.add(json_network); } // 15 bytes: {"networks":[]} // 75 bytes: {"ssid":"thisisa32characterlongstringyes!","rssi":-99,"encryption":"none"}, (-1 for leading ","), +1 for terminator char json_string[15 + (75 * this->_ssid_count) - 1 + 1]; size_t json_length = json.printTo(json_string, sizeof(json_string)); return String(json_string); } void BootConfig::_onNetworksRequest() { Logger.logln("Received networks request"); this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), this->_json_wifi_networks); } void BootConfig::_onConfigRequest() { Logger.logln("Received config request"); if (this->_flagged_for_reboot) { Logger.logln("✖ Device already configured"); this->_http.send(403, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } StaticJsonBuffer<JSON_OBJECT_SIZE(7)> parseJsonBuffer; // Max seven elements in object JsonObject& parsed_json = parseJsonBuffer.parseObject((char*)this->_http.arg("plain").c_str()); if (!parsed_json.success()) { Logger.logln("✖ Invalid or too big JSON"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (!parsed_json.containsKey("name") || !parsed_json["name"].is<const char*>()) { Logger.logln("✖ name is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (!parsed_json.containsKey("wifi_ssid") || !parsed_json["wifi_ssid"].is<const char*>()) { Logger.logln("✖ wifi_ssid is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (!parsed_json.containsKey("wifi_password") || !parsed_json["wifi_password"].is<const char*>()) { Logger.logln("✖ wifi_password is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (!parsed_json.containsKey("homie_host") || !parsed_json["homie_host"].is<const char*>()) { Logger.logln("✖ homie_host is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (parsed_json.containsKey("homie_port") && !parsed_json["homie_port"].is<uint16_t>()) { Logger.logln("✖ homie_port is not an unsigned integer"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (parsed_json.containsKey("homie_ota_path") && !parsed_json["homie_ota_path"].is<const char*>()) { Logger.logln("✖ homie_ota_path is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (parsed_json.containsKey("homie_ota_port") && !parsed_json["homie_ota_port"].is<uint16_t>()) { Logger.logln("✖ homie_ota_port is not an unsigned integer"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } const char* req_name = parsed_json["name"]; const char* req_wifi_ssid = parsed_json["wifi_ssid"]; const char* req_wifi_password = parsed_json["wifi_password"]; const char* req_homie_host = parsed_json["homie_host"]; uint16_t req_homie_port = DEFAULT_HOMIE_PORT; if (parsed_json.containsKey("homie_port")) { req_homie_port = parsed_json["homie_port"].as<uint16_t>(); } const char* req_homie_ota_path = DEFAULT_HOMIE_OTA_PATH; if (parsed_json.containsKey("homie_ota_path")) { req_homie_ota_path = parsed_json["homie_ota_path"]; } uint16_t req_homie_ota_port = DEFAULT_HOMIE_OTA_PORT; if (parsed_json.containsKey("homie_ota_port")) { req_homie_ota_port = parsed_json["homie_ota_port"].as<uint16_t>(); } if (strcmp(req_name, "") == 0) { Logger.logln("✖ name is empty"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (strcmp(req_wifi_ssid, "") == 0) { Logger.logln("✖ wifi_ssid is empty"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (strcmp(req_homie_host, "") == 0) { Logger.logln("✖ homie_host is empty"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } // Check if hostname only [a-z0-9\-] for (int i = 0; i < strlen(req_name); i++){ if (!((req_name[i] >= 'a' && req_name[i] <= 'z') || (req_name[i] >= '0' && req_name[i] <= '9') || req_name[i] == '-')) { Logger.logln("✖ name contains unauthorized characters"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } } // Check if hostname doesn't start or end with '-' if (req_name[0] == '-' || req_name[strlen(req_name) - 1] == '-') { Logger.logln("✖ name starts or ends with a dash"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } Config.hostname = req_name; Config.wifi_ssid = req_wifi_ssid; Config.wifi_password = req_wifi_password; Config.homie_host = req_homie_host; Config.homie_port = req_homie_port; Config.homie_ota_path = req_homie_ota_path; Config.homie_ota_port = req_homie_ota_port; Config.boot_mode = BOOT_NORMAL; Config.configured = true; Config.save(); Config.log(); Logger.logln("✔ Configured"); this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), "{\"success\":true}"); this->_flagged_for_reboot = true; // We don't reboot immediately, otherwise the response above is not sent this->_flagged_for_reboot_at = millis(); } void BootConfig::loop() { Boot::loop(); this->_dns.processNextRequest(); this->_http.handleClient(); if (this->_flagged_for_reboot) { if (millis() - this->_flagged_for_reboot_at >= 5000UL) { Logger.logln("↻ Rebooting in normal mode"); ESP.restart(); } return; } if (!this->_last_wifi_scan_ended) { int8_t scan_result = WiFi.scanComplete(); switch (scan_result) { case WIFI_SCAN_RUNNING: return; case WIFI_SCAN_FAILED: Logger.logln("✖ Wi-Fi scan failed"); this->_ssid_count = 0; break; default: Logger.logln("✔ Wi-Fi scan completed"); this->_ssid_count = scan_result; this->_json_wifi_networks = this->_generateNetworksJson(); break; } this->_last_wifi_scan_ended = true; } unsigned long now = millis(); if (now - this->_last_wifi_scan >= 20000UL && this->_last_wifi_scan_ended) { Logger.logln("Triggering Wi-Fi scan"); WiFi.scanNetworks(true); this->_last_wifi_scan = now; this->_last_wifi_scan_ended = false; } } <commit_msg>Fix #9<commit_after>#include "BootConfig.hpp" using namespace HomieInternals; BootConfig::BootConfig() : Boot("config") , _http(80) , _ssid_count(0) , _last_wifi_scan(0) , _last_wifi_scan_ended(true) , _flagged_for_reboot(false) , _flagged_for_reboot_at(0) { } BootConfig::~BootConfig() { } void BootConfig::setup() { Boot::setup(); char chip_id[6 + 1]; sprintf(chip_id, "%06x", ESP.getChipId()); char flash_chip_id[6 + 1]; sprintf(flash_chip_id, "%06x", ESP.getFlashChipId()); String truncated_flash_id = String(flash_chip_id); truncated_flash_id = truncated_flash_id.substring(4); String device_id = String(chip_id); device_id += truncated_flash_id; Logger.log("Device ID is "); Logger.logln(device_id); String tmp_hostname = String("Homie-"); tmp_hostname += device_id; WiFi.hostname(tmp_hostname); digitalWrite(BUILTIN_LED, LOW); WiFi.mode(WIFI_AP); IPAddress apIP(192, 168, 1, 1); WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); WiFi.softAP(tmp_hostname.c_str(), device_id.c_str()); Logger.log("AP started as "); Logger.logln(tmp_hostname); // Trigger sync Wi-Fi scan (don't do before AP init or doesn't work) this->_ssid_count = WiFi.scanNetworks(); this->_last_wifi_scan = millis(); this->_json_wifi_networks = this->_generateNetworksJson(); this->_dns.setTTL(300); this->_dns.setErrorReplyCode(DNSReplyCode::ServerFailure); this->_dns.start(53, "homie.config", apIP); this->_http.on("/heart", HTTP_GET, [this]() { Logger.logln("Received heart request"); this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), "{\"heart\":\"beat\"}"); }); this->_http.on("/networks", HTTP_GET, std::bind(&BootConfig::_onNetworksRequest, this)); this->_http.on("/config", HTTP_PUT, std::bind(&BootConfig::_onConfigRequest, this)); this->_http.on("/config", HTTP_OPTIONS, [this]() { // CORS this->_http.sendContent(FPSTR(PROGMEM_CONFIG_CORS)); }); this->_http.begin(); } String BootConfig::_generateNetworksJson() { DynamicJsonBuffer generatedJsonBuffer; JsonObject& json = generatedJsonBuffer.createObject(); JsonArray& networks = json.createNestedArray("networks"); for (int network = 0; network < this->_ssid_count; network++) { JsonObject& json_network = generatedJsonBuffer.createObject(); json_network["ssid"] = WiFi.SSID(network); json_network["rssi"] = WiFi.RSSI(network); switch (WiFi.encryptionType(network)) { case ENC_TYPE_WEP: json_network["encryption"] = "wep"; break; case ENC_TYPE_TKIP: json_network["encryption"] = "wpa"; break; case ENC_TYPE_CCMP: json_network["encryption"] = "wpa2"; break; case ENC_TYPE_NONE: json_network["encryption"] = "none"; break; case ENC_TYPE_AUTO: json_network["encryption"] = "auto"; break; } networks.add(json_network); } // 15 bytes: {"networks":[]} // 75 bytes: {"ssid":"thisisa32characterlongstringyes!","rssi":-99,"encryption":"none"}, (-1 for leading ","), +1 for terminator char json_string[15 + (75 * this->_ssid_count) - 1 + 1]; size_t json_length = json.printTo(json_string, sizeof(json_string)); return String(json_string); } void BootConfig::_onNetworksRequest() { Logger.logln("Received networks request"); this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), this->_json_wifi_networks); } void BootConfig::_onConfigRequest() { Logger.logln("Received config request"); if (this->_flagged_for_reboot) { Logger.logln("✖ Device already configured"); this->_http.send(403, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } StaticJsonBuffer<JSON_OBJECT_SIZE(7)> parseJsonBuffer; // Max seven elements in object JsonObject& parsed_json = parseJsonBuffer.parseObject((char*)this->_http.arg("plain").c_str()); if (!parsed_json.success()) { Logger.logln("✖ Invalid or too big JSON"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (!parsed_json.containsKey("name") || !parsed_json["name"].is<const char*>()) { Logger.logln("✖ name is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (!parsed_json.containsKey("wifi_ssid") || !parsed_json["wifi_ssid"].is<const char*>()) { Logger.logln("✖ wifi_ssid is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (!parsed_json.containsKey("wifi_password") || !parsed_json["wifi_password"].is<const char*>()) { Logger.logln("✖ wifi_password is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (!parsed_json.containsKey("homie_host") || !parsed_json["homie_host"].is<const char*>()) { Logger.logln("✖ homie_host is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (parsed_json.containsKey("homie_port") && !parsed_json["homie_port"].is<uint16_t>()) { Logger.logln("✖ homie_port is not an unsigned integer"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (parsed_json.containsKey("homie_ota_path") && !parsed_json["homie_ota_path"].is<const char*>()) { Logger.logln("✖ homie_ota_path is not a string"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (parsed_json.containsKey("homie_ota_port") && !parsed_json["homie_ota_port"].is<uint16_t>()) { Logger.logln("✖ homie_ota_port is not an unsigned integer"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } const char* req_name = parsed_json["name"]; const char* req_wifi_ssid = parsed_json["wifi_ssid"]; const char* req_wifi_password = parsed_json["wifi_password"]; const char* req_homie_host = parsed_json["homie_host"]; uint16_t req_homie_port = DEFAULT_HOMIE_PORT; if (parsed_json.containsKey("homie_port")) { req_homie_port = parsed_json["homie_port"].as<uint16_t>(); } const char* req_homie_ota_path = DEFAULT_HOMIE_OTA_PATH; if (parsed_json.containsKey("homie_ota_path")) { req_homie_ota_path = parsed_json["homie_ota_path"]; } uint16_t req_homie_ota_port = DEFAULT_HOMIE_OTA_PORT; if (parsed_json.containsKey("homie_ota_port")) { req_homie_ota_port = parsed_json["homie_ota_port"].as<uint16_t>(); } if (strcmp(req_name, "") == 0) { Logger.logln("✖ name is empty"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (strcmp(req_wifi_ssid, "") == 0) { Logger.logln("✖ wifi_ssid is empty"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } if (strcmp(req_homie_host, "") == 0) { Logger.logln("✖ homie_host is empty"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } // Check if hostname only [a-z0-9\-] for (int i = 0; i < strlen(req_name); i++){ if (!((req_name[i] >= 'a' && req_name[i] <= 'z') || (req_name[i] >= '0' && req_name[i] <= '9') || req_name[i] == '-')) { Logger.logln("✖ name contains unauthorized characters"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } } // Check if hostname doesn't start or end with '-' if (req_name[0] == '-' || req_name[strlen(req_name) - 1] == '-') { Logger.logln("✖ name starts or ends with a dash"); this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE)); return; } Config.hostname = req_name; Config.wifi_ssid = req_wifi_ssid; Config.wifi_password = req_wifi_password; Config.homie_host = req_homie_host; Config.homie_port = req_homie_port; Config.homie_ota_path = req_homie_ota_path; Config.homie_ota_port = req_homie_ota_port; Config.boot_mode = BOOT_NORMAL; Config.configured = true; Config.save(); Config.log(); Logger.logln("✔ Configured"); this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), "{\"success\":true}"); this->_flagged_for_reboot = true; // We don't reboot immediately, otherwise the response above is not sent this->_flagged_for_reboot_at = millis(); } void BootConfig::loop() { Boot::loop(); this->_dns.processNextRequest(); this->_http.handleClient(); if (this->_flagged_for_reboot) { if (millis() - this->_flagged_for_reboot_at >= 5000UL) { Logger.logln("↻ Rebooting in normal mode"); ESP.restart(); } return; } if (!this->_last_wifi_scan_ended) { int8_t scan_result = WiFi.scanComplete(); switch (scan_result) { case WIFI_SCAN_RUNNING: return; case WIFI_SCAN_FAILED: Logger.logln("✖ Wi-Fi scan failed"); this->_ssid_count = 0; break; default: Logger.logln("✔ Wi-Fi scan completed"); this->_ssid_count = scan_result; this->_json_wifi_networks = this->_generateNetworksJson(); break; } this->_last_wifi_scan_ended = true; } unsigned long now = millis(); if (now - this->_last_wifi_scan >= 20000UL && this->_last_wifi_scan_ended) { Logger.logln("Triggering Wi-Fi scan"); WiFi.scanNetworks(true); this->_last_wifi_scan = now; this->_last_wifi_scan_ended = false; } } <|endoftext|>
<commit_before>/* * soundpatty.cpp * * Copyright (c) 2010 Motiejus Jakštys * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "soundpatty.h" #include "input.h" void SoundPatty::dump_out(const treshold_t args) { // STATIC printf ("%d;%.6f;%.6f\n", args.r, args.place, args.sec); }; void SoundPatty::setAction(int action, char * cfg, void (*fn)(double)) { _action = action; read_captured_values(cfg); _callback = fn; // What to do when we catch a pattern }; void SoundPatty::setAction(int action) { _action = action; }; SoundPatty::SoundPatty(all_cfg_t all_cfg) { cfg = all_cfg.first; volume = all_cfg.second; gSCounter = gMCounter = 0; }; all_cfg_t SoundPatty::read_cfg (const char * filename) { map<string,double> cfg; vector<sVolumes> volume; ifstream file; file.open(filename); string line; int x; while (! file.eof() ) { getline(file, line); x = line.find(":"); if (x == -1) break; // Last line, exit istringstream i(line.substr(x+2)); double tmp; i >> tmp; cfg[line.substr(0,x)] = tmp; } sVolumes tmp; tmp.head = tmp.tail = tmp.max = tmp.min = tmp.proc = 0; volume.assign(cfg.size(), tmp); // Assign a bit more then nescesarry int max_index = 0; // Number of different tresholds for(map<string, double>::iterator C = cfg.begin(); C != cfg.end(); C++) { // Failed to use boost::regex :( if (C->first.find("treshold") == 0) { istringstream tmp(C->first.substr(8)); int i; tmp >> i; max_index = max(max_index, i); if (C->first.find("_min") != string::npos) { volume[i].min = C->second; } else { volume[i].max = C->second; } } } volume.assign(volume.begin(), volume.begin()+max_index+1); return all_cfg_t(cfg, volume); }; int SoundPatty::setInput(const int source_app, void * input_params) { if (0 <= source_app && source_app <= 2) { this->source_app = source_app; } switch(this->source_app) { case SRC_WAV: _input = new WavInput(this, input_params); break; case SRC_JACK_ONE: _input = new JackInput(this, input_params); break; case SRC_JACK_AUTO: _input = new JackInput(this, input_params); break; } return 0; }; void SoundPatty::go() { string which_timeout (_action == ACTION_DUMP ? "sampletimeout" : "catchtimeout"); buffer_t buf; while (_input->giveInput(&buf) != 0) { // Have pointer to data treshold_t ret; for (unsigned int i = 0; i < buf.nframes; gSCounter++, i++) { jack_default_audio_sample_t cur = buf.buf[i]<0?-buf.buf[i]:buf.buf[i]; if (search_patterns(cur, &ret)) { if (_action == ACTION_DUMP) { SoundPatty::dump_out(ret); } if (_action == ACTION_CATCH) { SoundPatty::do_checking(ret); } } } if ((double)gSCounter/_input->SAMPLE_RATE > cfg[which_timeout]) { return; } } }; void SoundPatty::read_captured_values(const char * filename) { ifstream file; file.open(filename); string line; for (int i = 0; !file.eof(); i++) { getline(file, line); if (line.size() == 0) break; vector<string> numbers = explode(";", line); istringstream num(numbers[0]); istringstream place(numbers[1]); istringstream range(numbers[2]); double tmp2; pair<pair<int, Range>,valsitm_t > tmp; num >> tmp2; tmp.first.first = tmp2; // Index in volume range >> tmp2; tmp.first.second = Range(tmp2); place >> tmp.second.place; // Place in the stream tmp.second.c = i; // Counter in the stream vals.insert(tmp); } }; int SoundPatty::search_patterns (jack_default_audio_sample_t cur, treshold_t * ret) { int v = 0; // Counter for volume for (vector<sVolumes>::iterator V = volume.begin(); V != volume.end(); V++, v++) { if (V->min <= cur && cur <= V->max) { // ------------------------------------------------------------ // If it's first item in this wave (proc = processing started) // if (!V->proc) { V->tail = gSCounter; V->proc = true; } // ------------------------------------------------------------ // Here we are just normally in the wave. // V->head = gSCounter; } else { // We are not in the wave if (V->proc && (V->min < 0.001 || gSCounter - V->head > WAVE)) { //------------------------------------------------------------ // This wave is over // V->proc = false; // Stop processing for both cases: found and not if (gSCounter - V->tail >= CHUNKSIZE) { // ------------------------------------------------------------ // The previous chunk is big enough to be noticed // ret -> r = v; ret -> place = (double)V->tail/_input->SAMPLE_RATE; ret -> sec = (double)(V->head - V->tail)/_input->SAMPLE_RATE; ret -> b = gMCounter++; return 1; } // ------------------------------------------------------------ // Else it is too small, but we don't want to do anything in that case // So therefore we just say that wave processing is over // } } } return 0; }; // -------------------------------------------------------------------------------- // This gets called every time there is a treshold found. // Work array is global // // int r - id of treshold found (in config.cfg: treshold_(<?r>\d)_(min|max)) // double place - place of sample from the stream start (sec) // double sec - length of a found sample (sec) // int b - index (overall) of sample found // void SoundPatty::do_checking(const treshold_t tr) { //pair<vals_t::iterator, vals_t::iterator> pa = vals.equal_range(pair<int,double>(r,sec)); // Manually searching for matching values because with that pairs equal_range doesnt work // Iterate through pa unsigned long b = tr.b; vals_t fina; // FoundInA Range demorange(tr.sec); pair<int,Range> sample(tr.r, demorange); for (vals_t::iterator it1 = vals.begin(); it1 != vals.end(); it1++) { if (it1->first == sample) { fina.insert(*it1); } } //------------------------------------------------------------ // We put a indexes here that we use for continued threads // (we don't want to create a new "thread" with already // used length of a sample) // set<int> used_a; //------------------------------------------------------------ // Iterating through samples that match the found sample // for (vals_t::iterator in_a = fina.begin(); in_a != fina.end(); in_a++) { //printf("%d %.6f matches %.6f (%d)\n", in_a->first.first, sec, in_a->first.second.tm, in_a->second.c); int a = in_a->second.c; //------------------------------------------------------------ // Check if it exists in our work array // for (list<workitm>::iterator w = work.begin(); w != work.end();) { if (b - w->b > round(cfg["maxsteps"])) { work.erase(w); w = work.begin(); continue; } if (b == w->b || a - w->a > round(cfg["maxsteps"]) || w->a >= a) { w++; continue; } // ------------------------------------------------------------ // We fit the "region" here. We either finished, // or just increasing len // w->a = a; w->b = b; w->trace.push_back(pair<int,unsigned long>(a,b)); if (++(w->len) < round(cfg["matchme"])) { // Proceeding with the "thread" used_a.insert(a); //printf ("Thread expanded to %d\n", w->len); } else { // This means the treshold is reached // This kind of function is called when the pattern is recognized //void(*end_fn)(workitm *, double) = (void*)(workitm *, double) _callback; _callback (tr.place + tr.sec); } w++; // End of work iteration array } if (used_a.find(a) == used_a.end()) { work.push_back(workitm(a,b)); //printf ("Pushed back %d %d\n", a,b); } } }; vector<string> explode(const string &delimiter, const string &str) { // Found somewhere on NET vector<string> arr; int strleng = str.length(); int delleng = delimiter.length(); if (delleng == 0) return arr; //no change int i = 0, k = 0; while (i < strleng) { int j = 0; while (i+j < strleng && j < delleng && str[i+j] == delimiter[j]) j++; if (j == delleng) { arr.push_back(str.substr(k, i-k)); i += delleng; k = i; } else { i++; } } arr.push_back(str.substr(k, i-k)); return arr; }; void fatal(void * r) { char * msg = (char*) r; printf (msg); exit (1); }; void fatal(char * msg) { printf (msg); exit (1); }; workitm::workitm(const int a, const unsigned long b) { this->a = a; this->b = b; len = 0; trace.push_back(pair<int,unsigned long>(a,b)); }; <commit_msg>Add timeout message (need feedback)<commit_after>/* * soundpatty.cpp * * Copyright (c) 2010 Motiejus Jakštys * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "soundpatty.h" #include "input.h" void SoundPatty::dump_out(const treshold_t args) { // STATIC printf ("%d;%.6f;%.6f\n", args.r, args.place, args.sec); }; void SoundPatty::setAction(int action, char * cfg, void (*fn)(double)) { _action = action; read_captured_values(cfg); _callback = fn; // What to do when we catch a pattern }; void SoundPatty::setAction(int action) { _action = action; }; SoundPatty::SoundPatty(all_cfg_t all_cfg) { cfg = all_cfg.first; volume = all_cfg.second; gSCounter = gMCounter = 0; }; all_cfg_t SoundPatty::read_cfg (const char * filename) { map<string,double> cfg; vector<sVolumes> volume; ifstream file; file.open(filename); string line; int x; while (! file.eof() ) { getline(file, line); x = line.find(":"); if (x == -1) break; // Last line, exit istringstream i(line.substr(x+2)); double tmp; i >> tmp; cfg[line.substr(0,x)] = tmp; } sVolumes tmp; tmp.head = tmp.tail = tmp.max = tmp.min = tmp.proc = 0; volume.assign(cfg.size(), tmp); // Assign a bit more then nescesarry int max_index = 0; // Number of different tresholds for(map<string, double>::iterator C = cfg.begin(); C != cfg.end(); C++) { // Failed to use boost::regex :( if (C->first.find("treshold") == 0) { istringstream tmp(C->first.substr(8)); int i; tmp >> i; max_index = max(max_index, i); if (C->first.find("_min") != string::npos) { volume[i].min = C->second; } else { volume[i].max = C->second; } } } volume.assign(volume.begin(), volume.begin()+max_index+1); return all_cfg_t(cfg, volume); }; int SoundPatty::setInput(const int source_app, void * input_params) { if (0 <= source_app && source_app <= 2) { this->source_app = source_app; } switch(this->source_app) { case SRC_WAV: _input = new WavInput(this, input_params); break; case SRC_JACK_ONE: _input = new JackInput(this, input_params); break; case SRC_JACK_AUTO: _input = new JackInput(this, input_params); break; } return 0; }; void SoundPatty::go() { string which_timeout (_action == ACTION_DUMP ? "sampletimeout" : "catchtimeout"); buffer_t buf; while (_input->giveInput(&buf) != 0) { // Have pointer to data treshold_t ret; for (unsigned int i = 0; i < buf.nframes; gSCounter++, i++) { jack_default_audio_sample_t cur = buf.buf[i]<0?-buf.buf[i]:buf.buf[i]; if (search_patterns(cur, &ret)) { if (_action == ACTION_DUMP) { SoundPatty::dump_out(ret); } if (_action == ACTION_CATCH) { SoundPatty::do_checking(ret); } } } if ((double)gSCounter/_input->SAMPLE_RATE > cfg[which_timeout]) { printf ("Timed out. Seconds passed: %.6f\n", (double)gSCounter/_input->SAMPLE_RATE); return; } } }; void SoundPatty::read_captured_values(const char * filename) { ifstream file; file.open(filename); string line; for (int i = 0; !file.eof(); i++) { getline(file, line); if (line.size() == 0) break; vector<string> numbers = explode(";", line); istringstream num(numbers[0]); istringstream place(numbers[1]); istringstream range(numbers[2]); double tmp2; pair<pair<int, Range>,valsitm_t > tmp; num >> tmp2; tmp.first.first = tmp2; // Index in volume range >> tmp2; tmp.first.second = Range(tmp2); place >> tmp.second.place; // Place in the stream tmp.second.c = i; // Counter in the stream vals.insert(tmp); } }; int SoundPatty::search_patterns (jack_default_audio_sample_t cur, treshold_t * ret) { int v = 0; // Counter for volume for (vector<sVolumes>::iterator V = volume.begin(); V != volume.end(); V++, v++) { if (V->min <= cur && cur <= V->max) { // ------------------------------------------------------------ // If it's first item in this wave (proc = processing started) // if (!V->proc) { V->tail = gSCounter; V->proc = true; } // ------------------------------------------------------------ // Here we are just normally in the wave. // V->head = gSCounter; } else { // We are not in the wave if (V->proc && (V->min < 0.001 || gSCounter - V->head > WAVE)) { //------------------------------------------------------------ // This wave is over // V->proc = false; // Stop processing for both cases: found and not if (gSCounter - V->tail >= CHUNKSIZE) { // ------------------------------------------------------------ // The previous chunk is big enough to be noticed // ret -> r = v; ret -> place = (double)V->tail/_input->SAMPLE_RATE; ret -> sec = (double)(V->head - V->tail)/_input->SAMPLE_RATE; ret -> b = gMCounter++; return 1; } // ------------------------------------------------------------ // Else it is too small, but we don't want to do anything in that case // So therefore we just say that wave processing is over // } } } return 0; }; // -------------------------------------------------------------------------------- // This gets called every time there is a treshold found. // Work array is global // // int r - id of treshold found (in config.cfg: treshold_(<?r>\d)_(min|max)) // double place - place of sample from the stream start (sec) // double sec - length of a found sample (sec) // int b - index (overall) of sample found // void SoundPatty::do_checking(const treshold_t tr) { //pair<vals_t::iterator, vals_t::iterator> pa = vals.equal_range(pair<int,double>(r,sec)); // Manually searching for matching values because with that pairs equal_range doesnt work // Iterate through pa unsigned long b = tr.b; vals_t fina; // FoundInA Range demorange(tr.sec); pair<int,Range> sample(tr.r, demorange); for (vals_t::iterator it1 = vals.begin(); it1 != vals.end(); it1++) { if (it1->first == sample) { fina.insert(*it1); } } //------------------------------------------------------------ // We put a indexes here that we use for continued threads // (we don't want to create a new "thread" with already // used length of a sample) // set<int> used_a; //------------------------------------------------------------ // Iterating through samples that match the found sample // for (vals_t::iterator in_a = fina.begin(); in_a != fina.end(); in_a++) { //printf("%d %.6f matches %.6f (%d)\n", in_a->first.first, sec, in_a->first.second.tm, in_a->second.c); int a = in_a->second.c; //------------------------------------------------------------ // Check if it exists in our work array // for (list<workitm>::iterator w = work.begin(); w != work.end();) { if (b - w->b > round(cfg["maxsteps"])) { work.erase(w); w = work.begin(); continue; } if (b == w->b || a - w->a > round(cfg["maxsteps"]) || w->a >= a) { w++; continue; } // ------------------------------------------------------------ // We fit the "region" here. We either finished, // or just increasing len // w->a = a; w->b = b; w->trace.push_back(pair<int,unsigned long>(a,b)); if (++(w->len) < round(cfg["matchme"])) { // Proceeding with the "thread" used_a.insert(a); //printf ("Thread expanded to %d\n", w->len); } else { // This means the treshold is reached // This kind of function is called when the pattern is recognized //void(*end_fn)(workitm *, double) = (void*)(workitm *, double) _callback; _callback (tr.place + tr.sec); } w++; // End of work iteration array } if (used_a.find(a) == used_a.end()) { work.push_back(workitm(a,b)); //printf ("Pushed back %d %d\n", a,b); } } }; vector<string> explode(const string &delimiter, const string &str) { // Found somewhere on NET vector<string> arr; int strleng = str.length(); int delleng = delimiter.length(); if (delleng == 0) return arr; //no change int i = 0, k = 0; while (i < strleng) { int j = 0; while (i+j < strleng && j < delleng && str[i+j] == delimiter[j]) j++; if (j == delleng) { arr.push_back(str.substr(k, i-k)); i += delleng; k = i; } else { i++; } } arr.push_back(str.substr(k, i-k)); return arr; }; void fatal(void * r) { char * msg = (char*) r; printf (msg); exit (1); }; void fatal(char * msg) { printf (msg); exit (1); }; workitm::workitm(const int a, const unsigned long b) { this->a = a; this->b = b; len = 0; trace.push_back(pair<int,unsigned long>(a,b)); }; <|endoftext|>
<commit_before>/* * Copyright 2014 David Moreno Montero <dmoreno@coralbits.com> * * 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. */ #pragma once #include "sequence.hpp" namespace underscore{ /** * @short Creates an sequence container of the given value. It copies the data. * * Example: * const std::vector<int> v{1,2,3,4}; * auto a=_(v); */ template<typename T> inline sequence<T> _(const T &v){ return sequence<T>(v); } /** * @short Creates an sequence container of the given value. Perfect forwarding version (std::move) * * Example: * auto v=std::vector<int>{1,2,3,4}; * auto a=_(std::move(v)) * * Or: * * auto a=_(std::vector<int>{1,2,3,4}); */ template<typename T> inline sequence<T> _(T &&v){ return sequence<T>(std::forward<T>(v)); } /** * @short Creates an sequence container with a vector of the elements into the initializer list. * * Allows creation directly as: * * auto a=_({1,2,3,4}) */ template<typename T> inline sequence<std::vector<T>> _(std::initializer_list<T> &&v){ return sequence<std::vector<T>>(std::vector<T>(std::forward<std::initializer_list<T>>(v))); } /** * @short Creates ansequence container from two ranges. Useful for subranges. * * It needs the ability to copy iterators. */ template<typename I> inline sequence<range<I>> _(I &&begin, I &&end){ return _(range<I>(begin, end)); } /** * @short Encapsulate a string. */ string _(std::string &&s); string _(const char *s); /** * @short zips two lists into one of tuples * * Example: * zip({1,2,3,4}, {'a','b','c','d'}) == {{1,'a'},{2,'b'},{3,'c'},{4,'d'}} * * This version allows two standard containers * * If the lists are uneven (diferent sizes) it creates new elements of the necesary type for the side with less elements: * * Example: * zip({1,2}, {'a','b','c','d'}) == {{1,'a'},{2,'b'},{0,'c'},{0,'d'}} */ template<typename A, typename B> inline sequence<std::vector<std::tuple<typename A::value_type, typename B::value_type>>> zip(const A &a, const B &b){ typedef std::tuple<typename A::value_type, typename B::value_type> ret_t; std::vector<ret_t> ret; ret.reserve(std::max(a.size(), b.size())); auto ia=std::begin(a); auto ea=std::end(a); auto ib=std::begin(b); auto eb=std::end(b); while (ia!=ea || ib!=eb){ if (ia==ea){ auto va=typename A::value_type(); ret.push_back(std::make_tuple(va, *ib)); ++ib; } else if (ib==eb){ auto vb=typename B::value_type(); ret.push_back(std::make_tuple(*ia, std::move(vb))); ++ia; } else{ ret.push_back(std::make_tuple(*ia, *ib)); ++ia; ++ib; } } return ret; } /** * @short zip two lists into a list of tuples. * * Specialization with the first as a initializer list. */ template<typename A_t, typename B> inline sequence<std::vector<std::tuple<A_t, typename B::value_type>>> zip(std::initializer_list<A_t> &&a, B &&b){ return zip(a, b); } /** * @short zip two lists into a list of tuples. * * Specialization with the two as initializer list. */ template<typename A_t, typename B_t> inline sequence<std::vector<std::tuple<A_t, B_t>>> zip(std::initializer_list<A_t> &&a, std::initializer_list<B_t> &&b){ return zip(a, b); } /** * @short zip two lists into a list of tuples. * * Specialization with the second as a initializer list. */ template<typename A, typename B_t> inline sequence<std::vector<std::tuple<typename A::value_type, B_t>>> zip(A &&a, std::initializer_list<B_t> &&b){ return zip(a, b); } }; <commit_msg>Fixes to let underscore.hpp know that there is a range class.<commit_after>/* * Copyright 2014 David Moreno Montero <dmoreno@coralbits.com> * * 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. */ #pragma once #include "sequence.hpp" namespace underscore{ class string; template<typename I> class range; /** * @short Creates an sequence container of the given value. It copies the data. * * Example: * const std::vector<int> v{1,2,3,4}; * auto a=_(v); */ template<typename T> inline sequence<T> _(const T &v){ return sequence<T>(v); } /** * @short Creates an sequence container of the given value. Perfect forwarding version (std::move) * * Example: * auto v=std::vector<int>{1,2,3,4}; * auto a=_(std::move(v)) * * Or: * * auto a=_(std::vector<int>{1,2,3,4}); */ template<typename T> inline sequence<T> _(T &&v){ return sequence<T>(std::forward<T>(v)); } /** * @short Creates an sequence container with a vector of the elements into the initializer list. * * Allows creation directly as: * * auto a=_({1,2,3,4}) */ template<typename T> inline sequence<std::vector<T>> _(std::initializer_list<T> &&v){ return sequence<std::vector<T>>(std::vector<T>(std::forward<std::initializer_list<T>>(v))); } /** * @short Creates ansequence container from two ranges. Useful for subranges. * * It needs the ability to copy iterators. */ template<typename I> inline sequence<range<I>> _(I &&begin, I &&end){ return _(range<I>(begin, end)); } /** * @short Encapsulate a string. */ string _(std::string &&s); string _(const char *s); /** * @short zips two lists into one of tuples * * Example: * zip({1,2,3,4}, {'a','b','c','d'}) == {{1,'a'},{2,'b'},{3,'c'},{4,'d'}} * * This version allows two standard containers * * If the lists are uneven (diferent sizes) it creates new elements of the necesary type for the side with less elements: * * Example: * zip({1,2}, {'a','b','c','d'}) == {{1,'a'},{2,'b'},{0,'c'},{0,'d'}} */ template<typename A, typename B> inline sequence<std::vector<std::tuple<typename A::value_type, typename B::value_type>>> zip(const A &a, const B &b){ typedef std::tuple<typename A::value_type, typename B::value_type> ret_t; std::vector<ret_t> ret; ret.reserve(std::max(a.size(), b.size())); auto ia=std::begin(a); auto ea=std::end(a); auto ib=std::begin(b); auto eb=std::end(b); while (ia!=ea || ib!=eb){ if (ia==ea){ auto va=typename A::value_type(); ret.push_back(std::make_tuple(va, *ib)); ++ib; } else if (ib==eb){ auto vb=typename B::value_type(); ret.push_back(std::make_tuple(*ia, std::move(vb))); ++ia; } else{ ret.push_back(std::make_tuple(*ia, *ib)); ++ia; ++ib; } } return ret; } /** * @short zip two lists into a list of tuples. * * Specialization with the first as a initializer list. */ template<typename A_t, typename B> inline sequence<std::vector<std::tuple<A_t, typename B::value_type>>> zip(std::initializer_list<A_t> &&a, B &&b){ return zip(a, b); } /** * @short zip two lists into a list of tuples. * * Specialization with the two as initializer list. */ template<typename A_t, typename B_t> inline sequence<std::vector<std::tuple<A_t, B_t>>> zip(std::initializer_list<A_t> &&a, std::initializer_list<B_t> &&b){ return zip(a, b); } /** * @short zip two lists into a list of tuples. * * Specialization with the second as a initializer list. */ template<typename A, typename B_t> inline sequence<std::vector<std::tuple<typename A::value_type, B_t>>> zip(A &&a, std::initializer_list<B_t> &&b){ return zip(a, b); } }; <|endoftext|>
<commit_before>/* * ecg.cpp * Author: Reece Stevens * Start Date: 4.6.15 * * The monitoring functions of the ECG probe for the * TEWH Patient Monitor. File still under construction. * * Function goals: * a. Detect the heart rate of the input signal * b. Detect abnormalities or changes in signal over time * * TODO: * 1. Fix heart rate function to use display fifo (more stable data) * 2. Use system interrupts to call the read() function * 3. Remove the arrays from the data structure (not needed) */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <avr/io.h> #include <avr/interrupt.h> #include "Vector.h" #include "ecg.h" // To determine heart rate, we need to know how fast // our system is sampling. volatile int avg_count = 0; // Constructor ECGReadout::ECGReadout(int coord_x, int coord_y, int width, int len, int pin, int reset_timer, Adafruit_ILI9341* tft):coord_x(coord_x), coord_y(coord_y), len(len), width(width), pin(pin),reset_timer(reset_timer), tft_interface(tft) { // Allocate space for one integer per pixel length-wise a fifo_multiplier = 9; fifo_size = width * fifo_multiplier; fifo = Vector<double> (fifo_size); averager_queue = Vector<double>(5); //this->fifo = fifo; display_fifo = Vector<double> (width); fifo_next = 0; fifo_end = 1; disp_start = fifo_next; disp_end = fifo_end; current_timer = 0; buffer_contents = 0; scaling_factor = len / 500; } void ECGReadout::draw(){ tft_interface->drawRect(coord_x,coord_y,len,width, ILI9341_BLACK); } /* * read() - read from analog pin and push data into circular fifo * */ void ECGReadout::read(){ //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_BLUE); if (avg_count < 5) { double input_num = (double) analogRead(pin); double adjusted_num = input_num * len; adjusted_num = (adjusted_num / 1023); // Put number in next location in fifo averager_queue[avg_count] = adjusted_num; avg_count += 1; //int result = fifo.set(fifo_next, adjusted_num); } else { avg_count = 0; double avg; for (uint32_t k = 0; k < 5; k += 1) { avg += averager_queue[k]; } avg /= 5; int result = fifo.set(fifo_next, avg); fifo_next = fifo_end; fifo_end = (fifo_end + 1) % fifo_size; } // Move our trackers //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_CYAN); } /* * display_signal() - clear previous signal and print existing signal onto display * */ void ECGReadout::display_signal(){ cli(); // Disable all interrupts //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_GREEN); // Trackers will always round down. Not ideal, but lets us shrink fifo size without much fuss. //nointerrupts(); int newest = fifo_next/fifo_multiplier; int oldest = fifo_end/fifo_multiplier; // Make our copy of the data so we can draw while the analog pin // keeps sampling and updating the buffer. Vector<double> new_input_data(fifo); sei(); // Re-enable all interrupts //interrupts(); Vector<double> new_display_data(width); for (uint32_t i = 0; i < fifo_size; i += fifo_multiplier) { double maximum = 0; for (uint32_t k = 0; k < fifo_multiplier; k += 1) { if (new_input_data[i+k] > maximum) { maximum = new_input_data[i+k]; } } new_display_data[i/fifo_multiplier] = maximum; } //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_WHITE); int i = 0; int line_thresh = 10; // Draw over old data in black and new data in white while ((((i + oldest + 1) % width) != newest)){ int k = (i + disp_end) % width; // Numerical position in old fifo vector (i is pixel location on screen) int prev = (i + disp_end + 1) % width; // Position of data point to be erased on display int new_k = (i + oldest) % width; // Numerical position in new fifo vector (i is pixel location on screen) int new_prev = (i + oldest + 1) % width; // Position of data point to be drawn on display /********* ERASING *********/ if ((display_fifo[k] - display_fifo[prev]) > line_thresh){ tft_interface->drawFastVLine(coord_x + i, (coord_y + len - display_fifo[k]), (display_fifo[k] - display_fifo[prev]), ILI9341_BLACK); //tft_interface->drawFastVLine(coord_x + i, (coord_y + display_fifo[k]), (display_fifo[k] - display_fifo[prev]), ILI9341_BLACK); } else if ((display_fifo[prev] - display_fifo[k]) > line_thresh){ tft_interface->drawFastVLine(coord_x + i, (coord_y + len - display_fifo[prev]), (display_fifo[prev] - display_fifo[k]), ILI9341_BLACK); //tft_interface->drawFastVLine(coord_x + i, (coord_y + display_fifo[prev]), (display_fifo[prev] - display_fifo[k]), ILI9341_BLACK); } else { // If not necessary, just color in the pixel tft_interface->drawPixel(coord_x + i, (coord_y + len - display_fifo[k]), ILI9341_BLACK); //tft_interface->drawPixel(coord_x + i, (coord_y + display_fifo[k]), ILI9341_BLACK); } /********* DRAWING *********/ if ((new_display_data[new_k] - new_display_data[new_prev]) > line_thresh){ tft_interface->drawFastVLine(coord_x + i, (coord_y + len - new_display_data[new_k]), (new_display_data[new_k] - new_display_data[new_prev]), ILI9341_WHITE); //tft_interface->drawFastVLine(coord_x + i, (coord_y + new_display_data[new_k]), (new_display_data[new_k] - new_display_data[new_prev]), ILI9341_WHITE); } else if ((new_display_data[new_prev] - new_display_data[new_k]) > line_thresh){ tft_interface->drawFastVLine(coord_x + i, (coord_y + len - new_display_data[new_prev]), (new_display_data[new_prev] - new_display_data[new_k]), ILI9341_WHITE); //tft_interface->drawFastVLine(coord_x + i, (coord_y + new_display_data[new_prev]), (new_display_data[new_prev] - new_display_data[new_k]), ILI9341_WHITE); } else { tft_interface->drawPixel(coord_x + i, (coord_y + len - new_display_data[new_k]), ILI9341_WHITE); } //tft_interface->drawPixel(coord_x + i, (coord_y + new_display_data[new_k]), ILI9341_WHITE); i += 1; } // Catch the last pixel tft_interface->drawPixel(coord_x + i, (coord_y + len - display_fifo[(i+1)%width]), ILI9341_BLACK); // Store our new display information for next time display_fifo = new_display_data; disp_start = newest; disp_end = oldest; //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_WHITE); } /* * ECGReadout::heart_rate() -- determine period of input signal * * Measure interval of "silence" between waves? */ int ECGReadout::heart_rate() { double sampling_period = 0.00827; // time between samples (in seconds) int threshold = 50; int wait = 15; int start = -1; int mid = -1; int finish = -1; // Calcluate the finite difference approximation for (int i = 0; i < (width - 1); i += 1){ // Find the first peak if ((display_fifo[i] > threshold) && (start == -1)){ start = i; wait = 0; } // Delay after we find the peak // so we don't detect another sample on the same peak if (wait < 15) { wait += 1; continue; } // Find the next peak if ((display_fifo[i] > threshold) && (mid == -1)){ mid = i; wait = 0; break; } if (wait < 15) { wait += 1; continue; } // Find the next peak if ((display_fifo[i] > threshold) && (finish == -1)){ finish = i; wait = 0; break; } } double heart_rate1; double heart_rate2; double heart_rate3; if ((mid != -1) && (start != -1)) { heart_rate1 = 60 / ((mid - start) * sampling_period); } else { return 0; } if (finish != -1) { heart_rate2 = 60 / ((finish - mid) * sampling_period); heart_rate3 = 120 / ((finish - start) * sampling_period); } else {return heart_rate1;} double maximum = 0; if ((heart_rate1 >= heart_rate2) && (heart_rate1 >= heart_rate3)) {return heart_rate1; } if ((heart_rate2 >= heart_rate1) && (heart_rate2 >= heart_rate3)) {return heart_rate2; } return heart_rate3; } <commit_msg>continuing work<commit_after>/* * ecg.cpp * Author: Reece Stevens * Start Date: 4.6.15 * * The monitoring functions of the ECG probe for the * TEWH Patient Monitor. File still under construction. * * Function goals: * a. Detect the heart rate of the input signal * b. Detect abnormalities or changes in signal over time * * TODO: * 1. Fix heart rate function to use display fifo (more stable data) * 2. Use system interrupts to call the read() function * 3. Remove the arrays from the data structure (not needed) */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <avr/io.h> #include <avr/interrupt.h> #include "Vector.h" #include "ecg.h" // To determine heart rate, we need to know how fast // our system is sampling. volatile int avg_count = 0; // Constructor ECGReadout::ECGReadout(int coord_x, int coord_y, int width, int len, int pin, int reset_timer, Adafruit_ILI9341* tft):coord_x(coord_x), coord_y(coord_y), len(len), width(width), pin(pin),reset_timer(reset_timer), tft_interface(tft) { // Allocate space for one integer per pixel length-wise a fifo_multiplier = 9; fifo_size = width * fifo_multiplier; fifo = Vector<double> (fifo_size); averager_queue = Vector<double>(5); //this->fifo = fifo; display_fifo = Vector<double> (width); fifo_next = 0; fifo_end = 1; disp_start = fifo_next; disp_end = fifo_end; current_timer = 0; buffer_contents = 0; scaling_factor = len / 500; } void ECGReadout::draw(){ tft_interface->drawRect(coord_x,coord_y,len,width, ILI9341_BLACK); } /* * read() - read from analog pin and push data into circular fifo * */ void ECGReadout::read(){ //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_BLUE); if (avg_count < 5) { double input_num = (double) analogRead(pin); double adjusted_num = input_num * len; adjusted_num = (adjusted_num / 1023); // Put number in next location in fifo averager_queue[avg_count] = adjusted_num; avg_count += 1; //int result = fifo.set(fifo_next, adjusted_num); } else { avg_count = 0; double avg; for (uint32_t k = 0; k < 5; k += 1) { avg += averager_queue[k]; } avg /= 5; int result = fifo.set(fifo_next, avg); fifo_next = fifo_end; fifo_end = (fifo_end + 1) % fifo_size; } // Move our trackers //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_CYAN); } /* * display_signal() - clear previous signal and print existing signal onto display * */ void ECGReadout::display_signal(){ cli(); // Disable all interrupts //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_GREEN); // Trackers will always round down. Not ideal, but lets us shrink fifo size without much fuss. //nointerrupts(); int newest = fifo_next/fifo_multiplier; int oldest = fifo_end/fifo_multiplier; // Make our copy of the data so we can draw while the analog pin // keeps sampling and updating the buffer. Vector<double> new_input_data(fifo); sei(); // Re-enable all interrupts //interrupts(); Vector<double> new_display_data(width); for (uint32_t i = 0; i < fifo_size; i += fifo_multiplier) { double maximum = 0; for (uint32_t k = 0; k < fifo_multiplier; k += 1) { if (new_input_data[i+k] > maximum) { maximum = new_input_data[i+k]; } } new_display_data[i/fifo_multiplier] = maximum; } //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_WHITE); int i = 0; int line_thresh = 10; // Draw over old data in black and new data in white while ((((i + oldest + 1) % width) != newest)){ int k = (i + disp_end) % width; // Numerical position in old fifo vector (i is pixel location on screen) int prev = (i + disp_end + 1) % width; // Position of data point to be erased on display int new_k = (i + oldest) % width; // Numerical position in new fifo vector (i is pixel location on screen) int new_prev = (i + oldest + 1) % width; // Position of data point to be drawn on display /********* ERASING *********/ if ((display_fifo[k] - display_fifo[prev]) > line_thresh){ tft_interface->drawFastVLine(coord_x + i, (coord_y + len - display_fifo[k]), (display_fifo[k] - display_fifo[prev]), ILI9341_BLACK); //tft_interface->drawFastVLine(coord_x + i, (coord_y + display_fifo[k]), (display_fifo[k] - display_fifo[prev]), ILI9341_BLACK); } else if ((display_fifo[prev] - display_fifo[k]) > line_thresh){ tft_interface->drawFastVLine(coord_x + i, (coord_y + len - display_fifo[prev]), (display_fifo[prev] - display_fifo[k]), ILI9341_BLACK); //tft_interface->drawFastVLine(coord_x + i, (coord_y + display_fifo[prev]), (display_fifo[prev] - display_fifo[k]), ILI9341_BLACK); } else { // If not necessary, just color in the pixel tft_interface->drawPixel(coord_x + i, (coord_y + len - display_fifo[k]), ILI9341_BLACK); //tft_interface->drawPixel(coord_x + i, (coord_y + display_fifo[k]), ILI9341_BLACK); } /********* DRAWING *********/ if ((new_display_data[new_k] - new_display_data[new_prev]) > line_thresh){ tft_interface->drawFastVLine(coord_x + i, (coord_y + len - new_display_data[new_k]), (new_display_data[new_k] - new_display_data[new_prev]), ILI9341_WHITE); //tft_interface->drawFastVLine(coord_x + i, (coord_y + new_display_data[new_k]), (new_display_data[new_k] - new_display_data[new_prev]), ILI9341_WHITE); } else if ((new_display_data[new_prev] - new_display_data[new_k]) > line_thresh){ tft_interface->drawFastVLine(coord_x + i, (coord_y + len - new_display_data[new_prev]), (new_display_data[new_prev] - new_display_data[new_k]), ILI9341_WHITE); //tft_interface->drawFastVLine(coord_x + i, (coord_y + new_display_data[new_prev]), (new_display_data[new_prev] - new_display_data[new_k]), ILI9341_WHITE); } else { tft_interface->drawPixel(coord_x + i, (coord_y + len - new_display_data[new_k]), ILI9341_WHITE); } //tft_interface->drawPixel(coord_x + i, (coord_y + new_display_data[new_k]), ILI9341_WHITE); i += 1; } // Catch the last pixel tft_interface->drawPixel(coord_x + i, (coord_y + len - display_fifo[(i+1)%width]), ILI9341_BLACK); // Store our new display information for next time display_fifo = new_display_data; disp_start = newest; disp_end = oldest; //tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_WHITE); } /* * ECGReadout::heart_rate() -- determine period of input signal * * Measure interval of "silence" between waves? */ int ECGReadout::heart_rate() { double sampling_period = 0.00827; // time between samples (in seconds) int threshold = 40; int wait = 15; int start = -1; int mid = -1; int finish = -1; // Calcluate the finite difference approximation for (int i = 0; i < (width - 1); i += 1){ // Find the first peak if ((display_fifo[i] > threshold) && (start == -1)){ start = i; wait = 0; } // Delay after we find the peak // so we don't detect another sample on the same peak if (wait < 15) { wait += 1; continue; } // Find the next peak if ((display_fifo[i] > threshold) && (mid == -1)){ mid = i; wait = 0; break; } if (wait < 15) { wait += 1; continue; } // Find the next peak if ((display_fifo[i] > threshold) && (finish == -1)){ finish = i; wait = 0; break; } } double heart_rate1; double heart_rate2; double heart_rate3; if ((mid != -1) && (start != -1)) { heart_rate1 = 60 / ((mid - start) * sampling_period); } else { return 0; } if (finish != -1) { heart_rate2 = 60 / ((finish - mid) * sampling_period); heart_rate3 = 120 / ((finish - start) * sampling_period); } else {return heart_rate1;} double maximum = 0; if ((heart_rate1 >= heart_rate2) && (heart_rate1 >= heart_rate3)) {return heart_rate1; } if ((heart_rate2 >= heart_rate1) && (heart_rate2 >= heart_rate3)) {return heart_rate2; } return heart_rate3; } <|endoftext|>
<commit_before>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "sal.h" #include "gcenv.structs.h" #include "gcenv.base.h" #include <stdlib.h> #ifndef CPPCODEGEN // // This is the mechanism whereby multiple linked modules contribute their global data for initialization at // startup of the application. // // ILC creates sections in the output obj file to mark the beginning and end of merged global data. // It defines sentinel symbols that are used to get the addresses of the start and end of global data // at runtime. The section names are platform-specific to match platform-specific linker conventions. // #if defined(_MSC_VER) #pragma section(".modules$A", read) #pragma section(".modules$Z", read) extern "C" __declspec(allocate(".modules$A")) void * __modules_a[]; extern "C" __declspec(allocate(".modules$Z")) void * __modules_z[]; __declspec(allocate(".modules$A")) void * __modules_a[] = { nullptr }; __declspec(allocate(".modules$Z")) void * __modules_z[] = { nullptr }; // // Each obj file compiled from managed code has a .modules$I section containing a pointer to its ReadyToRun // data (which points at eager class constructors, frozen strings, etc). // // The #pragma ... /merge directive folds the book-end sections and all .modules$I sections from all input // obj files into .rdata in alphabetical order. // #pragma comment(linker, "/merge:.modules=.rdata") extern "C" void __managedcode_a(); extern "C" void __managedcode_z(); #else // _MSC_VER #if defined(__APPLE__) extern void * __modules_a[] __asm("section$start$__DATA$__modules"); extern void * __modules_z[] __asm("section$end$__DATA$__modules"); extern char __managedcode_a __asm("section$start$__TEXT$__managedcode"); extern char __managedcode_z __asm("section$end$__TEXT$__managedcode"); #else // __APPLE__ extern "C" void * __start___modules[]; extern "C" void * __stop___modules[]; static void * (&__modules_a)[] = __start___modules; static void * (&__modules_z)[] = __stop___modules; extern "C" char __start___managedcode; extern "C" char __stop___managedcode; static char& __managedcode_a = __start___managedcode; static char& __managedcode_z = __stop___managedcode; #endif // __APPLE__ #endif // _MSC_VER #endif // !CPPCODEGEN #ifdef CPPCODEGEN #pragma warning(disable:4297) extern "C" Object * RhNewObject(MethodTable * pMT); extern "C" Object * RhNewArray(MethodTable * pMT, int32_t elements); extern "C" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT); extern "C" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT); extern "C" void RhpStelemRef(void * pArray, int index, void * pObj); extern "C" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT); extern "C" __NORETURN void RhpThrowEx(void * pEx); extern "C" Object * __allocate_object(MethodTable * pMT) { return RhNewObject(pMT); } extern "C" Object * __allocate_array(size_t elements, MethodTable * pMT) { return RhNewArray(pMT, (int32_t)elements); // TODO: type mismatch } extern "C" Object * __castclass(void * obj, MethodTable * pTargetMT) { return (Object *)RhTypeCast_CheckCast(obj, pTargetMT); } extern "C" Object * __isinst(void * obj, MethodTable * pTargetMT) { return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT); } extern "C" void __stelem_ref(void * pArray, unsigned idx, void * obj) { RhpStelemRef(pArray, idx, obj); } extern "C" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type) { return RhpLdelemaRef(pArray, idx, type); } extern "C" void __throw_exception(void * pEx) { RhpThrowEx(pEx); } void __range_check_fail() { throw "ThrowRangeOverflowException"; } extern "C" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame); extern "C" void RhpReversePInvokeReturn2(ReversePInvokeFrame* pRevFrame); void __reverse_pinvoke(ReversePInvokeFrame* pRevFrame) { RhpReversePInvoke2(pRevFrame); } void __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame) { RhpReversePInvokeReturn2(pRevFrame); } namespace System_Private_CoreLib { namespace System { class Object { public: MethodTable * get_EEType() { return *(MethodTable **)this; } }; class Array : public Object { public: int32_t GetArrayLength() { return *(int32_t *)((void **)this + 1); } void * GetArrayData() { return (void **)this + 2; } }; class String : public Object { public: static MethodTable * __getMethodTable(); }; class String__Array : public Object { public: static MethodTable * __getMethodTable(); }; class EETypePtr { public: intptr_t m_value; }; }; }; Object * __load_string_literal(const char * string) { // TODO: Cache/intern string literals // TODO: Unicode string literals size_t len = strlen(string); Object * pString = RhNewArray(System_Private_CoreLib::System::String::__getMethodTable(), (int32_t)len); uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t)); for (size_t i = 0; i < len; i++) p[i] = string[i]; return pString; } extern "C" void RhpThrowEx(void * pEx) { throw "RhpThrowEx"; } extern "C" void RhpThrowHwEx() { throw "RhpThrowHwEx"; } extern "C" void RhpCallCatchFunclet() { throw "RhpCallCatchFunclet"; } extern "C" void RhpCallFilterFunclet() { throw "RhpCallFilterFunclet"; } extern "C" void RhpCallFinallyFunclet() { throw "RhpCallFinallyFunclet"; } extern "C" void RhpUniversalTransition() { throw "RhpUniversalTransition"; } extern "C" void RhpUniversalTransition_DebugStepTailCall() { throw "RhpUniversalTransition_DebugStepTailCall"; } void* RtRHeaderWrapper(); #endif // CPPCODEGEN extern "C" void __fail_fast() { // TODO: FailFast throw "__fail_fast"; } extern "C" void RhpEtwExceptionThrown() { throw "RhpEtwExceptionThrown"; } extern "C" bool REDHAWK_PALAPI PalInit(); #define DLL_PROCESS_ATTACH 1 extern "C" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved); extern "C" int32_t RhpEnableConservativeStackReporting(); extern "C" void RhpShutdown(); #ifndef CPPCODEGEN extern "C" bool RhpRegisterCoffModule(void * pModule, void * pvStartRange, uint32_t cbRange, void ** pClasslibFunctions, uint32_t nClasslibFunctions); extern "C" bool RhpRegisterUnixModule(void * pModule, void * pvStartRange, uint32_t cbRange, void ** pClasslibFunctions, uint32_t nClasslibFunctions); #ifdef _WIN32 extern "C" void* WINAPI GetModuleHandleW(const wchar_t *); #else extern "C" void* WINAPI PalGetModuleHandleFromPointer(void* pointer); #endif extern "C" void GetRuntimeException(); extern "C" void FailFast(); extern "C" void AppendExceptionStackFrame(); typedef void(*pfn)(); static const pfn c_classlibFunctions[] = { &GetRuntimeException, &FailFast, nullptr, // &UnhandledExceptionHandler, &AppendExceptionStackFrame, }; #endif // !CPPCODEGEN extern "C" void InitializeModules(void ** modules, int count); #if defined(_WIN32) extern "C" int __managed__Main(int argc, wchar_t* argv[]); int wmain(int argc, wchar_t* argv[]) #else extern "C" int __managed__Main(int argc, char* argv[]); int main(int argc, char* argv[]) #endif { if (!PalInit()) return -1; if (!RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL)) return -1; if (!RhpEnableConservativeStackReporting()) return -1; #ifndef CPPCODEGEN #if defined(_WIN32) if (!RhpRegisterCoffModule(GetModuleHandleW(NULL), #else // _WIN32 if (!RhpRegisterUnixModule(PalGetModuleHandleFromPointer((void*)&main), #endif // _WIN32 (void*)&__managedcode_a, (uint32_t)((char *)&__managedcode_z - (char*)&__managedcode_a), (void **)&c_classlibFunctions, _countof(c_classlibFunctions))) { return -1; } #endif // !CPPCODEGEN #ifdef CPPCODEGEN ReversePInvokeFrame frame; __reverse_pinvoke(&frame); #endif #ifndef CPPCODEGEN InitializeModules(__modules_a, (int)((__modules_z - __modules_a))); #else // !CPPCODEGEN InitializeModules((void**)RtRHeaderWrapper(), 2); #endif // !CPPCODEGEN int retval; try { retval = __managed__Main(argc, argv); } catch (const char* &e) { printf("Call to an unimplemented runtime method; execution cannot continue.\n"); printf("Method: %s\n", e); retval = -1; } #ifdef CPPCODEGEN __reverse_pinvoke_return(&frame); #endif RhpShutdown(); return retval; } <commit_msg>Fix native build warnings (#2448)<commit_after>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "sal.h" #include "gcenv.structs.h" #include "gcenv.base.h" #include <stdlib.h> #ifndef CPPCODEGEN // // This is the mechanism whereby multiple linked modules contribute their global data for initialization at // startup of the application. // // ILC creates sections in the output obj file to mark the beginning and end of merged global data. // It defines sentinel symbols that are used to get the addresses of the start and end of global data // at runtime. The section names are platform-specific to match platform-specific linker conventions. // #if defined(_MSC_VER) #pragma section(".modules$A", read) #pragma section(".modules$Z", read) extern "C" __declspec(allocate(".modules$A")) void * __modules_a[]; extern "C" __declspec(allocate(".modules$Z")) void * __modules_z[]; __declspec(allocate(".modules$A")) void * __modules_a[] = { nullptr }; __declspec(allocate(".modules$Z")) void * __modules_z[] = { nullptr }; // // Each obj file compiled from managed code has a .modules$I section containing a pointer to its ReadyToRun // data (which points at eager class constructors, frozen strings, etc). // // The #pragma ... /merge directive folds the book-end sections and all .modules$I sections from all input // obj files into .rdata in alphabetical order. // #pragma comment(linker, "/merge:.modules=.rdata") extern "C" void __managedcode_a(); extern "C" void __managedcode_z(); #else // _MSC_VER #if defined(__APPLE__) extern void * __modules_a[] __asm("section$start$__DATA$__modules"); extern void * __modules_z[] __asm("section$end$__DATA$__modules"); extern char __managedcode_a __asm("section$start$__TEXT$__managedcode"); extern char __managedcode_z __asm("section$end$__TEXT$__managedcode"); #else // __APPLE__ extern "C" void * __start___modules[]; extern "C" void * __stop___modules[]; static void * (&__modules_a)[] = __start___modules; static void * (&__modules_z)[] = __stop___modules; extern "C" char __start___managedcode; extern "C" char __stop___managedcode; static char& __managedcode_a = __start___managedcode; static char& __managedcode_z = __stop___managedcode; #endif // __APPLE__ #endif // _MSC_VER #endif // !CPPCODEGEN #ifdef CPPCODEGEN #pragma warning(disable:4297) extern "C" Object * RhNewObject(MethodTable * pMT); extern "C" Object * RhNewArray(MethodTable * pMT, int32_t elements); extern "C" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT); extern "C" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT); extern "C" void RhpStelemRef(void * pArray, int index, void * pObj); extern "C" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT); extern "C" __NORETURN void RhpThrowEx(void * pEx); extern "C" Object * __allocate_object(MethodTable * pMT) { return RhNewObject(pMT); } extern "C" Object * __allocate_array(size_t elements, MethodTable * pMT) { return RhNewArray(pMT, (int32_t)elements); // TODO: type mismatch } extern "C" Object * __castclass(void * obj, MethodTable * pTargetMT) { return (Object *)RhTypeCast_CheckCast(obj, pTargetMT); } extern "C" Object * __isinst(void * obj, MethodTable * pTargetMT) { return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT); } extern "C" void __stelem_ref(void * pArray, unsigned idx, void * obj) { RhpStelemRef(pArray, idx, obj); } extern "C" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type) { return RhpLdelemaRef(pArray, idx, type); } extern "C" void __throw_exception(void * pEx) { RhpThrowEx(pEx); } void __range_check_fail() { throw "ThrowRangeOverflowException"; } extern "C" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame); extern "C" void RhpReversePInvokeReturn2(ReversePInvokeFrame* pRevFrame); void __reverse_pinvoke(ReversePInvokeFrame* pRevFrame) { RhpReversePInvoke2(pRevFrame); } void __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame) { RhpReversePInvokeReturn2(pRevFrame); } namespace System_Private_CoreLib { namespace System { class Object { public: MethodTable * get_EEType() { return *(MethodTable **)this; } }; class Array : public Object { public: int32_t GetArrayLength() { return *(int32_t *)((void **)this + 1); } void * GetArrayData() { return (void **)this + 2; } }; class String : public Object { public: static MethodTable * __getMethodTable(); }; class String__Array : public Object { public: static MethodTable * __getMethodTable(); }; class EETypePtr { public: intptr_t m_value; }; }; }; Object * __load_string_literal(const char * string) { // TODO: Cache/intern string literals // TODO: Unicode string literals size_t len = strlen(string); Object * pString = RhNewArray(System_Private_CoreLib::System::String::__getMethodTable(), (int32_t)len); uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t)); for (size_t i = 0; i < len; i++) p[i] = string[i]; return pString; } extern "C" void RhpThrowEx(void * pEx) { throw "RhpThrowEx"; } extern "C" void RhpThrowHwEx() { throw "RhpThrowHwEx"; } extern "C" void RhpCallCatchFunclet() { throw "RhpCallCatchFunclet"; } extern "C" void RhpCallFilterFunclet() { throw "RhpCallFilterFunclet"; } extern "C" void RhpCallFinallyFunclet() { throw "RhpCallFinallyFunclet"; } extern "C" void RhpUniversalTransition() { throw "RhpUniversalTransition"; } extern "C" void RhpUniversalTransition_DebugStepTailCall() { throw "RhpUniversalTransition_DebugStepTailCall"; } void* RtRHeaderWrapper(); #endif // CPPCODEGEN extern "C" void __fail_fast() { // TODO: FailFast printf("Call to an unimplemented runtime method; execution cannot continue.\n"); printf("Method: __fail_fast\n"); exit(-1); } extern "C" bool REDHAWK_PALAPI PalInit(); #define DLL_PROCESS_ATTACH 1 extern "C" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved); extern "C" int32_t RhpEnableConservativeStackReporting(); extern "C" void RhpShutdown(); #ifndef CPPCODEGEN extern "C" bool RhpRegisterCoffModule(void * pModule, void * pvStartRange, uint32_t cbRange, void ** pClasslibFunctions, uint32_t nClasslibFunctions); extern "C" bool RhpRegisterUnixModule(void * pModule, void * pvStartRange, uint32_t cbRange, void ** pClasslibFunctions, uint32_t nClasslibFunctions); #ifdef _WIN32 extern "C" void* WINAPI GetModuleHandleW(const wchar_t *); #else extern "C" void* WINAPI PalGetModuleHandleFromPointer(void* pointer); #endif extern "C" void GetRuntimeException(); extern "C" void FailFast(); extern "C" void AppendExceptionStackFrame(); typedef void(*pfn)(); static const pfn c_classlibFunctions[] = { &GetRuntimeException, &FailFast, nullptr, // &UnhandledExceptionHandler, &AppendExceptionStackFrame, }; #endif // !CPPCODEGEN extern "C" void InitializeModules(void ** modules, int count); #if defined(_WIN32) extern "C" int __managed__Main(int argc, wchar_t* argv[]); int wmain(int argc, wchar_t* argv[]) #else extern "C" int __managed__Main(int argc, char* argv[]); int main(int argc, char* argv[]) #endif { if (!PalInit()) return -1; if (!RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL)) return -1; if (!RhpEnableConservativeStackReporting()) return -1; #ifndef CPPCODEGEN #if defined(_WIN32) if (!RhpRegisterCoffModule(GetModuleHandleW(NULL), #else // _WIN32 if (!RhpRegisterUnixModule(PalGetModuleHandleFromPointer((void*)&main), #endif // _WIN32 (void*)&__managedcode_a, (uint32_t)((char *)&__managedcode_z - (char*)&__managedcode_a), (void **)&c_classlibFunctions, _countof(c_classlibFunctions))) { return -1; } #endif // !CPPCODEGEN #ifdef CPPCODEGEN ReversePInvokeFrame frame; __reverse_pinvoke(&frame); #endif #ifndef CPPCODEGEN InitializeModules(__modules_a, (int)((__modules_z - __modules_a))); #else // !CPPCODEGEN InitializeModules((void**)RtRHeaderWrapper(), 2); #endif // !CPPCODEGEN int retval; try { retval = __managed__Main(argc, argv); } catch (const char* &e) { printf("Call to an unimplemented runtime method; execution cannot continue.\n"); printf("Method: %s\n", e); retval = -1; } #ifdef CPPCODEGEN __reverse_pinvoke_return(&frame); #endif RhpShutdown(); return retval; } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "stx/protobuf/JSONEncoder.h" #include "logjoin/SessionContext.h" using namespace stx; namespace cm { JoinedEvent::JoinedEvent( RefPtr<msg::MessageSchema> _schema) : schema(_schema) {} void JoinedEvent::addUInt32Field(const String& name, uint32_t val) { if (!schema->hasField(name)) { return; } auto field_id = schema->fieldId(name); if (schema->fieldType(field_id) != msg::FieldType::UINT32) { return; } data.addChild(field_id, uint32_t(val)); } void JoinedEvent::addBoolField(const String& name, bool val) { if (!schema->hasField(name)) { return; } auto field_id = schema->fieldId(name); if (schema->fieldType(field_id) != msg::FieldType::BOOLEAN) { return; } if (val) { data.addChild(field_id, msg::TRUE); } else { data.addChild(field_id, msg::FALSE); } } void JoinedEvent::addStringField(const String& name, const String& value) { if (!schema->hasField(name)) { return; } auto field_id = schema->fieldId(name); if (schema->fieldType(field_id) != msg::FieldType::STRING) { return; } data.addChild(field_id, value); } void JoinedEvent::addObject( const String& name, Function<void (JoinedEvent* ev)> fn) { if (!schema->hasField(name)) { return; } auto field_id = schema->fieldId(name); if (schema->fieldType(field_id) != msg::FieldType::OBJECT) { return; } auto subschema = schema->fieldSchema(field_id); JoinedEvent subev(subschema); fn(&subev); subev.data.id = field_id; data.addChild(subev.data); } void JoinedEvent::toJSON(json::JSONOutputStream* json) const { json->beginObject(); json->addObjectEntry("type"); json->addString(schema->name()); json->addComma(); json->addObjectEntry("data"); msg::JSONEncoder::encode(data, *schema, json); json->endObject(); } SessionContext::SessionContext( TrackedSession session, RefPtr<CustomerConfigRef> cconf) : uuid(session.uuid), customer_key(session.customer_key), events(session.events), customer_config(cconf) {} JoinedEvent* SessionContext::addOutputEvent(const String& evtype) { const auto& logjoin_cfg = customer_config->config.logjoin_config(); for (const auto& evschema : logjoin_cfg.session_events()) { if (evschema.evtype() == evtype) { auto schema = msg::MessageSchema::decode(evschema.schema()); auto event = new JoinedEvent(schema); output_events_.emplace_back(event); return event; } } RAISEF(kNotFoundError, "event schema not found: $0", evtype); return nullptr; } const Vector<ScopedPtr<JoinedEvent>>& SessionContext::outputEvents() const { return output_events_; } } // namespace cm <commit_msg>debug log<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "stx/protobuf/JSONEncoder.h" #include "logjoin/SessionContext.h" using namespace stx; namespace cm { JoinedEvent::JoinedEvent( RefPtr<msg::MessageSchema> _schema) : schema(_schema) {} void JoinedEvent::addUInt32Field(const String& name, uint32_t val) { if (!schema->hasField(name)) { return; } auto field_id = schema->fieldId(name); if (schema->fieldType(field_id) != msg::FieldType::UINT32) { return; } data.addChild(field_id, uint32_t(val)); } void JoinedEvent::addBoolField(const String& name, bool val) { if (!schema->hasField(name)) { return; } auto field_id = schema->fieldId(name); if (schema->fieldType(field_id) != msg::FieldType::BOOLEAN) { return; } if (val) { data.addChild(field_id, msg::TRUE); } else { data.addChild(field_id, msg::FALSE); } } void JoinedEvent::addStringField(const String& name, const String& value) { if (!schema->hasField(name)) { return; } auto field_id = schema->fieldId(name); if (schema->fieldType(field_id) != msg::FieldType::STRING) { return; } data.addChild(field_id, value); } void JoinedEvent::addObject( const String& name, Function<void (JoinedEvent* ev)> fn) { if (!schema->hasField(name)) { return; } auto field_id = schema->fieldId(name); if (schema->fieldType(field_id) != msg::FieldType::OBJECT) { return; } auto subschema = schema->fieldSchema(field_id); JoinedEvent subev(subschema); fn(&subev); subev.data.id = field_id; data.addChild(subev.data); } void JoinedEvent::toJSON(json::JSONOutputStream* json) const { json->beginObject(); json->addObjectEntry("type"); json->addString(schema->name()); json->addComma(); json->addObjectEntry("data"); msg::JSONEncoder::encode(data, *schema, json); json->endObject(); } SessionContext::SessionContext( TrackedSession session, RefPtr<CustomerConfigRef> cconf) : uuid(session.uuid), customer_key(session.customer_key), events(session.events), customer_config(cconf) {} JoinedEvent* SessionContext::addOutputEvent(const String& evtype) { const auto& logjoin_cfg = customer_config->config.logjoin_config(); for (const auto& evschema : logjoin_cfg.session_events()) { if (evschema.evtype() == evtype) { auto schema = msg::MessageSchema::decode(evschema.schema()); auto event = new JoinedEvent(schema); output_events_.emplace_back(event); return event; } } RAISEF(kNotFoundError, "event schema not found: $0 -- $1", evtype, logjoin_cfg.DebugString()); return nullptr; } const Vector<ScopedPtr<JoinedEvent>>& SessionContext::outputEvents() const { return output_events_; } } // namespace cm <|endoftext|>
<commit_before> #include "accurate_intersections_approx.hpp" #include "accurate_intersections_incprec.hpp" #include "accurate_intersections_resultant.hpp" #include "geometry.hpp" #include "line.hpp" #include "quadric.hpp" #include "quadric_classify.hpp" #include "timer.hpp" #include <fstream> #include <iomanip> #include <list> #include <random> #include <signal.h> #include <unistd.h> struct GlobalVars { bool run = true; } globals; void sigInt(int signum) { globals.run = false; } template <int dim, typename fptype> std::list<Geometry::Quadric<dim, fptype>> parseQuadrics( const char *fname, int *minExp, int *maxExp) { std::ifstream file(fname); if(!file.is_open()) { return std::list<Geometry::Quadric<dim, fptype>>(); } int buf = 0; file >> buf; if(minExp != NULL) { *minExp = buf; } file >> buf; if(maxExp != NULL) { *maxExp = buf; } if(*minExp > 0) { std::cout << "Cannot generate a line with these exponents\n" << *minExp << ", " << *maxExp << "\n"; exit(1); } std::cout << "Using " << *minExp << ", " << *maxExp << " as the range of exponents\n"; using Qf = Geometry::Quadric<dim, fptype>; int qtypeCount[QuadricClassify::QUADT_ERRORINVALID]; for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID; i++) qtypeCount[i] = 0; std::list<Qf> quads; int imQuads = 0; int numQuads = 0; while(!file.eof()) { Qf q; file >> q; QuadricClassify::QuadType type = QuadricClassify::classifyQuadric(q); if(!QuadricClassify::isImaginary(type) && type != QuadricClassify::QUADT_ERROR && type != QuadricClassify::QUADT_DEGENERATE && type != QuadricClassify::QUADT_ERRORINVALID) { quads.push_back(q); qtypeCount[type]++; } else { std::cout << "Quadric " << numQuads << " is invalid, returned type " << QuadricClassify::QuadTypeNames[type] << "\n"; imQuads++; } numQuads++; } for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID; i++) { std::cout << qtypeCount[i] << " " << QuadricClassify::QuadTypeNames[i] << "\n"; } return quads; } bool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) { /* Use a heuristic on truth to determine whether adjacent * intersections occur at the same place. * This will basically be a threshold on the largest * different bit in the mantissa. */ /* A relative heuristic does not work when one (or both!) * is 0 */ if(int1 == 0.0 || int2 == 0.0) { constexpr const double eps = 0.000001; return (mpfr::fabs(int1 - int2) < eps); } mpfr::mpreal largest = mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2)); mp_exp_t largestExp = largest.get_exp(); mpfr::mpreal diff = mpfr::fabs(int1 - int2); int p1 = int1.getPrecision(), p2 = int2.getPrecision(); int minPrec = std::min(p1, p2); mp_exp_t maxExp = largestExp - minPrec * 1 / 48, diffExp = diff.get_exp(); return maxExp >= diffExp; } template <typename ListTest, typename ListTrue> bool validateResults(ListTest &inter, ListTrue &truth) { /* Note that because the same method is used to determine * if an intersection is in the list, these lists will be * the same length */ if(inter->size() != truth->size()) { return false; } auto j = truth->begin(); for(auto i = inter->begin(); i != inter->end() || j != truth->end(); i++, j++) { if(i->q != j->q || i->intPos != j->intPos) { return false; } } return true; } template <typename List> int countIP(List inter) { int numIP = 0; for(auto i : *inter) numIP += i.incPrecCount(); return numIP; } using rngAlg = std::mt19937_64; template <int dim, typename fptype> using randLineGen = Geometry::Line<dim, fptype> (*)( rngAlg &rng, int minExp, int maxExp); template <int dim, typename fptype, typename cmpAlg> std::shared_ptr<std::list<cmpAlg>> __attribute__((noinline)) runTest( std::list<Geometry::Quadric<dim, fptype>> &quads, Geometry::Line<dim, fptype> &line, Timer::Timer &timer, double eps = std::numeric_limits<fptype>::infinity()) { timer.startTimer(); auto inter = Geometry::sortIntersections<dim, fptype, cmpAlg>( line, quads, fptype(eps)); timer.stopTimer(); return inter; } template <int dim, typename fptype> void intersectionTest( std::list<Geometry::Quadric<dim, fptype>> &quads, std::ostream &results, const int numTests, randLineGen<dim, fptype> rlgf, int minExp, int maxExp) { /* First build a scene of quadrics. * Then generate random lines on a disk centered at the * intersection of the cylinders. * Then sort the intersections * Finally validate them with a higher precision sort */ using Vf = Geometry::Vector<dim, fptype>; using Pf = Geometry::Point<dim, fptype>; using Lf = Geometry::Line<dim, fptype>; std::random_device rd; rngAlg engine(rd()); const double eps = 0.75 / (2 * quads.size()); constexpr const int numTestTypes = 3; Timer::Timer testTimes[numTestTypes]; struct TimeArr { struct TestData { long long ns; int numIP; bool correct; } mpTime, fpTime, resTime; } *times = new struct TimeArr[numTests]; /* Run the tests */ int t; for(t = 0; t < numTests && globals.run; t++) { Lf line = rlgf(engine, minExp, maxExp); /* Then sort the intersections */ auto resultant = runTest< dim, fptype, Geometry::IntersectionResultant<dim, fptype>>( quads, line, testTimes[0], eps); auto fpApproximate = runTest< dim, fptype, Geometry::IntersectionApproximate<dim, fptype>>( quads, line, testTimes[1], eps); auto mpApproximate = runTest< dim, fptype, Geometry::IntersectionIncreasedPrec<dim, fptype>>( quads, line, testTimes[2], eps); times[t].resTime.ns = testTimes[0].instant_ns(); times[t].fpTime.ns = testTimes[1].instant_ns(); times[t].mpTime.ns = testTimes[2].instant_ns(); times[t].mpTime.correct = validateResults(mpApproximate, resultant); times[t].fpTime.correct = validateResults(fpApproximate, resultant); times[t].resTime.numIP = countIP(resultant); times[t].fpTime.numIP = countIP(fpApproximate); times[t].mpTime.numIP = countIP(mpApproximate); } /* Output all of the results */ results << "Test #, Approximate Times (ns), Approximates " "Correct, Increased Precs, MP Time (ns), MP " "Correct, Resultants, Resultant Time (ns)\n"; int resTotIP = 0; int fpTotIP = 0; int mpTotIP = 0; int mpTotIncorrect = 0; int fpTotIncorrect = 0; for(int i = 0; i < t; i++) { results << i + 1 << ", " << times[i].fpTime.ns << ", " << times[i].fpTime.correct << ", " << times[i].mpTime.numIP << ", " << times[i].mpTime.ns << ", " << times[i].mpTime.correct << ", " << times[i].resTime.numIP << ", " << times[i].resTime.ns << "\n"; resTotIP += times[i].resTime.numIP; mpTotIP += times[i].mpTime.numIP; fpTotIncorrect += 1 - times[i].fpTime.correct; mpTotIncorrect += 1 - times[i].mpTime.correct; } results << "\n" << "Total FP Time: " << testTimes[1].elapsed_s() << "." << std::setw(9) << std::setfill('0') << testTimes[1].elapsed_ns() << "\n" << "Total FP Disagreements: " << fpTotIncorrect << "\n\n" << "Total MP Computations: " << mpTotIP << "\n" << "Total MP Time (s): " << testTimes[2].elapsed_s() << "." << std::setw(9) << std::setfill('0') << testTimes[2].elapsed_ns() << "\n" << "Total Resultant Disagreements: " << mpTotIncorrect << "\n\n" << "Total Resultant Computations: " << resTotIP << "\n" << "Total Resultant Time (s): " << testTimes[0].elapsed_s() << "." << std::setw(9) << std::setfill('0') << testTimes[0].elapsed_ns() << "\n"; delete[] times; } void lockCPU() { const int numCPUs = sysconf(_SC_NPROCESSORS_ONLN); const int cpuSets = numCPUs / CPU_SETSIZE + ((numCPUs % CPU_SETSIZE) > 0); cpu_set_t *cpus = new cpu_set_t[cpuSets]; const size_t cpuSize = sizeof(cpu_set_t[cpuSets]); sched_getaffinity(0, cpuSize, cpus); for(int i = 1; i < numCPUs; i++) CPU_CLR(i, cpus); CPU_SET(0, cpus); sched_setaffinity(0, cpuSize, cpus); delete[] cpus; } template <typename fptype> bool checkExp(fptype fpVal, int minExp, int maxExp) { if(fpVal == fptype(0.0)) { return true; } GenericFP::fpconvert<fptype> *fpbits = reinterpret_cast<GenericFP::fpconvert<fptype> *>( &fpVal); int exponent = fpbits->exponent; exponent -= fpbits->centralExp; if(exponent < minExp || exponent > maxExp) { return false; } else { return true; } } template <int dim, typename fptype> Geometry::Line<dim, fptype> defRandLine(rngAlg &rng, int minExp, int maxExp) { constexpr const fptype minPos = 0, maxPos = 1; std::uniform_real_distribution<fptype> genPos(minPos, maxPos); std::uniform_real_distribution<fptype> genDir(-1.0, 1.0); /* First build the line */ Geometry::Vector<dim, fptype> lineDir; Geometry::Vector<dim, fptype> lineInt; for(int i = 0; i < dim; i++) { do { lineInt.set(i, genPos(rng)); } while(checkExp(lineInt.get(i), minExp, maxExp) == false); do { lineDir.set(i, genDir(rng)); } while(checkExp(lineDir.get(i), minExp, maxExp) == false); } return Geometry::Line<dim, fptype>( Geometry::Point<dim, fptype>(lineInt), lineInt); } template <int dim, typename fptype> Geometry::Line<dim, fptype> nestedEllRandLine(rngAlg &rng, int minExp, int maxExp) { constexpr const fptype minPos = 0.0, maxPos = 1.0; std::uniform_real_distribution<fptype> genPos(minPos, maxPos); Geometry::Vector<dim, fptype> lineInt; for(int i = 0; i < dim; i++) { fptype tmp = genPos(rng); lineInt.set(i, genPos(rng)); } /* Direct the line towards (1.0, 0.5, 0.5) */ const Geometry::Vector<dim, fptype> destination( {1.0, 0.5, 0.5}); Geometry::Vector<dim, fptype> lineDir = destination - lineInt; return Geometry::Line<dim, fptype>( Geometry::Point<dim, fptype>(lineInt), lineDir); } template <int dim, typename fptype> Geometry::Line<dim, fptype> cylRandLine(rngAlg &rng, int minExp, int maxExp) { constexpr const fptype minPos = 0.375, maxPos = 0.625; std::uniform_real_distribution<fptype> genPos(minPos, maxPos); std::uniform_real_distribution<fptype> genDir(-1.0, 1.0); /* First build the line */ Geometry::Vector<dim, fptype> lineDir; Geometry::Vector<dim, fptype> lineInt; lineInt.set(1, genPos(rng)); for(int i = 0; i < dim; i++) { lineInt.set(i, lineInt.get(1)); lineDir.set(i, genDir(rng)); } lineInt.set(0, genPos(rng)); return Geometry::Line<dim, fptype>( Geometry::Point<dim, fptype>(lineInt), lineInt); } int main(int argc, char **argv) { using fptype = float; constexpr const int dim = 3; lockCPU(); std::list<Geometry::Quadric<dim, fptype>> quads; const char *outFName = "results"; int numTests = 1e4; int minExp, maxExp; if(argc > 1) { quads = parseQuadrics<dim, fptype>(argv[1], &minExp, &maxExp); } else { quads = parseQuadrics<dim, fptype>("cylinders.csg", &minExp, &maxExp); } if(argc > 2) { outFName = argv[2]; } if(argc > 3) { numTests = atoi(argv[3]); } randLineGen<dim, fptype> rlg = cylRandLine<dim, fptype>; if(argc > 4) { int lineGenAlg = atoi(argv[4]); switch(lineGenAlg) { case 1: rlg = nestedEllRandLine<dim, fptype>; break; case 2: rlg = cylRandLine<dim, fptype>; break; default: rlg = defRandLine<dim, fptype>; } } std::ofstream results(outFName); signal(SIGINT, sigInt); intersectionTest(quads, results, numTests, rlg, minExp, maxExp); return 0; } <commit_msg>Fixed epsilon used, also fixed output<commit_after> #include "accurate_intersections_approx.hpp" #include "accurate_intersections_incprec.hpp" #include "accurate_intersections_resultant.hpp" #include "geometry.hpp" #include "line.hpp" #include "quadric.hpp" #include "quadric_classify.hpp" #include "timer.hpp" #include <fstream> #include <iomanip> #include <list> #include <random> #include <signal.h> #include <unistd.h> struct GlobalVars { bool run = true; } globals; void sigInt(int signum) { globals.run = false; } template <int dim, typename fptype> std::list<Geometry::Quadric<dim, fptype>> parseQuadrics( const char *fname, int *minExp, int *maxExp) { std::ifstream file(fname); if(!file.is_open()) { return std::list<Geometry::Quadric<dim, fptype>>(); } int buf = 0; file >> buf; if(minExp != NULL) { *minExp = buf; } file >> buf; if(maxExp != NULL) { *maxExp = buf; } if(*minExp > 0) { std::cout << "Cannot generate a line with these exponents\n" << *minExp << ", " << *maxExp << "\n"; exit(1); } std::cout << "Using " << *minExp << ", " << *maxExp << " as the range of exponents\n"; using Qf = Geometry::Quadric<dim, fptype>; int qtypeCount[QuadricClassify::QUADT_ERRORINVALID]; for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID; i++) qtypeCount[i] = 0; std::list<Qf> quads; int imQuads = 0; int numQuads = 0; while(!file.eof()) { Qf q; file >> q; QuadricClassify::QuadType type = QuadricClassify::classifyQuadric(q); if(!QuadricClassify::isImaginary(type) && type != QuadricClassify::QUADT_ERROR && type != QuadricClassify::QUADT_DEGENERATE && type != QuadricClassify::QUADT_ERRORINVALID) { quads.push_back(q); qtypeCount[type]++; } else { std::cout << "Quadric " << numQuads << " is invalid, returned type " << QuadricClassify::QuadTypeNames[type] << "\n"; imQuads++; } numQuads++; } for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID; i++) { std::cout << qtypeCount[i] << " " << QuadricClassify::QuadTypeNames[i] << "\n"; } return quads; } bool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) { /* Use a heuristic on truth to determine whether adjacent * intersections occur at the same place. * This will basically be a threshold on the largest * different bit in the mantissa. */ /* A relative heuristic does not work when one (or both!) * is 0 */ if(int1 == 0.0 || int2 == 0.0) { constexpr const double eps = 0.000001; return (mpfr::fabs(int1 - int2) < eps); } mpfr::mpreal largest = mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2)); mp_exp_t largestExp = largest.get_exp(); mpfr::mpreal diff = mpfr::fabs(int1 - int2); int p1 = int1.getPrecision(), p2 = int2.getPrecision(); int minPrec = std::min(p1, p2); mp_exp_t maxExp = largestExp - minPrec * 1 / 48, diffExp = diff.get_exp(); return maxExp >= diffExp; } template <typename ListTest, typename ListTrue> bool validateResults(ListTest &inter, ListTrue &truth) { /* Note that because the same method is used to determine * if an intersection is in the list, these lists will be * the same length */ if(inter->size() != truth->size()) { return false; } auto j = truth->begin(); for(auto i = inter->begin(); i != inter->end() || j != truth->end(); i++, j++) { if(i->q != j->q || i->intPos != j->intPos) { return false; } } return true; } template <typename List> int countIP(List inter) { int numIP = 0; for(auto i : *inter) numIP += i.incPrecCount(); return numIP; } using rngAlg = std::mt19937_64; template <int dim, typename fptype> using randLineGen = Geometry::Line<dim, fptype> (*)( rngAlg &rng, int minExp, int maxExp); template <int dim, typename fptype, typename cmpAlg> std::shared_ptr<std::list<cmpAlg>> __attribute__((noinline)) runTest( std::list<Geometry::Quadric<dim, fptype>> &quads, Geometry::Line<dim, fptype> &line, Timer::Timer &timer, double eps = std::numeric_limits<fptype>::infinity()) { timer.startTimer(); auto inter = Geometry::sortIntersections<dim, fptype, cmpAlg>( line, quads, fptype(eps)); timer.stopTimer(); return inter; } template <int dim, typename fptype> void intersectionTest( std::list<Geometry::Quadric<dim, fptype>> &quads, std::ostream &results, const int numTests, randLineGen<dim, fptype> rlgf, int minExp, int maxExp) { /* First build a scene of quadrics. * Then generate random lines on a disk centered at the * intersection of the cylinders. * Then sort the intersections * Finally validate them with a higher precision sort */ using Vf = Geometry::Vector<dim, fptype>; using Pf = Geometry::Point<dim, fptype>; using Lf = Geometry::Line<dim, fptype>; std::random_device rd; rngAlg engine(rd()); const double eps = 1.52587890625e-5; constexpr const int numTestTypes = 3; Timer::Timer testTimes[numTestTypes]; struct TimeArr { struct TestData { long long ns; int numIP; bool correct; } mpTime, fpTime, resTime; } *times = new struct TimeArr[numTests]; /* Run the tests */ int t; for(t = 0; t < numTests && globals.run; t++) { Lf line = rlgf(engine, minExp, maxExp); /* Then sort the intersections */ auto resultant = runTest< dim, fptype, Geometry::IntersectionResultant<dim, fptype>>( quads, line, testTimes[0], eps); auto fpApproximate = runTest< dim, fptype, Geometry::IntersectionApproximate<dim, fptype>>( quads, line, testTimes[1], eps); auto mpApproximate = runTest< dim, fptype, Geometry::IntersectionIncreasedPrec<dim, fptype>>( quads, line, testTimes[2], eps); times[t].resTime.ns = testTimes[0].instant_ns(); times[t].fpTime.ns = testTimes[1].instant_ns(); times[t].mpTime.ns = testTimes[2].instant_ns(); times[t].mpTime.correct = validateResults(mpApproximate, resultant); times[t].fpTime.correct = validateResults(fpApproximate, resultant); times[t].resTime.numIP = countIP(resultant); times[t].fpTime.numIP = countIP(fpApproximate); times[t].mpTime.numIP = countIP(mpApproximate); } /* Output all of the results */ results << "Test #, Approximate Times (ns), Approximates " "Correct, Increased Precs, MP Time (ns), MP " "Correct, Resultants, Resultant Time (ns)\n"; int resTotIP = 0; int fpTotIP = 0; int mpTotIP = 0; int mpTotIncorrect = 0; int fpTotIncorrect = 0; for(int i = 0; i < t; i++) { results << i + 1 << ", " << times[i].fpTime.ns << ", " << times[i].fpTime.correct << ", " << times[i].mpTime.numIP << ", " << times[i].mpTime.ns << ", " << times[i].mpTime.correct << ", " << times[i].resTime.numIP << ", " << times[i].resTime.ns << "\n"; resTotIP += times[i].resTime.numIP; mpTotIP += times[i].mpTime.numIP; fpTotIncorrect += 1 - times[i].fpTime.correct; mpTotIncorrect += 1 - times[i].mpTime.correct; } results << "\n" << "Total FP Time: " << testTimes[1].elapsed_s() << "." << std::setw(9) << std::setfill('0') << testTimes[1].elapsed_ns() << "\n" << "Total FP Disagreements: " << fpTotIncorrect << "\n\n" << "Total MP Computations: " << mpTotIP << "\n" << "Total MP Time (s): " << testTimes[2].elapsed_s() << "." << std::setw(9) << std::setfill('0') << testTimes[2].elapsed_ns() << "\n" << "Total MP Disagreements: " << mpTotIncorrect << "\n\n" << "Total Resultant Computations: " << resTotIP << "\n" << "Total Resultant Time (s): " << testTimes[0].elapsed_s() << "." << std::setw(9) << std::setfill('0') << testTimes[0].elapsed_ns() << "\n"; delete[] times; } void lockCPU() { const int numCPUs = sysconf(_SC_NPROCESSORS_ONLN); const int cpuSets = numCPUs / CPU_SETSIZE + ((numCPUs % CPU_SETSIZE) > 0); cpu_set_t *cpus = new cpu_set_t[cpuSets]; const size_t cpuSize = sizeof(cpu_set_t[cpuSets]); sched_getaffinity(0, cpuSize, cpus); for(int i = 1; i < numCPUs; i++) CPU_CLR(i, cpus); CPU_SET(0, cpus); sched_setaffinity(0, cpuSize, cpus); delete[] cpus; } template <typename fptype> bool checkExp(fptype fpVal, int minExp, int maxExp) { if(fpVal == fptype(0.0)) { return true; } GenericFP::fpconvert<fptype> *fpbits = reinterpret_cast<GenericFP::fpconvert<fptype> *>( &fpVal); int exponent = fpbits->exponent; exponent -= fpbits->centralExp; if(exponent < minExp || exponent > maxExp) { return false; } else { return true; } } template <int dim, typename fptype> Geometry::Line<dim, fptype> defRandLine(rngAlg &rng, int minExp, int maxExp) { constexpr const fptype minPos = 0, maxPos = 1; std::uniform_real_distribution<fptype> genPos(minPos, maxPos); std::uniform_real_distribution<fptype> genDir(-1.0, 1.0); /* First build the line */ Geometry::Vector<dim, fptype> lineDir; Geometry::Vector<dim, fptype> lineInt; for(int i = 0; i < dim; i++) { do { lineInt.set(i, genPos(rng)); } while(checkExp(lineInt.get(i), minExp, maxExp) == false); do { lineDir.set(i, genDir(rng)); } while(checkExp(lineDir.get(i), minExp, maxExp) == false); } return Geometry::Line<dim, fptype>( Geometry::Point<dim, fptype>(lineInt), lineInt); } template <int dim, typename fptype> Geometry::Line<dim, fptype> nestedEllRandLine(rngAlg &rng, int minExp, int maxExp) { constexpr const fptype minPos = 0.0, maxPos = 1.0; std::uniform_real_distribution<fptype> genPos(minPos, maxPos); Geometry::Vector<dim, fptype> lineInt; for(int i = 0; i < dim; i++) { fptype tmp = genPos(rng); lineInt.set(i, genPos(rng)); } /* Direct the line towards (1.0, 0.5, 0.5) */ const Geometry::Vector<dim, fptype> destination( {1.0, 0.5, 0.5}); Geometry::Vector<dim, fptype> lineDir = destination - lineInt; return Geometry::Line<dim, fptype>( Geometry::Point<dim, fptype>(lineInt), lineDir); } template <int dim, typename fptype> Geometry::Line<dim, fptype> cylRandLine(rngAlg &rng, int minExp, int maxExp) { constexpr const fptype minPos = 0.375, maxPos = 0.625; std::uniform_real_distribution<fptype> genPos(minPos, maxPos); std::uniform_real_distribution<fptype> genDir(-1.0, 1.0); /* First build the line */ Geometry::Vector<dim, fptype> lineDir; Geometry::Vector<dim, fptype> lineInt; lineInt.set(1, genPos(rng)); for(int i = 0; i < dim; i++) { lineInt.set(i, lineInt.get(1)); lineDir.set(i, genDir(rng)); } lineInt.set(0, genPos(rng)); return Geometry::Line<dim, fptype>( Geometry::Point<dim, fptype>(lineInt), lineInt); } int main(int argc, char **argv) { using fptype = float; constexpr const int dim = 3; lockCPU(); std::list<Geometry::Quadric<dim, fptype>> quads; const char *outFName = "results"; int numTests = 1e4; int minExp, maxExp; if(argc > 1) { quads = parseQuadrics<dim, fptype>(argv[1], &minExp, &maxExp); } else { quads = parseQuadrics<dim, fptype>("cylinders.csg", &minExp, &maxExp); } if(argc > 2) { outFName = argv[2]; } if(argc > 3) { numTests = atoi(argv[3]); } randLineGen<dim, fptype> rlg = cylRandLine<dim, fptype>; if(argc > 4) { int lineGenAlg = atoi(argv[4]); switch(lineGenAlg) { case 1: rlg = nestedEllRandLine<dim, fptype>; std::cout << "Using the nested spheres random lines\n"; break; case 2: std::cout << "Using the cylinders random lines\n"; rlg = cylRandLine<dim, fptype>; break; default: std::cout << "Using the default random lines\n"; rlg = defRandLine<dim, fptype>; } } std::ofstream results(outFName); signal(SIGINT, sigInt); intersectionTest(quads, results, numTests, rlg, minExp, maxExp); return 0; } <|endoftext|>
<commit_before>#include "terminalpp/ansi/control_sequence.hpp" #include <iostream> namespace terminalpp { namespace ansi { bool operator==(control_sequence const &lhs, control_sequence const &rhs) { if (lhs.initiator == rhs.initiator && lhs.command == rhs.command && lhs.meta == rhs.meta) { // TODO: look up an algorithm to do this. Mismatch? Equal_Range if (lhs.arguments.size() != rhs.arguments.size()) { return false; } for (auto itl = lhs.arguments.begin(), itr = rhs.arguments.begin(); itl != lhs.arguments.end(); ++itl, ++itr) { if (*itl != *itr) { return false; } } return true; } return false; } }} <commit_msg>Simplified ansi control sequence equality operator.<commit_after>#include "terminalpp/ansi/control_sequence.hpp" namespace terminalpp { namespace ansi { bool operator==(control_sequence const &lhs, control_sequence const &rhs) { return lhs.initiator == rhs.initiator && lhs.command == rhs.command && lhs.meta == rhs.meta && lhs.arguments.size() == rhs.arguments.size() && lhs.arguments == rhs.arguments; } }} <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * 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 the copyright holders 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. * * Authors: Gabe Black * Ali Saidi */ #ifndef __ARCH_SPARC_MISCREGFILE_HH__ #define __ARCH_SPARC_MISCREGFILE_HH__ #include "arch/sparc/faults.hh" #include "arch/sparc/isa_traits.hh" #include "arch/sparc/types.hh" #include "cpu/cpuevent.hh" #include <string> namespace SparcISA { //These functions map register indices to names std::string getMiscRegName(RegIndex); enum MiscRegIndex { /** Ancillary State Registers */ // MISCREG_Y, // MISCREG_CCR, MISCREG_ASI, MISCREG_TICK, MISCREG_FPRS, MISCREG_PCR, MISCREG_PIC, MISCREG_GSR, MISCREG_SOFTINT_SET, MISCREG_SOFTINT_CLR, MISCREG_SOFTINT, /* 10 */ MISCREG_TICK_CMPR, MISCREG_STICK, MISCREG_STICK_CMPR, /** Privilged Registers */ MISCREG_TPC, MISCREG_TNPC, MISCREG_TSTATE, MISCREG_TT, MISCREG_PRIVTICK, MISCREG_TBA, MISCREG_PSTATE, /* 20 */ MISCREG_TL, MISCREG_PIL, MISCREG_CWP, // MISCREG_CANSAVE, // MISCREG_CANRESTORE, // MISCREG_CLEANWIN, // MISCREG_OTHERWIN, // MISCREG_WSTATE, MISCREG_GL, /** Hyper privileged registers */ MISCREG_HPSTATE, /* 30 */ MISCREG_HTSTATE, MISCREG_HINTP, MISCREG_HTBA, MISCREG_HVER, MISCREG_STRAND_STS_REG, MISCREG_HSTICK_CMPR, /** Floating Point Status Register */ MISCREG_FSR, /** MMU Internal Registers */ MISCREG_MMU_P_CONTEXT, MISCREG_MMU_S_CONTEXT, /* 40 */ MISCREG_MMU_PART_ID, MISCREG_MMU_LSU_CTRL, MISCREG_MMU_ITLB_C0_TSB_PS0, MISCREG_MMU_ITLB_C0_TSB_PS1, MISCREG_MMU_ITLB_C0_CONFIG, MISCREG_MMU_ITLB_CX_TSB_PS0, MISCREG_MMU_ITLB_CX_TSB_PS1, MISCREG_MMU_ITLB_CX_CONFIG, MISCREG_MMU_ITLB_SFSR, MISCREG_MMU_ITLB_TAG_ACCESS, /* 50 */ MISCREG_MMU_DTLB_C0_TSB_PS0, MISCREG_MMU_DTLB_C0_TSB_PS1, MISCREG_MMU_DTLB_C0_CONFIG, MISCREG_MMU_DTLB_CX_TSB_PS0, MISCREG_MMU_DTLB_CX_TSB_PS1, MISCREG_MMU_DTLB_CX_CONFIG, MISCREG_MMU_DTLB_SFSR, MISCREG_MMU_DTLB_SFAR, MISCREG_MMU_DTLB_TAG_ACCESS, /** Scratchpad regiscers **/ MISCREG_SCRATCHPAD_R0, /* 60 */ MISCREG_SCRATCHPAD_R1, MISCREG_SCRATCHPAD_R2, MISCREG_SCRATCHPAD_R3, MISCREG_SCRATCHPAD_R4, MISCREG_SCRATCHPAD_R5, MISCREG_SCRATCHPAD_R6, MISCREG_SCRATCHPAD_R7, /* CPU Queue Registers */ MISCREG_QUEUE_CPU_MONDO_HEAD, MISCREG_QUEUE_CPU_MONDO_TAIL, MISCREG_QUEUE_DEV_MONDO_HEAD, /* 70 */ MISCREG_QUEUE_DEV_MONDO_TAIL, MISCREG_QUEUE_RES_ERROR_HEAD, MISCREG_QUEUE_RES_ERROR_TAIL, MISCREG_QUEUE_NRES_ERROR_HEAD, MISCREG_QUEUE_NRES_ERROR_TAIL, /* All the data for the TLB packed up in one register. */ MISCREG_TLB_DATA, MISCREG_NUMMISCREGS }; struct HPSTATE { const static uint64_t id = 0x800; // this impl. dependent (id) field m const static uint64_t ibe = 0x400; const static uint64_t red = 0x20; const static uint64_t hpriv = 0x4; const static uint64_t tlz = 0x1; }; struct PSTATE { const static int cle = 0x200; const static int tle = 0x100; const static int mm = 0xC0; const static int pef = 0x10; const static int am = 0x8; const static int priv = 0x4; const static int ie = 0x2; }; const int NumMiscArchRegs = MISCREG_NUMMISCREGS; const int NumMiscRegs = MISCREG_NUMMISCREGS; // The control registers, broken out into fields class MiscRegFile { private: /* ASR Registers */ //uint64_t y; // Y (used in obsolete multiplication) //uint8_t ccr; // Condition Code Register uint8_t asi; // Address Space Identifier uint64_t tick; // Hardware clock-tick counter uint8_t fprs; // Floating-Point Register State uint64_t gsr; // General Status Register uint64_t softint; uint64_t tick_cmpr; // Hardware tick compare registers uint64_t stick; // Hardware clock-tick counter uint64_t stick_cmpr; // Hardware tick compare registers /* Privileged Registers */ uint64_t tpc[MaxTL]; // Trap Program Counter (value from // previous trap level) uint64_t tnpc[MaxTL]; // Trap Next Program Counter (value from // previous trap level) uint64_t tstate[MaxTL]; // Trap State uint16_t tt[MaxTL]; // Trap Type (Type of trap which occured // on the previous level) uint64_t tba; // Trap Base Address uint16_t pstate; // Process State Register uint8_t tl; // Trap Level uint8_t pil; // Process Interrupt Register uint8_t cwp; // Current Window Pointer //uint8_t cansave; // Savable windows //uint8_t canrestore; // Restorable windows //uint8_t cleanwin; // Clean windows //uint8_t otherwin; // Other windows //uint8_t wstate; // Window State uint8_t gl; // Global level register /** Hyperprivileged Registers */ uint64_t hpstate; // Hyperprivileged State Register uint64_t htstate[MaxTL];// Hyperprivileged Trap State Register uint64_t hintp; uint64_t htba; // Hyperprivileged Trap Base Address register uint64_t hstick_cmpr; // Hardware tick compare registers uint64_t strandStatusReg;// Per strand status register /** Floating point misc registers. */ uint64_t fsr; // Floating-Point State Register /** MMU Internal Registers */ uint16_t priContext; uint16_t secContext; uint16_t partId; uint64_t lsuCtrlReg; uint64_t iTlbC0TsbPs0; uint64_t iTlbC0TsbPs1; uint64_t iTlbC0Config; uint64_t iTlbCXTsbPs0; uint64_t iTlbCXTsbPs1; uint64_t iTlbCXConfig; uint64_t iTlbSfsr; uint64_t iTlbTagAccess; uint64_t dTlbC0TsbPs0; uint64_t dTlbC0TsbPs1; uint64_t dTlbC0Config; uint64_t dTlbCXTsbPs0; uint64_t dTlbCXTsbPs1; uint64_t dTlbCXConfig; uint64_t dTlbSfsr; uint64_t dTlbSfar; uint64_t dTlbTagAccess; uint64_t scratchPad[8]; uint64_t cpu_mondo_head; uint64_t cpu_mondo_tail; uint64_t dev_mondo_head; uint64_t dev_mondo_tail; uint64_t res_error_head; uint64_t res_error_tail; uint64_t nres_error_head; uint64_t nres_error_tail; // These need to check the int_dis field and if 0 then // set appropriate bit in softint and checkinterrutps on the cpu #if FULL_SYSTEM void setFSRegWithEffect(int miscReg, const MiscReg &val, ThreadContext *tc); MiscReg readFSRegWithEffect(int miscReg, ThreadContext * tc); // Update interrupt state on softint or pil change void checkSoftInt(ThreadContext *tc); /** Process a tick compare event and generate an interrupt on the cpu if * appropriate. */ void processTickCompare(ThreadContext *tc); void processSTickCompare(ThreadContext *tc); void processHSTickCompare(ThreadContext *tc); typedef CpuEventWrapper<MiscRegFile, &MiscRegFile::processTickCompare> TickCompareEvent; TickCompareEvent *tickCompare; typedef CpuEventWrapper<MiscRegFile, &MiscRegFile::processSTickCompare> STickCompareEvent; STickCompareEvent *sTickCompare; typedef CpuEventWrapper<MiscRegFile, &MiscRegFile::processHSTickCompare> HSTickCompareEvent; HSTickCompareEvent *hSTickCompare; #endif public: void clear(); MiscRegFile() { clear(); } MiscReg readReg(int miscReg); MiscReg readRegWithEffect(int miscReg, ThreadContext *tc); void setReg(int miscReg, const MiscReg &val); void setRegWithEffect(int miscReg, const MiscReg &val, ThreadContext * tc); int getInstAsid() { return priContext | (uint32_t)partId << 13; } int getDataAsid() { return priContext | (uint32_t)partId << 13; } void serialize(std::ostream & os); void unserialize(Checkpoint * cp, const std::string & section); void copyMiscRegs(ThreadContext * tc); protected: bool isHyperPriv() { return (hpstate & (1 << 2)); } bool isPriv() { return (hpstate & (1 << 2)) || (pstate & (1 << 2)); } bool isNonPriv() { return !isPriv(); } }; } #endif <commit_msg>Add in a declaration of class Checkpoint rather than expecting it to come from some other include.<commit_after>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * 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 the copyright holders 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. * * Authors: Gabe Black * Ali Saidi */ #ifndef __ARCH_SPARC_MISCREGFILE_HH__ #define __ARCH_SPARC_MISCREGFILE_HH__ #include "arch/sparc/faults.hh" #include "arch/sparc/isa_traits.hh" #include "arch/sparc/types.hh" #include "cpu/cpuevent.hh" #include <string> class Checkpoint; namespace SparcISA { //These functions map register indices to names std::string getMiscRegName(RegIndex); enum MiscRegIndex { /** Ancillary State Registers */ // MISCREG_Y, // MISCREG_CCR, MISCREG_ASI, MISCREG_TICK, MISCREG_FPRS, MISCREG_PCR, MISCREG_PIC, MISCREG_GSR, MISCREG_SOFTINT_SET, MISCREG_SOFTINT_CLR, MISCREG_SOFTINT, /* 10 */ MISCREG_TICK_CMPR, MISCREG_STICK, MISCREG_STICK_CMPR, /** Privilged Registers */ MISCREG_TPC, MISCREG_TNPC, MISCREG_TSTATE, MISCREG_TT, MISCREG_PRIVTICK, MISCREG_TBA, MISCREG_PSTATE, /* 20 */ MISCREG_TL, MISCREG_PIL, MISCREG_CWP, // MISCREG_CANSAVE, // MISCREG_CANRESTORE, // MISCREG_CLEANWIN, // MISCREG_OTHERWIN, // MISCREG_WSTATE, MISCREG_GL, /** Hyper privileged registers */ MISCREG_HPSTATE, /* 30 */ MISCREG_HTSTATE, MISCREG_HINTP, MISCREG_HTBA, MISCREG_HVER, MISCREG_STRAND_STS_REG, MISCREG_HSTICK_CMPR, /** Floating Point Status Register */ MISCREG_FSR, /** MMU Internal Registers */ MISCREG_MMU_P_CONTEXT, MISCREG_MMU_S_CONTEXT, /* 40 */ MISCREG_MMU_PART_ID, MISCREG_MMU_LSU_CTRL, MISCREG_MMU_ITLB_C0_TSB_PS0, MISCREG_MMU_ITLB_C0_TSB_PS1, MISCREG_MMU_ITLB_C0_CONFIG, MISCREG_MMU_ITLB_CX_TSB_PS0, MISCREG_MMU_ITLB_CX_TSB_PS1, MISCREG_MMU_ITLB_CX_CONFIG, MISCREG_MMU_ITLB_SFSR, MISCREG_MMU_ITLB_TAG_ACCESS, /* 50 */ MISCREG_MMU_DTLB_C0_TSB_PS0, MISCREG_MMU_DTLB_C0_TSB_PS1, MISCREG_MMU_DTLB_C0_CONFIG, MISCREG_MMU_DTLB_CX_TSB_PS0, MISCREG_MMU_DTLB_CX_TSB_PS1, MISCREG_MMU_DTLB_CX_CONFIG, MISCREG_MMU_DTLB_SFSR, MISCREG_MMU_DTLB_SFAR, MISCREG_MMU_DTLB_TAG_ACCESS, /** Scratchpad regiscers **/ MISCREG_SCRATCHPAD_R0, /* 60 */ MISCREG_SCRATCHPAD_R1, MISCREG_SCRATCHPAD_R2, MISCREG_SCRATCHPAD_R3, MISCREG_SCRATCHPAD_R4, MISCREG_SCRATCHPAD_R5, MISCREG_SCRATCHPAD_R6, MISCREG_SCRATCHPAD_R7, /* CPU Queue Registers */ MISCREG_QUEUE_CPU_MONDO_HEAD, MISCREG_QUEUE_CPU_MONDO_TAIL, MISCREG_QUEUE_DEV_MONDO_HEAD, /* 70 */ MISCREG_QUEUE_DEV_MONDO_TAIL, MISCREG_QUEUE_RES_ERROR_HEAD, MISCREG_QUEUE_RES_ERROR_TAIL, MISCREG_QUEUE_NRES_ERROR_HEAD, MISCREG_QUEUE_NRES_ERROR_TAIL, /* All the data for the TLB packed up in one register. */ MISCREG_TLB_DATA, MISCREG_NUMMISCREGS }; struct HPSTATE { const static uint64_t id = 0x800; // this impl. dependent (id) field m const static uint64_t ibe = 0x400; const static uint64_t red = 0x20; const static uint64_t hpriv = 0x4; const static uint64_t tlz = 0x1; }; struct PSTATE { const static int cle = 0x200; const static int tle = 0x100; const static int mm = 0xC0; const static int pef = 0x10; const static int am = 0x8; const static int priv = 0x4; const static int ie = 0x2; }; const int NumMiscArchRegs = MISCREG_NUMMISCREGS; const int NumMiscRegs = MISCREG_NUMMISCREGS; // The control registers, broken out into fields class MiscRegFile { private: /* ASR Registers */ //uint64_t y; // Y (used in obsolete multiplication) //uint8_t ccr; // Condition Code Register uint8_t asi; // Address Space Identifier uint64_t tick; // Hardware clock-tick counter uint8_t fprs; // Floating-Point Register State uint64_t gsr; // General Status Register uint64_t softint; uint64_t tick_cmpr; // Hardware tick compare registers uint64_t stick; // Hardware clock-tick counter uint64_t stick_cmpr; // Hardware tick compare registers /* Privileged Registers */ uint64_t tpc[MaxTL]; // Trap Program Counter (value from // previous trap level) uint64_t tnpc[MaxTL]; // Trap Next Program Counter (value from // previous trap level) uint64_t tstate[MaxTL]; // Trap State uint16_t tt[MaxTL]; // Trap Type (Type of trap which occured // on the previous level) uint64_t tba; // Trap Base Address uint16_t pstate; // Process State Register uint8_t tl; // Trap Level uint8_t pil; // Process Interrupt Register uint8_t cwp; // Current Window Pointer //uint8_t cansave; // Savable windows //uint8_t canrestore; // Restorable windows //uint8_t cleanwin; // Clean windows //uint8_t otherwin; // Other windows //uint8_t wstate; // Window State uint8_t gl; // Global level register /** Hyperprivileged Registers */ uint64_t hpstate; // Hyperprivileged State Register uint64_t htstate[MaxTL];// Hyperprivileged Trap State Register uint64_t hintp; uint64_t htba; // Hyperprivileged Trap Base Address register uint64_t hstick_cmpr; // Hardware tick compare registers uint64_t strandStatusReg;// Per strand status register /** Floating point misc registers. */ uint64_t fsr; // Floating-Point State Register /** MMU Internal Registers */ uint16_t priContext; uint16_t secContext; uint16_t partId; uint64_t lsuCtrlReg; uint64_t iTlbC0TsbPs0; uint64_t iTlbC0TsbPs1; uint64_t iTlbC0Config; uint64_t iTlbCXTsbPs0; uint64_t iTlbCXTsbPs1; uint64_t iTlbCXConfig; uint64_t iTlbSfsr; uint64_t iTlbTagAccess; uint64_t dTlbC0TsbPs0; uint64_t dTlbC0TsbPs1; uint64_t dTlbC0Config; uint64_t dTlbCXTsbPs0; uint64_t dTlbCXTsbPs1; uint64_t dTlbCXConfig; uint64_t dTlbSfsr; uint64_t dTlbSfar; uint64_t dTlbTagAccess; uint64_t scratchPad[8]; uint64_t cpu_mondo_head; uint64_t cpu_mondo_tail; uint64_t dev_mondo_head; uint64_t dev_mondo_tail; uint64_t res_error_head; uint64_t res_error_tail; uint64_t nres_error_head; uint64_t nres_error_tail; // These need to check the int_dis field and if 0 then // set appropriate bit in softint and checkinterrutps on the cpu #if FULL_SYSTEM void setFSRegWithEffect(int miscReg, const MiscReg &val, ThreadContext *tc); MiscReg readFSRegWithEffect(int miscReg, ThreadContext * tc); // Update interrupt state on softint or pil change void checkSoftInt(ThreadContext *tc); /** Process a tick compare event and generate an interrupt on the cpu if * appropriate. */ void processTickCompare(ThreadContext *tc); void processSTickCompare(ThreadContext *tc); void processHSTickCompare(ThreadContext *tc); typedef CpuEventWrapper<MiscRegFile, &MiscRegFile::processTickCompare> TickCompareEvent; TickCompareEvent *tickCompare; typedef CpuEventWrapper<MiscRegFile, &MiscRegFile::processSTickCompare> STickCompareEvent; STickCompareEvent *sTickCompare; typedef CpuEventWrapper<MiscRegFile, &MiscRegFile::processHSTickCompare> HSTickCompareEvent; HSTickCompareEvent *hSTickCompare; #endif public: void clear(); MiscRegFile() { clear(); } MiscReg readReg(int miscReg); MiscReg readRegWithEffect(int miscReg, ThreadContext *tc); void setReg(int miscReg, const MiscReg &val); void setRegWithEffect(int miscReg, const MiscReg &val, ThreadContext * tc); int getInstAsid() { return priContext | (uint32_t)partId << 13; } int getDataAsid() { return priContext | (uint32_t)partId << 13; } void serialize(std::ostream & os); void unserialize(Checkpoint * cp, const std::string & section); void copyMiscRegs(ThreadContext * tc); protected: bool isHyperPriv() { return (hpstate & (1 << 2)); } bool isPriv() { return (hpstate & (1 << 2)) || (pstate & (1 << 2)); } bool isNonPriv() { return !isPriv(); } }; } #endif <|endoftext|>
<commit_before>// // Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved. // // 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. // /*! * @file */ #pragma once #include <atria/xform/config.hpp> #include <atria/xform/state_traits.hpp> #include <atria/estd/memory.hpp> #include <atria/meta/pack.hpp> #include <string> #include <stdexcept> #if ABL_TRACE_ANY_STATE_ALLOC #include <iostream> #endif namespace atria { namespace xform { /*! * Polymorphically holds any value implementing the `state_traits`. * This type is used for the implementation of `transducer`. */ class any_state { public: any_state() noexcept : data_(reinterpret_cast<char*>(&null_holder_)) , size_(0) {} ~any_state() noexcept { if (size_) { content()->~holder_base(); delete [] data_; } } any_state(any_state&& other) : data_(other.data_) { auto size = other.size_; other.size_ = 0; size_ = size; } any_state(const any_state& other) : data_(new char[other.size_]) , size_(other.size_) { #if ABL_TRACE_ANY_STATE_ALLOC std::cout << "alloc-c" << std::endl; #endif other.content()->clone(data_); } template<typename ValueType> any_state(ValueType&& value, estd::enable_if_t< !std::is_base_of<any_state, estd::decay_t<ValueType> >::value && !std::is_base_of<meta::bottom, estd::decay_t<ValueType> >::value >* = 0) : data_(new char[sizeof(holder<estd::decay_t<ValueType> >)]) , size_(sizeof(holder<estd::decay_t<ValueType> >)) { new (data_) holder<estd::decay_t<ValueType> >( std::forward<ValueType>(value)); #if ABL_TRACE_ANY_STATE_ALLOC std::cout << "alloc-n " << typeid(estd::decay_t<ValueType>).name() << std::endl; #endif } any_state& operator=(any_state&& other) { data_ = other.data_; size_ = other.size_; other.size_ = 0; return *this; } any_state& operator=(const any_state& rhs) { if (&rhs != this) { realloc_(rhs.content()->size()); rhs.content()->clone(data_); } return *this; } template <typename ValueType> auto operator=(ValueType&& rhs) -> estd::enable_if_t< !std::is_base_of<any_state, estd::decay_t<ValueType> >::value, any_state&> { realloc_(sizeof(holder<estd::decay_t<ValueType> >)); new (data_) holder<estd::decay_t<ValueType> >( std::forward<ValueType>(rhs)); return *this; } template <typename T> estd::decay_t<T>& as() & { return as_impl(meta::pack<estd::decay_t<T> >{}); } template <typename T> estd::decay_t<T>&& as() && { return std::move(as_impl(meta::pack<estd::decay_t<T> >{})); } template <typename T> const estd::decay_t<T>& as() const& { return const_cast<any_state*>(this)->as_impl( meta::pack<estd::decay_t<T> >{}); } template <typename T> void check() const { if (!has<T>()) { throw std::runtime_error( std::string("Have ") + type().name() + ", but expect " + typeid(estd::decay_t<T>).name()); } } template <typename T> bool has() const { return has_impl(meta::pack<estd::decay_t<T> >{}); } const std::type_info& type() const noexcept { return content()->type(); } private: void realloc_(std::size_t size) { if (size_ > 0) content()->~holder_base(); if (size_ < size) { if (size_ > 0) delete [] data_; data_ = new char[size]; size_ = size; #if ABL_TRACE_ANY_STATE_ALLOC std::cout << "alloc-r" << std::endl; #endif } } template <typename T> T& as_impl(meta::pack<T>) { #if ABL_SAFE_ANY_STATE check<T>(); #endif return reinterpret_cast<holder<T>*>(data_)->held; } any_state& as_impl(meta::pack<any_state>) { return *this; } template <typename T> bool has_impl(meta::pack<T>) const { return content()->type() == typeid(T); } bool has_impl(meta::pack<any_state>) const { return true; } friend struct state_traits<any_state>; struct holder_base { virtual ~holder_base(); virtual const std::type_info& type() const noexcept = 0; virtual void clone(char* data) const = 0; virtual void move(char* data) const = 0; virtual any_state complete() const = 0; virtual bool is_reduced() const = 0; virtual any_state unwrap() const = 0; virtual any_state unwrap_all() const = 0; virtual any_state rewrap(any_state) const = 0; virtual any_state data() const = 0; virtual std::size_t size() const = 0; }; template <typename T> struct holder : holder_base { T held; template <typename TT> holder(TT&& x) : held(std::forward<TT>(x)) {} const std::type_info& type() const noexcept override { return typeid(T); } void clone(char* data) const override { new (data) holder<T>(held); } void move(char* data) const override { new (data) holder<T>(std::move(held)); } any_state complete() const override { return state_complete(held); } bool is_reduced() const override { return state_is_reduced(held); } any_state unwrap() const override { return state_unwrap(held); } any_state unwrap_all() const override { return state_unwrap_all(held); } any_state rewrap(any_state x) const override { return state_rewrap(held, std::move(x)); } any_state data() const override { return state_data(held, [] { return any_state{}; }); } std::size_t size() const override { return sizeof(T); } }; struct null_holder : holder_base { virtual ~null_holder(); const std::type_info& type() const noexcept override { return typeid(void); } void clone(char* data) const override { new (data) null_holder; } void move(char* data) const override { new (data) null_holder; } any_state complete() const override { return {}; } bool is_reduced() const override { return false; } any_state unwrap() const override { return {}; } any_state unwrap_all() const override { return {}; } any_state rewrap(any_state x) const override { return x; } any_state data() const override { return {}; } std::size_t size() const override { return 0; } }; holder_base* content() const { return reinterpret_cast<holder_base*>(data_); } char* data_; std::size_t size_; static null_holder null_holder_; }; template <> struct state_traits<any_state> { template <typename T> static auto complete(T&& t) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->complete()) template <typename T> static auto is_reduced(T&& t) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->is_reduced()) template <typename T> static auto unwrap(T&& t) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->unwrap()) template <typename T> static auto unwrap_all(T&& t) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->unwrap_all()) template <typename T, typename U> static auto rewrap(T&& t, U&& x) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->rewrap(std::forward<U>(x))) template <typename T, typename D> static auto data(T&& t, D&& d) -> estd::decay_t<decltype(std::forward<D>(d)())> { using data_t = estd::decay_t<decltype(std::forward<D>(d)())>; auto data = t.content()->data(); return data.template has<data_t>() ? data.template as<data_t>() : std::forward<D>(d)(); } }; } // namespace xform } // namespace atria <commit_msg>xform: fix `any_state` would sometimes leak memory<commit_after>// // Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved. // // 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. // /*! * @file */ #pragma once #include <atria/xform/config.hpp> #include <atria/xform/state_traits.hpp> #include <atria/estd/memory.hpp> #include <atria/meta/pack.hpp> #include <string> #include <stdexcept> #if ABL_TRACE_ANY_STATE_ALLOC #include <iostream> #endif namespace atria { namespace xform { /*! * Polymorphically holds any value implementing the `state_traits`. * This type is used for the implementation of `transducer`. */ class any_state { public: any_state() noexcept : data_(reinterpret_cast<char*>(&null_holder_)) , size_(0) {} ~any_state() noexcept { if (size_) { content()->~holder_base(); delete [] data_; } } any_state(any_state&& other) : data_(other.data_) , size_{} { using std::swap; swap(size_, other.size_); } any_state(const any_state& other) : data_(other.size_ ? new char[other.size_] : nullptr) , size_(other.size_) { #if ABL_TRACE_ANY_STATE_ALLOC std::cout << "alloc-c" << std::endl; #endif other.content()->clone(data_); } template<typename ValueType> any_state(ValueType&& value, estd::enable_if_t< !std::is_base_of<any_state, estd::decay_t<ValueType> >::value && !std::is_base_of<meta::bottom, estd::decay_t<ValueType> >::value >* = 0) : data_(new char[sizeof(holder<estd::decay_t<ValueType> >)]) , size_(sizeof(holder<estd::decay_t<ValueType> >)) { new (data_) holder<estd::decay_t<ValueType> >( std::forward<ValueType>(value)); #if ABL_TRACE_ANY_STATE_ALLOC std::cout << "alloc-n " << typeid(estd::decay_t<ValueType>).name() << std::endl; #endif } any_state& operator=(any_state&& other) { using std::swap; swap(data_, other.data_); swap(size_, other.size_); return *this; } any_state& operator=(const any_state& rhs) { if (&rhs != this) { realloc_(rhs.content()->size()); rhs.content()->clone(data_); } return *this; } template <typename ValueType> auto operator=(ValueType&& rhs) -> estd::enable_if_t< !std::is_base_of<any_state, estd::decay_t<ValueType> >::value, any_state&> { realloc_(sizeof(holder<estd::decay_t<ValueType> >)); new (data_) holder<estd::decay_t<ValueType> >( std::forward<ValueType>(rhs)); return *this; } template <typename T> estd::decay_t<T>& as() & { return as_impl(meta::pack<estd::decay_t<T> >{}); } template <typename T> estd::decay_t<T>&& as() && { return std::move(as_impl(meta::pack<estd::decay_t<T> >{})); } template <typename T> const estd::decay_t<T>& as() const& { return const_cast<any_state*>(this)->as_impl( meta::pack<estd::decay_t<T> >{}); } template <typename T> void check() const { if (!has<T>()) { throw std::runtime_error( std::string("Have ") + type().name() + ", but expect " + typeid(estd::decay_t<T>).name()); } } template <typename T> bool has() const { return has_impl(meta::pack<estd::decay_t<T> >{}); } const std::type_info& type() const noexcept { return content()->type(); } private: void realloc_(std::size_t size) { if (size_ > 0) content()->~holder_base(); if (size_ < size) { if (size_ > 0) delete [] data_; data_ = new char[size]; size_ = size; #if ABL_TRACE_ANY_STATE_ALLOC std::cout << "alloc-r" << std::endl; #endif } } template <typename T> T& as_impl(meta::pack<T>) { #if ABL_SAFE_ANY_STATE check<T>(); #endif return reinterpret_cast<holder<T>*>(data_)->held; } any_state& as_impl(meta::pack<any_state>) { return *this; } template <typename T> bool has_impl(meta::pack<T>) const { return content()->type() == typeid(T); } bool has_impl(meta::pack<any_state>) const { return true; } friend struct state_traits<any_state>; struct holder_base { virtual ~holder_base(); virtual const std::type_info& type() const noexcept = 0; virtual void clone(char* data) const = 0; virtual void move(char* data) const = 0; virtual any_state complete() const = 0; virtual bool is_reduced() const = 0; virtual any_state unwrap() const = 0; virtual any_state unwrap_all() const = 0; virtual any_state rewrap(any_state) const = 0; virtual any_state data() const = 0; virtual std::size_t size() const = 0; }; template <typename T> struct holder : holder_base { T held; template <typename TT> holder(TT&& x) : held(std::forward<TT>(x)) {} const std::type_info& type() const noexcept override { return typeid(T); } void clone(char* data) const override { new (data) holder<T>(held); } void move(char* data) const override { new (data) holder<T>(std::move(held)); } any_state complete() const override { return state_complete(held); } bool is_reduced() const override { return state_is_reduced(held); } any_state unwrap() const override { return state_unwrap(held); } any_state unwrap_all() const override { return state_unwrap_all(held); } any_state rewrap(any_state x) const override { return state_rewrap(held, std::move(x)); } any_state data() const override { return state_data(held, [] { return any_state{}; }); } std::size_t size() const override { return sizeof(T); } }; struct null_holder : holder_base { virtual ~null_holder(); const std::type_info& type() const noexcept override { return typeid(void); } void clone(char* data) const override { new (data) null_holder; } void move(char* data) const override { new (data) null_holder; } any_state complete() const override { return {}; } bool is_reduced() const override { return false; } any_state unwrap() const override { return {}; } any_state unwrap_all() const override { return {}; } any_state rewrap(any_state x) const override { return x; } any_state data() const override { return {}; } std::size_t size() const override { return 0; } }; holder_base* content() const { return reinterpret_cast<holder_base*>(data_); } char* data_; std::size_t size_; static null_holder null_holder_; }; template <> struct state_traits<any_state> { template <typename T> static auto complete(T&& t) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->complete()) template <typename T> static auto is_reduced(T&& t) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->is_reduced()) template <typename T> static auto unwrap(T&& t) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->unwrap()) template <typename T> static auto unwrap_all(T&& t) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->unwrap_all()) template <typename T, typename U> static auto rewrap(T&& t, U&& x) -> ABL_DECLTYPE_RETURN( std::forward<T>(t).content()->rewrap(std::forward<U>(x))) template <typename T, typename D> static auto data(T&& t, D&& d) -> estd::decay_t<decltype(std::forward<D>(d)())> { using data_t = estd::decay_t<decltype(std::forward<D>(d)())>; auto data = t.content()->data(); return data.template has<data_t>() ? data.template as<data_t>() : std::forward<D>(d)(); } }; } // namespace xform } // namespace atria <|endoftext|>