text
stringlengths
54
60.6k
<commit_before>7f9e4b54-2e3a-11e5-81b4-c03896053bdd<commit_msg>7fb0ec5c-2e3a-11e5-be33-c03896053bdd<commit_after>7fb0ec5c-2e3a-11e5-be33-c03896053bdd<|endoftext|>
<commit_before>bc486c59-327f-11e5-bfed-9cf387a8033e<commit_msg>bc4e69f3-327f-11e5-9bdb-9cf387a8033e<commit_after>bc4e69f3-327f-11e5-9bdb-9cf387a8033e<|endoftext|>
<commit_before>8b332557-2d14-11e5-af21-0401358ea401<commit_msg>8b332558-2d14-11e5-af21-0401358ea401<commit_after>8b332558-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>23d422fe-2f67-11e5-928c-6c40088e03e4<commit_msg>23dabd2e-2f67-11e5-82be-6c40088e03e4<commit_after>23dabd2e-2f67-11e5-82be-6c40088e03e4<|endoftext|>
<commit_before>b9ad6d2e-327f-11e5-aa74-9cf387a8033e<commit_msg>b9b4097d-327f-11e5-a1c2-9cf387a8033e<commit_after>b9b4097d-327f-11e5-a1c2-9cf387a8033e<|endoftext|>
<commit_before>f4939d94-2e4e-11e5-aae0-28cfe91dbc4b<commit_msg>f49eb240-2e4e-11e5-bbcd-28cfe91dbc4b<commit_after>f49eb240-2e4e-11e5-bbcd-28cfe91dbc4b<|endoftext|>
<commit_before>5ae7ec38-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ec39-2d16-11e5-af21-0401358ea401<commit_after>5ae7ec39-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>779e52cf-2e4f-11e5-a0b9-28cfe91dbc4b<commit_msg>77a57a0f-2e4f-11e5-83aa-28cfe91dbc4b<commit_after>77a57a0f-2e4f-11e5-83aa-28cfe91dbc4b<|endoftext|>
<commit_before>921941c0-35ca-11e5-acea-6c40088e03e4<commit_msg>922047cc-35ca-11e5-99fd-6c40088e03e4<commit_after>922047cc-35ca-11e5-99fd-6c40088e03e4<|endoftext|>
<commit_before>988599dc-327f-11e5-9ddd-9cf387a8033e<commit_msg>988b50de-327f-11e5-8da9-9cf387a8033e<commit_after>988b50de-327f-11e5-8da9-9cf387a8033e<|endoftext|>
<commit_before>dd2cad9c-2e4e-11e5-885b-28cfe91dbc4b<commit_msg>dd331951-2e4e-11e5-a467-28cfe91dbc4b<commit_after>dd331951-2e4e-11e5-a467-28cfe91dbc4b<|endoftext|>
<commit_before>68bbddc6-2fa5-11e5-9ed8-00012e3d3f12<commit_msg>68be00a4-2fa5-11e5-9aa6-00012e3d3f12<commit_after>68be00a4-2fa5-11e5-9aa6-00012e3d3f12<|endoftext|>
<commit_before>762202c6-2d53-11e5-baeb-247703a38240<commit_msg>762282aa-2d53-11e5-baeb-247703a38240<commit_after>762282aa-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>5e39da23-2e4f-11e5-8c47-28cfe91dbc4b<commit_msg>5e407a3d-2e4f-11e5-897f-28cfe91dbc4b<commit_after>5e407a3d-2e4f-11e5-897f-28cfe91dbc4b<|endoftext|>
<commit_before>/* * NcursesWriter.cpp * * Created on: Jul 30, 2015 * Author: dpayne */ #include "Writer/NcursesWriter.h" #include "Utils/Logger.h" #include "Utils/NcursesUtils.h" vis::NcursesWriter::NcursesWriter(const vis::Settings *const settings) : m_settings{settings} { initscr(); noecho(); // disable printing of pressed keys curs_set(0); // sets the cursor to invisible setlocale(LC_ALL, ""); if (has_colors() == TRUE) { start_color(); // turns on color use_default_colors(); // uses default colors of terminal, which allows // transparency to work // initialize color pairs setup_colors(); } } void vis::NcursesWriter::setup_colors() { // initialize colors for (int16_t i = 0; i < COLORS; ++i) { init_pair(i, i, -1); // initialize colors as background, this is used in write_background to // create a // full block effect without using a custom font init_pair(static_cast<int16_t>(i + COLORS), i, i); } } void vis::NcursesWriter::write_background(int32_t height, int32_t width, vis::ColorIndex color, const std::wstring &msg) { // Add COLORS which will set it to have the color as the background, see // "setup_colors" auto color_pair = COLOR_PAIR(color + COLORS); attron(color_pair); mvaddwstr(height, width, msg.c_str()); attroff(color_pair); } void vis::NcursesWriter::write_foreground(int32_t height, int32_t width, vis::ColorIndex color, const std::wstring &msg) { attron(COLOR_PAIR(color)); mvaddwstr(height, width, msg.c_str()); attroff(COLOR_PAIR(color)); } void vis::NcursesWriter::write(const int32_t row, const int32_t column, const vis::ColorIndex color, const std::wstring &msg, const wchar_t character) { // This is a hack to achieve a solid bar look without using a custom font. // Instead of writing a real character, set the background to the color and // write a space if (character == VisConstants::k_space_wchar) { write_background(row, column, color, msg); } else { write_foreground(row, column, color, msg); } } void vis::NcursesWriter::clear() { standend(); erase(); } void vis::NcursesWriter::flush() { refresh(); } vis::ColorIndex vis::NcursesWriter::to_color_pair(int32_t number, int32_t max, bool wrap) const { const auto colors_size = static_cast<vis::ColorIndex>(m_settings->get_colors().size()); const auto index = (number * colors_size) / (max + 1); // no colors if (colors_size == 0) { return 0; } const auto color = m_settings->get_colors()[static_cast<size_t>( wrap ? index % colors_size : std::min(index, colors_size - 1))]; return color; } vis::NcursesWriter::~NcursesWriter() { endwin(); } <commit_msg>Fixing bug with Ncurses version 6.0.20170401<commit_after>/* * NcursesWriter.cpp * * Created on: Jul 30, 2015 * Author: dpayne */ #include "Writer/NcursesWriter.h" #include "Utils/Logger.h" #include "Utils/NcursesUtils.h" /* Ncurses version 6.0.20170401 introduced an issue with COLOR_PAIR which broke * setting more than 256 color pairs. Specifically it uses an A_COLOR macro * which uses a 8 bit mask. This will work for colors since only 256 colors are * supported but it breaks color pairs since 2^16 color pairs are supported. */ #define VIS_A_COLOR NCURSES_BITS(((1U) << 16) - 1U, 0) #define VIS_COLOR_PAIR(n) (NCURSES_BITS((n), 0) & VIS_A_COLOR) vis::NcursesWriter::NcursesWriter(const vis::Settings *const settings) : m_settings{settings} { initscr(); noecho(); // disable printing of pressed keys curs_set(0); // sets the cursor to invisible setlocale(LC_ALL, ""); if (has_colors() == TRUE) { start_color(); // turns on color use_default_colors(); // uses default colors of terminal, which allows // transparency to work // initialize color pairs setup_colors(); } } void vis::NcursesWriter::setup_colors() { // initialize colors for (int16_t i = 0; i < COLORS; ++i) { init_pair(i, i, -1); // initialize colors as background, this is used in write_background to // create a // full block effect without using a custom font init_pair(static_cast<int16_t>(i + COLORS), i, i); } } void vis::NcursesWriter::write_background(int32_t height, int32_t width, vis::ColorIndex color, const std::wstring &msg) { // Add COLORS which will set it to have the color as the background, see // "setup_colors" auto color_pair = VIS_COLOR_PAIR(color + COLORS); attron(color_pair); mvaddwstr(height, width, msg.c_str()); attroff(color_pair); } void vis::NcursesWriter::write_foreground(int32_t height, int32_t width, vis::ColorIndex color, const std::wstring &msg) { attron(VIS_COLOR_PAIR(color)); mvaddwstr(height, width, msg.c_str()); attroff(VIS_COLOR_PAIR(color)); } void vis::NcursesWriter::write(const int32_t row, const int32_t column, const vis::ColorIndex color, const std::wstring &msg, const wchar_t character) { // This is a hack to achieve a solid bar look without using a custom font. // Instead of writing a real character, set the background to the color and // write a space if (character == VisConstants::k_space_wchar) { write_background(row, column, color, msg); } else { write_foreground(row, column, color, msg); } } void vis::NcursesWriter::clear() { standend(); erase(); } void vis::NcursesWriter::flush() { refresh(); } vis::ColorIndex vis::NcursesWriter::to_color_pair(int32_t number, int32_t max, bool wrap) const { const auto colors_size = static_cast<vis::ColorIndex>(m_settings->get_colors().size()); const auto index = (number * colors_size) / (max + 1); // no colors if (colors_size == 0) { return 0; } const auto color = m_settings->get_colors()[static_cast<size_t>( wrap ? index % colors_size : std::min(index, colors_size - 1))]; return color; } vis::NcursesWriter::~NcursesWriter() { endwin(); } <|endoftext|>
<commit_before>8b33255d-2d14-11e5-af21-0401358ea401<commit_msg>8b33255e-2d14-11e5-af21-0401358ea401<commit_after>8b33255e-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>31ba7002-2e3a-11e5-a7fa-c03896053bdd<commit_msg>31c8ca82-2e3a-11e5-977d-c03896053bdd<commit_after>31c8ca82-2e3a-11e5-977d-c03896053bdd<|endoftext|>
<commit_before>d78c1d4c-35ca-11e5-823e-6c40088e03e4<commit_msg>d792d5b0-35ca-11e5-bc76-6c40088e03e4<commit_after>d792d5b0-35ca-11e5-bc76-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> #include "read_inifile.h" int main(int argc, char const* argv[]) { bool use_file = false; FILE* fp = nullptr; if (argc < 2) { fp = stdin; } else { if ((fp = fopen(*++argv, "r")) == nullptr) { exit(EXIT_FAILURE); } use_file = true; } std::map<std::string, std::string> keyval; parse(fp, keyval); for (auto kv : keyval) { std::cout << kv.first << ":" << kv.second << std::endl; } if (use_file) { fclose(fp); } return 0; } <commit_msg>for eachの効率を上げる<commit_after>#include <iostream> #include "read_inifile.h" int main(int argc, char const* argv[]) { bool use_file = false; FILE* fp = nullptr; if (argc < 2) { fp = stdin; } else { if ((fp = fopen(*++argv, "r")) == nullptr) { exit(EXIT_FAILURE); } use_file = true; } std::map<std::string, std::string> keyval; parse(fp, keyval); for (const auto& kv : keyval) { std::cout << kv.first << ":" << kv.second << std::endl; } if (use_file) { fclose(fp); } return 0; } <|endoftext|>
<commit_before>9bcebd6e-35ca-11e5-ae3d-6c40088e03e4<commit_msg>9bd5ba40-35ca-11e5-a1fb-6c40088e03e4<commit_after>9bd5ba40-35ca-11e5-a1fb-6c40088e03e4<|endoftext|>
<commit_before>70edaefa-4b02-11e5-aea1-28cfe9171a43<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>70fafae1-4b02-11e5-b71c-28cfe9171a43<|endoftext|>
<commit_before>5e589438-2d16-11e5-af21-0401358ea401<commit_msg>5e589439-2d16-11e5-af21-0401358ea401<commit_after>5e589439-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <stdio.h> #include <graphics.h> #include <time.h> #include "includes/peciman.h" #include "includes/ghost.h" #include "includes/game.h" #include "includes/map.h" #include "includes/score.h" #include "includes/interfaces.h" #include "includes/list.h" #include "includes/multiplayer.h" #include "map.cpp" #include "peciman.cpp" #include "ghost.cpp" #include "score.cpp" #include "game.cpp" #include "interfaces.cpp" #include "list.cpp" #include "multiplayer.cpp" //playerControl player1; int main() { initwindow(800, 600, "Pecimen Game"); PlaySound("sounds/bgm.wav",NULL,SND_ASYNC | SND_LOOP); menuutama(); getch(); closegraph(); return 0; } <commit_msg>unsave multyplayer<commit_after>#include <stdio.h> #include <graphics.h> #include <time.h> #include "includes/peciman.h" #include "includes/ghost.h" #include "includes/game.h" #include "includes/map.h" #include "includes/score.h" #include "includes/interfaces.h" #include "includes/list.h" //#include "includes/multiplayer.h" #include "map.cpp" #include "peciman.cpp" #include "ghost.cpp" #include "score.cpp" #include "game.cpp" #include "interfaces.cpp" #include "list.cpp" //#include "multiplayer.cpp" //playerControl player1; int main() { initwindow(800, 600, "Pecimen Game"); PlaySound("sounds/bgm.wav",NULL,SND_ASYNC | SND_LOOP); menuutama(); getch(); closegraph(); return 0; } <|endoftext|>
<commit_before>83000e62-2d15-11e5-af21-0401358ea401<commit_msg>83000e63-2d15-11e5-af21-0401358ea401<commit_after>83000e63-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>// Copyright (c) 2005-2022 Jay Berkenbilt // // This file is part of qpdf. // // 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. // // Versions of qpdf prior to version 7 were released under the terms // of version 2.0 of the Artistic License. At your option, you may // continue to consider qpdf to be licensed under those terms. Please // see the manual for additional information. #ifndef POINTERHOLDER_HH #define POINTERHOLDER_HH #define POINTERHOLDER_IS_SHARED_POINTER #ifndef POINTERHOLDER_TRANSITION // #define POINTERHOLDER_TRANSITION 0 to suppress this warning, and see below. // See also https://qpdf.readthedocs.io/en/stable/design.html#smart-pointers # warn "POINTERHOLDER_TRANSITION is not defined -- see qpdf/PointerHolder.hh" // undefined = define as 0 and issue a warning // 0 = no deprecation warnings, backward-compatible API // 1 = make PointerHolder<T>(T*) explicit // 2 = warn for use of getPointer() and getRefcount() // 3 = warn for all use of PointerHolder // 4 = don't define PointerHolder at all # define POINTERHOLDER_TRANSITION 0 #endif // !defined(POINTERHOLDER_TRANSITION) #if POINTERHOLDER_TRANSITION < 4 // *** WHAT IS HAPPENING *** // In qpdf 11, PointerHolder will be replaced with std::shared_ptr // wherever it appears in the qpdf API. The PointerHolder object will // be derived from std::shared_ptr to provide a backward-compatible // interface and will be mutually assignable with std::shared_ptr. // Code that uses containers of PointerHolder will require adjustment. // *** HOW TO TRANSITION *** // The symbol POINTERHOLDER_TRANSITION can be defined to help you // transition your code away from PointerHolder. You can define it // before including any qpdf header files or including its definition // in your build configuration. If not defined, it automatically gets // defined to 0, which enables full backward compatibility. That way, // you don't have to take action for your code to continue to work. // If you want to work gradually to transition your code away from // PointerHolder, you can define POINTERHOLDER_TRANSITION and fix the // code so it compiles without warnings and works correctly. If you // want to be able to continue to support old qpdf versions at the // same time, you can write code like this: // #ifndef POINTERHOLDER_TRANSITION // ... use PointerHolder as before 10.6 // #else // ... use PointerHolder or shared_ptr as needed // #endif // Each level of POINTERHOLDER_TRANSITION exposes differences between // PointerHolder and std::shared_ptr. The easiest way to transition is // to increase POINTERHOLDER_TRANSITION in steps of 1 so that you can // test and handle changes incrementally. // *** Transitions available starting at qpdf 10.6.0 *** // POINTERHOLDER_TRANSITION = 1 // // PointerHolder<T> has an implicit constructor that takes a T*, so // you can replace a PointerHolder<T>'s pointer by directly assigning // a T* to it or pass a T* to a function that expects a // PointerHolder<T>. std::shared_ptr does not have this (risky) // behavior. When POINTERHOLDER_TRANSITION = 1, PointerHolder<T>'s T* // constructor is declared explicit. For compatibility with // std::shared_ptr, you can still assign nullptr to a PointerHolder. // Constructing all your PointerHolder<T> instances explicitly is // backward compatible, so you can make this change without // conditional compilation and still use the changes with older qpdf // versions. // // Also defined is a make_pointer_holder method that acts like // std::make_shared. You can use this as well, but it is not // compatible with qpdf prior to 10.6. Like std::make_shared<T>, // make_pointer_holder<T> can only be used when the constructor // implied by its arguments is public. If you use this, you should be // able to just replace it with std::make_shared when qpdf 11 is out. // POINTERHOLDER_TRANSITION = 2 // // std::shared_ptr as get() and use_count(). PointerHolder has // getPointer() and getRefcount(). In 10.6.0, get() and use_count() // were added as well. When POINTERHOLDER_TRANSITION = 2, getPointer() // and getRefcount() are deprecated. Fix deprecation warnings by // replacing with get() and use_count(). This breaks compatibility // with qpdf older than 10.6. Search for CONST BEHAVIOR for an // additional note. // // Once your code is clean at POINTERHOLDER_TRANSITION = 2, the only // remaining issues that prevent simple replacement of PointerHolder // with std::shared_ptr are shared arrays and containers, and neither // of these are used in the qpdf API. // *** Transitions available starting at qpdf 11.0.0 ** // NOTE: Until qpdf 11 is released, this is a plan and is subject to // change. Be sure to check again after qpdf 11 is released. // POINTERHOLDER_TRANSITION = 3 // // Warn for all use of PointerHolder<T>. This helps you remove all use // of PointerHolder from your code and use std::shared_ptr instead. // You will also have to transition any containers of PointerHolder in // your code. // POINTERHOLDER_TRANSITION = 4 // // Suppress definition of the PointerHolder<T> type entirely. // CONST BEHAVIOR // PointerHolder<T> has had a long-standing bug in its const behavior. // const PointerHolder<T>'s getPointer() method returns a T const*. // This is incorrect and is not how regular pointers or standard // library smart pointers behave. Making a PointerHolder<T> const // should prevent reassignment of its pointer but not affect the thing // it points to. For that, use PointerHolder<T const>. The new get() // method behaves correctly in this respect and is therefore slightly // different from getPointer(). This shouldn't break any correctly // written code. If you are relying on the incorrect behavior, use // PointerHolder<T const> instead. # include <cstddef> # include <memory> template <class T> class PointerHolder: public std::shared_ptr<T> { public: # if POINTERHOLDER_TRANSITION >= 3 [[deprecated("use std::shared_ptr<T> instead")]] # endif // POINTERHOLDER_TRANSITION >= 3 PointerHolder(std::shared_ptr<T> other) : std::shared_ptr<T>(other) { } # if POINTERHOLDER_TRANSITION >= 3 [[deprecated("use std::shared_ptr<T> instead")]] # if POINTERHOLDER_TRANSITION >= 1 explicit # endif // POINTERHOLDER_TRANSITION >= 1 # endif // POINTERHOLDER_TRANSITION >= 3 PointerHolder(T* pointer = 0) : std::shared_ptr<T>(pointer) { } // Create a shared pointer to an array # if POINTERHOLDER_TRANSITION >= 3 [[deprecated("use std::shared_ptr<T> instead")]] # endif // POINTERHOLDER_TRANSITION >= 3 PointerHolder(bool, T* pointer) : std::shared_ptr<T>(pointer, std::default_delete<T[]>()) { } virtual ~PointerHolder() = default; # if POINTERHOLDER_TRANSITION >= 2 [[deprecated("use PointerHolder<T>::get() instead of getPointer()")]] # endif // POINTERHOLDER_TRANSITION >= 2 T* getPointer() { return this->get(); } # if POINTERHOLDER_TRANSITION >= 2 [[deprecated("use PointerHolder<T>::get() instead of getPointer()")]] # endif // POINTERHOLDER_TRANSITION >= 2 T const* getPointer() const { return this->get(); } # if POINTERHOLDER_TRANSITION >= 2 [[deprecated("use PointerHolder<T>::get() instead of getPointer()")]] # endif // POINTERHOLDER_TRANSITION >= 2 int getRefcount() const { return static_cast<int>(this->use_count()); } PointerHolder& operator=(decltype(nullptr)) { std::shared_ptr<T>::operator=(nullptr); return *this; } T const& operator*() const { return *(this->get()); } T& operator*() { return *(this->get()); } T const* operator->() const { return this->get(); } T* operator->() { return this->get(); } }; template <typename T, typename... _Args> inline PointerHolder<T> make_pointer_holder(_Args&&... __args) { return PointerHolder<T>(new T(__args...)); } template <typename T> PointerHolder<T> make_array_pointer_holder(size_t n) { return PointerHolder<T>(true, new T[n]); } #endif // POINTERHOLDER_TRANSITION < 4 #endif // POINTERHOLDER_HH <commit_msg>Typo: warn -> warning<commit_after>// Copyright (c) 2005-2022 Jay Berkenbilt // // This file is part of qpdf. // // 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. // // Versions of qpdf prior to version 7 were released under the terms // of version 2.0 of the Artistic License. At your option, you may // continue to consider qpdf to be licensed under those terms. Please // see the manual for additional information. #ifndef POINTERHOLDER_HH #define POINTERHOLDER_HH #define POINTERHOLDER_IS_SHARED_POINTER #ifndef POINTERHOLDER_TRANSITION // #define POINTERHOLDER_TRANSITION 0 to suppress this warning, and see below. // See also https://qpdf.readthedocs.io/en/stable/design.html#smart-pointers # warning "POINTERHOLDER_TRANSITION is not defined -- see qpdf/PointerHolder.hh" // undefined = define as 0 and issue a warning // 0 = no deprecation warnings, backward-compatible API // 1 = make PointerHolder<T>(T*) explicit // 2 = warn for use of getPointer() and getRefcount() // 3 = warn for all use of PointerHolder // 4 = don't define PointerHolder at all # define POINTERHOLDER_TRANSITION 0 #endif // !defined(POINTERHOLDER_TRANSITION) #if POINTERHOLDER_TRANSITION < 4 // *** WHAT IS HAPPENING *** // In qpdf 11, PointerHolder will be replaced with std::shared_ptr // wherever it appears in the qpdf API. The PointerHolder object will // be derived from std::shared_ptr to provide a backward-compatible // interface and will be mutually assignable with std::shared_ptr. // Code that uses containers of PointerHolder will require adjustment. // *** HOW TO TRANSITION *** // The symbol POINTERHOLDER_TRANSITION can be defined to help you // transition your code away from PointerHolder. You can define it // before including any qpdf header files or including its definition // in your build configuration. If not defined, it automatically gets // defined to 0, which enables full backward compatibility. That way, // you don't have to take action for your code to continue to work. // If you want to work gradually to transition your code away from // PointerHolder, you can define POINTERHOLDER_TRANSITION and fix the // code so it compiles without warnings and works correctly. If you // want to be able to continue to support old qpdf versions at the // same time, you can write code like this: // #ifndef POINTERHOLDER_TRANSITION // ... use PointerHolder as before 10.6 // #else // ... use PointerHolder or shared_ptr as needed // #endif // Each level of POINTERHOLDER_TRANSITION exposes differences between // PointerHolder and std::shared_ptr. The easiest way to transition is // to increase POINTERHOLDER_TRANSITION in steps of 1 so that you can // test and handle changes incrementally. // *** Transitions available starting at qpdf 10.6.0 *** // POINTERHOLDER_TRANSITION = 1 // // PointerHolder<T> has an implicit constructor that takes a T*, so // you can replace a PointerHolder<T>'s pointer by directly assigning // a T* to it or pass a T* to a function that expects a // PointerHolder<T>. std::shared_ptr does not have this (risky) // behavior. When POINTERHOLDER_TRANSITION = 1, PointerHolder<T>'s T* // constructor is declared explicit. For compatibility with // std::shared_ptr, you can still assign nullptr to a PointerHolder. // Constructing all your PointerHolder<T> instances explicitly is // backward compatible, so you can make this change without // conditional compilation and still use the changes with older qpdf // versions. // // Also defined is a make_pointer_holder method that acts like // std::make_shared. You can use this as well, but it is not // compatible with qpdf prior to 10.6. Like std::make_shared<T>, // make_pointer_holder<T> can only be used when the constructor // implied by its arguments is public. If you use this, you should be // able to just replace it with std::make_shared when qpdf 11 is out. // POINTERHOLDER_TRANSITION = 2 // // std::shared_ptr as get() and use_count(). PointerHolder has // getPointer() and getRefcount(). In 10.6.0, get() and use_count() // were added as well. When POINTERHOLDER_TRANSITION = 2, getPointer() // and getRefcount() are deprecated. Fix deprecation warnings by // replacing with get() and use_count(). This breaks compatibility // with qpdf older than 10.6. Search for CONST BEHAVIOR for an // additional note. // // Once your code is clean at POINTERHOLDER_TRANSITION = 2, the only // remaining issues that prevent simple replacement of PointerHolder // with std::shared_ptr are shared arrays and containers, and neither // of these are used in the qpdf API. // *** Transitions available starting at qpdf 11.0.0 ** // NOTE: Until qpdf 11 is released, this is a plan and is subject to // change. Be sure to check again after qpdf 11 is released. // POINTERHOLDER_TRANSITION = 3 // // Warn for all use of PointerHolder<T>. This helps you remove all use // of PointerHolder from your code and use std::shared_ptr instead. // You will also have to transition any containers of PointerHolder in // your code. // POINTERHOLDER_TRANSITION = 4 // // Suppress definition of the PointerHolder<T> type entirely. // CONST BEHAVIOR // PointerHolder<T> has had a long-standing bug in its const behavior. // const PointerHolder<T>'s getPointer() method returns a T const*. // This is incorrect and is not how regular pointers or standard // library smart pointers behave. Making a PointerHolder<T> const // should prevent reassignment of its pointer but not affect the thing // it points to. For that, use PointerHolder<T const>. The new get() // method behaves correctly in this respect and is therefore slightly // different from getPointer(). This shouldn't break any correctly // written code. If you are relying on the incorrect behavior, use // PointerHolder<T const> instead. # include <cstddef> # include <memory> template <class T> class PointerHolder: public std::shared_ptr<T> { public: # if POINTERHOLDER_TRANSITION >= 3 [[deprecated("use std::shared_ptr<T> instead")]] # endif // POINTERHOLDER_TRANSITION >= 3 PointerHolder(std::shared_ptr<T> other) : std::shared_ptr<T>(other) { } # if POINTERHOLDER_TRANSITION >= 3 [[deprecated("use std::shared_ptr<T> instead")]] # if POINTERHOLDER_TRANSITION >= 1 explicit # endif // POINTERHOLDER_TRANSITION >= 1 # endif // POINTERHOLDER_TRANSITION >= 3 PointerHolder(T* pointer = 0) : std::shared_ptr<T>(pointer) { } // Create a shared pointer to an array # if POINTERHOLDER_TRANSITION >= 3 [[deprecated("use std::shared_ptr<T> instead")]] # endif // POINTERHOLDER_TRANSITION >= 3 PointerHolder(bool, T* pointer) : std::shared_ptr<T>(pointer, std::default_delete<T[]>()) { } virtual ~PointerHolder() = default; # if POINTERHOLDER_TRANSITION >= 2 [[deprecated("use PointerHolder<T>::get() instead of getPointer()")]] # endif // POINTERHOLDER_TRANSITION >= 2 T* getPointer() { return this->get(); } # if POINTERHOLDER_TRANSITION >= 2 [[deprecated("use PointerHolder<T>::get() instead of getPointer()")]] # endif // POINTERHOLDER_TRANSITION >= 2 T const* getPointer() const { return this->get(); } # if POINTERHOLDER_TRANSITION >= 2 [[deprecated("use PointerHolder<T>::get() instead of getPointer()")]] # endif // POINTERHOLDER_TRANSITION >= 2 int getRefcount() const { return static_cast<int>(this->use_count()); } PointerHolder& operator=(decltype(nullptr)) { std::shared_ptr<T>::operator=(nullptr); return *this; } T const& operator*() const { return *(this->get()); } T& operator*() { return *(this->get()); } T const* operator->() const { return this->get(); } T* operator->() { return this->get(); } }; template <typename T, typename... _Args> inline PointerHolder<T> make_pointer_holder(_Args&&... __args) { return PointerHolder<T>(new T(__args...)); } template <typename T> PointerHolder<T> make_array_pointer_holder(size_t n) { return PointerHolder<T>(true, new T[n]); } #endif // POINTERHOLDER_TRANSITION < 4 #endif // POINTERHOLDER_HH <|endoftext|>
<commit_before>94194efd-2e4f-11e5-babf-28cfe91dbc4b<commit_msg>94214333-2e4f-11e5-8900-28cfe91dbc4b<commit_after>94214333-2e4f-11e5-8900-28cfe91dbc4b<|endoftext|>
<commit_before>#pragma once #include <quote/button.hpp> namespace quote{ template <class Traits> class flat_button: public button<Traits>{ typename Traits::solid_brush brush[3]; typename Traits::text text; typename Traits::color color[3]; protected: virtual void set_state(state) override; public: flat_button(); void set_text(const wchar_t *); void set_text_color(state, typename Traits::color); void set_text_size(float); void set_color(state, typename Traits::color); virtual void set_position(const typename Traits::point &) override; virtual void set_size(const typename Traits::size &) override; virtual bool create_resource(const typename Traits::creation_params &) override; virtual void destroy_resource() override; virtual void draw(const typename Traits::paint_params &) override; }; } #include <quote/impl/flat_button.hpp> <commit_msg>add quote::flat_button::get_font<commit_after>#pragma once #include <quote/button.hpp> namespace quote{ template <class Traits> class flat_button: public button<Traits>{ typename Traits::solid_brush brush[3]; typename Traits::text text; typename Traits::color color[3]; protected: virtual void set_state(state) override; public: flat_button(); void set_text(const wchar_t *); void set_text_color(state, typename Traits::color); void set_text_size(float); void set_color(state, typename Traits::color); virtual void set_position(const typename Traits::point &) override; virtual void set_size(const typename Traits::size &) override; virtual bool create_resource(const typename Traits::creation_params &) override; virtual void destroy_resource() override; virtual void draw(const typename Traits::paint_params &) override; typename Traits::font &get_font() { return text.get_font(); } }; } #include <quote/impl/flat_button.hpp> <|endoftext|>
<commit_before>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -lpthread -shared-libgcc opencv.cpp -o opencv #include "evision.h" #include "tracer.h" #include "gpio.h" // Global variables GPIO pwm_right(1, "out"), pwm_left(3, "out"); // led_right(2 , "out"); GPIO led_front(5, "out"), led_R(4, "out"), start(7 ,"out"); // 0,2,6 bulit int high_right = 600, high_left = 600, period = 20000; //PWM high time in us int top_edge = 50, servo_offset = 0, road_offset = 0; // GUI globals cv::Mat guiframe; bool new_frame = false; bool running = true; // Window titles char main_window_name[] = "Lightning Asystant :: Team eVision"; char settings_window_name[] = "Settings :: Team eVision"; // Settings variables int settings_show_step = 0; int settings_contrast = 0; int settings_blur = 1; int settings_threshold = 128; int settings_servo_offset = 500; int settings_road_approx = 5; int settings_middle_line = 240; // Graphics std::vector<std::vector<cv::Point>> contours; //Functions declaration void pwm_servo_right(int); void pwm_servo_left(int); int car_position(int); int obstacle_position(int); int main(int argc, char** argv) { pthread_t processing_thread; long time_old; int fps_counter = 0; int gui_key; // for cpu affinity cpu_set_t cpuset; int cpu = 0; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); // process priority setpriority(PRIO_PROCESS, 0, -20); // GUI setup cv::namedWindow(main_window_name); // Setup window cv::namedWindow(settings_window_name); cv::createTrackbar("Show Step ", settings_window_name, &settings_show_step, LAST_STEP-1); cv::createTrackbar("Contrast ", settings_window_name, &settings_contrast, 1); cv::createTrackbar("Mean Blur ", settings_window_name, &settings_blur, 1); cv::createTrackbar("Threshold ", settings_window_name, &settings_threshold, 255); cv::createTrackbar("Road Approx ", settings_window_name, &settings_road_approx, 30); cv::createTrackbar("Middle Line ", settings_window_name, &settings_middle_line, 320); cv::createTrackbar("Servo Offset", settings_window_name, &settings_servo_offset, 1000); cv::createTrackbar("Servo Right ", settings_window_name, &high_right, 1500); cv::createTrackbar("Servo Left ", settings_window_name, &high_left, 1500); pthread_create(&processing_thread, NULL, processing_thread_function, NULL); //pthread_create(&pwm_thread, NULL, pwm_thread_function, NULL); while(running){ while(!new_frame){ } // loop cv::imshow(main_window_name, guiframe); // calculate fps if(time(NULL) != time_old){ add_info(fps_counter); fps_counter = 1; time_old = time(NULL); } else { fps_counter++; } new_frame = 0; gui_key = cv::waitKey(5); if(gui_key >= 0) { gui_key %= 0xFF; // ESC if((gui_key == 43) || (gui_key == 27)){ led_front.low(); led_R.low(); running = false; } else if((gui_key == 48) || (gui_key == 32)) { start.high(); // 1 = start/stop usleep(50000); start.low(); } else if((gui_key == 50) || (gui_key == 66)) { led_front.toggle(); // 2 = faruri } else if((gui_key == 51) || (gui_key == 67)) { led_R.toggle(); // 3 = far pieton } else { std::cout << gui_key << std::endl; } } } pthread_join(processing_thread, NULL); // the camera will be deinitialized automatically in VideoCapture destructor return 0; } void send_frame_to_gui(cv::Mat &frame, int step){ if((new_frame == 0) && (step == settings_show_step)){ //cv::pyrUp(frame, guiframe); frame.copyTo(guiframe); new_frame = 1; } } bool contour_area(int a, int b){ return cv::contourArea(contours[a]) > cv::contourArea(contours[b]); } bool get_obstacle( int parent, std::vector<std::vector<cv::Point>> contours, std::vector<cv::Vec4i> hierarchy, cv::Rect &obstacle){ int start = hierarchy[parent][2]; int closest = -1; bool found = false; while(start > 0){ if(closest == -1){ closest = start; found = true; } else if(cv::boundingRect(contours[start]).y > cv::boundingRect(contours[closest]).y){ closest = start; } start = hierarchy[start][0]; } if(found){ obstacle = cv::boundingRect(contours[closest]); } return found; } void draw_obstacles(cv::Mat &threshold_frame, cv::Mat &cam_frame){ std::vector<std::vector<cv::Point>> road(2); std::vector<cv::Vec4i> hierarchy; cv::findContours(threshold_frame, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); if(contours.size() > 1){ // create index vector std::vector<int> contour_indexes(contours.size()); for(unsigned int i = 0; i < contours.size(); i++){ contour_indexes[i] = i; } // sorting index vector acording to controur area std::sort(contour_indexes.begin(), contour_indexes.end(), contour_area); cv::approxPolyDP(cv::Mat(contours[contour_indexes[0]]), road[0], settings_road_approx, true); cv::approxPolyDP(cv::Mat(contours[contour_indexes[1]]), road[1], settings_road_approx, true); // validate road detection int road_edge = -1; for(unsigned int i = 0; i < road[0].size(); ++i){ if((road[0][i].y > 235) && (road_edge == -1)){ road_edge = road[0][i].x; } else if((road[0][i].y > 235) && (road[0][i].x < road_edge)){ road_edge = road[0][i].x; } } if(road_edge < 0) return ; for(unsigned int i = 0; i < road[1].size(); ++i){ if((road[1][i].y > 235) && (road[1][i].x > road_edge)){ // wrong detection return; } } // paint road area cv::drawContours(cam_frame, road, 0, cv::Scalar(0, 255 ,0), 2); cv::drawContours(cam_frame, road, 1, cv::Scalar(255, 0, 0), 2); // get road offset // reference point is the left most point from the top edge of road contour int new_road_offset = 600; for(unsigned int i = 0; i < road[0].size(); ++i){ if((road[0][i].y == top_edge) && (road[0][i].x < new_road_offset)){ new_road_offset = road[0][i].x; } } if((new_road_offset > 50) && (new_road_offset < 250)){ road_offset = new_road_offset; } //std::cout << road_offset << std::endl; cv::Rect obstacle; if(get_obstacle(contour_indexes[0], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(0, 0, 255)); //std::cout << cv::Point(obstacle.x + (obstacle.width / 2), obstacle.y + (obstacle.height / 2)) << std::endl; pwm_servo_right(high_right + servo_offset + road_offset + obstacle_position(obstacle.y + (obstacle.height / 2))); } if(get_obstacle(contour_indexes[1], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(255, 0, 255)); pwm_servo_left(high_left + servo_offset + road_offset + car_position(0)); } cv::line(cam_frame, cv::Point(settings_middle_line, 320), cv::Point(settings_middle_line, top_edge), cv::Scalar(0, 255, 255)); } } void *processing_thread_function(void* unsused) { cv::VideoCapture cap(0); // camera interface cv::Mat frame, cam_frame, bw_frame, blur_frame, contrast_frame; cv::Mat threshold_frame, canny_frame, contour_frame; Tracer processing_tracer; // for cpu affinity cpu_set_t cpuset; int cpu = 1; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); if(!cap.isOpened()) // check if we succeeded { std::cout << "Could not open default video device" << std::endl; pthread_exit(NULL); } while(running) { if( !cap.read(frame) ){ std::cout << "Camera was disconected"; break; } cv::pyrDown(frame, cam_frame); send_frame_to_gui(cam_frame, SENSOR_IMAGE); processing_tracer.start(); // All processing are done on gray image cv::cvtColor(cam_frame, bw_frame, CV_BGR2GRAY); processing_tracer.event("Convert to Gray"); send_frame_to_gui(bw_frame, GRAY_IMAGE); // Increase contrast by distributing color histogram to contain all values if(settings_contrast){ cv::equalizeHist(bw_frame, contrast_frame); } else { contrast_frame = bw_frame; } processing_tracer.event("Equalize histogram"); send_frame_to_gui(contrast_frame, CONTRAST_IMAGE); // Apply a special blur filter which preserves edges if(settings_blur){ cv::medianBlur(contrast_frame, blur_frame, 7); } else { blur_frame = contrast_frame; } processing_tracer.event("Median blur"); send_frame_to_gui(blur_frame, BLUR_IMAGE); // detect edges using histeresys cv::Canny(contrast_frame, canny_frame, 30, 100); processing_tracer.event("Edge detection"); send_frame_to_gui(canny_frame, CANNY_IMAGE); // Apply threshhold threshold(blur_frame, threshold_frame, settings_threshold, 255, CV_THRESH_BINARY); // Disable image top from detection to remove false edges cv::rectangle(threshold_frame, cv::Rect(0, 0, 320, top_edge), cv::Scalar(0), CV_FILLED); processing_tracer.event("Appling threshold"); send_frame_to_gui(threshold_frame, THRESHOLD_IMAGE); // detect and paint contours draw_obstacles(threshold_frame, cam_frame); processing_tracer.event("Contour detection"); send_frame_to_gui(cam_frame, CONTOUR_IMAGE); } processing_tracer.end(); pthread_exit(NULL); } void pwm_servo_right(int h_r){ int static local_hr = 0; if(abs(h_r - local_hr) > 5){ local_hr = h_r; pwm_right.high(); usleep(local_hr); pwm_right.low(); usleep(period - local_hr); } } void pwm_servo_left(int h_l){ int static local_hl = 0; if(abs(h_l - local_hl) > 5){ local_hl = h_l; pwm_left.high(); usleep(local_hl); pwm_left.low(); usleep(period - local_hl); } } int obstacle_position(int y_position){ if(y_position > top_edge){ return int ( 0.9 * y_position + 15); } else { return 0; } } int car_position(int y_position){ if(y_position > top_edge){ return 1; } else { return 0; } } void add_info(int fps){ // white canvas cv::Mat img_info (25, 320, CV_8UC3, cv::Scalar(255, 255, 255)); cv::putText(img_info, std::string("FPS: ") + std::to_string(fps), cv::Point(5, 20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,0,255), 1, CV_AA); cv::imshow(settings_window_name, img_info); } <commit_msg>changed min servo step from 5 to 2<commit_after>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -lpthread -shared-libgcc opencv.cpp -o opencv #include "evision.h" #include "tracer.h" #include "gpio.h" // Global variables GPIO pwm_right(1, "out"), pwm_left(3, "out"); // led_right(2 , "out"); GPIO led_front(5, "out"), led_R(4, "out"), start(7 ,"out"); // 0,2,6 bulit int high_right = 600, high_left = 600, period = 20000; //PWM high time in us int top_edge = 50, servo_offset = 0, road_offset = 0; // GUI globals cv::Mat guiframe; bool new_frame = false; bool running = true; // Window titles char main_window_name[] = "Lightning Asystant :: Team eVision"; char settings_window_name[] = "Settings :: Team eVision"; // Settings variables int settings_show_step = 0; int settings_contrast = 0; int settings_blur = 1; int settings_threshold = 128; int settings_servo_offset = 500; int settings_road_approx = 5; int settings_middle_line = 240; // Graphics std::vector<std::vector<cv::Point>> contours; //Functions declaration void pwm_servo_right(int); void pwm_servo_left(int); int car_position(int); int obstacle_position(int); int main(int argc, char** argv) { pthread_t processing_thread; long time_old; int fps_counter = 0; int gui_key; // for cpu affinity cpu_set_t cpuset; int cpu = 0; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); // process priority setpriority(PRIO_PROCESS, 0, -20); // GUI setup cv::namedWindow(main_window_name); // Setup window cv::namedWindow(settings_window_name); cv::createTrackbar("Show Step ", settings_window_name, &settings_show_step, LAST_STEP-1); cv::createTrackbar("Contrast ", settings_window_name, &settings_contrast, 1); cv::createTrackbar("Mean Blur ", settings_window_name, &settings_blur, 1); cv::createTrackbar("Threshold ", settings_window_name, &settings_threshold, 255); cv::createTrackbar("Road Approx ", settings_window_name, &settings_road_approx, 30); cv::createTrackbar("Middle Line ", settings_window_name, &settings_middle_line, 320); cv::createTrackbar("Servo Offset", settings_window_name, &settings_servo_offset, 1000); cv::createTrackbar("Servo Right ", settings_window_name, &high_right, 1500); cv::createTrackbar("Servo Left ", settings_window_name, &high_left, 1500); pthread_create(&processing_thread, NULL, processing_thread_function, NULL); //pthread_create(&pwm_thread, NULL, pwm_thread_function, NULL); while(running){ while(!new_frame){ } // loop cv::imshow(main_window_name, guiframe); // calculate fps if(time(NULL) != time_old){ add_info(fps_counter); fps_counter = 1; time_old = time(NULL); } else { fps_counter++; } new_frame = 0; gui_key = cv::waitKey(5); if(gui_key >= 0) { gui_key %= 0xFF; // ESC if((gui_key == 43) || (gui_key == 27)){ led_front.low(); led_R.low(); running = false; } else if((gui_key == 48) || (gui_key == 32)) { start.high(); // 1 = start/stop usleep(50000); start.low(); } else if((gui_key == 50) || (gui_key == 66)) { led_front.toggle(); // 2 = faruri } else if((gui_key == 51) || (gui_key == 67)) { led_R.toggle(); // 3 = far pieton } else { std::cout << gui_key << std::endl; } } } pthread_join(processing_thread, NULL); // the camera will be deinitialized automatically in VideoCapture destructor return 0; } void send_frame_to_gui(cv::Mat &frame, int step){ if((new_frame == 0) && (step == settings_show_step)){ //cv::pyrUp(frame, guiframe); frame.copyTo(guiframe); new_frame = 1; } } bool contour_area(int a, int b){ return cv::contourArea(contours[a]) > cv::contourArea(contours[b]); } bool get_obstacle( int parent, std::vector<std::vector<cv::Point>> contours, std::vector<cv::Vec4i> hierarchy, cv::Rect &obstacle){ int start = hierarchy[parent][2]; int closest = -1; bool found = false; while(start > 0){ if(closest == -1){ closest = start; found = true; } else if(cv::boundingRect(contours[start]).y > cv::boundingRect(contours[closest]).y){ closest = start; } start = hierarchy[start][0]; } if(found){ obstacle = cv::boundingRect(contours[closest]); } return found; } void draw_obstacles(cv::Mat &threshold_frame, cv::Mat &cam_frame){ std::vector<std::vector<cv::Point>> road(2); std::vector<cv::Vec4i> hierarchy; cv::findContours(threshold_frame, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); if(contours.size() > 1){ // create index vector std::vector<int> contour_indexes(contours.size()); for(unsigned int i = 0; i < contours.size(); i++){ contour_indexes[i] = i; } // sorting index vector acording to controur area std::sort(contour_indexes.begin(), contour_indexes.end(), contour_area); cv::approxPolyDP(cv::Mat(contours[contour_indexes[0]]), road[0], settings_road_approx, true); cv::approxPolyDP(cv::Mat(contours[contour_indexes[1]]), road[1], settings_road_approx, true); // validate road detection int road_edge = -1; for(unsigned int i = 0; i < road[0].size(); ++i){ if((road[0][i].y > 235) && (road_edge == -1)){ road_edge = road[0][i].x; } else if((road[0][i].y > 235) && (road[0][i].x < road_edge)){ road_edge = road[0][i].x; } } if(road_edge < 0) return ; for(unsigned int i = 0; i < road[1].size(); ++i){ if((road[1][i].y > 235) && (road[1][i].x > road_edge)){ // wrong detection return; } } // paint road area cv::drawContours(cam_frame, road, 0, cv::Scalar(0, 255 ,0), 2); cv::drawContours(cam_frame, road, 1, cv::Scalar(255, 0, 0), 2); // get road offset // reference point is the left most point from the top edge of road contour int new_road_offset = 600; for(unsigned int i = 0; i < road[0].size(); ++i){ if((road[0][i].y == top_edge) && (road[0][i].x < new_road_offset)){ new_road_offset = road[0][i].x; } } if((new_road_offset > 50) && (new_road_offset < 250)){ road_offset = new_road_offset; } //std::cout << road_offset << std::endl; cv::Rect obstacle; if(get_obstacle(contour_indexes[0], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(0, 0, 255)); //std::cout << cv::Point(obstacle.x + (obstacle.width / 2), obstacle.y + (obstacle.height / 2)) << std::endl; pwm_servo_right(high_right + servo_offset + road_offset + obstacle_position(obstacle.y + (obstacle.height / 2))); } if(get_obstacle(contour_indexes[1], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(2 55, 0, 255)); pwm_servo_left(high_left + servo_offset + road_offset + car_position(0)); } cv::line(cam_frame, cv::Point(settings_middle_line, 320), cv::Point(settings_middle_line, top_edge), cv::Scalar(0, 255, 255)); } } void *processing_thread_function(void* unsused) { cv::VideoCapture cap(0); // camera interface cv::Mat frame, cam_frame, bw_frame, blur_frame, contrast_frame; cv::Mat threshold_frame, canny_frame, contour_frame; Tracer processing_tracer; // for cpu affinity cpu_set_t cpuset; int cpu = 1; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); if(!cap.isOpened()) // check if we succeeded { std::cout << "Could not open default video device" << std::endl; pthread_exit(NULL); } while(running) { if( !cap.read(frame) ){ std::cout << "Camera was disconected"; break; } cv::pyrDown(frame, cam_frame); send_frame_to_gui(cam_frame, SENSOR_IMAGE); processing_tracer.start(); // All processing are done on gray image cv::cvtColor(cam_frame, bw_frame, CV_BGR2GRAY); processing_tracer.event("Convert to Gray"); send_frame_to_gui(bw_frame, GRAY_IMAGE); // Increase contrast by distributing color histogram to contain all values if(settings_contrast){ cv::equalizeHist(bw_frame, contrast_frame); } else { contrast_frame = bw_frame; } processing_tracer.event("Equalize histogram"); send_frame_to_gui(contrast_frame, CONTRAST_IMAGE); // Apply a special blur filter which preserves edges if(settings_blur){ cv::medianBlur(contrast_frame, blur_frame, 7); } else { blur_frame = contrast_frame; } processing_tracer.event("Median blur"); send_frame_to_gui(blur_frame, BLUR_IMAGE); // detect edges using histeresys cv::Canny(contrast_frame, canny_frame, 30, 100); processing_tracer.event("Edge detection"); send_frame_to_gui(canny_frame, CANNY_IMAGE); // Apply threshhold threshold(blur_frame, threshold_frame, settings_threshold, 255, CV_THRESH_BINARY); // Disable image top from detection to remove false edges cv::rectangle(threshold_frame, cv::Rect(0, 0, 320, top_edge), cv::Scalar(0), CV_FILLED); processing_tracer.event("Appling threshold"); send_frame_to_gui(threshold_frame, THRESHOLD_IMAGE); // detect and paint contours draw_obstacles(threshold_frame, cam_frame); processing_tracer.event("Contour detection"); send_frame_to_gui(cam_frame, CONTOUR_IMAGE); } processing_tracer.end(); pthread_exit(NULL); } void pwm_servo_right(int h_r){ int static local_hr = 0; if(abs(h_r - local_hr) > 2){ local_hr = h_r; pwm_right.high(); usleep(local_hr); pwm_right.low(); usleep(period - local_hr); } } void pwm_servo_left(int h_l){ int static local_hl = 0; if(abs(h_l - local_hl) > 2){ local_hl = h_l; pwm_left.high(); usleep(local_hl); pwm_left.low(); usleep(period - local_hl); } } int obstacle_position(int y_position){ if(y_position > top_edge){ return int ( 0.9 * y_position + 15); } else { return 0; } } int car_position(int y_position){ if(y_position > top_edge){ return 1; } else { return 0; } } void add_info(int fps){ // white canvas cv::Mat img_info (25, 320, CV_8UC3, cv::Scalar(255, 255, 255)); cv::putText(img_info, std::string("FPS: ") + std::to_string(fps), cv::Point(5, 20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,0,255), 1, CV_AA); cv::imshow(settings_window_name, img_info); } <|endoftext|>
<commit_before>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -lpthread -shared-libgcc opencv.cpp -o opencv #include "evision.h" #include "tracer.h" #include "gpio.h" // Global variables GPIO pwm_right(1, "out"), pwm_left(3, "out"); // led_right(2 , "out"); GPIO led_front(5, "out"), led_R(4, "out"), start(7 ,"out"); // 0,2,6 bulit int high_right = 600, high_left = 600, period = 20000; //PWM high time in us int top_edge = 50, servo_offset = 0, road_offset = 0; int car_left_offset = 0, obstacle_offset = 0; // GUI globals cv::Mat guiframe; bool new_frame = false; bool running = true; // Window titles char main_window_name[] = "Lightning Asystant :: Team eVision"; char settings_window_name[] = "Settings :: Team eVision"; // Settings variables int settings_show_step = 0; int settings_contrast = 0; int settings_blur = 1; int settings_threshold = 128; int settings_servo_offset = 500; int settings_road_approx = 5; int settings_middle_line = 240; // Graphics std::vector<std::vector<cv::Point>> contours; //Functions declaration void pwm_servo_right(int); void pwm_servo_left(int); void set_servo_offset(int); void set_road_offset(int); void set_car_left_offset(int); void set_obstacle_offset(int); int main(int argc, char** argv) { pthread_t processing_thread; long time_old; int fps_counter = 0; int gui_key; // for cpu affinity cpu_set_t cpuset; int cpu = 0; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); // process priority setpriority(PRIO_PROCESS, 0, -20); // GUI setup cv::namedWindow(main_window_name); // Setup window cv::namedWindow(settings_window_name); cv::createTrackbar("Show Step ", settings_window_name, &settings_show_step, LAST_STEP-1); cv::createTrackbar("Contrast ", settings_window_name, &settings_contrast, 1); cv::createTrackbar("Mean Blur ", settings_window_name, &settings_blur, 1); cv::createTrackbar("Threshold ", settings_window_name, &settings_threshold, 255); cv::createTrackbar("Road Approx ", settings_window_name, &settings_road_approx, 30); cv::createTrackbar("Middle Line ", settings_window_name, &settings_middle_line, 320); cv::createTrackbar("Servo Offset", settings_window_name, &settings_servo_offset, 1000); cv::createTrackbar("Servo Right ", settings_window_name, &high_right, 1500); cv::createTrackbar("Servo Left ", settings_window_name, &high_left, 1500); pthread_create(&processing_thread, NULL, processing_thread_function, NULL); //pthread_create(&pwm_thread, NULL, pwm_thread_function, NULL); while(running){ while(!new_frame){ } // loop cv::imshow(main_window_name, guiframe); // calculate fps if(time(NULL) != time_old){ add_info(fps_counter); fps_counter = 1; time_old = time(NULL); } else { fps_counter++; } new_frame = 0; gui_key = cv::waitKey(5); if(gui_key >= 0) { gui_key %= 0xFF; // ESC if((gui_key == 43) || (gui_key == 27)){ led_front.low(); led_R.low(); running = false; } else if((gui_key == 48) || (gui_key == 32)) { start.high(); // 1 = start/stop usleep(50000); start.low(); } else if((gui_key == 50) || (gui_key == 66)) { led_front.toggle(); // 2 = faruri } else if((gui_key == 51) || (gui_key == 67)) { led_R.toggle(); // 3 = far pieton } else { std::cout << gui_key << std::endl; } } } pthread_join(processing_thread, NULL); // the camera will be deinitialized automatically in VideoCapture destructor return 0; } void send_frame_to_gui(cv::Mat &frame, int step){ if((new_frame == 0) && (step == settings_show_step)){ //cv::pyrUp(frame, guiframe); frame.copyTo(guiframe); new_frame = 1; } } bool contour_area(int a, int b){ return cv::contourArea(contours[a]) > cv::contourArea(contours[b]); } bool get_obstacle( int parent, std::vector<std::vector<cv::Point>> contours, std::vector<cv::Vec4i> hierarchy, cv::Rect &obstacle){ int start = hierarchy[parent][2]; int closest = -1; bool found = false; while(start > 0){ if(closest == -1){ closest = start; found = true; } else if(cv::boundingRect(contours[start]).y > cv::boundingRect(contours[closest]).y){ closest = start; } start = hierarchy[start][0]; } if(found){ obstacle = cv::boundingRect(contours[closest]); } return found; } void *processing_thread_function(void* unsused) { cv::VideoCapture cap(0); // camera interface cv::Mat frame, cam_frame, bw_frame, blur_frame, contrast_frame; cv::Mat threshold_frame, canny_frame, contour_frame; Tracer processing_tracer; std::vector<std::vector<cv::Point>> road(2); std::vector<cv::Vec4i> hierarchy; // for cpu affinity cpu_set_t cpuset; int cpu = 1; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); if(!cap.isOpened()) // check if we succeeded { std::cout << "Could not open default video device" << std::endl; pthread_exit(NULL); } while(running) { if( !cap.read(frame) ){ std::cout << "Camera was disconected"; break; } cv::pyrDown(frame, cam_frame); send_frame_to_gui(cam_frame, SENSOR_IMAGE); processing_tracer.start(); // All processing are done on gray image cv::cvtColor(cam_frame, bw_frame, CV_BGR2GRAY); processing_tracer.event("Convert to Gray"); send_frame_to_gui(bw_frame, GRAY_IMAGE); // Increase contrast by distributing color histogram to contain all values if(settings_contrast){ cv::equalizeHist(bw_frame, contrast_frame); } else { contrast_frame = bw_frame; } processing_tracer.event("Equalize histogram"); send_frame_to_gui(contrast_frame, CONTRAST_IMAGE); // Apply a special blur filter which preserves edges if(settings_blur){ cv::medianBlur(contrast_frame, blur_frame, 7); } else { blur_frame = contrast_frame; } processing_tracer.event("Median blur"); send_frame_to_gui(blur_frame, BLUR_IMAGE); // detect edges using histeresys cv::Canny(contrast_frame, canny_frame, 30, 100); processing_tracer.event("Edge detection"); send_frame_to_gui(canny_frame, CANNY_IMAGE); // Apply threshhold threshold(blur_frame, threshold_frame, settings_threshold, 255, CV_THRESH_BINARY); // Disable image top from detection to remove false edges cv::rectangle(threshold_frame, cv::Rect(0, 0, 320, top_edge), cv::Scalar(0), CV_FILLED); processing_tracer.event("Appling threshold"); send_frame_to_gui(threshold_frame, THRESHOLD_IMAGE); // detect and paint contours cv::findContours(threshold_frame, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); if(contours.size() > 1){ std::vector<int> contour_indexes(contours.size()); // create index vector for(unsigned int i = 0; i < contours.size(); i++){ contour_indexes[i] = i; } // sorting index vector acording to controur area std::sort(contour_indexes.begin(), contour_indexes.end(), contour_area); cv::approxPolyDP(cv::Mat(contours[contour_indexes[0]]), road[0], settings_road_approx, true); cv::drawContours(cam_frame, road, 0, cv::Scalar(0, 255 ,0), 2); cv::approxPolyDP(cv::Mat(contours[contour_indexes[1]]), road[1], settings_road_approx, true); cv::drawContours(cam_frame, road, 1, cv::Scalar(255, 0, 0), 2); // get road offset // reference point is the left most point from the top edge of road contour int new_road_offset = 600; for(unsigned int i = 0; i < road[0].size(); ++i){ if((road[0][i].y == top_edge) && (road[0][i].x < new_road_offset)){ new_road_offset = road[0][i].x; } } if((new_road_offset > 50) && (new_road_offset < 250)){ road_offset = new_road_offset; } std::cout << road_offset << std::endl; cv::Rect obstacle; if(get_obstacle(contour_indexes[0], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(0, 0, 255)); std::cout << cv::Point(obstacle.x + (obstacle.width / 2), obstacle.y + (obstacle.height / 2)) << std::endl; } if(get_obstacle(contour_indexes[1], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(255, 0, 255)); } cv::line(cam_frame, cv::Point(settings_middle_line, 320), cv::Point(settings_middle_line, top_edge), cv::Scalar(0, 255, 255)); } processing_tracer.event("Contour detection"); send_frame_to_gui(cam_frame, CONTOUR_IMAGE); pwm_servo_right(high_right); pwm_servo_left(high_left); } processing_tracer.end(); pthread_exit(NULL); } void pwm_servo_right(int h_r){ int static local_hr = 0; if(abs(h_r - local_hr) > 5){ local_hr = h_r; pwm_right.high(); usleep(local_hr); pwm_right.low(); usleep(period - local_hr); } } void pwm_servo_left(int h_l){ int static local_hl = 0; if(abs(h_l - local_hl) > 5){ local_hl = h_l; pwm_left.high(); usleep(local_hl); pwm_left.low(); usleep(period - local_hl); } } void set_servo_offset(int servo_offset){ high_right = high_right + servo_offset; high_left = high_left + servo_offset; } void set_road_offset(int road_offset){ high_right = high_right + road_offset; high_left = high_left + road_offset; } void set_obstacle_offset(int y_position){ obstacle_offset = int (0.9 * y_position + 15); high_right = high_right + obstacle_offset; //de facut dezactivarea obstacle_offset } void set_car_offset(int y_position){ //????? high_left = high_left + car_left_offset; } void add_info(int fps){ // white canvas cv::Mat img_info (25, 320, CV_8UC3, cv::Scalar(255, 255, 255)); cv::putText(img_info, std::string("FPS: ") + std::to_string(fps), cv::Point(5, 20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,0,255), 1, CV_AA); cv::imshow(settings_window_name, img_info); } <commit_msg>Road validation<commit_after>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -lpthread -shared-libgcc opencv.cpp -o opencv #include "evision.h" #include "tracer.h" #include "gpio.h" // Global variables GPIO pwm_right(1, "out"), pwm_left(3, "out"); // led_right(2 , "out"); GPIO led_front(5, "out"), led_R(4, "out"), start(7 ,"out"); // 0,2,6 bulit int high_right = 600, high_left = 600, period = 20000; //PWM high time in us int top_edge = 50, servo_offset = 0, road_offset = 0; int car_left_offset = 0, obstacle_offset = 0; // GUI globals cv::Mat guiframe; bool new_frame = false; bool running = true; // Window titles char main_window_name[] = "Lightning Asystant :: Team eVision"; char settings_window_name[] = "Settings :: Team eVision"; // Settings variables int settings_show_step = 0; int settings_contrast = 0; int settings_blur = 1; int settings_threshold = 128; int settings_servo_offset = 500; int settings_road_approx = 5; int settings_middle_line = 240; // Graphics std::vector<std::vector<cv::Point>> contours; //Functions declaration void pwm_servo_right(int); void pwm_servo_left(int); void set_servo_offset(int); void set_road_offset(int); void set_car_left_offset(int); void set_obstacle_offset(int); int main(int argc, char** argv) { pthread_t processing_thread; long time_old; int fps_counter = 0; int gui_key; // for cpu affinity cpu_set_t cpuset; int cpu = 0; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); // process priority setpriority(PRIO_PROCESS, 0, -20); // GUI setup cv::namedWindow(main_window_name); // Setup window cv::namedWindow(settings_window_name); cv::createTrackbar("Show Step ", settings_window_name, &settings_show_step, LAST_STEP-1); cv::createTrackbar("Contrast ", settings_window_name, &settings_contrast, 1); cv::createTrackbar("Mean Blur ", settings_window_name, &settings_blur, 1); cv::createTrackbar("Threshold ", settings_window_name, &settings_threshold, 255); cv::createTrackbar("Road Approx ", settings_window_name, &settings_road_approx, 30); cv::createTrackbar("Middle Line ", settings_window_name, &settings_middle_line, 320); cv::createTrackbar("Servo Offset", settings_window_name, &settings_servo_offset, 1000); cv::createTrackbar("Servo Right ", settings_window_name, &high_right, 1500); cv::createTrackbar("Servo Left ", settings_window_name, &high_left, 1500); pthread_create(&processing_thread, NULL, processing_thread_function, NULL); //pthread_create(&pwm_thread, NULL, pwm_thread_function, NULL); while(running){ while(!new_frame){ } // loop cv::imshow(main_window_name, guiframe); // calculate fps if(time(NULL) != time_old){ add_info(fps_counter); fps_counter = 1; time_old = time(NULL); } else { fps_counter++; } new_frame = 0; gui_key = cv::waitKey(5); if(gui_key >= 0) { gui_key %= 0xFF; // ESC if((gui_key == 43) || (gui_key == 27)){ led_front.low(); led_R.low(); running = false; } else if((gui_key == 48) || (gui_key == 32)) { start.high(); // 1 = start/stop usleep(50000); start.low(); } else if((gui_key == 50) || (gui_key == 66)) { led_front.toggle(); // 2 = faruri } else if((gui_key == 51) || (gui_key == 67)) { led_R.toggle(); // 3 = far pieton } else { std::cout << gui_key << std::endl; } } } pthread_join(processing_thread, NULL); // the camera will be deinitialized automatically in VideoCapture destructor return 0; } void send_frame_to_gui(cv::Mat &frame, int step){ if((new_frame == 0) && (step == settings_show_step)){ //cv::pyrUp(frame, guiframe); frame.copyTo(guiframe); new_frame = 1; } } bool contour_area(int a, int b){ return cv::contourArea(contours[a]) > cv::contourArea(contours[b]); } bool get_obstacle( int parent, std::vector<std::vector<cv::Point>> contours, std::vector<cv::Vec4i> hierarchy, cv::Rect &obstacle){ int start = hierarchy[parent][2]; int closest = -1; bool found = false; while(start > 0){ if(closest == -1){ closest = start; found = true; } else if(cv::boundingRect(contours[start]).y > cv::boundingRect(contours[closest]).y){ closest = start; } start = hierarchy[start][0]; } if(found){ obstacle = cv::boundingRect(contours[closest]); } return found; } void draw_obstacles(cv::Mat &threshold_frame, cv::Mat &cam_frame){ std::vector<std::vector<cv::Point>> road(2); std::vector<cv::Vec4i> hierarchy; cv::findContours(threshold_frame, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); if(contours.size() > 1){ // create index vector std::vector<int> contour_indexes(contours.size()); for(unsigned int i = 0; i < contours.size(); i++){ contour_indexes[i] = i; } // sorting index vector acording to controur area std::sort(contour_indexes.begin(), contour_indexes.end(), contour_area); cv::approxPolyDP(cv::Mat(contours[contour_indexes[0]]), road[0], settings_road_approx, true); cv::drawContours(cam_frame, road, 0, cv::Scalar(0, 255 ,0), 2); cv::approxPolyDP(cv::Mat(contours[contour_indexes[1]]), road[1], settings_road_approx, true); cv::drawContours(cam_frame, road, 1, cv::Scalar(255, 0, 0), 2); // validate road detection int road_edge = -1; for(unsigned int i = 0; i < road[0].size(); ++i){ if((road[0][i].y == 320) && (road_edge == -1)){ road_edge = road[0][i].x; } else if((road[0][i].y == 320) && (road[0][i].x < road_edge)){ road_edge = road[0][i].x; } } if(road_edge < 0) return ; for(unsigned int i = 0; i < road[1].size(); ++i){ if((road[1][i].y == 320) && (road[1][i].x > road_edge)){ // wrong detection return; } } // get road offset // reference point is the left most point from the top edge of road contour int new_road_offset = 600; for(unsigned int i = 0; i < road[0].size(); ++i){ if((road[0][i].y == top_edge) && (road[0][i].x < new_road_offset)){ new_road_offset = road[0][i].x; } } if((new_road_offset > 50) && (new_road_offset < 250)){ road_offset = new_road_offset; } std::cout << road_offset << std::endl; cv::Rect obstacle; if(get_obstacle(contour_indexes[0], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(0, 0, 255)); std::cout << cv::Point(obstacle.x + (obstacle.width / 2), obstacle.y + (obstacle.height / 2)) << std::endl; } if(get_obstacle(contour_indexes[1], contours, hierarchy, obstacle)){ cv::rectangle(cam_frame, obstacle, cv::Scalar(255, 0, 255)); } cv::line(cam_frame, cv::Point(settings_middle_line, 320), cv::Point(settings_middle_line, top_edge), cv::Scalar(0, 255, 255)); } } void *processing_thread_function(void* unsused) { cv::VideoCapture cap(0); // camera interface cv::Mat frame, cam_frame, bw_frame, blur_frame, contrast_frame; cv::Mat threshold_frame, canny_frame, contour_frame; Tracer processing_tracer; // for cpu affinity cpu_set_t cpuset; int cpu = 1; CPU_ZERO(&cpuset); //clears the cpuset CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset sched_setaffinity(0, sizeof(cpuset), &cpuset); if(!cap.isOpened()) // check if we succeeded { std::cout << "Could not open default video device" << std::endl; pthread_exit(NULL); } while(running) { if( !cap.read(frame) ){ std::cout << "Camera was disconected"; break; } cv::pyrDown(frame, cam_frame); send_frame_to_gui(cam_frame, SENSOR_IMAGE); processing_tracer.start(); // All processing are done on gray image cv::cvtColor(cam_frame, bw_frame, CV_BGR2GRAY); processing_tracer.event("Convert to Gray"); send_frame_to_gui(bw_frame, GRAY_IMAGE); // Increase contrast by distributing color histogram to contain all values if(settings_contrast){ cv::equalizeHist(bw_frame, contrast_frame); } else { contrast_frame = bw_frame; } processing_tracer.event("Equalize histogram"); send_frame_to_gui(contrast_frame, CONTRAST_IMAGE); // Apply a special blur filter which preserves edges if(settings_blur){ cv::medianBlur(contrast_frame, blur_frame, 7); } else { blur_frame = contrast_frame; } processing_tracer.event("Median blur"); send_frame_to_gui(blur_frame, BLUR_IMAGE); // detect edges using histeresys cv::Canny(contrast_frame, canny_frame, 30, 100); processing_tracer.event("Edge detection"); send_frame_to_gui(canny_frame, CANNY_IMAGE); // Apply threshhold threshold(blur_frame, threshold_frame, settings_threshold, 255, CV_THRESH_BINARY); // Disable image top from detection to remove false edges cv::rectangle(threshold_frame, cv::Rect(0, 0, 320, top_edge), cv::Scalar(0), CV_FILLED); processing_tracer.event("Appling threshold"); send_frame_to_gui(threshold_frame, THRESHOLD_IMAGE); // detect and paint contours draw_obstacles(threshold_frame, cam_frame); processing_tracer.event("Contour detection"); send_frame_to_gui(cam_frame, CONTOUR_IMAGE); pwm_servo_right(high_right); pwm_servo_left(high_left); } processing_tracer.end(); pthread_exit(NULL); } void pwm_servo_right(int h_r){ int static local_hr = 0; if(abs(h_r - local_hr) > 5){ local_hr = h_r; pwm_right.high(); usleep(local_hr); pwm_right.low(); usleep(period - local_hr); } } void pwm_servo_left(int h_l){ int static local_hl = 0; if(abs(h_l - local_hl) > 5){ local_hl = h_l; pwm_left.high(); usleep(local_hl); pwm_left.low(); usleep(period - local_hl); } } void set_servo_offset(int servo_offset){ high_right = high_right + servo_offset; high_left = high_left + servo_offset; } void set_road_offset(int road_offset){ high_right = high_right + road_offset; high_left = high_left + road_offset; } void set_obstacle_offset(int y_position){ obstacle_offset = int (0.9 * y_position + 15); high_right = high_right + obstacle_offset; //de facut dezactivarea obstacle_offset } void set_car_offset(int y_position){ //????? high_left = high_left + car_left_offset; } void add_info(int fps){ // white canvas cv::Mat img_info (25, 320, CV_8UC3, cv::Scalar(255, 255, 255)); cv::putText(img_info, std::string("FPS: ") + std::to_string(fps), cv::Point(5, 20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,0,255), 1, CV_AA); cv::imshow(settings_window_name, img_info); } <|endoftext|>
<commit_before>97006fee-2e4f-11e5-8e84-28cfe91dbc4b<commit_msg>97082568-2e4f-11e5-9801-28cfe91dbc4b<commit_after>97082568-2e4f-11e5-9801-28cfe91dbc4b<|endoftext|>
<commit_before>d9920a4f-2e4e-11e5-a665-28cfe91dbc4b<commit_msg>d9992c66-2e4e-11e5-b88b-28cfe91dbc4b<commit_after>d9992c66-2e4e-11e5-b88b-28cfe91dbc4b<|endoftext|>
<commit_before>1c248346-2f67-11e5-b1c4-6c40088e03e4<commit_msg>1c2b6012-2f67-11e5-b3f0-6c40088e03e4<commit_after>1c2b6012-2f67-11e5-b3f0-6c40088e03e4<|endoftext|>
<commit_before>3fb6c2eb-2e4f-11e5-8e25-28cfe91dbc4b<commit_msg>3fbecb40-2e4f-11e5-a904-28cfe91dbc4b<commit_after>3fbecb40-2e4f-11e5-a904-28cfe91dbc4b<|endoftext|>
<commit_before>a0abec19-327f-11e5-ab17-9cf387a8033e<commit_msg>a0b1c645-327f-11e5-b010-9cf387a8033e<commit_after>a0b1c645-327f-11e5-b010-9cf387a8033e<|endoftext|>
<commit_before>801055dc-ad5b-11e7-b734-ac87a332f658<commit_msg>Really doesn't crash if X, now<commit_after>806f4859-ad5b-11e7-8caa-ac87a332f658<|endoftext|>
<commit_before>e457186e-2747-11e6-9b0b-e0f84713e7b8<commit_msg>I'm done<commit_after>e467d4a6-2747-11e6-903f-e0f84713e7b8<|endoftext|>
<commit_before>d3a4474f-2747-11e6-b56e-e0f84713e7b8<commit_msg>My Backup<commit_after>d3bcf3f3-2747-11e6-bc69-e0f84713e7b8<|endoftext|>
<commit_before>cf956d80-327f-11e5-a01f-9cf387a8033e<commit_msg>cf9bab26-327f-11e5-a5bc-9cf387a8033e<commit_after>cf9bab26-327f-11e5-a5bc-9cf387a8033e<|endoftext|>
<commit_before>620d31a6-5216-11e5-9626-6c40088e03e4<commit_msg>62141494-5216-11e5-b2de-6c40088e03e4<commit_after>62141494-5216-11e5-b2de-6c40088e03e4<|endoftext|>
<commit_before>9b9307d1-2747-11e6-9c79-e0f84713e7b8<commit_msg>Initial commit.2<commit_after>9b9cc95c-2747-11e6-95e0-e0f84713e7b8<|endoftext|>
<commit_before>2a14a7bd-2d3f-11e5-8193-c82a142b6f9b<commit_msg>2a728fb0-2d3f-11e5-8807-c82a142b6f9b<commit_after>2a728fb0-2d3f-11e5-8807-c82a142b6f9b<|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: bulkDataNTGenReceiver.cpp,v 1.14 2013/03/15 17:51:57 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * bjeram 2011-04-19 created */ #include "bulkDataNTReceiverStream.h" #include "bulkDataNTCallback.h" #include <iostream> #include <ace/Get_Opt.h> #include <ace/Tokenizer_T.h> using namespace std; class TestCB: public BulkDataNTCallback { public: TestCB() { totalRcvData=0; } virtual ~TestCB() { std::cout << "Total received data for: " << getStreamName() << "#" << getFlowName() << " : " << totalRcvData << std::endl; } int cbStart(unsigned char* userParam_p, unsigned int size) { // we cannot initialize flow name and flow stream in ctor, because they are after CB object is created fn = getFlowName(); sn = getStreamName(); std::cout << "cbStart[ " << sn << "#" << fn << " ]: got a parameter: "; for(unsigned int i=0; i<size; i++) { std::cout << *(char*)(userParam_p+i); } std::cout << " of size: " << size << std::endl; frameCount = 0; rcvDataStartStop = 0; return 0; }//cbStart int cbReceive(unsigned char* data, unsigned int size) { rcvDataStartStop+=size; totalRcvData+=size; frameCount++; if (cbReceivePrint) { std::cout << "cbReceive[ " << sn << "#" << fn << " ]: got data of size: " << size << " ("; std::cout << rcvDataStartStop << ", " << frameCount << ") :"; /* for(unsigned int i=0; i<frame_p->length(); i++) { std::cout << *(char*)(frame_p->base()+i); } */ std::cout << std::endl; } if (cbDealy>0) { ACE_Time_Value start_time, elapsed_time; start_time = ACE_OS::gettimeofday(); elapsed_time = ACE_OS::gettimeofday() - start_time; // usleep(cbDealy); while (elapsed_time.usec() < cbDealy) { elapsed_time = ACE_OS::gettimeofday() - start_time; } } return 0; } int cbStop() { std::cout << "cbStop[ " << sn << "#" << fn << " ]" << std::endl; return 0; } static long cbDealy; static bool cbReceivePrint; private: std::string fn; ///flow Name std::string sn; ///stream name unsigned int totalRcvData; ///total size of all received data unsigned int rcvDataStartStop; ///size of received data between Start/stop unsigned int frameCount; ///frame count }; long TestCB::cbDealy = 0; bool TestCB::cbReceivePrint=true; void print_usage(char *argv[]) { cout << "Usage: " << argv[0] << " [-s streamName] -f flow1Name[,flow2Name,flow3Name...] [-d cbReceive delay(sleep) in usec] [-u[unicast port] unicast mode] [-m multicast address] [-n suppers printing in cbReceive]" << endl; exit(1); } int main(int argc, char *argv[]) { char c; ReceiverStreamConfiguration streamCfg; ReceiverFlowConfiguration flowCfg; char *streamName = "DefaultStream"; string qosLib="BulkDataQoSLibrary"; /*char unicastPortQoS[250]; unsigned int unicastPort=24000; */ //char multicastAdd[100]; list<char *> flowNames; // Parse the args ACE_Get_Opt get_opts (argc, argv, "s:f:d:m:u::n"); if(get_opts.long_option(ACE_TEXT ("qos_lib"), 0, ACE_Get_Opt::ARG_REQUIRED) == -1) { cerr << "long option: qos_lib can not be added" << endl; return -1; } while(( c = get_opts()) != -1 ) { switch(c) { case 0: //long option (qos_lib) { qosLib = get_opts.opt_arg(); break; } case 'n': { TestCB::cbReceivePrint=false; break; } case 'm': { flowCfg.setMulticastAddress(get_opts.opt_arg()); break; } case 'u': { flowCfg.setEnableMulticast(false); char *op=get_opts.opt_arg(); if (op!=NULL) { flowCfg.setUnicastPort(atoi(op)); } break; } case 's': { streamName = get_opts.opt_arg(); break; } case 'f': { ACE_Tokenizer tok(get_opts.opt_arg()); tok.delimiter_replace(',', 0); for(char *p = tok.next(); p; p = tok.next()) flowNames.push_back(p); break; } case 'd': { TestCB::cbDealy = atoi(get_opts.opt_arg()); break; } }//case }//while if( flowNames.size() == 0 ) print_usage(argv); LoggingProxy m_logger(0, 0, 31, 0); LoggingProxy::init (&m_logger); ACS_CHECK_LOGGER; vector<BulkDataNTReceiverFlow*> flows; //streamCfg.setUseIncrementUnicastPort(false); //streamCfg.setParticipantPerStream(true); streamCfg.setQosLibrary(qosLib.c_str());//"TCPBulkDataQoSLibrary"); /* ReceiverStreamConfiguration streamCfg100; streamCfg100.setQosLibrary("XBulkDataQoSLibrary"); AcsBulkdata::BulkDataNTReceiverStream<TestCB> receiverStream100("TEST", streamCfg100); */ AcsBulkdata::BulkDataNTReceiverStream<TestCB> receiverStream(streamName, streamCfg); //flowCfg.setUnicastPort(47000); flowCfg.setQosLibrary(qosLib.c_str());//"TCPBulkDataQoSLibrary"); list<char *>::iterator it; //unsigned int j=0; for(it = flowNames.begin(); it != flowNames.end(); it++) { /* sprintf(unicastPortQoS, "<datareader_qos><unicast><value><element><receive_port>%ud</receive_port></element></value></unicast></datareader_qos>", unicastPort++); flowCfg.setDDSReceiverFlowQoS((*it), unicastPortQoS); */ /* sprintf(multicastAdd, "225.3.2.%d", j++); flowCfg.setMulticastAddress(multicastAdd); */ BulkDataNTReceiverFlow *flow = receiverStream.createFlow((*it), flowCfg); flows.push_back(flow); flow->getCallback<TestCB>(); //flowCfg.setProfileQos("TCPDefaultStreamQosProfile"); // BulkDataNTReceiverFlow *flow100 = receiverStream100.createFlow((*it), flowCfg); } std::vector<string> actflowNames = receiverStream.getFlowNames(); std::cout << "Waiting on the following " << receiverStream.getFlowNumber() << " flow(s):[ "; for(unsigned int i=0;i<actflowNames.size(); i++) std::cout << actflowNames[i] << " "; std::cout << "] of stream: " << streamName << std::endl; std::cout << "Press a key to exit.." << std::endl; getchar(); unsigned int numOfCreatedFlows = receiverStream.getFlowNumber(); for(unsigned int i=0; i<numOfCreatedFlows; i++) { flows[i]->dumpStatistics(); } } <commit_msg>Added the possibility to save the data that is being received on the generic receiver into a file<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: bulkDataNTGenReceiver.cpp,v 1.15 2013/03/16 20:25:02 rtobar Exp $" * * who when what * -------- -------- ---------------------------------------------- * bjeram 2011-04-19 created */ #include "bulkDataNTReceiverStream.h" #include "bulkDataNTCallback.h" #include <iostream> #include <iosfwd> #include <ace/Get_Opt.h> #include <ace/Tokenizer_T.h> using namespace std; class TestCB: public BulkDataNTCallback { public: TestCB() : dataToStore(0) { totalRcvData=0; } virtual ~TestCB() { std::cout << "Total received data for: " << getStreamName() << "#" << getFlowName() << " : " << totalRcvData << std::endl; } int cbStart(unsigned char* userParam_p, unsigned int size) { // we cannot initialize flow name and flow stream in ctor, because they are after CB object is created fn = getFlowName(); sn = getStreamName(); std::cout << "cbStart[ " << sn << "#" << fn << " ]: got a parameter: "; if( storeData ) { dataToStore.push_back(size); // TODO: this trims an uint into an unsigned char (2/4 bytes to 1) } for(unsigned int i=0; i<size; i++) { std::cout << *(char*)(userParam_p+i); if( storeData ) { dataToStore.push_back(*(userParam_p+i)); } } std::cout << " of size: " << size << std::endl; frameCount = 0; rcvDataStartStop = 0; return 0; }//cbStart int cbReceive(unsigned char* data, unsigned int size) { rcvDataStartStop+=size; totalRcvData+=size; frameCount++; if (cbReceivePrint) { std::cout << "cbReceive[ " << sn << "#" << fn << " ]: got data of size: " << size << " ("; std::cout << rcvDataStartStop << ", " << frameCount << ") :"; /* for(unsigned int i=0; i<frame_p->length(); i++) { std::cout << *(char*)(frame_p->base()+i); } */ std::cout << std::endl; } if (cbDealy>0) { ACE_Time_Value start_time, elapsed_time; start_time = ACE_OS::gettimeofday(); elapsed_time = ACE_OS::gettimeofday() - start_time; // usleep(cbDealy); while (elapsed_time.usec() < cbDealy) { elapsed_time = ACE_OS::gettimeofday() - start_time; } } if( storeData ) { for(unsigned int i=0; i<size; i++) { dataToStore.push_back(*(data + i)); } } return 0; } int cbStop() { std::cout << "cbStop[ " << sn << "#" << fn << " ]" << std::endl; return 0; } void setStoreData(bool shouldStoreData) { storeData = shouldStoreData; } list<unsigned char> getData() { return dataToStore; } uint16_t getUserParamSize() { return userParamSize; } static long cbDealy; static bool cbReceivePrint; private: std::string fn; ///flow Name std::string sn; ///stream name unsigned int totalRcvData; ///total size of all received data unsigned int rcvDataStartStop; ///size of received data between Start/stop unsigned int frameCount; ///frame count bool storeData; uint16_t userParamSize; list<unsigned char> dataToStore; }; long TestCB::cbDealy = 0; bool TestCB::cbReceivePrint=true; void print_usage(char *argv[]) { cout << "Usage: " << argv[0] << " [-s streamName] -f flow1Name[,flow2Name,flow3Name...] [-d cbReceive delay(sleep) in usec] [-u[unicast port] unicast mode] [-m multicast address] [-n suppers printing in cbReceive] [-w output filename prefix]" << endl; exit(1); } int main(int argc, char *argv[]) { char c; ReceiverStreamConfiguration streamCfg; ReceiverFlowConfiguration flowCfg; char *streamName = "DefaultStream"; char *outputFilenamePrefix = 0; string qosLib="BulkDataQoSLibrary"; /*char unicastPortQoS[250]; unsigned int unicastPort=24000; */ //char multicastAdd[100]; list<char *> flowNames; // Parse the args ACE_Get_Opt get_opts (argc, argv, "s:f:d:m:u::nw:"); if(get_opts.long_option(ACE_TEXT ("qos_lib"), 0, ACE_Get_Opt::ARG_REQUIRED) == -1) { cerr << "long option: qos_lib can not be added" << endl; return -1; } while(( c = get_opts()) != -1 ) { switch(c) { case 0: //long option (qos_lib) { qosLib = get_opts.opt_arg(); break; } case 'n': { TestCB::cbReceivePrint=false; break; } case 'm': { flowCfg.setMulticastAddress(get_opts.opt_arg()); break; } case 'u': { flowCfg.setEnableMulticast(false); char *op=get_opts.opt_arg(); if (op!=NULL) { flowCfg.setUnicastPort(atoi(op)); } break; } case 's': { streamName = get_opts.opt_arg(); break; } case 'f': { ACE_Tokenizer tok(get_opts.opt_arg()); tok.delimiter_replace(',', 0); for(char *p = tok.next(); p; p = tok.next()) flowNames.push_back(p); break; } case 'd': { TestCB::cbDealy = atoi(get_opts.opt_arg()); break; } case 'w': { outputFilenamePrefix = strdup(get_opts.opt_arg()); break; } }//case }//while if( flowNames.size() == 0 ) print_usage(argv); LoggingProxy m_logger(0, 0, 31, 0); LoggingProxy::init (&m_logger); ACS_CHECK_LOGGER; vector<BulkDataNTReceiverFlow*> flows; vector<TestCB*> callbacks; //streamCfg.setUseIncrementUnicastPort(false); //streamCfg.setParticipantPerStream(true); streamCfg.setQosLibrary(qosLib.c_str());//"TCPBulkDataQoSLibrary"); /* ReceiverStreamConfiguration streamCfg100; streamCfg100.setQosLibrary("XBulkDataQoSLibrary"); AcsBulkdata::BulkDataNTReceiverStream<TestCB> receiverStream100("TEST", streamCfg100); */ AcsBulkdata::BulkDataNTReceiverStream<TestCB> receiverStream(streamName, streamCfg); //flowCfg.setUnicastPort(47000); flowCfg.setQosLibrary(qosLib.c_str());//"TCPBulkDataQoSLibrary"); list<char *>::iterator it; //unsigned int j=0; for(it = flowNames.begin(); it != flowNames.end(); it++) { /* sprintf(unicastPortQoS, "<datareader_qos><unicast><value><element><receive_port>%ud</receive_port></element></value></unicast></datareader_qos>", unicastPort++); flowCfg.setDDSReceiverFlowQoS((*it), unicastPortQoS); */ /* sprintf(multicastAdd, "225.3.2.%d", j++); flowCfg.setMulticastAddress(multicastAdd); */ TestCB *cb = new TestCB(); cb->setStoreData(outputFilenamePrefix != 0); BulkDataNTReceiverFlow *flow = receiverStream.createFlow((*it), flowCfg, cb); flows.push_back(flow); callbacks.push_back(cb); // flow->getCallback<TestCB>(); //flowCfg.setProfileQos("TCPDefaultStreamQosProfile"); // BulkDataNTReceiverFlow *flow100 = receiverStream100.createFlow((*it), flowCfg); } std::vector<string> actflowNames = receiverStream.getFlowNames(); std::cout << "Waiting on the following " << receiverStream.getFlowNumber() << " flow(s):[ "; for(unsigned int i=0;i<actflowNames.size(); i++) std::cout << actflowNames[i] << " "; std::cout << "] of stream: " << streamName << std::endl; std::cout << "Press a key to exit.." << std::endl; getchar(); unsigned int numOfCreatedFlows = receiverStream.getFlowNumber(); for(unsigned int i=0; i<numOfCreatedFlows; i++) { flows[i]->dumpStatistics(); if( outputFilenamePrefix != 0 ) { string filename; filename += outputFilenamePrefix; filename += "_"; filename += flows[i]->getName(); list<unsigned char> data = callbacks[i]->getData(); std::ofstream ofs(filename.c_str()); std::ostream_iterator<unsigned char> it(ofs); std::copy(data.begin(), data.end(), it); ofs.close(); } delete callbacks[i]; } } <|endoftext|>
<commit_before>78703fca-2d53-11e5-baeb-247703a38240<commit_msg>7870bc84-2d53-11e5-baeb-247703a38240<commit_after>7870bc84-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkVersorRigid3DTransform_hxx #define itkVersorRigid3DTransform_hxx #include "itkVersorRigid3DTransform.h" namespace itk { // Constructor with default arguments template<typename TParametersValueType> VersorRigid3DTransform<TParametersValueType> ::VersorRigid3DTransform() : Superclass(ParametersDimension) { } // Constructor with arguments template<typename TParametersValueType> VersorRigid3DTransform<TParametersValueType>::VersorRigid3DTransform(unsigned int paramDim) : Superclass(paramDim) { } // Constructor with arguments template<typename TParametersValueType> VersorRigid3DTransform<TParametersValueType>::VersorRigid3DTransform(const MatrixType & matrix, const OutputVectorType & offset) : Superclass(matrix, offset) { } // Set Parameters template<typename TParametersValueType> void VersorRigid3DTransform<TParametersValueType> ::SetParameters(const ParametersType & parameters) { itkDebugMacro(<< "Setting parameters " << parameters); // Save parameters. Needed for proper operation of TransformUpdateParameters. if( &parameters != &(this->m_Parameters) ) { this->m_Parameters = parameters; } // Transfer the versor part AxisType axis; double norm = parameters[0] * parameters[0]; axis[0] = parameters[0]; norm += parameters[1] * parameters[1]; axis[1] = parameters[1]; norm += parameters[2] * parameters[2]; axis[2] = parameters[2]; if( norm > 0 ) { norm = std::sqrt(norm); } double epsilon = 1e-10; if( norm >= 1.0 - epsilon ) { axis = axis / ( norm + epsilon * norm ); } VersorType newVersor; newVersor.Set(axis); this->SetVarVersor(newVersor); this->ComputeMatrix(); itkDebugMacro( << "Versor is now " << this->GetVersor() ); // Transfer the translation part TranslationType newTranslation; newTranslation[0] = parameters[3]; newTranslation[1] = parameters[4]; newTranslation[2] = parameters[5]; this->SetVarTranslation(newTranslation); this->ComputeOffset(); // Modified is always called since we just have a pointer to the // parameters and cannot know if the parameters have changed. this->Modified(); itkDebugMacro(<< "After setting parameters "); } // // Get Parameters // // Parameters are ordered as: // // p[0:2] = right part of the versor (axis times std::sin(t/2)) // p[3:5} = translation components // template<typename TParametersValueType> const typename VersorRigid3DTransform<TParametersValueType>::ParametersType & VersorRigid3DTransform<TParametersValueType> ::GetParameters(void) const { itkDebugMacro(<< "Getting parameters "); this->m_Parameters[0] = this->GetVersor().GetX(); this->m_Parameters[1] = this->GetVersor().GetY(); this->m_Parameters[2] = this->GetVersor().GetZ(); // Transfer the translation this->m_Parameters[3] = this->GetTranslation()[0]; this->m_Parameters[4] = this->GetTranslation()[1]; this->m_Parameters[5] = this->GetTranslation()[2]; itkDebugMacro(<< "After getting parameters " << this->m_Parameters); return this->m_Parameters; } template<typename TParametersValueType> void VersorRigid3DTransform<TParametersValueType> ::UpdateTransformParameters( const DerivativeType & update, TParametersValueType factor ) { SizeValueType numberOfParameters = this->GetNumberOfParameters(); if( update.Size() != numberOfParameters ) { itkExceptionMacro("Parameter update size, " << update.Size() << ", must " " be same as transform parameter size, " << numberOfParameters << std::endl); } /* Make sure m_Parameters is updated to reflect the current values in * the transform's other parameter-related variables. This is effective for * managing the parallel variables used for storing parameter data, * but inefficient. However for small global transforms, shouldn't be * too bad. Dense-field transform will want to make sure m_Parameters * is always updated whenever the transform is changed, so GetParameters * can be skipped in their implementations of UpdateTransformParameters. */ this->GetParameters(); VectorType rightPart; for ( unsigned int i = 0; i < 3; i++ ) { rightPart[i] = this->m_Parameters[i]; } VersorType currentRotation; currentRotation.Set(rightPart); // The gradient indicate the contribution of each one // of the axis to the direction of highest change in // the function VectorType axis; axis[0] = update[0]; axis[1] = update[1]; axis[2] = update[2]; // gradientRotation is a rotation along the // versor direction which maximize the // variation of the cost function in question. // An additional Exponentiation produce a jump // of a particular length along the versor gradient // direction. VersorType gradientRotation; gradientRotation.Set( axis, factor * axis.GetNorm() ); // // Composing the currentRotation with the gradientRotation // produces the new Rotation versor // VersorType newRotation = currentRotation * gradientRotation; ParametersType newParameters( numberOfParameters ); newParameters[0] = newRotation.GetX(); newParameters[1] = newRotation.GetY(); newParameters[2] = newRotation.GetZ(); // Optimize the non-versor parameters as the // RegularStepGradientDescentOptimizer for ( unsigned int k = 3; k < numberOfParameters; k++ ) { newParameters[k] = this->m_Parameters[k] + update[k] * factor; } /* Call SetParameters with the updated parameters. * SetParameters in most transforms is used to assign the input params * to member variables, possibly with some processing. The member variables * are then used in TransformPoint. * In the case of dense-field transforms that are updated in blocks from * a threaded implementation, SetParameters doesn't do this, and is * optimized to not copy the input parameters when == m_Parameters. */ this->SetParameters( newParameters ); /* Call Modified, following behavior of other transform when their * parameters change, e.g. MatrixOffsetTransformBase */ this->Modified(); } template<typename TParametersValueType> void VersorRigid3DTransform<TParametersValueType> ::ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian) const { typedef typename VersorType::ValueType ValueType; // compute derivatives with respect to rotation const ValueType vx = this->GetVersor().GetX(); const ValueType vy = this->GetVersor().GetY(); const ValueType vz = this->GetVersor().GetZ(); const ValueType vw = this->GetVersor().GetW(); jacobian.SetSize( 3, this->GetNumberOfLocalParameters() ); jacobian.Fill(0.0); const double px = p[0] - this->GetCenter()[0]; const double py = p[1] - this->GetCenter()[1]; const double pz = p[2] - this->GetCenter()[2]; const double vxx = vx * vx; const double vyy = vy * vy; const double vzz = vz * vz; const double vww = vw * vw; const double vxy = vx * vy; const double vxz = vx * vz; const double vxw = vx * vw; const double vyz = vy * vz; const double vyw = vy * vw; const double vzw = vz * vw; // compute Jacobian with respect to quaternion parameters jacobian[0][0] = 2.0 * ( ( vyw + vxz ) * py + ( vzw - vxy ) * pz ) / vw; jacobian[1][0] = 2.0 * ( ( vyw - vxz ) * px - 2 * vxw * py + ( vxx - vww ) * pz ) / vw; jacobian[2][0] = 2.0 * ( ( vzw + vxy ) * px + ( vww - vxx ) * py - 2 * vxw * pz ) / vw; jacobian[0][1] = 2.0 * ( -2 * vyw * px + ( vxw + vyz ) * py + ( vww - vyy ) * pz ) / vw; jacobian[1][1] = 2.0 * ( ( vxw - vyz ) * px + ( vzw + vxy ) * pz ) / vw; jacobian[2][1] = 2.0 * ( ( vyy - vww ) * px + ( vzw - vxy ) * py - 2 * vyw * pz ) / vw; jacobian[0][2] = 2.0 * ( -2 * vzw * px + ( vzz - vww ) * py + ( vxw - vyz ) * pz ) / vw; jacobian[1][2] = 2.0 * ( ( vww - vzz ) * px - 2 * vzw * py + ( vyw + vxz ) * pz ) / vw; jacobian[2][2] = 2.0 * ( ( vxw + vyz ) * px + ( vyw - vxz ) * py ) / vw; jacobian[0][3] = 1.0; jacobian[1][4] = 1.0; jacobian[2][5] = 1.0; } // Print self template<typename TParametersValueType> void VersorRigid3DTransform<TParametersValueType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } } // namespace #endif <commit_msg>BUG: do not pass 0,0,0 to Versor.Set()<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkVersorRigid3DTransform_hxx #define itkVersorRigid3DTransform_hxx #include "itkVersorRigid3DTransform.h" namespace itk { // Constructor with default arguments template<typename TParametersValueType> VersorRigid3DTransform<TParametersValueType> ::VersorRigid3DTransform() : Superclass(ParametersDimension) { } // Constructor with arguments template<typename TParametersValueType> VersorRigid3DTransform<TParametersValueType>::VersorRigid3DTransform(unsigned int paramDim) : Superclass(paramDim) { } // Constructor with arguments template<typename TParametersValueType> VersorRigid3DTransform<TParametersValueType>::VersorRigid3DTransform(const MatrixType & matrix, const OutputVectorType & offset) : Superclass(matrix, offset) { } // Set Parameters template<typename TParametersValueType> void VersorRigid3DTransform<TParametersValueType> ::SetParameters(const ParametersType & parameters) { itkDebugMacro(<< "Setting parameters " << parameters); // Save parameters. Needed for proper operation of TransformUpdateParameters. if( &parameters != &(this->m_Parameters) ) { this->m_Parameters = parameters; } // Transfer the versor part AxisType axis; double norm = parameters[0] * parameters[0]; axis[0] = parameters[0]; norm += parameters[1] * parameters[1]; axis[1] = parameters[1]; norm += parameters[2] * parameters[2]; axis[2] = parameters[2]; if( norm > 0 ) { norm = std::sqrt(norm); } double epsilon = 1e-10; if( norm >= 1.0 - epsilon ) { axis = axis / ( norm + epsilon * norm ); } VersorType newVersor; newVersor.Set(axis); this->SetVarVersor(newVersor); this->ComputeMatrix(); itkDebugMacro( << "Versor is now " << this->GetVersor() ); // Transfer the translation part TranslationType newTranslation; newTranslation[0] = parameters[3]; newTranslation[1] = parameters[4]; newTranslation[2] = parameters[5]; this->SetVarTranslation(newTranslation); this->ComputeOffset(); // Modified is always called since we just have a pointer to the // parameters and cannot know if the parameters have changed. this->Modified(); itkDebugMacro(<< "After setting parameters "); } // // Get Parameters // // Parameters are ordered as: // // p[0:2] = right part of the versor (axis times std::sin(t/2)) // p[3:5} = translation components // template<typename TParametersValueType> const typename VersorRigid3DTransform<TParametersValueType>::ParametersType & VersorRigid3DTransform<TParametersValueType> ::GetParameters(void) const { itkDebugMacro(<< "Getting parameters "); this->m_Parameters[0] = this->GetVersor().GetX(); this->m_Parameters[1] = this->GetVersor().GetY(); this->m_Parameters[2] = this->GetVersor().GetZ(); // Transfer the translation this->m_Parameters[3] = this->GetTranslation()[0]; this->m_Parameters[4] = this->GetTranslation()[1]; this->m_Parameters[5] = this->GetTranslation()[2]; itkDebugMacro(<< "After getting parameters " << this->m_Parameters); return this->m_Parameters; } template<typename TParametersValueType> void VersorRigid3DTransform<TParametersValueType> ::UpdateTransformParameters( const DerivativeType & update, TParametersValueType factor ) { SizeValueType numberOfParameters = this->GetNumberOfParameters(); if( update.Size() != numberOfParameters ) { itkExceptionMacro("Parameter update size, " << update.Size() << ", must " " be same as transform parameter size, " << numberOfParameters << std::endl); } /* Make sure m_Parameters is updated to reflect the current values in * the transform's other parameter-related variables. This is effective for * managing the parallel variables used for storing parameter data, * but inefficient. However for small global transforms, shouldn't be * too bad. Dense-field transform will want to make sure m_Parameters * is always updated whenever the transform is changed, so GetParameters * can be skipped in their implementations of UpdateTransformParameters. */ this->GetParameters(); VectorType rightPart; for ( unsigned int i = 0; i < 3; i++ ) { rightPart[i] = this->m_Parameters[i]; } VersorType currentRotation; currentRotation.Set(rightPart); // The gradient indicate the contribution of each one // of the axis to the direction of highest change in // the function VectorType axis; axis[0] = update[0]; axis[1] = update[1]; axis[2] = update[2]; // gradientRotation is a rotation along the // versor direction which maximize the // variation of the cost function in question. // An additional Exponentiation produce a jump // of a particular length along the versor gradient // direction. VersorType gradientRotation; const TParametersValueType norm = axis.GetNorm(); if (Math::FloatAlmostEqual<TParametersValueType>(norm, 0.0)) { axis[2] = 1; gradientRotation.Set(axis, 0.0); } else { gradientRotation.Set(axis, factor * norm); } // // Composing the currentRotation with the gradientRotation // produces the new Rotation versor // VersorType newRotation = currentRotation * gradientRotation; ParametersType newParameters( numberOfParameters ); newParameters[0] = newRotation.GetX(); newParameters[1] = newRotation.GetY(); newParameters[2] = newRotation.GetZ(); // Optimize the non-versor parameters as the // RegularStepGradientDescentOptimizer for ( unsigned int k = 3; k < numberOfParameters; k++ ) { newParameters[k] = this->m_Parameters[k] + update[k] * factor; } /* Call SetParameters with the updated parameters. * SetParameters in most transforms is used to assign the input params * to member variables, possibly with some processing. The member variables * are then used in TransformPoint. * In the case of dense-field transforms that are updated in blocks from * a threaded implementation, SetParameters doesn't do this, and is * optimized to not copy the input parameters when == m_Parameters. */ this->SetParameters( newParameters ); /* Call Modified, following behavior of other transform when their * parameters change, e.g. MatrixOffsetTransformBase */ this->Modified(); } template<typename TParametersValueType> void VersorRigid3DTransform<TParametersValueType> ::ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian) const { typedef typename VersorType::ValueType ValueType; // compute derivatives with respect to rotation const ValueType vx = this->GetVersor().GetX(); const ValueType vy = this->GetVersor().GetY(); const ValueType vz = this->GetVersor().GetZ(); const ValueType vw = this->GetVersor().GetW(); jacobian.SetSize( 3, this->GetNumberOfLocalParameters() ); jacobian.Fill(0.0); const double px = p[0] - this->GetCenter()[0]; const double py = p[1] - this->GetCenter()[1]; const double pz = p[2] - this->GetCenter()[2]; const double vxx = vx * vx; const double vyy = vy * vy; const double vzz = vz * vz; const double vww = vw * vw; const double vxy = vx * vy; const double vxz = vx * vz; const double vxw = vx * vw; const double vyz = vy * vz; const double vyw = vy * vw; const double vzw = vz * vw; // compute Jacobian with respect to quaternion parameters jacobian[0][0] = 2.0 * ( ( vyw + vxz ) * py + ( vzw - vxy ) * pz ) / vw; jacobian[1][0] = 2.0 * ( ( vyw - vxz ) * px - 2 * vxw * py + ( vxx - vww ) * pz ) / vw; jacobian[2][0] = 2.0 * ( ( vzw + vxy ) * px + ( vww - vxx ) * py - 2 * vxw * pz ) / vw; jacobian[0][1] = 2.0 * ( -2 * vyw * px + ( vxw + vyz ) * py + ( vww - vyy ) * pz ) / vw; jacobian[1][1] = 2.0 * ( ( vxw - vyz ) * px + ( vzw + vxy ) * pz ) / vw; jacobian[2][1] = 2.0 * ( ( vyy - vww ) * px + ( vzw - vxy ) * py - 2 * vyw * pz ) / vw; jacobian[0][2] = 2.0 * ( -2 * vzw * px + ( vzz - vww ) * py + ( vxw - vyz ) * pz ) / vw; jacobian[1][2] = 2.0 * ( ( vww - vzz ) * px - 2 * vzw * py + ( vyw + vxz ) * pz ) / vw; jacobian[2][2] = 2.0 * ( ( vxw + vyz ) * px + ( vyw - vxz ) * py ) / vw; jacobian[0][3] = 1.0; jacobian[1][4] = 1.0; jacobian[2][5] = 1.0; } // Print self template<typename TParametersValueType> void VersorRigid3DTransform<TParametersValueType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } } // namespace #endif <|endoftext|>
<commit_before>327d3ba6-2f67-11e5-b3ce-6c40088e03e4<commit_msg>3283ceee-2f67-11e5-9df8-6c40088e03e4<commit_after>3283ceee-2f67-11e5-9df8-6c40088e03e4<|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFastMarchingTool3D.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include "mitkInteractionConst.h" #include "mitkGlobalInteraction.h" #include "itkOrImageFilter.h" #include "mitkImageTimeSelector.h" #include "mitkImageCast.h" // us #include <usModule.h> #include <usModuleResource.h> #include <usGetModuleContext.h> #include <usModuleContext.h> namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, FastMarchingTool3D, "FastMarching3D tool"); } mitk::FastMarchingTool3D::FastMarchingTool3D() :/*FeedbackContourTool*/AutoSegmentationTool(), m_NeedUpdate(true), m_CurrentTimeStep(0), m_LowerThreshold(0), m_UpperThreshold(200), m_StoppingValue(100), m_Sigma(1.0), m_Alpha(-0.5), m_Beta(3.0) { } mitk::FastMarchingTool3D::~FastMarchingTool3D() { } const char** mitk::FastMarchingTool3D::GetXPM() const { return NULL;//mitkFastMarchingTool3D_xpm; } us::ModuleResource mitk::FastMarchingTool3D::GetIconResource() const { us::Module* module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("FastMarching_48x48.png"); return resource; } const char* mitk::FastMarchingTool3D::GetName() const { return "FastMarching3D"; } void mitk::FastMarchingTool3D::SetUpperThreshold(double value) { m_UpperThreshold = value / 10.0; m_ThresholdFilter->SetUpperThreshold( m_UpperThreshold ); m_NeedUpdate = true; } void mitk::FastMarchingTool3D::SetLowerThreshold(double value) { m_LowerThreshold = value / 10.0; m_ThresholdFilter->SetLowerThreshold( m_LowerThreshold ); m_NeedUpdate = true; } void mitk::FastMarchingTool3D::SetBeta(double value) { if (m_Beta != value) { m_Beta = value; m_SigmoidFilter->SetBeta( m_Beta ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::SetSigma(double value) { if (m_Sigma != value) { m_Sigma = value; m_GradientMagnitudeFilter->SetSigma( m_Sigma ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::SetAlpha(double value) { if (m_Alpha != value) { m_Alpha = value; m_SigmoidFilter->SetAlpha( m_Alpha ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::SetStoppingValue(double value) { if (m_StoppingValue != value) { m_StoppingValue = value; m_FastMarchingFilter->SetStoppingValue( m_StoppingValue ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::Activated() { Superclass::Activated(); m_ResultImageNode = mitk::DataNode::New(); m_ResultImageNode->SetName("FastMarching_Preview"); m_ResultImageNode->SetBoolProperty("helper object", true); m_ResultImageNode->SetColor(0.0, 1.0, 0.0); m_ResultImageNode->SetVisibility(true); m_ToolManager->GetDataStorage()->Add( this->m_ResultImageNode, m_ToolManager->GetReferenceData(0)); m_SeedsAsPointSet = mitk::PointSet::New(); m_SeedsAsPointSetNode = mitk::DataNode::New(); m_SeedsAsPointSetNode->SetData(m_SeedsAsPointSet); m_SeedsAsPointSetNode->SetName("3D_FastMarching_PointSet"); m_SeedsAsPointSetNode->SetBoolProperty("helper object", true); m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0); m_SeedsAsPointSetNode->SetVisibility(true); m_SeedPointInteractor = mitk::PointSetInteractor::New("PressMoveReleaseAndPointSetting", m_SeedsAsPointSetNode); m_ReferenceImageAsITK = InternalImageType::New(); m_ProgressCommand = mitk::ToolCommand::New(); m_ThresholdFilter = ThresholdingFilterType::New(); m_ThresholdFilter->SetLowerThreshold( m_LowerThreshold ); m_ThresholdFilter->SetUpperThreshold( m_UpperThreshold ); m_ThresholdFilter->SetOutsideValue( 0 ); m_ThresholdFilter->SetInsideValue( 1.0 ); m_SmoothFilter = SmoothingFilterType::New(); m_SmoothFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_SmoothFilter->SetTimeStep( 0.05 ); m_SmoothFilter->SetNumberOfIterations( 2 ); m_SmoothFilter->SetConductanceParameter( 9.0 ); m_GradientMagnitudeFilter = GradientFilterType::New(); m_GradientMagnitudeFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_GradientMagnitudeFilter->SetSigma( m_Sigma ); m_SigmoidFilter = SigmoidFilterType::New(); m_SigmoidFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_SigmoidFilter->SetAlpha( m_Alpha ); m_SigmoidFilter->SetBeta( m_Beta ); m_SigmoidFilter->SetOutputMinimum( 0.0 ); m_SigmoidFilter->SetOutputMaximum( 1.0 ); m_FastMarchingFilter = FastMarchingFilterType::New(); m_FastMarchingFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_FastMarchingFilter->SetStoppingValue( m_StoppingValue ); m_SeedContainer = NodeContainer::New(); m_SeedContainer->Initialize(); m_FastMarchingFilter->SetTrialPoints( m_SeedContainer ); //set up pipeline m_SmoothFilter->SetInput( m_ReferenceImageAsITK ); m_GradientMagnitudeFilter->SetInput( m_SmoothFilter->GetOutput() ); m_SigmoidFilter->SetInput( m_GradientMagnitudeFilter->GetOutput() ); m_FastMarchingFilter->SetInput( m_SigmoidFilter->GetOutput() ); m_ThresholdFilter->SetInput( m_FastMarchingFilter->GetOutput() ); m_ToolManager->GetDataStorage()->Add(m_SeedsAsPointSetNode, m_ToolManager->GetWorkingData(0)); mitk::GlobalInteraction::GetInstance()->AddInteractor(m_SeedPointInteractor); itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointAddedCommand = itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New(); pointAddedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnAddPoint); m_PointSetAddObserverTag = m_SeedsAsPointSet->AddObserver( mitk::PointSetAddEvent(), pointAddedCommand); itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointRemovedCommand = itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New(); pointRemovedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnDelete); m_PointSetRemoveObserverTag = m_SeedsAsPointSet->AddObserver( mitk::PointSetRemoveEvent(), pointRemovedCommand); this->Initialize(); } void mitk::FastMarchingTool3D::Deactivated() { Superclass::Deactivated(); m_ToolManager->GetDataStorage()->Remove( this->m_ResultImageNode ); m_ToolManager->GetDataStorage()->Remove( this->m_SeedsAsPointSetNode ); this->ClearSeeds(); this->m_SmoothFilter->RemoveAllObservers(); this->m_SigmoidFilter->RemoveAllObservers(); this->m_GradientMagnitudeFilter->RemoveAllObservers(); this->m_FastMarchingFilter->RemoveAllObservers(); m_ResultImageNode = NULL; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); unsigned int numberOfPoints = m_SeedsAsPointSet->GetSize(); for (unsigned int i = 0; i < numberOfPoints; ++i) { mitk::Point3D point = m_SeedsAsPointSet->GetPoint(i); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, point, 0); m_SeedsAsPointSet->ExecuteOperation(doOp); } mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_SeedPointInteractor); m_ToolManager->GetDataStorage()->Remove(m_SeedsAsPointSetNode); m_SeedsAsPointSet->RemoveObserver(m_PointSetAddObserverTag); m_SeedsAsPointSet->RemoveObserver(m_PointSetRemoveObserverTag); } void mitk::FastMarchingTool3D::Initialize() { m_ReferenceImage = dynamic_cast<mitk::Image*>(m_ToolManager->GetReferenceData(0)->GetData()); if(m_ReferenceImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1) { mitk::ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput( m_ReferenceImage ); timeSelector->SetTimeNr( m_CurrentTimeStep ); timeSelector->UpdateLargestPossibleRegion(); m_ReferenceImage = timeSelector->GetOutput(); } CastToItkImage(m_ReferenceImage, m_ReferenceImageAsITK); m_SmoothFilter->SetInput( m_ReferenceImageAsITK ); m_NeedUpdate = true; } void mitk::FastMarchingTool3D::ConfirmSegmentation() { // combine preview image with current working segmentation if (dynamic_cast<mitk::Image*>(m_ResultImageNode->GetData())) { //logical or combination of preview and segmentation slice OutputImageType::Pointer segmentationImageInITK = OutputImageType::New(); mitk::Image::Pointer workingImage = dynamic_cast<mitk::Image*>(GetTargetSegmentationNode()->GetData()); if(workingImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput( workingImage ); timeSelector->SetTimeNr( m_CurrentTimeStep ); timeSelector->UpdateLargestPossibleRegion(); CastToItkImage( timeSelector->GetOutput(), segmentationImageInITK ); } else { CastToItkImage( workingImage, segmentationImageInITK ); } typedef itk::OrImageFilter<OutputImageType, OutputImageType> OrImageFilterType; OrImageFilterType::Pointer orFilter = OrImageFilterType::New(); orFilter->SetInput(0, m_ThresholdFilter->GetOutput()); orFilter->SetInput(1, segmentationImageInITK); orFilter->Update(); //set image volume in current time step from itk image workingImage->SetVolume( (void*)(m_ThresholdFilter->GetOutput()->GetPixelContainer()->GetBufferPointer()), m_CurrentTimeStep); this->m_ResultImageNode->SetVisibility(false); this->ClearSeeds(); workingImage->Modified(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::FastMarchingTool3D::OnAddPoint() { // Add a new seed point for FastMarching algorithm mitk::Point3D clickInIndex; m_ReferenceImage->GetGeometry()->WorldToIndex(m_SeedsAsPointSet->GetPoint(m_SeedsAsPointSet->GetSize()-1), clickInIndex); itk::Index<3> seedPosition; seedPosition[0] = clickInIndex[0]; seedPosition[1] = clickInIndex[1]; seedPosition[2] = clickInIndex[2]; NodeType node; const double seedValue = 0.0; node.SetValue( seedValue ); node.SetIndex( seedPosition ); this->m_SeedContainer->InsertElement(this->m_SeedContainer->Size(), node); m_FastMarchingFilter->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_NeedUpdate = true; m_ReadyMessage.Send(); this->Update(); } void mitk::FastMarchingTool3D::OnDelete() { // delete last seed point if(!(this->m_SeedContainer->empty())) { //delete last element of seeds container this->m_SeedContainer->pop_back(); m_FastMarchingFilter->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_NeedUpdate = true; this->Update(); } } void mitk::FastMarchingTool3D::Update() { if (m_NeedUpdate) { m_ProgressCommand->AddStepsToDo(200); CurrentlyBusy.Send(true); try { m_ThresholdFilter->Update(); } catch( itk::ExceptionObject & excep ) { MITK_ERROR << "Exception caught: " << excep.GetDescription(); m_ProgressCommand->SetRemainingProgress(100); CurrentlyBusy.Send(false); std::string msg = excep.GetDescription(); ErrorMessage.Send(msg); return; } m_ProgressCommand->SetRemainingProgress(100); CurrentlyBusy.Send(false); //make output visible mitk::Image::Pointer result = mitk::Image::New(); CastToMitkImage( m_ThresholdFilter->GetOutput(), result); result->GetGeometry()->SetOrigin(m_ReferenceImage->GetGeometry()->GetOrigin() ); result->GetGeometry()->SetIndexToWorldTransform(m_ReferenceImage->GetGeometry()->GetIndexToWorldTransform() ); m_ResultImageNode->SetData(result); m_ResultImageNode->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void mitk::FastMarchingTool3D::ClearSeeds() { // clear seeds for FastMarching as well as the PointSet for visualization if(this->m_SeedContainer.IsNotNull()) this->m_SeedContainer->Initialize(); if(this->m_SeedsAsPointSet.IsNotNull()) { this->m_SeedsAsPointSet = mitk::PointSet::New(); this->m_SeedsAsPointSetNode->SetData(this->m_SeedsAsPointSet); m_SeedsAsPointSetNode->SetName("Seeds_Preview"); m_SeedsAsPointSetNode->SetBoolProperty("helper object", true); m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0); m_SeedsAsPointSetNode->SetVisibility(true); } if(this->m_FastMarchingFilter.IsNotNull()) m_FastMarchingFilter->Modified(); this->m_NeedUpdate = true; } void mitk::FastMarchingTool3D::Reset() { //clear all seeds and preview empty result this->ClearSeeds(); m_ResultImageNode->SetVisibility(false); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::FastMarchingTool3D::SetCurrentTimeStep(int t) { if( m_CurrentTimeStep != t ) { m_CurrentTimeStep = t; this->Initialize(); } } <commit_msg>Add callback function after clearing pointset.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFastMarchingTool3D.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include "mitkInteractionConst.h" #include "mitkGlobalInteraction.h" #include "itkOrImageFilter.h" #include "mitkImageTimeSelector.h" #include "mitkImageCast.h" // us #include <usModule.h> #include <usModuleResource.h> #include <usGetModuleContext.h> #include <usModuleContext.h> namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, FastMarchingTool3D, "FastMarching3D tool"); } mitk::FastMarchingTool3D::FastMarchingTool3D() :/*FeedbackContourTool*/AutoSegmentationTool(), m_NeedUpdate(true), m_CurrentTimeStep(0), m_LowerThreshold(0), m_UpperThreshold(200), m_StoppingValue(100), m_Sigma(1.0), m_Alpha(-0.5), m_Beta(3.0) { } mitk::FastMarchingTool3D::~FastMarchingTool3D() { } const char** mitk::FastMarchingTool3D::GetXPM() const { return NULL;//mitkFastMarchingTool3D_xpm; } us::ModuleResource mitk::FastMarchingTool3D::GetIconResource() const { us::Module* module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("FastMarching_48x48.png"); return resource; } const char* mitk::FastMarchingTool3D::GetName() const { return "FastMarching3D"; } void mitk::FastMarchingTool3D::SetUpperThreshold(double value) { m_UpperThreshold = value / 10.0; m_ThresholdFilter->SetUpperThreshold( m_UpperThreshold ); m_NeedUpdate = true; } void mitk::FastMarchingTool3D::SetLowerThreshold(double value) { m_LowerThreshold = value / 10.0; m_ThresholdFilter->SetLowerThreshold( m_LowerThreshold ); m_NeedUpdate = true; } void mitk::FastMarchingTool3D::SetBeta(double value) { if (m_Beta != value) { m_Beta = value; m_SigmoidFilter->SetBeta( m_Beta ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::SetSigma(double value) { if (m_Sigma != value) { if(value > 0.0) { m_Sigma = value; m_GradientMagnitudeFilter->SetSigma( m_Sigma ); m_NeedUpdate = true; } } } void mitk::FastMarchingTool3D::SetAlpha(double value) { if (m_Alpha != value) { m_Alpha = value; m_SigmoidFilter->SetAlpha( m_Alpha ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::SetStoppingValue(double value) { if (m_StoppingValue != value) { m_StoppingValue = value; m_FastMarchingFilter->SetStoppingValue( m_StoppingValue ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::Activated() { Superclass::Activated(); m_ResultImageNode = mitk::DataNode::New(); m_ResultImageNode->SetName("FastMarching_Preview"); m_ResultImageNode->SetBoolProperty("helper object", true); m_ResultImageNode->SetColor(0.0, 1.0, 0.0); m_ResultImageNode->SetVisibility(true); m_ToolManager->GetDataStorage()->Add( this->m_ResultImageNode, m_ToolManager->GetReferenceData(0)); m_SeedsAsPointSet = mitk::PointSet::New(); m_SeedsAsPointSetNode = mitk::DataNode::New(); m_SeedsAsPointSetNode->SetData(m_SeedsAsPointSet); m_SeedsAsPointSetNode->SetName("3D_FastMarching_PointSet"); m_SeedsAsPointSetNode->SetBoolProperty("helper object", true); m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0); m_SeedsAsPointSetNode->SetVisibility(true); m_SeedPointInteractor = mitk::PointSetInteractor::New("PressMoveReleaseAndPointSetting", m_SeedsAsPointSetNode); m_ReferenceImageAsITK = InternalImageType::New(); m_ProgressCommand = mitk::ToolCommand::New(); m_ThresholdFilter = ThresholdingFilterType::New(); m_ThresholdFilter->SetLowerThreshold( m_LowerThreshold ); m_ThresholdFilter->SetUpperThreshold( m_UpperThreshold ); m_ThresholdFilter->SetOutsideValue( 0 ); m_ThresholdFilter->SetInsideValue( 1.0 ); m_SmoothFilter = SmoothingFilterType::New(); m_SmoothFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_SmoothFilter->SetTimeStep( 0.05 ); m_SmoothFilter->SetNumberOfIterations( 2 ); m_SmoothFilter->SetConductanceParameter( 9.0 ); m_GradientMagnitudeFilter = GradientFilterType::New(); m_GradientMagnitudeFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_GradientMagnitudeFilter->SetSigma( m_Sigma ); m_SigmoidFilter = SigmoidFilterType::New(); m_SigmoidFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_SigmoidFilter->SetAlpha( m_Alpha ); m_SigmoidFilter->SetBeta( m_Beta ); m_SigmoidFilter->SetOutputMinimum( 0.0 ); m_SigmoidFilter->SetOutputMaximum( 1.0 ); m_FastMarchingFilter = FastMarchingFilterType::New(); m_FastMarchingFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_FastMarchingFilter->SetStoppingValue( m_StoppingValue ); m_SeedContainer = NodeContainer::New(); m_SeedContainer->Initialize(); m_FastMarchingFilter->SetTrialPoints( m_SeedContainer ); //set up pipeline m_SmoothFilter->SetInput( m_ReferenceImageAsITK ); m_GradientMagnitudeFilter->SetInput( m_SmoothFilter->GetOutput() ); m_SigmoidFilter->SetInput( m_GradientMagnitudeFilter->GetOutput() ); m_FastMarchingFilter->SetInput( m_SigmoidFilter->GetOutput() ); m_ThresholdFilter->SetInput( m_FastMarchingFilter->GetOutput() ); m_ToolManager->GetDataStorage()->Add(m_SeedsAsPointSetNode, m_ToolManager->GetWorkingData(0)); mitk::GlobalInteraction::GetInstance()->AddInteractor(m_SeedPointInteractor); itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointAddedCommand = itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New(); pointAddedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnAddPoint); m_PointSetAddObserverTag = m_SeedsAsPointSet->AddObserver( mitk::PointSetAddEvent(), pointAddedCommand); itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointRemovedCommand = itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New(); pointRemovedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnDelete); m_PointSetRemoveObserverTag = m_SeedsAsPointSet->AddObserver( mitk::PointSetRemoveEvent(), pointRemovedCommand); this->Initialize(); } void mitk::FastMarchingTool3D::Deactivated() { Superclass::Deactivated(); m_ToolManager->GetDataStorage()->Remove( this->m_ResultImageNode ); m_ToolManager->GetDataStorage()->Remove( this->m_SeedsAsPointSetNode ); this->ClearSeeds(); this->m_SmoothFilter->RemoveAllObservers(); this->m_SigmoidFilter->RemoveAllObservers(); this->m_GradientMagnitudeFilter->RemoveAllObservers(); this->m_FastMarchingFilter->RemoveAllObservers(); m_ResultImageNode = NULL; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); unsigned int numberOfPoints = m_SeedsAsPointSet->GetSize(); for (unsigned int i = 0; i < numberOfPoints; ++i) { mitk::Point3D point = m_SeedsAsPointSet->GetPoint(i); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, point, 0); m_SeedsAsPointSet->ExecuteOperation(doOp); } mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_SeedPointInteractor); m_ToolManager->GetDataStorage()->Remove(m_SeedsAsPointSetNode); m_SeedsAsPointSet->RemoveObserver(m_PointSetAddObserverTag); m_SeedsAsPointSet->RemoveObserver(m_PointSetRemoveObserverTag); } void mitk::FastMarchingTool3D::Initialize() { m_ReferenceImage = dynamic_cast<mitk::Image*>(m_ToolManager->GetReferenceData(0)->GetData()); if(m_ReferenceImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1) { mitk::ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput( m_ReferenceImage ); timeSelector->SetTimeNr( m_CurrentTimeStep ); timeSelector->UpdateLargestPossibleRegion(); m_ReferenceImage = timeSelector->GetOutput(); } CastToItkImage(m_ReferenceImage, m_ReferenceImageAsITK); m_SmoothFilter->SetInput( m_ReferenceImageAsITK ); m_NeedUpdate = true; } void mitk::FastMarchingTool3D::ConfirmSegmentation() { // combine preview image with current working segmentation if (dynamic_cast<mitk::Image*>(m_ResultImageNode->GetData())) { //logical or combination of preview and segmentation slice OutputImageType::Pointer segmentationImageInITK = OutputImageType::New(); mitk::Image::Pointer workingImage = dynamic_cast<mitk::Image*>(GetTargetSegmentationNode()->GetData()); if(workingImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput( workingImage ); timeSelector->SetTimeNr( m_CurrentTimeStep ); timeSelector->UpdateLargestPossibleRegion(); CastToItkImage( timeSelector->GetOutput(), segmentationImageInITK ); } else { CastToItkImage( workingImage, segmentationImageInITK ); } typedef itk::OrImageFilter<OutputImageType, OutputImageType> OrImageFilterType; OrImageFilterType::Pointer orFilter = OrImageFilterType::New(); orFilter->SetInput(0, m_ThresholdFilter->GetOutput()); orFilter->SetInput(1, segmentationImageInITK); orFilter->Update(); //set image volume in current time step from itk image workingImage->SetVolume( (void*)(m_ThresholdFilter->GetOutput()->GetPixelContainer()->GetBufferPointer()), m_CurrentTimeStep); this->m_ResultImageNode->SetVisibility(false); this->ClearSeeds(); workingImage->Modified(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::FastMarchingTool3D::OnAddPoint() { // Add a new seed point for FastMarching algorithm mitk::Point3D clickInIndex; m_ReferenceImage->GetGeometry()->WorldToIndex(m_SeedsAsPointSet->GetPoint(m_SeedsAsPointSet->GetSize()-1), clickInIndex); itk::Index<3> seedPosition; seedPosition[0] = clickInIndex[0]; seedPosition[1] = clickInIndex[1]; seedPosition[2] = clickInIndex[2]; NodeType node; const double seedValue = 0.0; node.SetValue( seedValue ); node.SetIndex( seedPosition ); this->m_SeedContainer->InsertElement(this->m_SeedContainer->Size(), node); m_FastMarchingFilter->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_NeedUpdate = true; m_ReadyMessage.Send(); this->Update(); } void mitk::FastMarchingTool3D::OnDelete() { // delete last seed point if(!(this->m_SeedContainer->empty())) { //delete last element of seeds container this->m_SeedContainer->pop_back(); m_FastMarchingFilter->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_NeedUpdate = true; this->Update(); } } void mitk::FastMarchingTool3D::Update() { if (m_NeedUpdate) { m_ProgressCommand->AddStepsToDo(200); CurrentlyBusy.Send(true); try { m_ThresholdFilter->Update(); } catch( itk::ExceptionObject & excep ) { MITK_ERROR << "Exception caught: " << excep.GetDescription(); m_ProgressCommand->SetRemainingProgress(100); CurrentlyBusy.Send(false); std::string msg = excep.GetDescription(); ErrorMessage.Send(msg); return; } m_ProgressCommand->SetRemainingProgress(100); CurrentlyBusy.Send(false); //make output visible mitk::Image::Pointer result = mitk::Image::New(); CastToMitkImage( m_ThresholdFilter->GetOutput(), result); result->GetGeometry()->SetOrigin(m_ReferenceImage->GetGeometry()->GetOrigin() ); result->GetGeometry()->SetIndexToWorldTransform(m_ReferenceImage->GetGeometry()->GetIndexToWorldTransform() ); m_ResultImageNode->SetData(result); m_ResultImageNode->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void mitk::FastMarchingTool3D::ClearSeeds() { // clear seeds for FastMarching as well as the PointSet for visualization if(this->m_SeedContainer.IsNotNull()) this->m_SeedContainer->Initialize(); if(this->m_SeedsAsPointSet.IsNotNull()) { //remove observers from current pointset m_SeedsAsPointSet->RemoveObserver(m_PointSetAddObserverTag); m_SeedsAsPointSet->RemoveObserver(m_PointSetRemoveObserverTag); //renew pointset this->m_SeedsAsPointSet = mitk::PointSet::New(); this->m_SeedsAsPointSetNode->SetData(this->m_SeedsAsPointSet); m_SeedsAsPointSetNode->SetName("Seeds_Preview"); m_SeedsAsPointSetNode->SetBoolProperty("helper object", true); m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0); m_SeedsAsPointSetNode->SetVisibility(true); //add callback function for adding and removing points itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointAddedCommand = itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New(); pointAddedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnAddPoint); m_PointSetAddObserverTag = m_SeedsAsPointSet->AddObserver( mitk::PointSetAddEvent(), pointAddedCommand); itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointRemovedCommand = itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New(); pointRemovedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnDelete); m_PointSetRemoveObserverTag = m_SeedsAsPointSet->AddObserver( mitk::PointSetRemoveEvent(), pointRemovedCommand); } if(this->m_FastMarchingFilter.IsNotNull()) m_FastMarchingFilter->Modified(); this->m_NeedUpdate = true; } void mitk::FastMarchingTool3D::Reset() { //clear all seeds and preview empty result this->ClearSeeds(); m_ResultImageNode->SetVisibility(false); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::FastMarchingTool3D::SetCurrentTimeStep(int t) { if( m_CurrentTimeStep != t ) { m_CurrentTimeStep = t; this->Initialize(); } } <|endoftext|>
<commit_before>/* Copyright 2008 Larry Gritz and the other authors and contributors. 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 software's owners 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. (This is the Modified BSD License) */ #include <cstdio> #include <cstdlib> #include <cmath> #include <iostream> #include <iterator> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/foreach.hpp> #include <boost/filesystem.hpp> #include "argparse.h" #include "imageio.h" using namespace OpenImageIO; static std::string uninitialized = "uninitialized \001 HHRU dfvAS: efjl"; static std::string dataformatname = ""; static float gammaval = 1.0f; static bool depth = false; static bool verbose = false; static std::vector<std::string> filenames; static int tile[3] = { 0, 0, 1 }; static bool scanline = false; static bool zfile = false; static std::string channellist; static std::string compression; static bool no_copy_image = false; static int quality = -1; static bool adjust_time = false; static std::string caption = uninitialized; static std::vector<std::string> keywords; static bool clear_keywords = false; static std::vector<std::string> attribnames, attribvals; static bool inplace = false; static int orientation = 0; static bool rotcw = false, rotccw = false, rot180 = false; static bool sRGB = false; static int parse_files (int argc, const char *argv[]) { for (int i = 0; i < argc; i++) filenames.push_back (argv[i]); return 0; } static void getargs (int argc, char *argv[]) { bool help = false; ArgParse ap (argc, (const char **)argv); if (ap.parse ("Usage: iconvert [options] inputfile outputfile\n" " or: iconvert --inplace [options] file...\n", "%*", parse_files, "", "--help", &help, "Print help message", "-v", &verbose, "Verbose status messages", "-d %s", &dataformatname, "Set the output data format to one of:\n" "\t\t\tuint8, sint8, uint16, sint16, half, float, double", "-g %f", &gammaval, "Set gamma correction (default = 1)", "--tile %d %d", &tile[0], &tile[1], "Output as a tiled image", "--scanline", &scanline, "Output as a scanline image", "--compression %s", &compression, "Set the compression method (default = same as input)", "--quality %d", &quality, "Set the compression quality, 1-100", "--no-copy-image", &no_copy_image, "Do not use ImageOutput copy_image functionality (dbg)", "--adjust-time", &adjust_time, "Adjust file times to match DateTime metadata", "--caption %s", &caption, "Set caption (ImageDescription)", "--keyword %L", &keywords, "Add a keyword", "--clear-keywords", &clear_keywords, "Clear keywords", "--attrib %L %L", &attribnames, &attribvals, "Set a string attribute (name, value)", "--orientation %d", &orientation, "Set the orientation", "--rotcw", &rotcw, "Rotate 90 deg clockwise", "--rotccw", &rotccw, "Rotate 90 deg counter-clockwise", "--rot180", &rot180, "Rotate 180 deg", "--inplace", &inplace, "Do operations in place on images", "--sRGB", &sRGB, "This file is in sRGB color space", //FIXME "-z", &zfile, "Treat input as a depth file", //FIXME "-c %s", &channellist, "Restrict/shuffle channels", NULL) < 0) { std::cerr << ap.error_message() << std::endl; ap.usage (); exit (EXIT_FAILURE); } if (help) { ap.usage (); exit (EXIT_FAILURE); } if (filenames.size() != 2 && ! inplace) { std::cerr << "iconvert: Must have both an input and output filename specified.\n"; ap.usage(); exit (EXIT_FAILURE); } if (filenames.size() == 0 && inplace) { std::cerr << "iconvert: Must have at least one filename\n"; ap.usage(); exit (EXIT_FAILURE); } if (((int)rotcw + (int)rotccw + (int)rot180 + (orientation>0)) > 1) { std::cerr << "iconvert: more than one of --rotcw, --rotccw, --rot180, --orientation\n"; ap.usage(); exit (EXIT_FAILURE); } } static bool DateTime_to_time_t (const char *datetime, time_t &timet) { int year, month, day, hour, min, sec; int r = sscanf (datetime, "%d:%d:%d %d:%d:%d", &year, &month, &day, &hour, &min, &sec); // printf ("%d %d:%d:%d %d:%d:%d\n", r, year, month, day, hour, min, sec); if (r != 6) return false; struct tm tmtime; time_t now; localtime_r (&now, &tmtime); // fill in defaults tmtime.tm_sec = sec; tmtime.tm_min = min; tmtime.tm_hour = hour; tmtime.tm_mday = day; tmtime.tm_mon = month-1; tmtime.tm_year = year-1900; timet = mktime (&tmtime); return true; } // Utility: split semicolon-separated list static void split_list (const std::string &list, std::vector<std::string> &items) { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep(";"); tokenizer tokens (list, sep); for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) { std::string t = *tok_iter; while (t.length() && t[0] == ' ') t.erase (t.begin()); if (t.length()) items.push_back (t); } } // Utility: join list into a single semicolon-separated string static std::string join_list (const std::vector<std::string> &items) { std::string s; for (size_t i = 0; i < items.size(); ++i) { if (i > 0) s += "; "; s += items[i]; } return s; } bool convert_file (const std::string &in_filename, const std::string &out_filename) { std::cout << "Converting " << in_filename << " to " << out_filename << "\n"; std::string tempname = out_filename; if (tempname == in_filename) { #if (BOOST_VERSION >= 103700) tempname = out_filename + ".tmp" + boost::filesystem::path(out_filename).extension(); #else tempname = out_filename + ".tmp" + boost::filesystem::extension(out_filename); #endif } // Find an ImageIO plugin that can open the input file, and open it. ImageInput *in = ImageInput::create (in_filename.c_str(), "" /* searchpath */); if (! in) { std::cerr << "iconvert ERROR: Could not find an ImageIO plugin to read \"" << in_filename << "\" : " << OpenImageIO::error_message() << "\n"; return false; } ImageSpec inspec; if (! in->open (in_filename.c_str(), inspec)) { std::cerr << "iconvert ERROR: Could not open \"" << in_filename << "\" : " << in->error_message() << "\n"; delete in; return false; } // Copy the spec, with possible change in format ImageSpec outspec = inspec; outspec.set_format (inspec.format); if (! dataformatname.empty()) { if (dataformatname == "uint8") outspec.set_format (TypeDesc::UINT8); else if (dataformatname == "int8") outspec.set_format (TypeDesc::INT8); else if (dataformatname == "uint16") outspec.set_format (TypeDesc::UINT16); else if (dataformatname == "int16") outspec.set_format (TypeDesc::INT16); else if (dataformatname == "half") outspec.set_format (TypeDesc::HALF); else if (dataformatname == "float") outspec.set_format (TypeDesc::FLOAT); else if (dataformatname == "double") outspec.set_format (TypeDesc::DOUBLE); if (outspec.format != inspec.format) no_copy_image = true; } outspec.gamma = gammaval; if (sRGB) { outspec.linearity = ImageSpec::sRGB; if (!strcmp (in->format_name(), "jpeg") || outspec.find_attribute ("Exif:ColorSpace")) outspec.attribute ("Exif:ColorSpace", 1); } if (tile[0]) { outspec.tile_width = tile[0]; outspec.tile_height = tile[1]; outspec.tile_depth = tile[2]; } if (scanline) { outspec.tile_width = 0; outspec.tile_height = 0; outspec.tile_depth = 0; } if (outspec.tile_width != inspec.tile_width || outspec.tile_height != inspec.tile_height || outspec.tile_depth != inspec.tile_depth) no_copy_image = true; if (! compression.empty()) { outspec.attribute ("compression", compression); if (compression != inspec.get_string_attribute ("compression")) no_copy_image = true; } if (quality > 0) { outspec.attribute ("CompressionQuality", quality); if (quality != inspec.get_int_attribute ("CompressionQuality")) no_copy_image = true; } if (orientation >= 1) outspec.attribute ("Orientation", orientation); else { orientation = outspec.get_int_attribute ("Orientation", 1); if (orientation >= 1 && orientation <= 8) { static int cw[] = { 0, 6, 7, 8, 5, 2, 3, 4, 1 }; if (rotcw || rotccw || rot180) orientation = cw[orientation]; if (rotccw || rot180) orientation = cw[orientation]; if (rotccw) orientation = cw[orientation]; outspec.attribute ("Orientation", orientation); } } if (caption != uninitialized) outspec.attribute ("ImageDescription", caption); if (clear_keywords) outspec.attribute ("Keywords", ""); if (keywords.size()) { std::string oldkw = outspec.get_string_attribute ("Keywords"); std::vector<std::string> oldkwlist; if (! oldkw.empty()) split_list (oldkw, oldkwlist); BOOST_FOREACH (const std::string &nk, keywords) { bool dup = false; BOOST_FOREACH (const std::string &ok, oldkwlist) dup |= (ok == nk); if (! dup) oldkwlist.push_back (nk); } outspec.attribute ("Keywords", join_list (oldkwlist)); } for (size_t i = 0; i < attribnames.size(); ++i) { outspec.attribute (attribnames[i].c_str(), attribvals[i].c_str()); } // Find an ImageIO plugin that can open the output file, and open it ImageOutput *out = ImageOutput::create (tempname.c_str()); if (! out) { std::cerr << "iconvert ERROR: Could not find an ImageIO plugin to write \"" << out_filename << "\" :" << OpenImageIO::error_message() << "\n"; return false; } if (! out->open (tempname.c_str(), outspec)) { std::cerr << "iconvert ERROR: Could not open \"" << out_filename << "\" : " << out->error_message() << "\n"; return false; } bool ok = true; if (! no_copy_image) { ok = out->copy_image (in); if (! ok) std::cerr << "iconvert ERROR copying \"" << in_filename << "\" to \"" << in_filename << "\" :\n\t" << in->error_message() << "\n"; } else { // Need to do it by hand for some reason. Future expansion in which // only a subset of channels are copied, or some such. std::vector<char> pixels (outspec.image_bytes()); ok = in->read_image (outspec.format, &pixels[0]); if (! ok) { std::cerr << "iconvert ERROR reading \"" << in_filename << "\" : " << in->error_message() << "\n"; } else { ok = out->write_image (outspec.format, &pixels[0]); if (! ok) std::cerr << "iconvert ERROR writing \"" << out_filename << "\" : " << out->error_message() << "\n"; } } out->close (); delete out; in->close (); delete in; if (out_filename != tempname) { if (ok) { boost::filesystem::remove (out_filename); boost::filesystem::rename (tempname, out_filename); } else boost::filesystem::remove (tempname); } // If user requested, try to adjust the file's modification time to // the creation time indicated by the file's DateTime metadata. if (ok && adjust_time) { time_t timet; ImageIOParameter *p = outspec.find_attribute ("DateTime", TypeDesc::TypeString); if (p && DateTime_to_time_t (*(const char **)p->data(), timet)) { boost::filesystem::last_write_time (out_filename, timet); } } return ok; } int main (int argc, char *argv[]) { getargs (argc, argv); bool ok = true; if (inplace) { BOOST_FOREACH (const std::string &s, filenames) ok &= convert_file (s, s); } else { ok = convert_file (filenames[0], filenames[1]); } return ok ? EXIT_SUCCESS : EXIT_FAILURE; } <commit_msg>When --adjust-time is used, if there is no DateTime metadata, at least adjust the time to match that of the input file.<commit_after>/* Copyright 2008 Larry Gritz and the other authors and contributors. 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 software's owners 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. (This is the Modified BSD License) */ #include <cstdio> #include <cstdlib> #include <cmath> #include <iostream> #include <iterator> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/foreach.hpp> #include <boost/filesystem.hpp> #include "argparse.h" #include "imageio.h" using namespace OpenImageIO; static std::string uninitialized = "uninitialized \001 HHRU dfvAS: efjl"; static std::string dataformatname = ""; static float gammaval = 1.0f; static bool depth = false; static bool verbose = false; static std::vector<std::string> filenames; static int tile[3] = { 0, 0, 1 }; static bool scanline = false; static bool zfile = false; static std::string channellist; static std::string compression; static bool no_copy_image = false; static int quality = -1; static bool adjust_time = false; static std::string caption = uninitialized; static std::vector<std::string> keywords; static bool clear_keywords = false; static std::vector<std::string> attribnames, attribvals; static bool inplace = false; static int orientation = 0; static bool rotcw = false, rotccw = false, rot180 = false; static bool sRGB = false; static int parse_files (int argc, const char *argv[]) { for (int i = 0; i < argc; i++) filenames.push_back (argv[i]); return 0; } static void getargs (int argc, char *argv[]) { bool help = false; ArgParse ap (argc, (const char **)argv); if (ap.parse ("Usage: iconvert [options] inputfile outputfile\n" " or: iconvert --inplace [options] file...\n", "%*", parse_files, "", "--help", &help, "Print help message", "-v", &verbose, "Verbose status messages", "-d %s", &dataformatname, "Set the output data format to one of:\n" "\t\t\tuint8, sint8, uint16, sint16, half, float, double", "-g %f", &gammaval, "Set gamma correction (default = 1)", "--tile %d %d", &tile[0], &tile[1], "Output as a tiled image", "--scanline", &scanline, "Output as a scanline image", "--compression %s", &compression, "Set the compression method (default = same as input)", "--quality %d", &quality, "Set the compression quality, 1-100", "--no-copy-image", &no_copy_image, "Do not use ImageOutput copy_image functionality (dbg)", "--adjust-time", &adjust_time, "Adjust file times to match DateTime metadata", "--caption %s", &caption, "Set caption (ImageDescription)", "--keyword %L", &keywords, "Add a keyword", "--clear-keywords", &clear_keywords, "Clear keywords", "--attrib %L %L", &attribnames, &attribvals, "Set a string attribute (name, value)", "--orientation %d", &orientation, "Set the orientation", "--rotcw", &rotcw, "Rotate 90 deg clockwise", "--rotccw", &rotccw, "Rotate 90 deg counter-clockwise", "--rot180", &rot180, "Rotate 180 deg", "--inplace", &inplace, "Do operations in place on images", "--sRGB", &sRGB, "This file is in sRGB color space", //FIXME "-z", &zfile, "Treat input as a depth file", //FIXME "-c %s", &channellist, "Restrict/shuffle channels", NULL) < 0) { std::cerr << ap.error_message() << std::endl; ap.usage (); exit (EXIT_FAILURE); } if (help) { ap.usage (); exit (EXIT_FAILURE); } if (filenames.size() != 2 && ! inplace) { std::cerr << "iconvert: Must have both an input and output filename specified.\n"; ap.usage(); exit (EXIT_FAILURE); } if (filenames.size() == 0 && inplace) { std::cerr << "iconvert: Must have at least one filename\n"; ap.usage(); exit (EXIT_FAILURE); } if (((int)rotcw + (int)rotccw + (int)rot180 + (orientation>0)) > 1) { std::cerr << "iconvert: more than one of --rotcw, --rotccw, --rot180, --orientation\n"; ap.usage(); exit (EXIT_FAILURE); } } static bool DateTime_to_time_t (const char *datetime, time_t &timet) { int year, month, day, hour, min, sec; int r = sscanf (datetime, "%d:%d:%d %d:%d:%d", &year, &month, &day, &hour, &min, &sec); // printf ("%d %d:%d:%d %d:%d:%d\n", r, year, month, day, hour, min, sec); if (r != 6) return false; struct tm tmtime; time_t now; localtime_r (&now, &tmtime); // fill in defaults tmtime.tm_sec = sec; tmtime.tm_min = min; tmtime.tm_hour = hour; tmtime.tm_mday = day; tmtime.tm_mon = month-1; tmtime.tm_year = year-1900; timet = mktime (&tmtime); return true; } // Utility: split semicolon-separated list static void split_list (const std::string &list, std::vector<std::string> &items) { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep(";"); tokenizer tokens (list, sep); for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) { std::string t = *tok_iter; while (t.length() && t[0] == ' ') t.erase (t.begin()); if (t.length()) items.push_back (t); } } // Utility: join list into a single semicolon-separated string static std::string join_list (const std::vector<std::string> &items) { std::string s; for (size_t i = 0; i < items.size(); ++i) { if (i > 0) s += "; "; s += items[i]; } return s; } bool convert_file (const std::string &in_filename, const std::string &out_filename) { std::cout << "Converting " << in_filename << " to " << out_filename << "\n"; std::string tempname = out_filename; if (tempname == in_filename) { #if (BOOST_VERSION >= 103700) tempname = out_filename + ".tmp" + boost::filesystem::path(out_filename).extension(); #else tempname = out_filename + ".tmp" + boost::filesystem::extension(out_filename); #endif } // Find an ImageIO plugin that can open the input file, and open it. ImageInput *in = ImageInput::create (in_filename.c_str(), "" /* searchpath */); if (! in) { std::cerr << "iconvert ERROR: Could not find an ImageIO plugin to read \"" << in_filename << "\" : " << OpenImageIO::error_message() << "\n"; return false; } ImageSpec inspec; if (! in->open (in_filename.c_str(), inspec)) { std::cerr << "iconvert ERROR: Could not open \"" << in_filename << "\" : " << in->error_message() << "\n"; delete in; return false; } // Copy the spec, with possible change in format ImageSpec outspec = inspec; outspec.set_format (inspec.format); if (! dataformatname.empty()) { if (dataformatname == "uint8") outspec.set_format (TypeDesc::UINT8); else if (dataformatname == "int8") outspec.set_format (TypeDesc::INT8); else if (dataformatname == "uint16") outspec.set_format (TypeDesc::UINT16); else if (dataformatname == "int16") outspec.set_format (TypeDesc::INT16); else if (dataformatname == "half") outspec.set_format (TypeDesc::HALF); else if (dataformatname == "float") outspec.set_format (TypeDesc::FLOAT); else if (dataformatname == "double") outspec.set_format (TypeDesc::DOUBLE); if (outspec.format != inspec.format) no_copy_image = true; } outspec.gamma = gammaval; if (sRGB) { outspec.linearity = ImageSpec::sRGB; if (!strcmp (in->format_name(), "jpeg") || outspec.find_attribute ("Exif:ColorSpace")) outspec.attribute ("Exif:ColorSpace", 1); } if (tile[0]) { outspec.tile_width = tile[0]; outspec.tile_height = tile[1]; outspec.tile_depth = tile[2]; } if (scanline) { outspec.tile_width = 0; outspec.tile_height = 0; outspec.tile_depth = 0; } if (outspec.tile_width != inspec.tile_width || outspec.tile_height != inspec.tile_height || outspec.tile_depth != inspec.tile_depth) no_copy_image = true; if (! compression.empty()) { outspec.attribute ("compression", compression); if (compression != inspec.get_string_attribute ("compression")) no_copy_image = true; } if (quality > 0) { outspec.attribute ("CompressionQuality", quality); if (quality != inspec.get_int_attribute ("CompressionQuality")) no_copy_image = true; } if (orientation >= 1) outspec.attribute ("Orientation", orientation); else { orientation = outspec.get_int_attribute ("Orientation", 1); if (orientation >= 1 && orientation <= 8) { static int cw[] = { 0, 6, 7, 8, 5, 2, 3, 4, 1 }; if (rotcw || rotccw || rot180) orientation = cw[orientation]; if (rotccw || rot180) orientation = cw[orientation]; if (rotccw) orientation = cw[orientation]; outspec.attribute ("Orientation", orientation); } } if (caption != uninitialized) outspec.attribute ("ImageDescription", caption); if (clear_keywords) outspec.attribute ("Keywords", ""); if (keywords.size()) { std::string oldkw = outspec.get_string_attribute ("Keywords"); std::vector<std::string> oldkwlist; if (! oldkw.empty()) split_list (oldkw, oldkwlist); BOOST_FOREACH (const std::string &nk, keywords) { bool dup = false; BOOST_FOREACH (const std::string &ok, oldkwlist) dup |= (ok == nk); if (! dup) oldkwlist.push_back (nk); } outspec.attribute ("Keywords", join_list (oldkwlist)); } for (size_t i = 0; i < attribnames.size(); ++i) { outspec.attribute (attribnames[i].c_str(), attribvals[i].c_str()); } // Find an ImageIO plugin that can open the output file, and open it ImageOutput *out = ImageOutput::create (tempname.c_str()); if (! out) { std::cerr << "iconvert ERROR: Could not find an ImageIO plugin to write \"" << out_filename << "\" :" << OpenImageIO::error_message() << "\n"; return false; } if (! out->open (tempname.c_str(), outspec)) { std::cerr << "iconvert ERROR: Could not open \"" << out_filename << "\" : " << out->error_message() << "\n"; return false; } bool ok = true; if (! no_copy_image) { ok = out->copy_image (in); if (! ok) std::cerr << "iconvert ERROR copying \"" << in_filename << "\" to \"" << in_filename << "\" :\n\t" << in->error_message() << "\n"; } else { // Need to do it by hand for some reason. Future expansion in which // only a subset of channels are copied, or some such. std::vector<char> pixels (outspec.image_bytes()); ok = in->read_image (outspec.format, &pixels[0]); if (! ok) { std::cerr << "iconvert ERROR reading \"" << in_filename << "\" : " << in->error_message() << "\n"; } else { ok = out->write_image (outspec.format, &pixels[0]); if (! ok) std::cerr << "iconvert ERROR writing \"" << out_filename << "\" : " << out->error_message() << "\n"; } } out->close (); delete out; in->close (); delete in; // Figure out a time for the input file -- either one supplied by // the metadata, or the actual time stamp of the input file. std::time_t in_time; std::string metadatatime = outspec.get_string_attribute ("DateTime"); if (metadatatime.empty() || ! DateTime_to_time_t (metadatatime.c_str(), in_time)) in_time = boost::filesystem::last_write_time (in_filename); if (out_filename != tempname) { if (ok) { boost::filesystem::remove (out_filename); boost::filesystem::rename (tempname, out_filename); } else boost::filesystem::remove (tempname); } // If user requested, try to adjust the file's modification time to // the creation time indicated by the file's DateTime metadata. if (ok && adjust_time) boost::filesystem::last_write_time (out_filename, in_time); return ok; } int main (int argc, char *argv[]) { getargs (argc, argv); bool ok = true; if (inplace) { BOOST_FOREACH (const std::string &s, filenames) ok &= convert_file (s, s); } else { ok = convert_file (filenames[0], filenames[1]); } return ok ? EXIT_SUCCESS : EXIT_FAILURE; } <|endoftext|>
<commit_before>65771302-2fa5-11e5-957b-00012e3d3f12<commit_msg>65790ed2-2fa5-11e5-a113-00012e3d3f12<commit_after>65790ed2-2fa5-11e5-a113-00012e3d3f12<|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: MinMaxCurvatureFlowImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // \itkpiccaption[MinMaxCurvatureFlow computation]{Elements involved in the // computation of min-max curvature flow. // \label{fig:MinMaxCurvatureFlowFunctionDiagram}} // \parpic(7cm,6cm)[r]{\includegraphics[width=6cm]{MinMaxCurvatureFlowFunctionDiagram.eps}} // // The \doxygen{MinMaxCurvatureFlowImageFilter} applies a variant of the // \doxygen{CurvatureFlowImageFilter} algorithm where diffusion is turned on // or off depending of the scale of the noise that one wants to remove. The // evolution speed is switched between $\min(\kappa,0)$ and $\max(\kappa,0)$ // such that: // // \begin{equation} // I_t = F |\nabla I| // \end{equation} // // where $F$ is defined as // // \begin{equation} // F = \left\{ \begin{array} {r@{\quad:\quad}l} // \max(\kappa,0) & \mbox{Average} < Threshold \\ \min(\kappa,0) & \mbox{Average} \ge Threshold // \end{array} \right. // \end{equation} // // The $Average$ is the average intensity computed over a neighborhood of a // user specified radius of the pixel. The choice of the radius governs the // scale of the noise to be removed. The $Threshold$ is calculated as the // average of pixel intensities along the direction perpendicular to the // gradient at the \emph{extrema} of the local neighborhood. // // A speed of $F = max(\kappa,0)$ will cause small dark regions in a // predominantly light region to shrink. Conversely, a speed of $F = // min(\kappa,0)$, will cause light regions in a predominantly dark region to // shrink. Comparison between the neighborhood average and the threshold is // used to select the the right speed function to use. This switching // prevents the unwanted diffusion of the simple curvature flow method. // // Figure~\ref{fig:MinMaxCurvatureFlowFunctionDiagram} shows the main // elements involved in the computation. The set of square pixels represent // the neighborhood over which the average intensity is being computed. The // gray pixels are those lying close to the direction perpendicular to the // gradient. The pixels which intersect the neighborhood bounds are used to // compute the threshold value in the equation above. The integer radius of // the neighborhood is selected by the user. // // \index{itk::MinMaxCurvatureFlowImageFilter|textbf} // // Software Guide : EndLatex #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginLatex // // The first step required to use this filter is to include its header file. // // \index{itk::MinMaxCurvatureFlowImageFilter!header} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkMinMaxCurvatureFlowImageFilter.h" // Software Guide : EndCodeSnippet int main( int argc, char * argv[] ) { if( argc < 6 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile "; std::cerr << "numberOfIterations timeStep stencilRadius" << std::endl; return 1; } // Software Guide : BeginLatex // // Types should be selected based on the pixel types required for the // input and output images. The input and output image types are // instantiated. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef float InputPixelType; typedef float OutputPixelType; typedef itk::Image< InputPixelType, 2 > InputImageType; typedef itk::Image< OutputPixelType, 2 > OutputImageType; // Software Guide : EndCodeSnippet typedef itk::ImageFileReader< InputImageType > ReaderType; // Software Guide : BeginLatex // // The \doxygen{MinMaxCurvatureFlowImageFilter} type is now instantiated // using both the input image and the output image types. The filter is // then created using the New() method. // // \index{itk::MinMaxCurvatureFlowImageFilter!instantiation} // \index{itk::MinMaxCurvatureFlowImageFilter!New()} // \index{itk::MinMaxCurvatureFlowImageFilter!Pointer} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::MinMaxCurvatureFlowImageFilter< InputImageType, OutputImageType > FilterType; FilterType::Pointer filter = FilterType::New(); // Software Guide : EndCodeSnippet ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); // Software Guide : BeginLatex // // The input image can be obtained from the output of another filter. Here, // an image reader is used as source. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput( reader->GetOutput() ); // Software Guide : EndCodeSnippet const unsigned int numberOfIterations = atoi( argv[3] ); const double timeStep = atof( argv[4] ); typedef FilterType::RadiusValueType RadiusType; const RadiusType radius = atol( argv[5] ); // Software Guide : BeginLatex // // The \doxygen{MinMaxCurvatureFlowImageFilter} requires the two normal // parameters of the CurvatureFlow image, the number of iterations to be // performed and the time step used in the computation of the level set // evolution. In addition to them, the radius of the neighborhood is also // required. This last parameter is passed using the // SetStencilRadius() method. Note that the radius is provided as an // integer number since it is refering to a number of pixels from the center // to the border of the neighborhood. Then the filter can be executed by // invoking Update(). // // \index{itk::MinMaxCurvatureFlowImageFilter!Update()} // \index{itk::MinMaxCurvatureFlowImageFilter!SetTimeStep()} // \index{itk::MinMaxCurvatureFlowImageFilter!SetNumberOfIterations()} // \index{SetTimeStep()!itk::MinMaxCurvatureFlowImageFilter} // \index{SetNumberOfIterations()!itk::MinMaxCurvatureFlowImageFilter} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetTimeStep( timeStep ); filter->SetNumberOfIterations( numberOfIterations ); filter->SetStencilRadius( radius ); filter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Typical values for the time step are $0.125$ in $2D$ images and // $0.0625$ in $3D$ images. The number of iterations can be usually around // $10$, more iterations will result in further smoothing and will // increase the computing time linearly. The radius of the stencil can be // typically $1$. The \emph{edge-preserving} characteristic is not perfect // on this filter, some degradation will occur on the edges and will // increase as the number of iterations is increased. // // Software Guide : EndLatex // Software Guide : BeginLatex // // If the output of this filter has been connected to other filters down // the pipeline, updating any of the downstream filters would have // triggered the execution of this one. For example, a writer filter could // have been used after the curvatur flow filter. // // Software Guide : EndLatex typedef unsigned char WritePixelType; typedef itk::Image< WritePixelType, 2 > WriteImageType; typedef itk::RescaleIntensityImageFilter< OutputImageType, WriteImageType > RescaleFilterType; RescaleFilterType::Pointer rescaler = RescaleFilterType::New(); rescaler->SetOutputMinimum( 0 ); rescaler->SetOutputMaximum( 255 ); typedef itk::ImageFileWriter< WriteImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); // Software Guide : BeginCodeSnippet rescaler->SetInput( filter->GetOutput() ); writer->SetInput( rescaler->GetOutput() ); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // \begin{figure} // \center // \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps} // \includegraphics[width=0.44\textwidth]{MinMaxCurvatureFlowImageFilterOutput.eps} // \itkcaption[MinMaxCurvatureFlowImageFilter output]{Effect of the // MinMaxCurvatureFlowImageFilter on a slice from a MRI proton density image // of the brain.} // \label{fig:MinMaxCurvatureFlowImageFilterInputOutput} // \end{figure} // // Figure \ref{fig:MinMaxCurvatureFlowImageFilterInputOutput} illustrates // the effect of this filter on a MRI proton density image of the // brain. In this example the filter was run with a time step of $0.125$, // $10$ iterations and a radius of $1$. The figure shows how homogeneous // regions are smoothed and edges are preserved. Notice also, that the // results in the figure has sharper edges than the same example using // simple curvature flow in Figure // \ref{fig:CurvatureFlowImageFilterInputOutput}. // // // Software Guide : EndLatex return 0; } <commit_msg>DOC: ENH: piccaption figure reformatted for the software guide. Related classes added at the end.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: MinMaxCurvatureFlowImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // \itkpiccaption[MinMaxCurvatureFlow computation]{Elements involved in the // computation of min-max curvature flow. // \label{fig:MinMaxCurvatureFlowFunctionDiagram}} // \parpic(6cm,5cm)[r]{\includegraphics[width=5cm]{MinMaxCurvatureFlowFunctionDiagram.eps}} // // The MinMax curvature flow filter applies a variant of the curvature flow // algorithm where diffusion is turned on or off depending of the scale of the // noise that one wants to remove. The evolution speed is switched between // $\min(\kappa,0)$ and $\max(\kappa,0)$ such that: // // \begin{equation} // I_t = F |\nabla I| // \end{equation} // // where $F$ is defined as // // \begin{equation} // F = \left\{ \begin{array} {r@{\quad:\quad}l} // \max(\kappa,0) & \mbox{Average} < Threshold \\ \min(\kappa,0) & \mbox{Average} \ge Threshold // \end{array} \right. // \end{equation} // // The $Average$ is the average intensity computed over a neighborhood of a // user specified radius of the pixel. The choice of the radius governs the // scale of the noise to be removed. The $Threshold$ is calculated as the // average of pixel intensities along the direction perpendicular to the // gradient at the \emph{extrema} of the local neighborhood. // // A speed of $F = max(\kappa,0)$ will cause small dark regions in a // predominantly light region to shrink. Conversely, a speed of $F = // min(\kappa,0)$, will cause light regions in a predominantly dark region to // shrink. Comparison between the neighborhood average and the threshold is // used to select the the right speed function to use. This switching // prevents the unwanted diffusion of the simple curvature flow method. // // Figure~\ref{fig:MinMaxCurvatureFlowFunctionDiagram} shows the main // elements involved in the computation. The set of square pixels represent // the neighborhood over which the average intensity is being computed. The // gray pixels are those lying close to the direction perpendicular to the // gradient. The pixels which intersect the neighborhood bounds are used to // compute the threshold value in the equation above. The integer radius of // the neighborhood is selected by the user. // // \index{itk::MinMaxCurvatureFlowImageFilter|textbf} // // Software Guide : EndLatex #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginLatex // // The first step required to use the \doxygen{MinMaxCurvatureFlowImageFilter} // is to include its header file. // // \index{itk::MinMaxCurvatureFlowImageFilter!header} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkMinMaxCurvatureFlowImageFilter.h" // Software Guide : EndCodeSnippet int main( int argc, char * argv[] ) { if( argc < 6 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile "; std::cerr << "numberOfIterations timeStep stencilRadius" << std::endl; return 1; } // Software Guide : BeginLatex // // Types should be selected based on the pixel types required for the // input and output images. The input and output image types are // instantiated. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef float InputPixelType; typedef float OutputPixelType; typedef itk::Image< InputPixelType, 2 > InputImageType; typedef itk::Image< OutputPixelType, 2 > OutputImageType; // Software Guide : EndCodeSnippet typedef itk::ImageFileReader< InputImageType > ReaderType; // Software Guide : BeginLatex // // The \doxygen{MinMaxCurvatureFlowImageFilter} type is now instantiated // using both the input image and the output image types. The filter is // then created using the New() method. // // \index{itk::MinMaxCurvatureFlowImageFilter!instantiation} // \index{itk::MinMaxCurvatureFlowImageFilter!New()} // \index{itk::MinMaxCurvatureFlowImageFilter!Pointer} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::MinMaxCurvatureFlowImageFilter< InputImageType, OutputImageType > FilterType; FilterType::Pointer filter = FilterType::New(); // Software Guide : EndCodeSnippet ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); // Software Guide : BeginLatex // // The input image can be obtained from the output of another filter. Here, // an image reader is used as source. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput( reader->GetOutput() ); // Software Guide : EndCodeSnippet const unsigned int numberOfIterations = atoi( argv[3] ); const double timeStep = atof( argv[4] ); typedef FilterType::RadiusValueType RadiusType; const RadiusType radius = atol( argv[5] ); // Software Guide : BeginLatex // // The \doxygen{MinMaxCurvatureFlowImageFilter} requires the two normal // parameters of the CurvatureFlow image, the number of iterations to be // performed and the time step used in the computation of the level set // evolution. In addition to them, the radius of the neighborhood is also // required. This last parameter is passed using the // SetStencilRadius() method. Note that the radius is provided as an // integer number since it is refering to a number of pixels from the center // to the border of the neighborhood. Then the filter can be executed by // invoking Update(). // // \index{itk::MinMaxCurvatureFlowImageFilter!Update()} // \index{itk::MinMaxCurvatureFlowImageFilter!SetTimeStep()} // \index{itk::MinMaxCurvatureFlowImageFilter!SetNumberOfIterations()} // \index{SetTimeStep()!itk::MinMaxCurvatureFlowImageFilter} // \index{SetNumberOfIterations()!itk::MinMaxCurvatureFlowImageFilter} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetTimeStep( timeStep ); filter->SetNumberOfIterations( numberOfIterations ); filter->SetStencilRadius( radius ); filter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Typical values for the time step are $0.125$ in $2D$ images and // $0.0625$ in $3D$ images. The number of iterations can be usually around // $10$, more iterations will result in further smoothing and will // increase the computing time linearly. The radius of the stencil can be // typically $1$. The \emph{edge-preserving} characteristic is not perfect // on this filter, some degradation will occur on the edges and will // increase as the number of iterations is increased. // // Software Guide : EndLatex // Software Guide : BeginLatex // // If the output of this filter has been connected to other filters down // the pipeline, updating any of the downstream filters would have // triggered the execution of this one. For example, a writer filter could // have been used after the curvatur flow filter. // // Software Guide : EndLatex typedef unsigned char WritePixelType; typedef itk::Image< WritePixelType, 2 > WriteImageType; typedef itk::RescaleIntensityImageFilter< OutputImageType, WriteImageType > RescaleFilterType; RescaleFilterType::Pointer rescaler = RescaleFilterType::New(); rescaler->SetOutputMinimum( 0 ); rescaler->SetOutputMaximum( 255 ); typedef itk::ImageFileWriter< WriteImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); // Software Guide : BeginCodeSnippet rescaler->SetInput( filter->GetOutput() ); writer->SetInput( rescaler->GetOutput() ); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // \begin{figure} // \center // \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps} // \includegraphics[width=0.44\textwidth]{MinMaxCurvatureFlowImageFilterOutput.eps} // \itkcaption[MinMaxCurvatureFlowImageFilter output]{Effect of the // MinMaxCurvatureFlowImageFilter on a slice from a MRI proton density image // of the brain.} // \label{fig:MinMaxCurvatureFlowImageFilterInputOutput} // \end{figure} // // Figure \ref{fig:MinMaxCurvatureFlowImageFilterInputOutput} illustrates // the effect of this filter on a MRI proton density image of the // brain. In this example the filter was run with a time step of $0.125$, // $10$ iterations and a radius of $1$. The figure shows how homogeneous // regions are smoothed and edges are preserved. Notice also, that the // results in the figure has sharper edges than the same example using // simple curvature flow in Figure // \ref{fig:CurvatureFlowImageFilterInputOutput}. // // \relatedClasses // \begin{itemize} // \item \doxygen{CurvatureFlowImageFilter} // \end{itemize} // // // Software Guide : EndLatex return 0; } <|endoftext|>
<commit_before>/** * @file * @brief Implementation of config reader * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "ConfigReader.hpp" #include <algorithm> #include <cstdlib> #include <fstream> #include <string> #include <vector> #include "core/utils/file.h" #include "core/utils/log.h" #include "exceptions.h" using namespace allpix; ConfigReader::ConfigReader() = default; ConfigReader::ConfigReader(std::istream& stream, std::string file_name) : ConfigReader() { add(stream, std::move(file_name)); } ConfigReader::ConfigReader(const ConfigReader& other) : conf_array_(other.conf_array_) { copy_init_map(); } ConfigReader& ConfigReader::operator=(const ConfigReader& other) { conf_array_ = other.conf_array_; copy_init_map(); return *this; } void ConfigReader::copy_init_map() { conf_map_.clear(); for(auto iter = conf_array_.begin(); iter != conf_array_.end(); ++iter) { conf_map_[iter->getName()].push_back(iter); } } /** * @throws KeyValueParseError If the key / value pair could not be parsed * * The key / value pair is split according to the format specifications */ std::pair<std::string, std::string> ConfigReader::parseKeyValue(std::string line) { line = allpix::trim(line); size_t equals_pos = line.find('='); if(equals_pos != std::string::npos) { std::string key = trim(std::string(line, 0, equals_pos)); std::string value = trim(std::string(line, equals_pos + 1)); char last_quote = 0; for(size_t i = 0; i < value.size(); ++i) { if(value[i] == '\'' || value[i] == '\"') { if(last_quote == 0) { last_quote = value[i]; } else if(last_quote == value[i]) { last_quote = 0; } } if(last_quote == 0 && value[i] == '#') { value = std::string(value, 0, i); break; } } // Check if key contains only alphanumeric or underscores bool valid_key = true; for(auto& ch : key) { if(isalnum(ch) == 0 && ch != '_' && ch != '.' && ch != ':') { valid_key = false; break; } } // Check if value is not empty and key is valid if(!valid_key) { throw KeyValueParseError(line, "key is not valid"); } if(value.empty()) { throw KeyValueParseError(line, "value is empty"); } return std::make_pair(key, allpix::trim(value)); } // Key / value pair does not contain equal sign throw KeyValueParseError(line, "missing equality sign to split key and value"); } /** * @throws ConfigParseError If an error occurred during the parsing of the stream * * The configuration is immediately parsed and all of its configurations are available after the functions returns. */ void ConfigReader::add(std::istream& stream, std::string file_name) { LOG(TRACE) << "Parsing configuration file " << file_name; // Convert file name to absolute path (if given) if(!file_name.empty()) { file_name = allpix::get_absolute_path(file_name); } // Build first empty configuration std::string section_name; Configuration conf(section_name, file_name); int line_num = 0; while(true) { // Process config line by line std::string line; if(stream.eof()) { break; } std::getline(stream, line); ++line_num; // Ignore empty lines or comments if(line.empty() || line.front() == '#') { continue; } // Check if section header or key-value pair if(line.front() == '[') { // Line should be a section header with an alphanumeric name size_t idx = 1; for(; idx < line.length() - 1; ++idx) { if(isalnum(line[idx]) == 0 && line[idx] != '_') { break; } } std::string remain = allpix::trim(line.substr(idx + 1)); if(line[idx] == ']' && (remain.empty() || remain.front() == '#')) { // Ignore empty sections if they contain no configurations if(!conf.getName().empty() || conf.countSettings() > 0) { // Add previous section addConfiguration(std::move(conf)); } // Begin new section section_name = std::string(line, 1, idx - 1); conf = Configuration(section_name, file_name); } else { // Section header is not valid throw ConfigParseError(file_name, line_num); } } else if(isalpha(line.front()) != 0) { // Line should be a key / value pair with an equal sign try { // Parse the key value pair auto key_value = parseKeyValue(line); // Add the config key conf.setText(key_value.first, key_value.second); } catch(KeyValueParseError& e) { // Rethrow key / value parse error as a configuration parse error throw ConfigParseError(file_name, line_num); } } else { // Line is not a comment, key/value pair or section header throw ConfigParseError(file_name, line_num); } } // Add last section addConfiguration(std::move(conf)); } void ConfigReader::addConfiguration(Configuration config) { conf_array_.push_back(std::move(config)); std::string section_name = conf_array_.back().getName(); std::transform(section_name.begin(), section_name.end(), section_name.begin(), ::tolower); conf_map_[section_name].push_back(--conf_array_.end()); } void ConfigReader::clear() { conf_map_.clear(); conf_array_.clear(); } bool ConfigReader::hasConfiguration(std::string name) const { std::transform(name.begin(), name.end(), name.begin(), ::tolower); return conf_map_.find(name) != conf_map_.end(); } unsigned int ConfigReader::countConfigurations(std::string name) const { std::transform(name.begin(), name.end(), name.begin(), ::tolower); if(!hasConfiguration(name)) { return 0; } return static_cast<unsigned int>(conf_map_.at(name).size()); } /** * @warning This will have the file path of the first header section * @note An empty configuration is returned if no empty section is found */ Configuration ConfigReader::getHeaderConfiguration() const { // Get empty configurations std::vector<Configuration> configurations = getConfigurations(""); if(configurations.empty()) { // Use all configurations to find the file name if no empty configurations = getConfigurations(); std::string file_name; if(!configurations.empty()) { file_name = configurations.at(0).getFilePath(); } return Configuration("", file_name); } // Merge all configurations Configuration header_config = configurations.at(0); for(auto& config : configurations) { // NOTE: Merging first configuration again has no effect header_config.merge(config); } return header_config; } std::vector<Configuration> ConfigReader::getConfigurations(std::string name) const { std::transform(name.begin(), name.end(), name.begin(), ::tolower); if(!hasConfiguration(name)) { return std::vector<Configuration>(); } std::vector<Configuration> result; for(auto& iter : conf_map_.at(name)) { result.push_back(*iter); } return result; } std::vector<Configuration> ConfigReader::getConfigurations() const { return std::vector<Configuration>(conf_array_.begin(), conf_array_.end()); } <commit_msg>Fix bug: user manual states that all whitespace at beginning & end shall be stripped. Do that.<commit_after>/** * @file * @brief Implementation of config reader * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "ConfigReader.hpp" #include <algorithm> #include <cstdlib> #include <fstream> #include <string> #include <vector> #include "core/utils/file.h" #include "core/utils/log.h" #include "exceptions.h" using namespace allpix; ConfigReader::ConfigReader() = default; ConfigReader::ConfigReader(std::istream& stream, std::string file_name) : ConfigReader() { add(stream, std::move(file_name)); } ConfigReader::ConfigReader(const ConfigReader& other) : conf_array_(other.conf_array_) { copy_init_map(); } ConfigReader& ConfigReader::operator=(const ConfigReader& other) { conf_array_ = other.conf_array_; copy_init_map(); return *this; } void ConfigReader::copy_init_map() { conf_map_.clear(); for(auto iter = conf_array_.begin(); iter != conf_array_.end(); ++iter) { conf_map_[iter->getName()].push_back(iter); } } /** * @throws KeyValueParseError If the key / value pair could not be parsed * * The key / value pair is split according to the format specifications */ std::pair<std::string, std::string> ConfigReader::parseKeyValue(std::string line) { line = allpix::trim(line); size_t equals_pos = line.find('='); if(equals_pos != std::string::npos) { std::string key = trim(std::string(line, 0, equals_pos)); std::string value = trim(std::string(line, equals_pos + 1)); char last_quote = 0; for(size_t i = 0; i < value.size(); ++i) { if(value[i] == '\'' || value[i] == '\"') { if(last_quote == 0) { last_quote = value[i]; } else if(last_quote == value[i]) { last_quote = 0; } } if(last_quote == 0 && value[i] == '#') { value = std::string(value, 0, i); break; } } // Check if key contains only alphanumeric or underscores bool valid_key = true; for(auto& ch : key) { if(isalnum(ch) == 0 && ch != '_' && ch != '.' && ch != ':') { valid_key = false; break; } } // Check if value is not empty and key is valid if(!valid_key) { throw KeyValueParseError(line, "key is not valid"); } if(value.empty()) { throw KeyValueParseError(line, "value is empty"); } return std::make_pair(key, allpix::trim(value)); } // Key / value pair does not contain equal sign throw KeyValueParseError(line, "missing equality sign to split key and value"); } /** * @throws ConfigParseError If an error occurred during the parsing of the stream * * The configuration is immediately parsed and all of its configurations are available after the functions returns. */ void ConfigReader::add(std::istream& stream, std::string file_name) { LOG(TRACE) << "Parsing configuration file " << file_name; // Convert file name to absolute path (if given) if(!file_name.empty()) { file_name = allpix::get_absolute_path(file_name); } // Build first empty configuration std::string section_name; Configuration conf(section_name, file_name); int line_num = 0; while(true) { // Process config line by line std::string line; if(stream.eof()) { break; } std::getline(stream, line); ++line_num; // Trim whitespaces at beginning and end of line: line = allpix::trim(line); // Ignore empty lines or comments if(line.empty() || line.front() == '#') { continue; } // Check if section header or key-value pair if(line.front() == '[') { // Line should be a section header with an alphanumeric name size_t idx = 1; for(; idx < line.length() - 1; ++idx) { if(isalnum(line[idx]) == 0 && line[idx] != '_') { break; } } std::string remain = allpix::trim(line.substr(idx + 1)); if(line[idx] == ']' && (remain.empty() || remain.front() == '#')) { // Ignore empty sections if they contain no configurations if(!conf.getName().empty() || conf.countSettings() > 0) { // Add previous section addConfiguration(std::move(conf)); } // Begin new section section_name = std::string(line, 1, idx - 1); conf = Configuration(section_name, file_name); } else { // Section header is not valid throw ConfigParseError(file_name, line_num); } } else if(isalpha(line.front()) != 0) { // Line should be a key / value pair with an equal sign try { // Parse the key value pair auto key_value = parseKeyValue(line); // Add the config key conf.setText(key_value.first, key_value.second); } catch(KeyValueParseError& e) { // Rethrow key / value parse error as a configuration parse error throw ConfigParseError(file_name, line_num); } } else { // Line is not a comment, key/value pair or section header throw ConfigParseError(file_name, line_num); } } // Add last section addConfiguration(std::move(conf)); } void ConfigReader::addConfiguration(Configuration config) { conf_array_.push_back(std::move(config)); std::string section_name = conf_array_.back().getName(); std::transform(section_name.begin(), section_name.end(), section_name.begin(), ::tolower); conf_map_[section_name].push_back(--conf_array_.end()); } void ConfigReader::clear() { conf_map_.clear(); conf_array_.clear(); } bool ConfigReader::hasConfiguration(std::string name) const { std::transform(name.begin(), name.end(), name.begin(), ::tolower); return conf_map_.find(name) != conf_map_.end(); } unsigned int ConfigReader::countConfigurations(std::string name) const { std::transform(name.begin(), name.end(), name.begin(), ::tolower); if(!hasConfiguration(name)) { return 0; } return static_cast<unsigned int>(conf_map_.at(name).size()); } /** * @warning This will have the file path of the first header section * @note An empty configuration is returned if no empty section is found */ Configuration ConfigReader::getHeaderConfiguration() const { // Get empty configurations std::vector<Configuration> configurations = getConfigurations(""); if(configurations.empty()) { // Use all configurations to find the file name if no empty configurations = getConfigurations(); std::string file_name; if(!configurations.empty()) { file_name = configurations.at(0).getFilePath(); } return Configuration("", file_name); } // Merge all configurations Configuration header_config = configurations.at(0); for(auto& config : configurations) { // NOTE: Merging first configuration again has no effect header_config.merge(config); } return header_config; } std::vector<Configuration> ConfigReader::getConfigurations(std::string name) const { std::transform(name.begin(), name.end(), name.begin(), ::tolower); if(!hasConfiguration(name)) { return std::vector<Configuration>(); } std::vector<Configuration> result; for(auto& iter : conf_map_.at(name)) { result.push_back(*iter); } return result; } std::vector<Configuration> ConfigReader::getConfigurations() const { return std::vector<Configuration>(conf_array_.begin(), conf_array_.end()); } <|endoftext|>
<commit_before>/* * This file is part of accounts-ui * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * Contact: Lucian Horga <ext-lucian.horga@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 */ //project #include "credentialwidget.h" #include "credentialwidgetview.h" //Qt #include <QDebug> //M #include <MTheme> #include <MWidgetCreator> #include <MLibrary> M_LIBRARY CredentialWidget::CredentialWidget(CredentialWidgetModel *model, QGraphicsItem *parent) : MWidgetController(model == 0 ? new CredentialWidgetModel : model, parent) { MWidgetView *defaultWidgetView = MTheme::view(this); // looks at the .conf file and constructs the view there. Q_ASSERT_X(defaultWidgetView, "no CredentialWidgetView", "There is no available WidgetView class for this widget - is there an existing and correct conf file?"); setView(defaultWidgetView); setStyleName("CredentialWidget"); } CredentialWidget::~CredentialWidget() { } void CredentialWidget::showEvent(QShowEvent *event) { model()->setFocusOnPasswordField(true); MWidgetController::showEvent(event); } QString CredentialWidget::username() { Q_ASSERT(model()); return model()->username(); } QString CredentialWidget::password() { Q_ASSERT(model()); return model()->password(); } QString CredentialWidget::captchaText() { Q_ASSERT(model()); return model()->captchaText(); } bool CredentialWidget::rememberPasswordChecked() { Q_ASSERT(model()); return model()->checkboxPressed(); } bool CredentialWidget::enabled() { Q_ASSERT(model()); return model()->enabled(); } void CredentialWidget::setUsername(const QString &aUserName) { Q_ASSERT(model()); model()->setUsername(aUserName); } void CredentialWidget::setPassword(const QString &aPassword) { Q_ASSERT(model()); model()->setPassword(aPassword); } void CredentialWidget::setCaptcha(const QImage &image) { Q_ASSERT(model()); model()->setCaptcha(image); } void CredentialWidget::setRememberPasswordChecked(bool checked) { Q_ASSERT(model()); model()->setCheckboxPressed(checked); } void CredentialWidget::setFocusOnUserNameField() { CredentialWidgetView* cdView = NULL; cdView = const_cast<CredentialWidgetView*>(qobject_cast<const CredentialWidgetView*> (view())); if (NULL != cdView) cdView->setFocusOnUserNameField(); } void CredentialWidget::setFocusOnPasswordField() { CredentialWidgetView* cdView = NULL; cdView = (CredentialWidgetView*)view(); if (NULL != cdView) cdView->setFocusOnUserNameField(); model()->setFocusOnPasswordField(true); } void CredentialWidget::setFocusOnCaptchaField() { Q_ASSERT(model()); model()->setFocusOnCaptchaTextField(true); } void CredentialWidget::setEnabled(bool value) { Q_ASSERT(model()); model()->setEnabled(value); } void CredentialWidget::setInformativeNoteText(const QString &text) { Q_ASSERT(model()); model()->setInformativeNoteText(text); } M_REGISTER_WIDGET_NO_CREATE(CredentialWidget); <commit_msg>review comments. interim checkin<commit_after>/* * This file is part of accounts-ui * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * Contact: Lucian Horga <ext-lucian.horga@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 */ //project #include "credentialwidget.h" #include "credentialwidgetview.h" //Qt #include <QDebug> //M #include <MTheme> #include <MWidgetCreator> #include <MLibrary> M_LIBRARY CredentialWidget::CredentialWidget(CredentialWidgetModel *model, QGraphicsItem *parent) : MWidgetController(model == 0 ? new CredentialWidgetModel : model, parent) { MWidgetView *defaultWidgetView = MTheme::view(this); // looks at the .conf file and constructs the view there. Q_ASSERT_X(defaultWidgetView, "no CredentialWidgetView", "There is no available WidgetView class for this widget - is there an existing and correct conf file?"); setView(defaultWidgetView); setStyleName("CredentialWidget"); } CredentialWidget::~CredentialWidget() { } void CredentialWidget::showEvent(QShowEvent *event) { model()->setFocusOnPasswordField(true); MWidgetController::showEvent(event); } QString CredentialWidget::username() { Q_ASSERT(model()); return model()->username(); } QString CredentialWidget::password() { Q_ASSERT(model()); return model()->password(); } QString CredentialWidget::captchaText() { Q_ASSERT(model()); return model()->captchaText(); } bool CredentialWidget::rememberPasswordChecked() { Q_ASSERT(model()); return model()->checkboxPressed(); } bool CredentialWidget::enabled() { Q_ASSERT(model()); return model()->enabled(); } void CredentialWidget::setUsername(const QString &aUserName) { Q_ASSERT(model()); model()->setUsername(aUserName); } void CredentialWidget::setPassword(const QString &aPassword) { Q_ASSERT(model()); model()->setPassword(aPassword); } void CredentialWidget::setCaptcha(const QImage &image) { Q_ASSERT(model()); model()->setCaptcha(image); } void CredentialWidget::setRememberPasswordChecked(bool checked) { Q_ASSERT(model()); model()->setCheckboxPressed(checked); } void CredentialWidget::setFocusOnUserNameField() { CredentialWidgetView* cdView = NULL; cdView = const_cast<CredentialWidgetView*>(qobject_cast<const CredentialWidgetView*> (view())); if (NULL != cdView) cdView->setFocusOnUserNameField(); } void CredentialWidget::setFocusOnPasswordField() { CredentialWidgetView* cdView = NULL; cdView = const_cast<CredentialWidgetView*>(qobject_cast<const CredentialWidgetView*> (view())); if (NULL != cdView) cdView->setFocusOnPasswordField(); model()->setFocusOnPasswordField(true); } void CredentialWidget::setFocusOnCaptchaField() { Q_ASSERT(model()); model()->setFocusOnCaptchaTextField(true); } void CredentialWidget::setEnabled(bool value) { Q_ASSERT(model()); model()->setEnabled(value); } void CredentialWidget::setInformativeNoteText(const QString &text) { Q_ASSERT(model()); model()->setInformativeNoteText(text); } M_REGISTER_WIDGET_NO_CREATE(CredentialWidget); <|endoftext|>
<commit_before>/** * @file Tools/ImageProcessing/SpiderScan.cpp * * Utility class which performs a SpiderScan algorithm for blob region scanning * */ #include "SpiderScan.h" #include <Tools/Debug/DebugImageDrawings.h> #include "Tools/Debug/DebugModify.h" #include "Tools/Debug/DebugRequest.h" SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier) : theImage(theImage), theColorClassifier(theColorClassifier) { searchColors = vector<ColorClasses::Color>(1, ColorClasses::numOfColors); borderColors = vector<ColorClasses::Color>(1, ColorClasses::green); init(); } SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier, ColorClasses::Color searchColor) : theImage(theImage), theColorClassifier(theColorClassifier) { searchColors = vector<ColorClasses::Color>(1, searchColor); borderColors = vector<ColorClasses::Color>(1, ColorClasses::numOfColors); init(); } SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier, vector<ColorClasses::Color>& searchColors) : theImage(theImage), theColorClassifier(theColorClassifier), searchColors(searchColors) { borderColors = vector<ColorClasses::Color>(1, ColorClasses::numOfColors); init(); } SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier, ColorClasses::Color searchColor, ColorClasses::Color borderColor) : theImage(theImage), theColorClassifier(theColorClassifier) { searchColors = vector<ColorClasses::Color>(1, searchColor); borderColors = vector<ColorClasses::Color>(1, borderColor); init(); } SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier, vector<ColorClasses::Color>& searchColors, vector<ColorClasses::Color>& borderColors) : theImage(theImage), theColorClassifier(theColorClassifier), searchColors(searchColors), borderColors(borderColors) { init(); } bool SpiderScan::isBorderColor(ColorClasses::Color color) const { for(unsigned int i = 0; i < borderColors.size(); i++) { if(color == borderColors[i]) { return true; } } return false; }//end isBorderColor bool SpiderScan::isSearchColor(ColorClasses::Color color) const { for(unsigned int i = 0; i < searchColors.size(); i++) { if(color == searchColors[i]) { return true; } } return false; }//end isSearchColor void SpiderScan::setMaxBeamLength(unsigned int length) { max_length_of_beam = length; } void SpiderScan::setCurrentColorSimThreshold(double threshold) { currentColorSimThreshold = threshold; } void SpiderScan::setMaxColorPointsToSkip(unsigned int maxToSkip) { maxColorPointsToSkip = maxToSkip; } void SpiderScan::setMaxNumberOfScans(unsigned int maxScans) { maxNumberOfScans = maxScans; } void SpiderScan::init() { drawScanLines = false; max_length_of_beam = 30; //maximum length of the scan line currentColorSimThreshold = 8; //... maxColorPointsToSkip = 12; // maximum number of non search color ... maxNumberOfScans = 15; //maximum number of scanlines ... } void SpiderScan::setDrawScanLines(bool draw) { drawScanLines = draw; } void SpiderScan::scan(const Vector2<int>& start, PointList<20>& goodPoints, PointList<20>& badPoints) { Scans scans; //a list of scans to perform //add the standard scan lines scans.add(start, Vector2<int>( 0,-1));// down scans.add(start, Vector2<int>(-1,-1));// to the lower left scans.add(start, Vector2<int>(-1, 0));// to the left scans.add(start, Vector2<int>(-1, 1));// to the upper left scans.add(start, Vector2<int>( 0, 1));// up scans.add(start, Vector2<int>( 1, 1));// to the upper right scans.add(start, Vector2<int>( 1, 0));// to the right scans.add(start, Vector2<int>( 1,-1));// to the lower right scan(goodPoints, badPoints, scans); } void SpiderScan::scan(PointList<20>& goodPoints, PointList<20>& badPoints, Scans scans) { //remember the number of performed scans int numberOfScans = 0; while(scans.number > 0 && numberOfScans < maxNumberOfScans) //while there are scans to perform (but not too much) { // ... numberOfScans++; //Vector2<int>& direction = scans.direction[0]; //get the direction of the scan line // Vector2<int> currentPoint(scans.start[0]); //and the starting point int badPointsBeforeScan = badPoints.length; //remember the number of bad points (to see if one was added after the scan) //perform the scan, see if it was successful if(scanLine(scans.start[0], scans.direction[0], maxColorPointsToSkip, goodPoints, badPoints)) { if(badPoints.length > badPointsBeforeScan) //if a bad point was found { Vector2<int>& badPoint = badPoints[badPoints.length-1]; //get this point //if the pixel lies at the image border and was not the result of a scan along that border if(pixelAtImageBorder(badPoint, 2) && !isBorderScan(scans.start[0], scans.direction[0], 2)) { if(badPoint.x <= 1 || (unsigned int)badPoint.x >= theImage.cameraInfo.resolutionWidth-2) { //... its not reliable and we should scan along the imageborder to find the real border point scans.add(badPoint, Vector2<int>(0, 1)); scans.add(badPoint, Vector2<int>(0, -1)); } //same for the vertical borders else if(badPoint.y <= 1 || (unsigned int)badPoint.y >= theImage.cameraInfo.resolutionHeight-2) { scans.add(badPoint, Vector2<int>( 1, 0)); scans.add(badPoint, Vector2<int>(-1, 0)); } badPoints.remove(badPoints.length-1); //kick the unreliable Pixel }//end if pixelAtImageBorder }//end if BadPointFound }//end if borderPointFound scans.remove(0); //scan done, remove it from the list }//end while scans left; }//end spiderSearch bool SpiderScan::scanLine(const Vector2<int>& start, const Vector2<int>& direction, int maxColorPointsToSkip, PointList<20>& goodPoints, PointList<20>& badPoints) const { Vector2<int> currentPoint(start); //set the starting point int searchColorPointsSkipIndex = 0; //reset number of skipped pixels Vector2<int> borderPoint; // to remember the border point ... bool borderPointFound = false; //if one was found bool borderPixelFound = false; //and if it was followed by a border pixel Vector2<int> lastSearchColorPoint(start); //expand in the selected direction for(unsigned int j = 0; j < max_length_of_beam; j++) { // check the current point if( searchColorPointsSkipIndex > maxColorPointsToSkip || // point outside the image !pixelInImage(currentPoint)) { break; }//end if //////////////////////////////// // process the current point //////////////////////////////// Pixel pixel = theImage.get(currentPoint.x,currentPoint.y); ColorClasses::Color currentPixelColor = theColorClassifier.getColorClass(pixel); // bool hasColor = (currentPixelColor == searchColor) || (searchColor == ColorClasses::numOfColors && currentPixelColor != borderColor); bool hasColor = isSearchColor(currentPixelColor) || (searchColors[0] == ColorClasses::numOfColors && !isBorderColor(currentPixelColor)); // HACK: taken from GT07 // TODO: make it more general by taking the criteria out of the method if(!hasColor) { //hasColor = currentOrangeSim > currentColorSimThreshold; Pixel pixelLast = theImage.get(lastSearchColorPoint.x,lastSearchColorPoint.y); double yDiff = pixel.y - pixelLast.y; double uDiff = pixel.u - pixelLast.u; double vDiff = pixel.v - pixelLast.v; double useY = 0.0; // MODIFY("ImageProcessor:Detector:currentColorSimThreshold", currentColorSimThreshold); // MODIFY("ImageProcessor:Detector:useY", useY); // hasColor = // ((currentPixelColor == ColorClasses::none) || (searchColor == ColorClasses::numOfColors && currentPixelColor != borderColor)) && // searchColorPointsSkipIndex == 0 && // sqrt( useY*Math::sqr(yDiff) + Math::sqr(uDiff) + Math::sqr(vDiff) ) < currentColorSimThreshold; hasColor = (currentPixelColor == ColorClasses::none || (searchColors[0] == ColorClasses::numOfColors && !isBorderColor(currentPixelColor))) && searchColorPointsSkipIndex == 0 && sqrt( useY*Math::sqr(yDiff) + Math::sqr(uDiff) + Math::sqr(vDiff) ) < currentColorSimThreshold; } else { lastSearchColorPoint = currentPoint; } if(hasColor) { borderPoint = currentPoint; searchColorPointsSkipIndex = 0; borderPointFound = true; borderPixelFound = false; } else { // if // ( // currentPixelColor == borderColor || // (borderColor == ColorClasses::numOfColors && currentPixelColor != searchColor) //// (currentPixelColor != searchColor && borderColor == ColorClasses::numOfColors) || //// (searchColor == ColorClasses::numOfColors && currentPixelColor != borderColor) // ) if ( isBorderColor(currentPixelColor) || (borderColors[0] == ColorClasses::numOfColors && !isSearchColor(currentPixelColor) ) ) { borderPixelFound = true; } searchColorPointsSkipIndex++; }//end if if(drawScanLines) { if(hasColor) { if(currentPixelColor == ColorClasses::none) { POINT_PX(ColorClasses::orange, (unsigned int)(currentPoint.x), (unsigned int)(currentPoint.y)); } else { POINT_PX(ColorClasses::green, (unsigned int)(currentPoint.x), (unsigned int)(currentPoint.y)); } } else { POINT_PX(ColorClasses::red, (unsigned int)(currentPoint.x), (unsigned int)(currentPoint.y)); } } currentPoint += direction; }//end for if(borderPointFound) //if a point was found ... { //that point was followed by a border pixel, does not lie at the images border or is the result of a scan along that border ... if(borderPixelFound && (!pixelAtImageBorder(borderPoint, 2) || isBorderScan(borderPoint, direction, 2))) { goodPoints.add(borderPoint); //it's good point } else { badPoints.add(borderPoint); //otherwise it's a bad one } }//end if return borderPointFound; //return if a borderpoint was found }//end scanLine //check wether a scan line goes along an image border bool SpiderScan::isBorderScan(const Vector2<int>& point, const Vector2<int>& direction, int borderWidth) const { return ((point.x<borderWidth || (unsigned int)point.x>=theImage.cameraInfo.resolutionWidth-borderWidth) && direction.x==0) || ((point.y<borderWidth || (unsigned int)point.y>=theImage.cameraInfo.resolutionHeight-borderWidth) && direction.y==0); }//end isBorderScan //check wether a point is in the image bool SpiderScan::pixelInImage(const Vector2<int>& pixel) const { return (pixel.x >= 0 && pixel.y >= 0 && (unsigned int)pixel.x<theImage.cameraInfo.resolutionWidth && (unsigned int)pixel.y<theImage.cameraInfo.resolutionHeight); }//end pixelInImage //check wether a point lies at the images border bool SpiderScan::pixelAtImageBorder(const Vector2<int>& pixel, int borderWidth) const { return (pixel.x < borderWidth || pixel.y < borderWidth || (unsigned int)pixel.x>=theImage.cameraInfo.resolutionWidth-borderWidth || (unsigned int)pixel.y>=theImage.cameraInfo.resolutionHeight-borderWidth); }//end pixelAtImageBorder <commit_msg>bugfix: don't scan wrong color<commit_after>/** * @file Tools/ImageProcessing/SpiderScan.cpp * * Utility class which performs a SpiderScan algorithm for blob region scanning * */ #include "SpiderScan.h" #include <Tools/Debug/DebugImageDrawings.h> #include "Tools/Debug/DebugModify.h" #include "Tools/Debug/DebugRequest.h" SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier) : theImage(theImage), theColorClassifier(theColorClassifier) { searchColors = vector<ColorClasses::Color>(1, ColorClasses::numOfColors); borderColors = vector<ColorClasses::Color>(1, ColorClasses::green); init(); } SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier, ColorClasses::Color searchColor) : theImage(theImage), theColorClassifier(theColorClassifier) { searchColors = vector<ColorClasses::Color>(1, searchColor); borderColors = vector<ColorClasses::Color>(1, ColorClasses::numOfColors); init(); } SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier, vector<ColorClasses::Color>& searchColors) : theImage(theImage), theColorClassifier(theColorClassifier), searchColors(searchColors) { borderColors = vector<ColorClasses::Color>(1, ColorClasses::numOfColors); init(); } SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier, ColorClasses::Color searchColor, ColorClasses::Color borderColor) : theImage(theImage), theColorClassifier(theColorClassifier) { searchColors = vector<ColorClasses::Color>(1, searchColor); borderColors = vector<ColorClasses::Color>(1, borderColor); init(); } SpiderScan::SpiderScan(const Image& theImage, const ColorClassifier& theColorClassifier, vector<ColorClasses::Color>& searchColors, vector<ColorClasses::Color>& borderColors) : theImage(theImage), theColorClassifier(theColorClassifier), searchColors(searchColors), borderColors(borderColors) { init(); } bool SpiderScan::isBorderColor(ColorClasses::Color color) const { for(unsigned int i = 0; i < borderColors.size(); i++) { if(color == borderColors[i]) { return true; } } return false; }//end isBorderColor bool SpiderScan::isSearchColor(ColorClasses::Color color) const { for(unsigned int i = 0; i < searchColors.size(); i++) { if(color == searchColors[i]) { return true; } } return false; }//end isSearchColor void SpiderScan::setMaxBeamLength(unsigned int length) { max_length_of_beam = length; } void SpiderScan::setCurrentColorSimThreshold(double threshold) { currentColorSimThreshold = threshold; } void SpiderScan::setMaxColorPointsToSkip(unsigned int maxToSkip) { maxColorPointsToSkip = maxToSkip; } void SpiderScan::setMaxNumberOfScans(unsigned int maxScans) { maxNumberOfScans = maxScans; } void SpiderScan::init() { drawScanLines = false; max_length_of_beam = 30; //maximum length of the scan line currentColorSimThreshold = 8; //... maxColorPointsToSkip = 12; // maximum number of non search color ... maxNumberOfScans = 15; //maximum number of scanlines ... } void SpiderScan::setDrawScanLines(bool draw) { drawScanLines = draw; } void SpiderScan::scan(const Vector2<int>& start, PointList<20>& goodPoints, PointList<20>& badPoints) { Scans scans; //a list of scans to perform //add the standard scan lines scans.add(start, Vector2<int>( 0,-1));// down scans.add(start, Vector2<int>(-1,-1));// to the lower left scans.add(start, Vector2<int>(-1, 0));// to the left scans.add(start, Vector2<int>(-1, 1));// to the upper left scans.add(start, Vector2<int>( 0, 1));// up scans.add(start, Vector2<int>( 1, 1));// to the upper right scans.add(start, Vector2<int>( 1, 0));// to the right scans.add(start, Vector2<int>( 1,-1));// to the lower right scan(goodPoints, badPoints, scans); } void SpiderScan::scan(PointList<20>& goodPoints, PointList<20>& badPoints, Scans scans) { //remember the number of performed scans int numberOfScans = 0; while(scans.number > 0 && numberOfScans < maxNumberOfScans) //while there are scans to perform (but not too much) { // ... numberOfScans++; //Vector2<int>& direction = scans.direction[0]; //get the direction of the scan line // Vector2<int> currentPoint(scans.start[0]); //and the starting point int badPointsBeforeScan = badPoints.length; //remember the number of bad points (to see if one was added after the scan) //perform the scan, see if it was successful if(scanLine(scans.start[0], scans.direction[0], maxColorPointsToSkip, goodPoints, badPoints)) { if(badPoints.length > badPointsBeforeScan) //if a bad point was found { Vector2<int>& badPoint = badPoints[badPoints.length-1]; //get this point //if the pixel lies at the image border and was not the result of a scan along that border if(pixelAtImageBorder(badPoint, 2) && !isBorderScan(scans.start[0], scans.direction[0], 2)) { if(badPoint.x <= 1 || (unsigned int)badPoint.x >= theImage.cameraInfo.resolutionWidth-2) { //... its not reliable and we should scan along the imageborder to find the real border point scans.add(badPoint, Vector2<int>(0, 1)); scans.add(badPoint, Vector2<int>(0, -1)); } //same for the vertical borders else if(badPoint.y <= 1 || (unsigned int)badPoint.y >= theImage.cameraInfo.resolutionHeight-2) { scans.add(badPoint, Vector2<int>( 1, 0)); scans.add(badPoint, Vector2<int>(-1, 0)); } badPoints.remove(badPoints.length-1); //kick the unreliable Pixel }//end if pixelAtImageBorder }//end if BadPointFound }//end if borderPointFound scans.remove(0); //scan done, remove it from the list }//end while scans left; }//end spiderSearch bool SpiderScan::scanLine(const Vector2<int>& start, const Vector2<int>& direction, int maxColorPointsToSkip, PointList<20>& goodPoints, PointList<20>& badPoints) const { Vector2<int> currentPoint(start); //set the starting point int searchColorPointsSkipIndex = 0; //reset number of skipped pixels Vector2<int> borderPoint; // to remember the border point ... bool borderPointFound = false; //if one was found bool borderPixelFound = false; //and if it was followed by a border pixel Vector2<int> lastSearchColorPoint(-1,-1); //expand in the selected direction for(unsigned int j = 0; j < max_length_of_beam; j++) { // check the current point if( searchColorPointsSkipIndex > maxColorPointsToSkip || // point outside the image !pixelInImage(currentPoint)) { break; }//end if //////////////////////////////// // process the current point //////////////////////////////// Pixel pixel = theImage.get(currentPoint.x,currentPoint.y); ColorClasses::Color currentPixelColor = theColorClassifier.getColorClass(pixel); // bool hasColor = (currentPixelColor == searchColor) || (searchColor == ColorClasses::numOfColors && currentPixelColor != borderColor); bool hasColor = isSearchColor(currentPixelColor) || (searchColors[0] == ColorClasses::numOfColors && !isBorderColor(currentPixelColor)); // HACK: taken from GT07 // TODO: make it more general by taking the criteria out of the method if(!hasColor) { if(lastSearchColorPoint.x != -1 && lastSearchColorPoint.y != -1) { //hasColor = currentOrangeSim > currentColorSimThreshold; Pixel pixelLast = theImage.get(lastSearchColorPoint.x,lastSearchColorPoint.y); double yDiff = pixel.y - pixelLast.y; double uDiff = pixel.u - pixelLast.u; double vDiff = pixel.v - pixelLast.v; double useY = 0.0; // MODIFY("ImageProcessor:Detector:currentColorSimThreshold", currentColorSimThreshold); // MODIFY("ImageProcessor:Detector:useY", useY); // hasColor = // ((currentPixelColor == ColorClasses::none) || (searchColor == ColorClasses::numOfColors && currentPixelColor != borderColor)) && // searchColorPointsSkipIndex == 0 && // sqrt( useY*Math::sqr(yDiff) + Math::sqr(uDiff) + Math::sqr(vDiff) ) < currentColorSimThreshold; hasColor = (currentPixelColor == ColorClasses::none || (searchColors[0] == ColorClasses::numOfColors && !isBorderColor(currentPixelColor))) && searchColorPointsSkipIndex == 0 && sqrt( useY*Math::sqr(yDiff) + Math::sqr(uDiff) + Math::sqr(vDiff) ) < currentColorSimThreshold; }//end if } else { lastSearchColorPoint = currentPoint; } if(hasColor) { borderPoint = currentPoint; searchColorPointsSkipIndex = 0; borderPointFound = true; borderPixelFound = false; } else { // if // ( // currentPixelColor == borderColor || // (borderColor == ColorClasses::numOfColors && currentPixelColor != searchColor) //// (currentPixelColor != searchColor && borderColor == ColorClasses::numOfColors) || //// (searchColor == ColorClasses::numOfColors && currentPixelColor != borderColor) // ) if ( isBorderColor(currentPixelColor) || (borderColors[0] == ColorClasses::numOfColors && !isSearchColor(currentPixelColor) ) ) { borderPixelFound = true; } searchColorPointsSkipIndex++; }//end if if(drawScanLines) { if(hasColor) { if(currentPixelColor == ColorClasses::none) { POINT_PX(ColorClasses::orange, (unsigned int)(currentPoint.x), (unsigned int)(currentPoint.y)); } else { POINT_PX(ColorClasses::green, (unsigned int)(currentPoint.x), (unsigned int)(currentPoint.y)); } } else { POINT_PX(ColorClasses::red, (unsigned int)(currentPoint.x), (unsigned int)(currentPoint.y)); } } currentPoint += direction; }//end for if(borderPointFound) //if a point was found ... { //that point was followed by a border pixel, does not lie at the images border or is the result of a scan along that border ... if(borderPixelFound && (!pixelAtImageBorder(borderPoint, 2) || isBorderScan(borderPoint, direction, 2))) { goodPoints.add(borderPoint); //it's good point } else { badPoints.add(borderPoint); //otherwise it's a bad one } }//end if return borderPointFound; //return if a borderpoint was found }//end scanLine //check wether a scan line goes along an image border bool SpiderScan::isBorderScan(const Vector2<int>& point, const Vector2<int>& direction, int borderWidth) const { return ((point.x<borderWidth || (unsigned int)point.x>=theImage.cameraInfo.resolutionWidth-borderWidth) && direction.x==0) || ((point.y<borderWidth || (unsigned int)point.y>=theImage.cameraInfo.resolutionHeight-borderWidth) && direction.y==0); }//end isBorderScan //check wether a point is in the image bool SpiderScan::pixelInImage(const Vector2<int>& pixel) const { return (pixel.x >= 0 && pixel.y >= 0 && (unsigned int)pixel.x<theImage.cameraInfo.resolutionWidth && (unsigned int)pixel.y<theImage.cameraInfo.resolutionHeight); }//end pixelInImage //check wether a point lies at the images border bool SpiderScan::pixelAtImageBorder(const Vector2<int>& pixel, int borderWidth) const { return (pixel.x < borderWidth || pixel.y < borderWidth || (unsigned int)pixel.x>=theImage.cameraInfo.resolutionWidth-borderWidth || (unsigned int)pixel.y>=theImage.cameraInfo.resolutionHeight-borderWidth); }//end pixelAtImageBorder <|endoftext|>
<commit_before>#include "SkImageRef.h" #include "SkBitmap.h" #include "SkFlattenable.h" #include "SkImageDecoder.h" #include "SkStream.h" #include "SkTemplates.h" #include "SkThread.h" // can't be static, as SkImageRef_Pool needs to see it SkMutex gImageRefMutex; /////////////////////////////////////////////////////////////////////////////// SkImageRef::SkImageRef(SkStream* stream, SkBitmap::Config config, int sampleSize) : SkPixelRef(&gImageRefMutex), fErrorInDecoding(false) { SkASSERT(stream); stream->ref(); fStream = stream; fConfig = config; fSampleSize = sampleSize; fPrev = fNext = NULL; fFactory = NULL; #ifdef DUMP_IMAGEREF_LIFECYCLE SkDebugf("add ImageRef %p [%d] data=%d\n", this, config, (int)stream->getLength()); #endif } SkImageRef::~SkImageRef() { SkASSERT(&gImageRefMutex == this->mutex()); #ifdef DUMP_IMAGEREF_LIFECYCLE SkDebugf("delete ImageRef %p [%d] data=%d\n", this, fConfig, (int)fStream->getLength()); #endif fStream->unref(); fFactory->safeUnref(); } bool SkImageRef::getInfo(SkBitmap* bitmap) { SkAutoMutexAcquire ac(gImageRefMutex); if (!this->prepareBitmap(SkImageDecoder::kDecodeBounds_Mode)) { return false; } SkASSERT(SkBitmap::kNo_Config != fBitmap.config()); if (bitmap) { bitmap->setConfig(fBitmap.config(), fBitmap.width(), fBitmap.height()); } return true; } SkImageDecoderFactory* SkImageRef::setDecoderFactory( SkImageDecoderFactory* fact) { SkRefCnt_SafeAssign(fFactory, fact); return fact; } /////////////////////////////////////////////////////////////////////////////// bool SkImageRef::onDecode(SkImageDecoder* codec, SkStream* stream, SkBitmap* bitmap, SkBitmap::Config config, SkImageDecoder::Mode mode) { return codec->decode(stream, bitmap, config, mode); } bool SkImageRef::prepareBitmap(SkImageDecoder::Mode mode) { SkASSERT(&gImageRefMutex == this->mutex()); if (fErrorInDecoding) { return false; } /* As soon as we really know our config, we record it, so that on subsequent calls to the codec, we are sure we will always get the same result. */ if (SkBitmap::kNo_Config != fBitmap.config()) { fConfig = fBitmap.config(); } if (NULL != fBitmap.getPixels() || (SkBitmap::kNo_Config != fBitmap.config() && SkImageDecoder::kDecodeBounds_Mode == mode)) { return true; } SkASSERT(fBitmap.getPixels() == NULL); fStream->rewind(); SkImageDecoder* codec; if (fFactory) { codec = fFactory->newDecoder(fStream); } else { codec = SkImageDecoder::Factory(fStream); } if (codec) { SkAutoTDelete<SkImageDecoder> ad(codec); codec->setSampleSize(fSampleSize); if (this->onDecode(codec, fStream, &fBitmap, fConfig, mode)) { return true; } } #ifdef DUMP_IMAGEREF_LIFECYCLE if (NULL == codec) { SkDebugf("--- ImageRef: <%s> failed to find codec\n", this->getURI()); } else { SkDebugf("--- ImageRef: <%s> failed in codec for %d mode\n", this->getURI(), mode); } #endif fErrorInDecoding = true; fBitmap.reset(); return false; } void* SkImageRef::onLockPixels(SkColorTable** ct) { SkASSERT(&gImageRefMutex == this->mutex()); if (NULL == fBitmap.getPixels()) { (void)this->prepareBitmap(SkImageDecoder::kDecodePixels_Mode); } if (ct) { *ct = fBitmap.getColorTable(); } return fBitmap.getPixels(); } void SkImageRef::onUnlockPixels() { // we're already have the mutex locked SkASSERT(&gImageRefMutex == this->mutex()); } size_t SkImageRef::ramUsed() const { size_t size = 0; if (fBitmap.getPixels()) { size = fBitmap.getSize(); if (fBitmap.getColorTable()) { size += fBitmap.getColorTable()->count() * sizeof(SkPMColor); } } return size; } /////////////////////////////////////////////////////////////////////////////// SkImageRef::SkImageRef(SkFlattenableReadBuffer& buffer) : INHERITED(buffer, &gImageRefMutex), fErrorInDecoding(false) { fConfig = (SkBitmap::Config)buffer.readU8(); fSampleSize = buffer.readU8(); size_t length = buffer.readU32(); fStream = SkNEW_ARGS(SkMemoryStream, (length)); buffer.read((void*)fStream->getMemoryBase(), length); fPrev = fNext = NULL; } void SkImageRef::flatten(SkFlattenableWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.write8(fConfig); buffer.write8(fSampleSize); size_t length = fStream->getLength(); buffer.write32(length); fStream->rewind(); buffer.readFromStream(fStream, length); } <commit_msg>Automated import from //branches/donutburger/...@141342,141342<commit_after>#include "SkImageRef.h" #include "SkBitmap.h" #include "SkFlattenable.h" #include "SkImageDecoder.h" #include "SkStream.h" #include "SkTemplates.h" #include "SkThread.h" // can't be static, as SkImageRef_Pool needs to see it SkMutex gImageRefMutex; /////////////////////////////////////////////////////////////////////////////// SkImageRef::SkImageRef(SkStream* stream, SkBitmap::Config config, int sampleSize) : SkPixelRef(&gImageRefMutex), fErrorInDecoding(false) { SkASSERT(stream); stream->ref(); fStream = stream; fConfig = config; fSampleSize = sampleSize; fPrev = fNext = NULL; fFactory = NULL; #ifdef DUMP_IMAGEREF_LIFECYCLE SkDebugf("add ImageRef %p [%d] data=%d\n", this, config, (int)stream->getLength()); #endif } SkImageRef::~SkImageRef() { SkASSERT(&gImageRefMutex == this->mutex()); #ifdef DUMP_IMAGEREF_LIFECYCLE SkDebugf("delete ImageRef %p [%d] data=%d\n", this, fConfig, (int)fStream->getLength()); #endif fStream->unref(); fFactory->safeUnref(); } bool SkImageRef::getInfo(SkBitmap* bitmap) { SkAutoMutexAcquire ac(gImageRefMutex); if (!this->prepareBitmap(SkImageDecoder::kDecodeBounds_Mode)) { return false; } SkASSERT(SkBitmap::kNo_Config != fBitmap.config()); if (bitmap) { bitmap->setConfig(fBitmap.config(), fBitmap.width(), fBitmap.height()); } return true; } SkImageDecoderFactory* SkImageRef::setDecoderFactory( SkImageDecoderFactory* fact) { SkRefCnt_SafeAssign(fFactory, fact); return fact; } /////////////////////////////////////////////////////////////////////////////// bool SkImageRef::onDecode(SkImageDecoder* codec, SkStream* stream, SkBitmap* bitmap, SkBitmap::Config config, SkImageDecoder::Mode mode) { return codec->decode(stream, bitmap, config, mode); } bool SkImageRef::prepareBitmap(SkImageDecoder::Mode mode) { SkASSERT(&gImageRefMutex == this->mutex()); if (fErrorInDecoding) { return false; } /* As soon as we really know our config, we record it, so that on subsequent calls to the codec, we are sure we will always get the same result. */ if (SkBitmap::kNo_Config != fBitmap.config()) { fConfig = fBitmap.config(); } if (NULL != fBitmap.getPixels() || (SkBitmap::kNo_Config != fBitmap.config() && SkImageDecoder::kDecodeBounds_Mode == mode)) { return true; } SkASSERT(fBitmap.getPixels() == NULL); fStream->rewind(); SkImageDecoder* codec; if (fFactory) { codec = fFactory->newDecoder(fStream); } else { codec = SkImageDecoder::Factory(fStream); } if (codec) { SkAutoTDelete<SkImageDecoder> ad(codec); codec->setSampleSize(fSampleSize); if (this->onDecode(codec, fStream, &fBitmap, fConfig, mode)) { return true; } } #ifdef DUMP_IMAGEREF_LIFECYCLE if (NULL == codec) { SkDebugf("--- ImageRef: <%s> failed to find codec\n", this->getURI()); } else { SkDebugf("--- ImageRef: <%s> failed in codec for %d mode\n", this->getURI(), mode); } #endif fErrorInDecoding = true; fBitmap.reset(); return false; } void* SkImageRef::onLockPixels(SkColorTable** ct) { SkASSERT(&gImageRefMutex == this->mutex()); if (NULL == fBitmap.getPixels()) { (void)this->prepareBitmap(SkImageDecoder::kDecodePixels_Mode); } if (ct) { *ct = fBitmap.getColorTable(); } return fBitmap.getPixels(); } void SkImageRef::onUnlockPixels() { // we're already have the mutex locked SkASSERT(&gImageRefMutex == this->mutex()); } size_t SkImageRef::ramUsed() const { size_t size = 0; if (fBitmap.getPixels()) { size = fBitmap.getSize(); if (fBitmap.getColorTable()) { size += fBitmap.getColorTable()->count() * sizeof(SkPMColor); } } return size; } /////////////////////////////////////////////////////////////////////////////// SkImageRef::SkImageRef(SkFlattenableReadBuffer& buffer) : INHERITED(buffer, &gImageRefMutex), fErrorInDecoding(false) { fConfig = (SkBitmap::Config)buffer.readU8(); fSampleSize = buffer.readU8(); size_t length = buffer.readU32(); fStream = SkNEW_ARGS(SkMemoryStream, (length)); buffer.read((void*)fStream->getMemoryBase(), length); fPrev = fNext = NULL; fFactory = NULL; } void SkImageRef::flatten(SkFlattenableWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.write8(fConfig); buffer.write8(fSampleSize); size_t length = fStream->getLength(); buffer.write32(length); fStream->rewind(); buffer.readFromStream(fStream, length); } <|endoftext|>
<commit_before>556ac6e1-ad5c-11e7-9a9e-ac87a332f658<commit_msg>add file<commit_after>55e32861-ad5c-11e7-973b-ac87a332f658<|endoftext|>
<commit_before>9bcfef85-2e4f-11e5-bd5d-28cfe91dbc4b<commit_msg>9bd73c28-2e4f-11e5-a61f-28cfe91dbc4b<commit_after>9bd73c28-2e4f-11e5-a61f-28cfe91dbc4b<|endoftext|>
<commit_before>/* * Copyright (c)2015 - 2019 Oasis LMF Limited * 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 original author of this software 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. */ /* Index the summarycalc output Author: Ben Matharu email: ben.matharu@oasislmf.org */ #include <stdio.h> #include <string> #if defined(_MSC_VER) #include "../include/dirent.h" #else #include <dirent.h> #endif #include "../include/oasis.h" #include <vector> #include <string> #include <map> bool operator<(const summary_period &lhs, const summary_period &rhs) { if (lhs.summary_id != rhs.summary_id) { return lhs.summary_id < rhs.summary_id; } else if (lhs.period_no != rhs.period_no) { return lhs.period_no < rhs.period_no; } else { return lhs.fileindex < rhs.fileindex; } } namespace summaryindex { void indexevents(const std::string& fullfilename, std::map<summary_period, std::vector<long long>> &summaryfileperiod_to_offset, int file_id, const std::map<int, std::vector<int>> &eventtoperiods) { FILE* fin = fopen(fullfilename.c_str(), "rb"); if (fin == NULL) { fprintf(stderr, "%s: cannot open %s\n", __func__, fullfilename.c_str()); exit(EXIT_FAILURE); } long long offset = 0; int summarycalcstream_type = 0; size_t i = fread(&summarycalcstream_type, sizeof(summarycalcstream_type), 1, fin); if (i != 0) offset += sizeof(summarycalcstream_type); int stream_type = summarycalcstream_type & summarycalc_id; if (stream_type != summarycalc_id) { fprintf(stderr, "%s: Not a summarycalc stream type %d\n", __func__, stream_type); exit(-1); } stream_type = streamno_mask & summarycalcstream_type; int samplesize; i = fread(&samplesize, sizeof(samplesize), 1, fin); if (i != 0) offset += sizeof(samplesize); int summary_set = 0; if (i != 0) i = fread(&summary_set, sizeof(summary_set), 1, fin); if (i != 0) offset += sizeof(summary_set); summarySampleslevelHeader sh; int last_event_id = -1; while (i != 0) { i = fread(&sh, sizeof(sh), 1, fin); if (i != 0) { summary_period k; k.summary_id = sh.summary_id; k.fileindex = file_id; for (auto period : eventtoperiods.at(sh.event_id)) { k.period_no = period; summaryfileperiod_to_offset[k].push_back(offset); } offset += sizeof(sh); } while (i != 0) { sampleslevelRec sr; i = fread(&sr, sizeof(sr), 1, fin); if (i != 0) offset += sizeof(sr); if (i == 0) break; if (sr.sidx == 0) break; } } fclose(fin); } void indexevents(const std::string &binfilename, std::string &idxfilename, std::map<summary_period, std::vector<long long>> &summaryfileperiod_to_offset, int file_id, const std::map<int, std::vector<int>> &eventtoperiods) { FILE * fidx = fopen(idxfilename.c_str(), "r"); if (fidx == nullptr) { fprintf(stderr, "FATAL: Cannot open %s\n", idxfilename.c_str()); exit(EXIT_FAILURE); } FILE * fbin = fopen(binfilename.c_str(), "r"); if (fbin == nullptr) { fprintf(stderr, "FATAL: Cannot open %s\n", binfilename.c_str()); exit(EXIT_FAILURE); } char line[4096]; summary_period k; k.fileindex = file_id; while (fgets(line, sizeof(line), fidx) != 0) { long long offset; int ret = sscanf(line, "%d,%lld", &k.summary_id, &offset); if (ret != 2) { fprintf(stderr, "FATAL: Invalid data in file %s:\n%s", idxfilename.c_str(), line); exit(EXIT_FAILURE); } // Get period numbers from event IDs flseek(fbin, offset, SEEK_SET); summarySampleslevelHeader sh; size_t i = fread(&sh, sizeof(sh), 1, fbin); std::map<int, std::vector<int>>::const_iterator iter = eventtoperiods.find(sh.event_id); if (iter == eventtoperiods.end()) continue; // Event not found so don't process it for (auto period : iter->second) { k.period_no = period; summaryfileperiod_to_offset[k].push_back(offset); } } fclose(fidx); fclose(fbin); } void doit(const std::string& subfolder, const std::map<int, std::vector<int>> &eventtoperiods) { std::string path = "work/" + subfolder; if (path.substr(path.length() - 1, 1) != "/") { path = path + "/"; } std::vector<std::string> files; std::map<summary_period, std::vector<long long>> summaryfileperiod_to_offset; DIR* dir; struct dirent* ent; int file_index = 0; if ((dir = opendir(path.c_str())) != NULL) { while ((ent = readdir(dir)) != NULL) { std::string s = ent->d_name; if (s.length() > 4 && s.substr(s.length() - 4, 4) == ".bin") { std::string s2 = path + ent->d_name; files.push_back(s); std::string s3 = s2; s3.erase(s2.length() - 4); s3 += ".idx"; FILE * fidx = fopen(s3.c_str(), "r"); if (fidx == nullptr) { indexevents(s2, summaryfileperiod_to_offset, file_index, eventtoperiods); } else { fclose(fidx); indexevents(s2, s3, summaryfileperiod_to_offset, file_index, eventtoperiods); } file_index++; } } } else { fprintf(stderr, "Unable to open directory %s\n", path.c_str()); exit(-1); } std::string filename = path + "filelist.idx"; FILE* fout = fopen(filename.c_str(), "wb"); if (fout == NULL) { fprintf(stderr, "%s: cannot open %s\n", __func__, filename.c_str()); exit(EXIT_FAILURE); } auto iter = files.begin(); while (iter != files.end()) { fprintf(fout, "%s\n", iter->c_str()); iter++; } fclose(fout); int max_summary_id = 0; filename = path + "summaries.idx"; fout = fopen(filename.c_str(), "wb"); if (fout == NULL) { fprintf(stderr, "%s: cannot open %s\n", __func__, filename.c_str()); exit(EXIT_FAILURE); } auto s_iter = summaryfileperiod_to_offset.begin(); while (s_iter != summaryfileperiod_to_offset.end()) { if (s_iter->first.summary_id > max_summary_id) max_summary_id = s_iter->first.summary_id; auto v_iter = s_iter->second.begin(); while (v_iter != s_iter->second.end()) { fprintf(fout, "%d, %d, %d, %lld\n", s_iter->first.summary_id, s_iter->first.fileindex, s_iter->first.period_no, *v_iter); v_iter++; } s_iter++; } fclose(fout); filename = path + "max_summary_id.idx"; fout = fopen(filename.c_str(), "wb"); if (fout == NULL) { fprintf(stderr, "%s: cannot open %s\n", __func__, filename.c_str()); exit(EXIT_FAILURE); } fprintf(fout, "%d", max_summary_id); fclose(fout); } }; <commit_msg>Ignore events that do not exist in occurrence file when creating summary indexes in aalcalc (#284)<commit_after>/* * Copyright (c)2015 - 2019 Oasis LMF Limited * 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 original author of this software 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. */ /* Index the summarycalc output Author: Ben Matharu email: ben.matharu@oasislmf.org */ #include <stdio.h> #include <string> #if defined(_MSC_VER) #include "../include/dirent.h" #else #include <dirent.h> #endif #include "../include/oasis.h" #include <vector> #include <string> #include <map> bool operator<(const summary_period &lhs, const summary_period &rhs) { if (lhs.summary_id != rhs.summary_id) { return lhs.summary_id < rhs.summary_id; } else if (lhs.period_no != rhs.period_no) { return lhs.period_no < rhs.period_no; } else { return lhs.fileindex < rhs.fileindex; } } namespace summaryindex { void indexevents(const std::string& fullfilename, std::map<summary_period, std::vector<long long>> &summaryfileperiod_to_offset, int file_id, const std::map<int, std::vector<int>> &eventtoperiods) { FILE* fin = fopen(fullfilename.c_str(), "rb"); if (fin == NULL) { fprintf(stderr, "%s: cannot open %s\n", __func__, fullfilename.c_str()); exit(EXIT_FAILURE); } long long offset = 0; int summarycalcstream_type = 0; size_t i = fread(&summarycalcstream_type, sizeof(summarycalcstream_type), 1, fin); if (i != 0) offset += sizeof(summarycalcstream_type); int stream_type = summarycalcstream_type & summarycalc_id; if (stream_type != summarycalc_id) { fprintf(stderr, "%s: Not a summarycalc stream type %d\n", __func__, stream_type); exit(-1); } stream_type = streamno_mask & summarycalcstream_type; int samplesize; i = fread(&samplesize, sizeof(samplesize), 1, fin); if (i != 0) offset += sizeof(samplesize); int summary_set = 0; if (i != 0) i = fread(&summary_set, sizeof(summary_set), 1, fin); if (i != 0) offset += sizeof(summary_set); summarySampleslevelHeader sh; int last_event_id = -1; while (i != 0) { i = fread(&sh, sizeof(sh), 1, fin); if (i != 0) { auto iter = eventtoperiods.find(sh.event_id); if (iter != eventtoperiods.end()) { summary_period k; k.summary_id = sh.summary_id; k.fileindex = file_id; for (auto period : iter->second) { k.period_no = period; summaryfileperiod_to_offset[k].push_back(offset); } } offset += sizeof(sh); } while (i != 0) { sampleslevelRec sr; i = fread(&sr, sizeof(sr), 1, fin); if (i != 0) offset += sizeof(sr); if (i == 0) break; if (sr.sidx == 0) break; } } fclose(fin); } void indexevents(const std::string &binfilename, std::string &idxfilename, std::map<summary_period, std::vector<long long>> &summaryfileperiod_to_offset, int file_id, const std::map<int, std::vector<int>> &eventtoperiods) { FILE * fidx = fopen(idxfilename.c_str(), "r"); if (fidx == nullptr) { fprintf(stderr, "FATAL: Cannot open %s\n", idxfilename.c_str()); exit(EXIT_FAILURE); } FILE * fbin = fopen(binfilename.c_str(), "r"); if (fbin == nullptr) { fprintf(stderr, "FATAL: Cannot open %s\n", binfilename.c_str()); exit(EXIT_FAILURE); } char line[4096]; summary_period k; k.fileindex = file_id; while (fgets(line, sizeof(line), fidx) != 0) { long long offset; int ret = sscanf(line, "%d,%lld", &k.summary_id, &offset); if (ret != 2) { fprintf(stderr, "FATAL: Invalid data in file %s:\n%s", idxfilename.c_str(), line); exit(EXIT_FAILURE); } // Get period numbers from event IDs flseek(fbin, offset, SEEK_SET); summarySampleslevelHeader sh; size_t i = fread(&sh, sizeof(sh), 1, fbin); std::map<int, std::vector<int>>::const_iterator iter = eventtoperiods.find(sh.event_id); if (iter == eventtoperiods.end()) continue; // Event not found so don't process it for (auto period : iter->second) { k.period_no = period; summaryfileperiod_to_offset[k].push_back(offset); } } fclose(fidx); fclose(fbin); } void doit(const std::string& subfolder, const std::map<int, std::vector<int>> &eventtoperiods) { std::string path = "work/" + subfolder; if (path.substr(path.length() - 1, 1) != "/") { path = path + "/"; } std::vector<std::string> files; std::map<summary_period, std::vector<long long>> summaryfileperiod_to_offset; DIR* dir; struct dirent* ent; int file_index = 0; if ((dir = opendir(path.c_str())) != NULL) { while ((ent = readdir(dir)) != NULL) { std::string s = ent->d_name; if (s.length() > 4 && s.substr(s.length() - 4, 4) == ".bin") { std::string s2 = path + ent->d_name; files.push_back(s); std::string s3 = s2; s3.erase(s2.length() - 4); s3 += ".idx"; FILE * fidx = fopen(s3.c_str(), "r"); if (fidx == nullptr) { indexevents(s2, summaryfileperiod_to_offset, file_index, eventtoperiods); } else { fclose(fidx); indexevents(s2, s3, summaryfileperiod_to_offset, file_index, eventtoperiods); } file_index++; } } } else { fprintf(stderr, "Unable to open directory %s\n", path.c_str()); exit(-1); } std::string filename = path + "filelist.idx"; FILE* fout = fopen(filename.c_str(), "wb"); if (fout == NULL) { fprintf(stderr, "%s: cannot open %s\n", __func__, filename.c_str()); exit(EXIT_FAILURE); } auto iter = files.begin(); while (iter != files.end()) { fprintf(fout, "%s\n", iter->c_str()); iter++; } fclose(fout); int max_summary_id = 0; filename = path + "summaries.idx"; fout = fopen(filename.c_str(), "wb"); if (fout == NULL) { fprintf(stderr, "%s: cannot open %s\n", __func__, filename.c_str()); exit(EXIT_FAILURE); } auto s_iter = summaryfileperiod_to_offset.begin(); while (s_iter != summaryfileperiod_to_offset.end()) { if (s_iter->first.summary_id > max_summary_id) max_summary_id = s_iter->first.summary_id; auto v_iter = s_iter->second.begin(); while (v_iter != s_iter->second.end()) { fprintf(fout, "%d, %d, %d, %lld\n", s_iter->first.summary_id, s_iter->first.fileindex, s_iter->first.period_no, *v_iter); v_iter++; } s_iter++; } fclose(fout); filename = path + "max_summary_id.idx"; fout = fopen(filename.c_str(), "wb"); if (fout == NULL) { fprintf(stderr, "%s: cannot open %s\n", __func__, filename.c_str()); exit(EXIT_FAILURE); } fprintf(fout, "%d", max_summary_id); fclose(fout); } }; <|endoftext|>
<commit_before>e96e3278-313a-11e5-8d9b-3c15c2e10482<commit_msg>e9772b75-313a-11e5-9fe4-3c15c2e10482<commit_after>e9772b75-313a-11e5-9fe4-3c15c2e10482<|endoftext|>
<commit_before> #include "UniformBuffer.hh" #include "Shader.hh" #include "Utils/OpenGL.hh" #include "glm/gtc/type_ptr.hpp" #include <memory.h> #include <list> #include <cstdint> namespace OpenGLTools { UniformBuffer::UniformBuffer(GLuint bindingPoint) : _bindingPoint(bindingPoint), _bufferId(0), _dataSize(0), _buffer(NULL) { } UniformBuffer::~UniformBuffer(void) { glDeleteBuffers(1, &_bufferId); if (_buffer) delete[] _buffer; } void UniformBuffer::init(std::shared_ptr<Shader> referent, std::string const &blockName, std::uint32_t bufferSize) { glGenBuffers(1, &_bufferId); glBindBufferBase(GL_UNIFORM_BUFFER, _bindingPoint, _bufferId); GLint blockIdx = glGetUniformBlockIndex(referent->getId(), blockName.c_str()); // find the total size to check if the size passed as a parameter is correct glGetActiveUniformBlockiv(referent->getId(), blockIdx, GL_UNIFORM_BLOCK_DATA_SIZE, (GLint*)&_dataSize); _buffer = new char[glm::max(_dataSize, bufferSize)]; } void UniformBuffer::setBufferData(size_t size, const char *data) { assert(size <= _dataSize && "Size to big for this uniform buffer"); memcpy(_buffer, data, size); } void UniformBuffer::init(std::shared_ptr<Shader> referent, std::string const &blockName, std::string const vars[]) { GLint blockIdx, varNbr; GLint *varsInfos; glGenBuffers(1, &_bufferId); glBindBufferBase(GL_UNIFORM_BUFFER, _bindingPoint, _bufferId); blockIdx = glGetUniformBlockIndex(referent->getId(), blockName.c_str()); // find the total size to allocate the buffer glGetActiveUniformBlockiv(referent->getId(), blockIdx, GL_UNIFORM_BLOCK_DATA_SIZE, (GLint*)&_dataSize); _buffer = new char[_dataSize]; // get the number of uniforms glGetActiveUniformBlockiv(referent->getId(), blockIdx, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &varNbr); assert(varNbr > 0 && "glGetActiveUniformBlockid Error"); // we store the uniforms informations in this table with this layout: // Indices - Types - Offset varsInfos = new GLint[varNbr * 3]; glGetActiveUniformBlockiv(referent->getId(), blockIdx, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, varsInfos); glGetActiveUniformsiv(referent->getId(), varNbr, (GLuint*)varsInfos, GL_UNIFORM_TYPE, varsInfos + varNbr); glGetActiveUniformsiv(referent->getId(), varNbr, (GLuint*)varsInfos, GL_UNIFORM_OFFSET, varsInfos + 2 * varNbr); // sort the vars by offset to make them correspond with the order of the names std::list<std::pair<GLint, GLint> > sorted; std::list<std::pair<GLint, GLint> >::iterator it; GLint curOffset; GLint i; // insertion sort for (i = 0; i < varNbr; ++i) { curOffset = varsInfos[varNbr * 2 + i]; it = sorted.begin(); while (it != sorted.end() && it->second < curOffset) ++it; sorted.insert(it, std::pair<GLint, GLint>(i, curOffset)); } // bind the name with the offset and type it = sorted.begin(); for (i = 0; it != sorted.end() && i < varNbr; ++i) { SUniformVars added; added.offset = varsInfos[varNbr * 2 + it->first]; added.type = varsInfos[varNbr + it->first]; _vars[vars[i]] = added; ++it; } delete[] varsInfos; } void UniformBuffer::setUniform(std::string const &name, int data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_INT); memcpy(_buffer + it->second.offset, &data, sizeof(int)); } void UniformBuffer::setUniform(std::string const &name, unsigned int data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_UNSIGNED_INT); memcpy(_buffer + it->second.offset, &data, sizeof(unsigned int)); } void UniformBuffer::setUniform(std::string const &name, float data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT); memcpy(_buffer + it->second.offset, &data, sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::vec2 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_VEC2); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 2 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::vec3 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_VEC3); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 3 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::vec4 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_VEC4); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 4 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::mat2 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_MAT2); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 2 * 2 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::mat3 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_MAT3); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 3 * 3 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::mat4 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_MAT4); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 4 * 4 * sizeof(float)); } void UniformBuffer::flushChanges() { // dirty fix for @cesar AMD gpu -> to fixe later // www.opengl.org/discussion_boards/archive/index.php/t-178601.html // www.opengl.org/discussion_boards/showthread.php/178326-Uniform-Buffer-Object-Performance?p=1240435#post1240435 glBindBufferBase(GL_UNIFORM_BUFFER, _bindingPoint, _bufferId); // !end glBindBuffer(GL_UNIFORM_BUFFER, _bufferId); glBufferData(GL_UNIFORM_BUFFER, _dataSize, _buffer, GL_DYNAMIC_DRAW); } GLuint UniformBuffer::getBindingPoint() const { return (_bindingPoint); } }<commit_msg>threads on bullet removed<commit_after> #include "UniformBuffer.hh" #include "Shader.hh" #include "Utils/OpenGL.hh" #include "glm/gtc/type_ptr.hpp" #include <memory.h> #include <list> #include <cstdint> namespace OpenGLTools { UniformBuffer::UniformBuffer(GLuint bindingPoint) : _bindingPoint(bindingPoint), _bufferId(0), _dataSize(0), _buffer(NULL) { } UniformBuffer::~UniformBuffer(void) { glDeleteBuffers(1, &_bufferId); if (_buffer) delete[] _buffer; } void UniformBuffer::init(std::shared_ptr<Shader> referent, std::string const &blockName, std::uint32_t bufferSize) { glGenBuffers(1, &_bufferId); glBindBufferBase(GL_UNIFORM_BUFFER, _bindingPoint, _bufferId); GLint blockIdx = glGetUniformBlockIndex(referent->getId(), blockName.c_str()); // find the total size to check if the size passed as a parameter is correct glGetActiveUniformBlockiv(referent->getId(), blockIdx, GL_UNIFORM_BLOCK_DATA_SIZE, (GLint*)&_dataSize); _dataSize = glm::max(_dataSize, bufferSize); _buffer = new char[_dataSize]; } void UniformBuffer::setBufferData(size_t size, const char *data) { assert(size <= _dataSize && "Size to big for this uniform buffer"); memcpy(_buffer, data, size); } void UniformBuffer::init(std::shared_ptr<Shader> referent, std::string const &blockName, std::string const vars[]) { GLint blockIdx, varNbr; GLint *varsInfos; glGenBuffers(1, &_bufferId); glBindBufferBase(GL_UNIFORM_BUFFER, _bindingPoint, _bufferId); blockIdx = glGetUniformBlockIndex(referent->getId(), blockName.c_str()); // find the total size to allocate the buffer glGetActiveUniformBlockiv(referent->getId(), blockIdx, GL_UNIFORM_BLOCK_DATA_SIZE, (GLint*)&_dataSize); _buffer = new char[_dataSize]; // get the number of uniforms glGetActiveUniformBlockiv(referent->getId(), blockIdx, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &varNbr); assert(varNbr > 0 && "glGetActiveUniformBlockid Error"); // we store the uniforms informations in this table with this layout: // Indices - Types - Offset varsInfos = new GLint[varNbr * 3]; glGetActiveUniformBlockiv(referent->getId(), blockIdx, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, varsInfos); glGetActiveUniformsiv(referent->getId(), varNbr, (GLuint*)varsInfos, GL_UNIFORM_TYPE, varsInfos + varNbr); glGetActiveUniformsiv(referent->getId(), varNbr, (GLuint*)varsInfos, GL_UNIFORM_OFFSET, varsInfos + 2 * varNbr); // sort the vars by offset to make them correspond with the order of the names std::list<std::pair<GLint, GLint> > sorted; std::list<std::pair<GLint, GLint> >::iterator it; GLint curOffset; GLint i; // insertion sort for (i = 0; i < varNbr; ++i) { curOffset = varsInfos[varNbr * 2 + i]; it = sorted.begin(); while (it != sorted.end() && it->second < curOffset) ++it; sorted.insert(it, std::pair<GLint, GLint>(i, curOffset)); } // bind the name with the offset and type it = sorted.begin(); for (i = 0; it != sorted.end() && i < varNbr; ++i) { SUniformVars added; added.offset = varsInfos[varNbr * 2 + it->first]; added.type = varsInfos[varNbr + it->first]; _vars[vars[i]] = added; ++it; } delete[] varsInfos; } void UniformBuffer::setUniform(std::string const &name, int data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_INT); memcpy(_buffer + it->second.offset, &data, sizeof(int)); } void UniformBuffer::setUniform(std::string const &name, unsigned int data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_UNSIGNED_INT); memcpy(_buffer + it->second.offset, &data, sizeof(unsigned int)); } void UniformBuffer::setUniform(std::string const &name, float data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT); memcpy(_buffer + it->second.offset, &data, sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::vec2 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_VEC2); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 2 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::vec3 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_VEC3); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 3 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::vec4 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_VEC4); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 4 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::mat2 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_MAT2); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 2 * 2 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::mat3 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_MAT3); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 3 * 3 * sizeof(float)); } void UniformBuffer::setUniform(std::string const &name, glm::mat4 const &data) { std::map<std::string, SUniformVars>::iterator it = _vars.find(name); assert(_buffer && it != _vars.end() && it->second.type == GL_FLOAT_MAT4); memcpy(_buffer + it->second.offset, glm::value_ptr(data), 4 * 4 * sizeof(float)); } void UniformBuffer::flushChanges() { // dirty fix for @cesar AMD gpu -> to fixe later // www.opengl.org/discussion_boards/archive/index.php/t-178601.html // www.opengl.org/discussion_boards/showthread.php/178326-Uniform-Buffer-Object-Performance?p=1240435#post1240435 glBindBufferBase(GL_UNIFORM_BUFFER, _bindingPoint, _bufferId); // !end glBindBuffer(GL_UNIFORM_BUFFER, _bufferId); glBufferData(GL_UNIFORM_BUFFER, _dataSize, _buffer, GL_DYNAMIC_DRAW); } GLuint UniformBuffer::getBindingPoint() const { return (_bindingPoint); } }<|endoftext|>
<commit_before>/** * \file Geodesic.hpp * \brief Header for GeographicLib::Geodesic class * * Copyright (c) Charles Karney (2008, 2009) <charles@karney.com> * and licensed under the LGPL. For more information, see * http://charles.karney.info/geographic/ **********************************************************************/ #if !defined(GEODESIC_HPP) #define GEODESIC_HPP "$Id$" #if !defined(GEOD_TAU_ORD) /** * The order of the series relating \e s and \e sigma when expanded in powers * of \e u<sup>2</sup> = e'<sup>2</sup> cos<sup>2</sup> alpha<sub>0</sub>. **********************************************************************/ #define GEOD_TAU_ORD 6 #endif #if !defined(GEOD_ETA_ORD) /** * The order of the series relating \e lambda and \e eta when expanded in * powers of \e f. Typically, this can be one less that GEOD_TAU_ORD because * the convergence of the series is more rapid when \e f is used as the * expansion parameter (Rainsford 1955). **********************************************************************/ #define GEOD_ETA_ORD 5 #endif #include <cmath> namespace GeographicLib { class GeodesicLine; /** * \brief %Geodesic calculations * * The shortest path between two points on a spheroid at (\e lat1, \e lon1) * and (\e lat2, \e lon2) is called the geodesic. Its length is \e s12 and * the geodesic from point 1 to point 2 has azimuths \e azi1 and \e azi2 at * the two end points. (The azimuth is the heading measured clockwise from * north. \e azi2 is the "forward" azimuth, i.e., the heading that takes you * beyond point 2 not back to point 1.) * * Given \e lat1, \e lon1, \e azi1, and \e s12, we can determine \e lat2, \e * lon2, \e azi2. This is the \e direct geodesic problem. (If \e s12 is * sufficiently large that the geodesic wraps more than halfway around the * earth, there will be another geodesic between the points with a smaller \e * s12.) * * Given \e lat1, \e lon1, \e lat2, and \e lon2, we can determine \e azi1, \e * azi2, \e s12. This is the \e inverse geodesic problem. Usually, the * solution to the inverse problem is unique. In cases where there are * muliple solutions (all with the same \e s12, of course), all the solutions * can be easily generated once a particular solution is provided. * * As an alternative to using distance to measure \e s12, the class can also * use the arc length (in degrees) on the auxiliary sphere. This is a * mathematical construct used in solving the geodesic problems. However, an * arc length in excess of 180<sup>o</sup> indicates that the geodesic is not * a shortest path. In addition, the arc length between an equatorial * crossing and the next extremum of latitude for a geodesic is * 90<sup>o</sup>. * * The calculations are accurate to better than 15 nm. (See \ref geoderrors * for details.) **********************************************************************/ class Geodesic { private: friend class GeodesicLine; static const int tauord = GEOD_TAU_ORD; static const int ntau = tauord; static const int nsig = tauord; static const int etaord = GEOD_TAU_ORD; // etaCoeff is multiplied by etaFactor which is O(f), so we reduce the // order to which etaCoeff is computed by 1. static const int neta = etaord > 0 ? etaord - 1 : 0; static const unsigned maxit = 50; static inline double sq(double x) throw() { return x * x; } #if defined(_MSC_VER) static inline double hypot(double x, double y) throw() { return _hypot(x, y); } static inline double cbrt(double x) throw() { double y = std::pow(std::abs(x), 1/3.0); return x < 0 ? -y : y; } #else static inline double hypot(double x, double y) throw() { return ::hypot(x, y); } static inline double cbrt(double x) throw() { return ::cbrt(x); } #endif void InverseStart(double sbet1, double cbet1, double n1, double sbet2, double cbet2, double lam12, double slam12, double clam12, double& salp1, double& calp1, double c[]) const throw(); double Lambda12(double sbet1, double cbet1, double sbet2, double cbet2, double salp1, double calp1, double& salp2, double& calp2, double& sig12, double& ssig1, double& csig1, double& ssig2, double& csig2, double& u2, bool diffp, double& dlam12, double c[]) const throw(); static const double eps2, tol0, tol1, tol2, xthresh; const double _a, _f, _f1, _e2, _ep2, _b; static double SinSeries(double sinx, double cosx, const double c[], int n) throw(); static inline double AngNormalize(double x) throw() { // Place angle in [-180, 180). Assumes x is in [-540, 540). return x >= 180 ? x - 360 : x < -180 ? x + 360 : x; } static inline double AngRound(double x) throw() { // The makes the smallest gap in x = 1/16 - nextafter(1/16, 0) = 1/2^57 // for doubles = 0.7 pm on the earth if x is an angle in degrees. (This // is about 1000 times more resolution than we get with angles around 90 // degrees.) We use this to avoid having to deal with near singular // cases when x is non-zero but tiny (e.g., 1.0e-200). const double z = 0.0625; // 1/16 double y = std::abs(x); // The compiler mustn't "simplify" z - (z - y) to y y = y < z ? z - (z - y) : y; return x < 0 ? -y : y; } static inline void SinCosNorm(double& sinx, double& cosx) throw() { double r = hypot(sinx, cosx); sinx /= r; cosx /= r; } // These are maxima generated functions to provide series approximations to // the integrals for the spheroidal geodesic. static double tauFactor(double u2) throw(); static void tauCoeff(double u2, double t[]) throw(); static void sigCoeff(double u2, double tp[]) throw(); static double etaFactor(double f, double mu) throw(); static void etaCoeff(double f, double mu, double h[]) throw(); static double etaFactormu(double f, double mu) throw(); static void etaCoeffmu(double f, double mu, double hp[]) throw(); public: /** * Constructor for a spheroid with equatorial radius \e a (meters) and * reciprocal flattening \e r. Setting \e r = 0 implies \e r = inf or * flattening = 0 (i.e., a sphere). Negative \e r indicates a prolate * spheroid. **********************************************************************/ Geodesic(double a, double r) throw(); /** * Perform the direct geodesic calculation. Given a latitude, \e lat1, * longitude, \e lon1, and azimuth \e azi1 (in degrees) for point 1 and a * range, \e s12 (in meters) from point 1 to point 2, return the latitude, * \e lat2, longitude, \e lon2, and forward azimuth, \e azi2 (in degrees) * for point 2. If \e arcmode (default false) is set to true, \e s12 is * interpreted as the arc length (in degrees) on the auxiliary sphere. An * arc length greater that 180 degrees results in a geodesic which is not a * shortest path. For a prolate spheroid, an additional condition is * necessary for a shortest path: the longitudinal extent must not exceed * of 180 degrees. Returned value is the arc length (in degrees). **********************************************************************/ double Direct(double lat1, double lon1, double azi1, double s12, double& lat2, double& lon2, double& azi2, bool arcmode = false) const throw(); /** * Perform the inverse geodesic calculation. Given a latitude, \e lat1, * longitude, \e lon1, for point 1 and a latitude, \e lat2, longitude, \e * lon2, for point 2 (all in degrees), return the geodesic distance, \e s12 * (in meters), and the forward azimuths, \e azi1 and \e azi2 (in degrees), * at points 1 and 2. Returned value is the arc length (in degrees) on the * auxiliary sphere. The routine uses an iterative method. If the method * fails to converge, the negative of the distances (\e s12 and the * function value) and reverse of the azimuths are returned. This is not * expected to happen with spheroidal models of the earth. Please report * all cases where this occurs. **********************************************************************/ double Inverse(double lat1, double lon1, double lat2, double lon2, double& s12, double& azi1, double& azi2) const throw(); /** * Set up to do a series of ranges. This returns a GeodesicLine object * with point 1 given by latitude, \e lat1, longitude, \e lon1, and azimuth * \e azi1 (in degrees). Calls to GeodesicLine::Position return the * position and azimuth for point 2 a specified distance away. Using * GeodesicLine::Position is approximately 2.1 faster than calling * Geodesic::Direct. **********************************************************************/ GeodesicLine Line(double lat1, double lon1, double azi1) const throw(); /** * A global instantiation of Geodesic with the parameters for the WGS84 * ellipsoid. **********************************************************************/ const static Geodesic WGS84; }; /** * \brief A geodesic line. * * GeodesicLine facilitates the determination of a series of points on a * single geodesic. Geodesic.Line returns a GeodesicLine object with the * geodesic defined by by \e lat1, \e lon1, and \e azi1. * GeodesicLine.Position returns the \e lat2, \e lon2, and \e azi2 given \e * s12. An example of use of this class is: \verbatim // Print positions on a geodesic going through latitude 30, // longitude 10 at azimuth 80. Points at intervals of 10km // in the range [-1000km, 1000km] are given. GeodesicLine line(Geodesic::WGS84.Line(30.0, 10.0, 80.0)); double step = 10e3; for (int s = -100; s <= 100; ++s) { double lat2, lon2, azi2; double s12 = s * step; line.Position(s12, lat2, lon2, azi2); cout << s12 << " " << lat2 << " " << lon2 << " " << azi2 << "\n"; } \endverbatim * The default copy constructor and assignment operators work with this * class, so that, for example, the previous example could start \verbatim GeodesicLine line; line = Geodesic::WGS84.Line(30.0, 10.0, 80.0); ... \endverbatim * Similarly, a vector can be used to hold GeodesicLine objects. * * The calculations are accurate to better than 12 nm. (See \ref geoderrors * for details.) **********************************************************************/ class GeodesicLine { private: friend class Geodesic; static const int ntau = Geodesic::ntau; static const int nsig = Geodesic::nsig; static const int neta = Geodesic::neta; double _lat1, _lon1, _azi1; double _f1, _salp0, _calp0, _ssig1, _csig1, _stau1, _ctau1, _schi1, _cchi1, _sScale, _etaFactor, _dtau1, _dlam1; double _sigCoeff[ntau > nsig ? (ntau ? ntau : 1) : (nsig ? nsig : 1)], _etaCoeff[neta ? neta : 1]; GeodesicLine(const Geodesic& g, double lat1, double lon1, double azi1) throw(); void ArcPosition(double sig12, double ssig12, double csig12, double& lat2, double& lon2, double& azi2) const throw(); public: /** * A default constructor. If GeodesicLine::Position is called on the * resulting object, it returns immediately (without doing any * calculations). The object should be set with a call to Geodesic::Line. * Use Init() to test whether object is still in this uninitialized state. **********************************************************************/ GeodesicLine() throw() : _sScale(0) {}; /** * Return the latitude, \e lat2, longitude, \e lon2, and forward azimuth, * \e azi2 (in degrees) of the point 2 which is a distance, \e s12 (in * meters), from point 1. \e s12 can be signed. If \e arcmode (default * false) is set to true, \e s12 is interpreted as the arc length (in * degrees) on the auxiliary sphere; this speeds up the calculation by a * factor of 1.6. Returned value is the arc length (in degrees). **********************************************************************/ double Position(double s12, double& lat2, double& lon2, double& azi2, bool arcmode = false) const throw(); /** * Has this object been initialized so that Position can be called? **********************************************************************/ bool Init() const throw() { return _sScale > 0; } /** * Return the latitude of point 1 (in degrees). **********************************************************************/ double Latitude() const throw() { return _lat1; } /** * Return the longitude of point 1 (in degrees). **********************************************************************/ double Longitude() const throw() { return _lon1; } /** * Return the azimuth of the geodesic line as it passes through point 1. **********************************************************************/ double Azimuth() const throw() { return _azi1; } }; } //namespace GeographicLib #endif <commit_msg>Get ready for release.<commit_after>/** * \file Geodesic.hpp * \brief Header for GeographicLib::Geodesic class * * Copyright (c) Charles Karney (2008, 2009) <charles@karney.com> * and licensed under the LGPL. For more information, see * http://charles.karney.info/geographic/ **********************************************************************/ #if !defined(GEODESIC_HPP) #define GEODESIC_HPP "$Id$" #if !defined(GEOD_TAU_ORD) /** * The order of the series relating \e s and \e sigma when expanded in powers * of \e u<sup>2</sup> = e'<sup>2</sup> cos<sup>2</sup> alpha<sub>0</sub>. **********************************************************************/ #define GEOD_TAU_ORD 6 #endif #if !defined(GEOD_ETA_ORD) /** * The order of the series relating \e lambda and \e eta when expanded in * powers of \e f. Typically, this can be one less that GEOD_TAU_ORD because * the convergence of the series is more rapid when \e f is used as the * expansion parameter (Rainsford 1955). **********************************************************************/ #define GEOD_ETA_ORD 5 #endif #include <cmath> namespace GeographicLib { class GeodesicLine; /** * \brief %Geodesic calculations * * The shortest path between two points on a spheroid at (\e lat1, \e lon1) * and (\e lat2, \e lon2) is called the geodesic. Its length is \e s12 and * the geodesic from point 1 to point 2 has azimuths \e azi1 and \e azi2 at * the two end points. (The azimuth is the heading measured clockwise from * north. \e azi2 is the "forward" azimuth, i.e., the heading that takes you * beyond point 2 not back to point 1.) * * Given \e lat1, \e lon1, \e azi1, and \e s12, we can determine \e lat2, \e * lon2, \e azi2. This is the \e direct geodesic problem. (If \e s12 is * sufficiently large that the geodesic wraps more than halfway around the * earth, there will be another geodesic between the points with a smaller \e * s12.) * * Given \e lat1, \e lon1, \e lat2, and \e lon2, we can determine \e azi1, \e * azi2, \e s12. This is the \e inverse geodesic problem. Usually, the * solution to the inverse problem is unique. In cases where there are * muliple solutions (all with the same \e s12, of course), all the solutions * can be easily generated once a particular solution is provided. * * As an alternative to using distance to measure \e s12, the class can also * use the arc length (in degrees) on the auxiliary sphere. This is a * mathematical construct used in solving the geodesic problems. However, an * arc length in excess of 180<sup>o</sup> indicates that the geodesic is not * a shortest path. In addition, the arc length between an equatorial * crossing and the next extremum of latitude for a geodesic is * 90<sup>o</sup>. * * The calculations are accurate to better than 15 nm. (See \ref geoderrors * for details.) **********************************************************************/ class Geodesic { private: friend class GeodesicLine; static const int tauord = GEOD_TAU_ORD; static const int ntau = tauord; static const int nsig = tauord; static const int etaord = GEOD_TAU_ORD; // etaCoeff is multiplied by etaFactor which is O(f), so we reduce the // order to which etaCoeff is computed by 1. static const int neta = etaord > 0 ? etaord - 1 : 0; static const unsigned maxit = 50; static inline double sq(double x) throw() { return x * x; } #if defined(_MSC_VER) static inline double hypot(double x, double y) throw() { return _hypot(x, y); } static inline double cbrt(double x) throw() { double y = std::pow(std::abs(x), 1/3.0); return x < 0 ? -y : y; } #else static inline double hypot(double x, double y) throw() { return ::hypot(x, y); } static inline double cbrt(double x) throw() { return ::cbrt(x); } #endif void InverseStart(double sbet1, double cbet1, double n1, double sbet2, double cbet2, double lam12, double slam12, double clam12, double& salp1, double& calp1, double c[]) const throw(); double Lambda12(double sbet1, double cbet1, double sbet2, double cbet2, double salp1, double calp1, double& salp2, double& calp2, double& sig12, double& ssig1, double& csig1, double& ssig2, double& csig2, double& u2, bool diffp, double& dlam12, double c[]) const throw(); static const double eps2, tol0, tol1, tol2, xthresh; const double _a, _f, _f1, _e2, _ep2, _b; static double SinSeries(double sinx, double cosx, const double c[], int n) throw(); static inline double AngNormalize(double x) throw() { // Place angle in [-180, 180). Assumes x is in [-540, 540). return x >= 180 ? x - 360 : x < -180 ? x + 360 : x; } static inline double AngRound(double x) throw() { // The makes the smallest gap in x = 1/16 - nextafter(1/16, 0) = 1/2^57 // for doubles = 0.7 pm on the earth if x is an angle in degrees. (This // is about 1000 times more resolution than we get with angles around 90 // degrees.) We use this to avoid having to deal with near singular // cases when x is non-zero but tiny (e.g., 1.0e-200). const double z = 0.0625; // 1/16 double y = std::abs(x); // The compiler mustn't "simplify" z - (z - y) to y y = y < z ? z - (z - y) : y; return x < 0 ? -y : y; } static inline void SinCosNorm(double& sinx, double& cosx) throw() { double r = hypot(sinx, cosx); sinx /= r; cosx /= r; } // These are maxima generated functions to provide series approximations to // the integrals for the spheroidal geodesic. static double tauFactor(double u2) throw(); static void tauCoeff(double u2, double t[]) throw(); static void sigCoeff(double u2, double tp[]) throw(); static double etaFactor(double f, double mu) throw(); static void etaCoeff(double f, double mu, double h[]) throw(); static double etaFactormu(double f, double mu) throw(); static void etaCoeffmu(double f, double mu, double hp[]) throw(); public: /** * Constructor for a spheroid with equatorial radius \e a (meters) and * reciprocal flattening \e r. Setting \e r = 0 implies \e r = inf or * flattening = 0 (i.e., a sphere). Negative \e r indicates a prolate * spheroid. **********************************************************************/ Geodesic(double a, double r) throw(); /** * Perform the direct geodesic calculation. Given a latitude, \e lat1, * longitude, \e lon1, and azimuth \e azi1 (in degrees) for point 1 and a * range, \e s12 (in meters) from point 1 to point 2, return the latitude, * \e lat2, longitude, \e lon2, and forward azimuth, \e azi2 (in degrees) * for point 2. If \e arcmode (default false) is set to true, \e s12 is * interpreted as the arc length (in degrees) on the auxiliary sphere. An * arc length greater that 180 degrees results in a geodesic which is not a * shortest path. For a prolate spheroid, an additional condition is * necessary for a shortest path: the longitudinal extent must not exceed * of 180 degrees. Returned value is the arc length (in degrees). **********************************************************************/ double Direct(double lat1, double lon1, double azi1, double s12, double& lat2, double& lon2, double& azi2, bool arcmode = false) const throw(); /** * Perform the inverse geodesic calculation. Given a latitude, \e lat1, * longitude, \e lon1, for point 1 and a latitude, \e lat2, longitude, \e * lon2, for point 2 (all in degrees), return the geodesic distance, \e s12 * (in meters), and the forward azimuths, \e azi1 and \e azi2 (in degrees), * at points 1 and 2. Returned value is the arc length (in degrees) on the * auxiliary sphere. The routine uses an iterative method. If the method * fails to converge, the negative of the distances (\e s12 and the * function value) and reverse of the azimuths are returned. This is not * expected to happen with spheroidal models of the earth. Please report * all cases where this occurs. **********************************************************************/ double Inverse(double lat1, double lon1, double lat2, double lon2, double& s12, double& azi1, double& azi2) const throw(); /** * Set up to do a series of ranges. This returns a GeodesicLine object * with point 1 given by latitude, \e lat1, longitude, \e lon1, and azimuth * \e azi1 (in degrees). Calls to GeodesicLine::Position return the * position and azimuth for point 2 a specified distance away. Using * GeodesicLine::Position is approximately 2.1 faster than calling * Geodesic::Direct. **********************************************************************/ GeodesicLine Line(double lat1, double lon1, double azi1) const throw(); /** * A global instantiation of Geodesic with the parameters for the WGS84 * ellipsoid. **********************************************************************/ const static Geodesic WGS84; }; /** * \brief A geodesic line. * * GeodesicLine facilitates the determination of a series of points on a * single geodesic. Geodesic.Line returns a GeodesicLine object with the * geodesic defined by by \e lat1, \e lon1, and \e azi1. * GeodesicLine.Position returns the \e lat2, \e lon2, and \e azi2 given \e * s12. An example of use of this class is: \verbatim // Print positions on a geodesic going through latitude 30, // longitude 10 at azimuth 80. Points at intervals of 10km // in the range [-1000km, 1000km] are given. GeodesicLine line(Geodesic::WGS84.Line(30.0, 10.0, 80.0)); double step = 10e3; for (int s = -100; s <= 100; ++s) { double lat2, lon2, azi2; double s12 = s * step; line.Position(s12, lat2, lon2, azi2); cout << s12 << " " << lat2 << " " << lon2 << " " << azi2 << "\n"; } \endverbatim * The default copy constructor and assignment operators work with this * class, so that, for example, the previous example could start \verbatim GeodesicLine line; line = Geodesic::WGS84.Line(30.0, 10.0, 80.0); ... \endverbatim * Similarly, a vector can be used to hold GeodesicLine objects. * * The calculations are accurate to better than 12 nm. (See \ref geoderrors * for details.) **********************************************************************/ class GeodesicLine { private: friend class Geodesic; static const int ntau = Geodesic::ntau; static const int nsig = Geodesic::nsig; static const int neta = Geodesic::neta; double _lat1, _lon1, _azi1; double _f1, _salp0, _calp0, _ssig1, _csig1, _stau1, _ctau1, _schi1, _cchi1, _sScale, _etaFactor, _dtau1, _dlam1; double _sigCoeff[ntau > nsig ? (ntau ? ntau : 1) : (nsig ? nsig : 1)], _etaCoeff[neta ? neta : 1]; GeodesicLine(const Geodesic& g, double lat1, double lon1, double azi1) throw(); void ArcPosition(double sig12, double ssig12, double csig12, double& lat2, double& lon2, double& azi2) const throw(); public: /** * A default constructor. If GeodesicLine::Position is called on the * resulting object, it returns immediately (without doing any * calculations). The object should be set with a call to Geodesic::Line. * Use Init() to test whether object is still in this uninitialized state. **********************************************************************/ GeodesicLine() throw() : _sScale(0) {}; /** * Return the latitude, \e lat2, longitude, \e lon2, and forward azimuth, * \e azi2 (in degrees) of the point 2 which is a distance, \e s12 (in * meters), from point 1. \e s12 can be signed. If \e arcmode (default * false) is set to true, \e s12 is interpreted as the arc length (in * degrees) on the auxiliary sphere; this speeds up the calculation by a * factor of 1.6. Returned value is the arc length (in degrees). **********************************************************************/ double Position(double s12, double& lat2, double& lon2, double& azi2, bool arcmode = false) const throw(); /** * Has this object been initialized so that Position can be called? **********************************************************************/ bool Init() const throw() { return _sScale > 0; } /** * Return the latitude of point 1 (in degrees). **********************************************************************/ double Latitude() const throw() { return _lat1; } /** * Return the longitude of point 1 (in degrees). **********************************************************************/ double Longitude() const throw() { return _lon1; } /** * Return the azimuth (in degrees) of the geodesic line as it passes * through point 1. **********************************************************************/ double Azimuth() const throw() { return _azi1; } }; } //namespace GeographicLib #endif <|endoftext|>
<commit_before>/* This file is part of the KDE libraries Copyright (C) 2005 Hamish Rodda <rodda@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "katelayoutcache.h" #include <QtCore/QMutex> #include "katerenderer.h" #include "kateview.h" #include "katedocument.h" #include "kateedit.h" #include <kdebug.h> static bool enableLayoutCache = false; KateLayoutCache::KateLayoutCache(KateRenderer* renderer, QObject* parent) : QObject(parent) , m_renderer(renderer) , m_startPos(-1,-1) , m_viewWidth(0) , m_wrap(false) { Q_ASSERT(m_renderer); connect(m_renderer->doc()->history(), SIGNAL(editDone(KateEditInfo*)), SLOT(slotEditDone(KateEditInfo*))); } void KateLayoutCache::updateViewCache(const KTextEditor::Cursor& startPos, int newViewLineCount, int viewLinesScrolled) { //kDebug() << startPos << " nvlc " << newViewLineCount << " vls " << viewLinesScrolled; int oldViewLineCount = m_textLayouts.count(); if (newViewLineCount == -1) newViewLineCount = oldViewLineCount; enableLayoutCache = true; int realLine = m_renderer->doc()->getRealLine(startPos.line()); int _viewLine = 0; if (wrap()) { // TODO check these assumptions are ok... probably they don't give much speedup anyway? if (startPos == m_startPos && m_textLayouts.count()) { _viewLine = m_textLayouts.first().viewLine(); } else if (viewLinesScrolled > 0 && viewLinesScrolled < m_textLayouts.count()) { _viewLine = m_textLayouts[viewLinesScrolled].viewLine(); } else { KateLineLayoutPtr l = line(realLine); if (l) { Q_ASSERT(l->isValid()); Q_ASSERT(l->length() >= startPos.column() || m_renderer->view()->wrapCursor()); for (; _viewLine < l->viewLineCount(); ++_viewLine) { const KateTextLayout& t = l->viewLine(_viewLine); if (t.startCol() >= startPos.column() || _viewLine == l->viewLineCount() - 1) goto foundViewLine; } // FIXME FIXME need to calculate past-end-of-line position here... Q_ASSERT(false); foundViewLine: Q_ASSERT(true); } } } m_startPos = startPos; // Move the text layouts if we've just scrolled... if (viewLinesScrolled != 0) { // loop backwards if we've just scrolled up... bool forwards = viewLinesScrolled >= 0 ? true : false; for (int z = forwards ? 0 : m_textLayouts.count() - 1; forwards ? (z < m_textLayouts.count()) : (z >= 0); forwards ? z++ : z--) { int oldZ = z + viewLinesScrolled; if (oldZ >= 0 && oldZ < m_textLayouts.count()) m_textLayouts[z] = m_textLayouts[oldZ]; } } // Resize functionality if (newViewLineCount > oldViewLineCount) { m_textLayouts.reserve(newViewLineCount); } else if (newViewLineCount < oldViewLineCount) { /* FIXME reintroduce... check we're not missing any int lastLine = m_textLayouts[newSize - 1].line(); for (int i = oldSize; i < newSize; i++) { const KateTextLayout& layout = m_textLayouts[i]; if (layout.line() > lastLine && !layout.viewLine()) layout.kateLineLayout()->layout()->setCacheEnabled(false); }*/ m_textLayouts.resize(newViewLineCount); } KateLineLayoutPtr l = line(realLine); for (int i = 0; i < newViewLineCount; ++i) { if (!l) { if (i < m_textLayouts.count()) m_textLayouts[i] = KateTextLayout::invalid(); else m_textLayouts.append(KateTextLayout::invalid()); continue; } Q_ASSERT(l->isValid()); Q_ASSERT(_viewLine < l->viewLineCount()); if (i < m_textLayouts.count()) { bool dirty = false; if (m_textLayouts[i].line() != realLine || m_textLayouts[i].viewLine() != _viewLine || !m_textLayouts[i].isValid()) dirty = true; m_textLayouts[i] = l->viewLine(_viewLine); if (dirty) m_textLayouts[i].setDirty(true); } else { m_textLayouts.append(l->viewLine(_viewLine)); } //kDebug() << "Laid out line " << realLine << " (" << l << "), viewLine " << _viewLine << " (" << m_textLayouts[i].kateLineLayout().data() << ")"; //m_textLayouts[i].debugOutput(); _viewLine++; if (_viewLine > l->viewLineCount() - 1) { int virtualLine = l->virtualLine() + 1; realLine = m_renderer->doc()->getRealLine(virtualLine); _viewLine = 0; l = line(realLine, virtualLine); } } enableLayoutCache = false; } KateLineLayoutPtr KateLayoutCache::line( int realLine, int virtualLine ) const { if (m_lineLayouts.contains(realLine)) { KateLineLayoutPtr l = m_lineLayouts[realLine]; if (virtualLine != -1) l->setVirtualLine(virtualLine); if (!l->isValid()) m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache); else if (l->isLayoutDirty()) m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache); Q_ASSERT(l->isValid() && !l->isLayoutDirty()); return l; } if (realLine < 0 || realLine >= m_renderer->doc()->lines()) return KateLineLayoutPtr(); KateLineLayoutPtr l(new KateLineLayout(m_renderer->doc())); l->setLine(realLine, virtualLine); m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache); Q_ASSERT(l->isValid()); m_lineLayouts.insert(realLine, l); return l; } KateLineLayoutPtr KateLayoutCache::line( const KTextEditor::Cursor & realCursor ) const { return line(realCursor.line()); } KateTextLayout KateLayoutCache::textLayout( const KTextEditor::Cursor & realCursor ) const { /*if (realCursor >= viewCacheStart() && (realCursor < viewCacheEnd() || realCursor == viewCacheEnd() && !m_textLayouts.last().wrap())) foreach (const KateTextLayout& l, m_textLayouts) if (l.line() == realCursor.line() && (l.endCol() < realCursor.column() || !l.wrap())) return l;*/ return line(realCursor.line())->viewLine(viewLine(realCursor)); } KateTextLayout KateLayoutCache::textLayout( uint realLine, int _viewLine ) const { /*if (m_textLayouts.count() && (realLine >= m_textLayouts.first().line() && _viewLine >= m_textLayouts.first().viewLine()) && (realLine <= m_textLayouts.last().line() && _viewLine <= m_textLayouts.first().viewLine())) foreach (const KateTextLayout& l, m_textLayouts) if (l.line() == realLine && l.viewLine() == _viewLine) return const_cast<KateTextLayout&>(l);*/ return line(realLine)->viewLine(_viewLine); } KateTextLayout & KateLayoutCache::viewLine( int _viewLine ) const { Q_ASSERT(_viewLine >= 0 && _viewLine < m_textLayouts.count()); return m_textLayouts[_viewLine]; } int KateLayoutCache::viewCacheLineCount( ) const { return m_textLayouts.count(); } KTextEditor::Cursor KateLayoutCache::viewCacheStart( ) const { return m_textLayouts.count() ? m_textLayouts.first().start() : KTextEditor::Cursor(); } KTextEditor::Cursor KateLayoutCache::viewCacheEnd( ) const { return m_textLayouts.count() ? m_textLayouts.last().end() : KTextEditor::Cursor(); } int KateLayoutCache::viewWidth( ) const { return m_viewWidth; } /** * This returns the view line upon which realCursor is situated. * The view line is the number of lines in the view from the first line * The supplied cursor should be in real lines. */ int KateLayoutCache::viewLine(const KTextEditor::Cursor& realCursor) const { if (realCursor.column() == 0) return 0; KateLineLayoutPtr thisLine = line(realCursor.line()); for (int i = 0; i < thisLine->viewLineCount(); ++i) { const KateTextLayout& l = thisLine->viewLine(i); if (realCursor.column() >= l.startCol() && realCursor.column() < l.endCol()) return i; } return thisLine->viewLineCount() - 1; } int KateLayoutCache::displayViewLine(const KTextEditor::Cursor& virtualCursor, bool limitToVisible) const { KTextEditor::Cursor work = viewCacheStart(); work.setLine(m_renderer->doc()->getVirtualLine(work.line())); int limit = m_textLayouts.count(); // Efficient non-word-wrapped path if (!m_renderer->view()->dynWordWrap()) { int ret = virtualCursor.line() - work.line(); if (limitToVisible && (ret < 0 || ret > limit)) return -1; else return ret; } if (work == virtualCursor) { return 0; } int ret = -(int)viewLine(work); bool forwards = (work < virtualCursor) ? true : false; // FIXME switch to using ranges? faster? if (forwards) { while (work.line() != virtualCursor.line()) { ret += viewLineCount(m_renderer->doc()->getRealLine(work.line())); work.setLine(work.line() + 1); if (limitToVisible && ret > limit) return -1; } } else { while (work.line() != virtualCursor.line()) { work.setLine(work.line() - 1); ret -= viewLineCount(m_renderer->doc()->getRealLine(work.line())); if (limitToVisible && ret < 0) return -1; } } // final difference KTextEditor::Cursor realCursor = virtualCursor; realCursor.setLine(m_renderer->doc()->getRealLine(realCursor.line())); if (realCursor.column() == -1) realCursor.setColumn(m_renderer->doc()->lineLength(realCursor.line())); ret += viewLine(realCursor); if (limitToVisible && (ret < 0 || ret > limit)) return -1; return ret; } int KateLayoutCache::lastViewLine(int realLine) const { if (!m_renderer->view()->dynWordWrap()) return 0; KateLineLayoutPtr l = line(realLine); Q_ASSERT(l); return l->viewLineCount() - 1; } int KateLayoutCache::viewLineCount(int realLine) const { return lastViewLine(realLine) + 1; } void KateLayoutCache::viewCacheDebugOutput( ) const { kDebug() << "Printing values for " << m_textLayouts.count() << " lines:"; if (m_textLayouts.count()) foreach (const KateTextLayout& t, m_textLayouts) if (t.isValid()) t.debugOutput(); else kDebug() << "Line Invalid."; } void KateLayoutCache::slotEditDone(KateEditInfo* edit) { int fromLine = edit->oldRange().start().line(); int toLine = edit->oldRange().end().line(); int shiftAmount = edit->translate().line(); if (shiftAmount) { QMap<int, KateLineLayoutPtr> oldMap = m_lineLayouts; m_lineLayouts.clear(); QMapIterator<int, KateLineLayoutPtr> it = oldMap; while (it.hasNext()) { it.next(); if (it.key() > toLine) { KateLineLayoutPtr layout = it.value(); layout->setLine(layout->line() + shiftAmount); m_lineLayouts.insert(it.key() + shiftAmount, layout); } else if (it.key() < fromLine) { m_lineLayouts.insert(it.key(), it.value()); } else { //gets deleted when oldMap goes but invalidate it just in case const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout(); } } } else { for (int i = fromLine; i <= toLine; ++i) if (m_lineLayouts.contains(i)) { const_cast<KateLineLayoutPtr&>(m_lineLayouts[i])->setLayoutDirty(); m_lineLayouts.remove(i); } } } void KateLayoutCache::clear( ) { m_textLayouts.clear(); m_lineLayouts.clear(); m_startPos = KTextEditor::Cursor(-1,-1); } void KateLayoutCache::setViewWidth( int width ) { bool wider = width > m_viewWidth; m_viewWidth = width; m_lineLayouts.clear(); m_startPos = KTextEditor::Cursor(-1,-1); // Only get rid of layouts that we have to if (wider) { QMapIterator<int, KateLineLayoutPtr> it = m_lineLayouts; while (it.hasNext()) { it.next(); if (it.value()->viewLineCount() > 1) const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout(); } } else { QMapIterator<int, KateLineLayoutPtr> it = m_lineLayouts; while (it.hasNext()) { it.next(); if (it.value()->viewLineCount() > 1 || it.value()->width() > m_viewWidth) const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout(); } } } bool KateLayoutCache::wrap( ) const { return m_wrap; } void KateLayoutCache::setWrap( bool wrap ) { m_wrap = wrap; clear(); } void KateLayoutCache::relayoutLines( int startRealLine, int endRealLine ) { for (int i = startRealLine; i <= endRealLine; ++i) if (m_lineLayouts.contains(i)) m_lineLayouts[i]->setLayoutDirty(); } #include "katelayoutcache.moc" <commit_msg>contains() + operator[] is searching twice, just find and use the resulting iterator<commit_after>/* This file is part of the KDE libraries Copyright (C) 2005 Hamish Rodda <rodda@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "katelayoutcache.h" #include <QtCore/QMutex> #include "katerenderer.h" #include "kateview.h" #include "katedocument.h" #include "kateedit.h" #include <kdebug.h> static bool enableLayoutCache = false; KateLayoutCache::KateLayoutCache(KateRenderer* renderer, QObject* parent) : QObject(parent) , m_renderer(renderer) , m_startPos(-1,-1) , m_viewWidth(0) , m_wrap(false) { Q_ASSERT(m_renderer); connect(m_renderer->doc()->history(), SIGNAL(editDone(KateEditInfo*)), SLOT(slotEditDone(KateEditInfo*))); } void KateLayoutCache::updateViewCache(const KTextEditor::Cursor& startPos, int newViewLineCount, int viewLinesScrolled) { //kDebug() << startPos << " nvlc " << newViewLineCount << " vls " << viewLinesScrolled; int oldViewLineCount = m_textLayouts.count(); if (newViewLineCount == -1) newViewLineCount = oldViewLineCount; enableLayoutCache = true; int realLine = m_renderer->doc()->getRealLine(startPos.line()); int _viewLine = 0; if (wrap()) { // TODO check these assumptions are ok... probably they don't give much speedup anyway? if (startPos == m_startPos && m_textLayouts.count()) { _viewLine = m_textLayouts.first().viewLine(); } else if (viewLinesScrolled > 0 && viewLinesScrolled < m_textLayouts.count()) { _viewLine = m_textLayouts[viewLinesScrolled].viewLine(); } else { KateLineLayoutPtr l = line(realLine); if (l) { Q_ASSERT(l->isValid()); Q_ASSERT(l->length() >= startPos.column() || m_renderer->view()->wrapCursor()); for (; _viewLine < l->viewLineCount(); ++_viewLine) { const KateTextLayout& t = l->viewLine(_viewLine); if (t.startCol() >= startPos.column() || _viewLine == l->viewLineCount() - 1) goto foundViewLine; } // FIXME FIXME need to calculate past-end-of-line position here... Q_ASSERT(false); foundViewLine: Q_ASSERT(true); } } } m_startPos = startPos; // Move the text layouts if we've just scrolled... if (viewLinesScrolled != 0) { // loop backwards if we've just scrolled up... bool forwards = viewLinesScrolled >= 0 ? true : false; for (int z = forwards ? 0 : m_textLayouts.count() - 1; forwards ? (z < m_textLayouts.count()) : (z >= 0); forwards ? z++ : z--) { int oldZ = z + viewLinesScrolled; if (oldZ >= 0 && oldZ < m_textLayouts.count()) m_textLayouts[z] = m_textLayouts[oldZ]; } } // Resize functionality if (newViewLineCount > oldViewLineCount) { m_textLayouts.reserve(newViewLineCount); } else if (newViewLineCount < oldViewLineCount) { /* FIXME reintroduce... check we're not missing any int lastLine = m_textLayouts[newSize - 1].line(); for (int i = oldSize; i < newSize; i++) { const KateTextLayout& layout = m_textLayouts[i]; if (layout.line() > lastLine && !layout.viewLine()) layout.kateLineLayout()->layout()->setCacheEnabled(false); }*/ m_textLayouts.resize(newViewLineCount); } KateLineLayoutPtr l = line(realLine); for (int i = 0; i < newViewLineCount; ++i) { if (!l) { if (i < m_textLayouts.count()) m_textLayouts[i] = KateTextLayout::invalid(); else m_textLayouts.append(KateTextLayout::invalid()); continue; } Q_ASSERT(l->isValid()); Q_ASSERT(_viewLine < l->viewLineCount()); if (i < m_textLayouts.count()) { bool dirty = false; if (m_textLayouts[i].line() != realLine || m_textLayouts[i].viewLine() != _viewLine || !m_textLayouts[i].isValid()) dirty = true; m_textLayouts[i] = l->viewLine(_viewLine); if (dirty) m_textLayouts[i].setDirty(true); } else { m_textLayouts.append(l->viewLine(_viewLine)); } //kDebug() << "Laid out line " << realLine << " (" << l << "), viewLine " << _viewLine << " (" << m_textLayouts[i].kateLineLayout().data() << ")"; //m_textLayouts[i].debugOutput(); _viewLine++; if (_viewLine > l->viewLineCount() - 1) { int virtualLine = l->virtualLine() + 1; realLine = m_renderer->doc()->getRealLine(virtualLine); _viewLine = 0; l = line(realLine, virtualLine); } } enableLayoutCache = false; } KateLineLayoutPtr KateLayoutCache::line( int realLine, int virtualLine ) const { if (m_lineLayouts.contains(realLine)) { KateLineLayoutPtr l = m_lineLayouts[realLine]; if (virtualLine != -1) l->setVirtualLine(virtualLine); if (!l->isValid()) m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache); else if (l->isLayoutDirty()) m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache); Q_ASSERT(l->isValid() && !l->isLayoutDirty()); return l; } if (realLine < 0 || realLine >= m_renderer->doc()->lines()) return KateLineLayoutPtr(); KateLineLayoutPtr l(new KateLineLayout(m_renderer->doc())); l->setLine(realLine, virtualLine); m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache); Q_ASSERT(l->isValid()); m_lineLayouts.insert(realLine, l); return l; } KateLineLayoutPtr KateLayoutCache::line( const KTextEditor::Cursor & realCursor ) const { return line(realCursor.line()); } KateTextLayout KateLayoutCache::textLayout( const KTextEditor::Cursor & realCursor ) const { /*if (realCursor >= viewCacheStart() && (realCursor < viewCacheEnd() || realCursor == viewCacheEnd() && !m_textLayouts.last().wrap())) foreach (const KateTextLayout& l, m_textLayouts) if (l.line() == realCursor.line() && (l.endCol() < realCursor.column() || !l.wrap())) return l;*/ return line(realCursor.line())->viewLine(viewLine(realCursor)); } KateTextLayout KateLayoutCache::textLayout( uint realLine, int _viewLine ) const { /*if (m_textLayouts.count() && (realLine >= m_textLayouts.first().line() && _viewLine >= m_textLayouts.first().viewLine()) && (realLine <= m_textLayouts.last().line() && _viewLine <= m_textLayouts.first().viewLine())) foreach (const KateTextLayout& l, m_textLayouts) if (l.line() == realLine && l.viewLine() == _viewLine) return const_cast<KateTextLayout&>(l);*/ return line(realLine)->viewLine(_viewLine); } KateTextLayout & KateLayoutCache::viewLine( int _viewLine ) const { Q_ASSERT(_viewLine >= 0 && _viewLine < m_textLayouts.count()); return m_textLayouts[_viewLine]; } int KateLayoutCache::viewCacheLineCount( ) const { return m_textLayouts.count(); } KTextEditor::Cursor KateLayoutCache::viewCacheStart( ) const { return m_textLayouts.count() ? m_textLayouts.first().start() : KTextEditor::Cursor(); } KTextEditor::Cursor KateLayoutCache::viewCacheEnd( ) const { return m_textLayouts.count() ? m_textLayouts.last().end() : KTextEditor::Cursor(); } int KateLayoutCache::viewWidth( ) const { return m_viewWidth; } /** * This returns the view line upon which realCursor is situated. * The view line is the number of lines in the view from the first line * The supplied cursor should be in real lines. */ int KateLayoutCache::viewLine(const KTextEditor::Cursor& realCursor) const { if (realCursor.column() == 0) return 0; KateLineLayoutPtr thisLine = line(realCursor.line()); for (int i = 0; i < thisLine->viewLineCount(); ++i) { const KateTextLayout& l = thisLine->viewLine(i); if (realCursor.column() >= l.startCol() && realCursor.column() < l.endCol()) return i; } return thisLine->viewLineCount() - 1; } int KateLayoutCache::displayViewLine(const KTextEditor::Cursor& virtualCursor, bool limitToVisible) const { KTextEditor::Cursor work = viewCacheStart(); work.setLine(m_renderer->doc()->getVirtualLine(work.line())); int limit = m_textLayouts.count(); // Efficient non-word-wrapped path if (!m_renderer->view()->dynWordWrap()) { int ret = virtualCursor.line() - work.line(); if (limitToVisible && (ret < 0 || ret > limit)) return -1; else return ret; } if (work == virtualCursor) { return 0; } int ret = -(int)viewLine(work); bool forwards = (work < virtualCursor) ? true : false; // FIXME switch to using ranges? faster? if (forwards) { while (work.line() != virtualCursor.line()) { ret += viewLineCount(m_renderer->doc()->getRealLine(work.line())); work.setLine(work.line() + 1); if (limitToVisible && ret > limit) return -1; } } else { while (work.line() != virtualCursor.line()) { work.setLine(work.line() - 1); ret -= viewLineCount(m_renderer->doc()->getRealLine(work.line())); if (limitToVisible && ret < 0) return -1; } } // final difference KTextEditor::Cursor realCursor = virtualCursor; realCursor.setLine(m_renderer->doc()->getRealLine(realCursor.line())); if (realCursor.column() == -1) realCursor.setColumn(m_renderer->doc()->lineLength(realCursor.line())); ret += viewLine(realCursor); if (limitToVisible && (ret < 0 || ret > limit)) return -1; return ret; } int KateLayoutCache::lastViewLine(int realLine) const { if (!m_renderer->view()->dynWordWrap()) return 0; KateLineLayoutPtr l = line(realLine); Q_ASSERT(l); return l->viewLineCount() - 1; } int KateLayoutCache::viewLineCount(int realLine) const { return lastViewLine(realLine) + 1; } void KateLayoutCache::viewCacheDebugOutput( ) const { kDebug() << "Printing values for " << m_textLayouts.count() << " lines:"; if (m_textLayouts.count()) foreach (const KateTextLayout& t, m_textLayouts) if (t.isValid()) t.debugOutput(); else kDebug() << "Line Invalid."; } void KateLayoutCache::slotEditDone(KateEditInfo* edit) { int fromLine = edit->oldRange().start().line(); int toLine = edit->oldRange().end().line(); int shiftAmount = edit->translate().line(); if (shiftAmount) { QMap<int, KateLineLayoutPtr> oldMap = m_lineLayouts; m_lineLayouts.clear(); QMapIterator<int, KateLineLayoutPtr> it = oldMap; while (it.hasNext()) { it.next(); if (it.key() > toLine) { KateLineLayoutPtr layout = it.value(); layout->setLine(layout->line() + shiftAmount); m_lineLayouts.insert(it.key() + shiftAmount, layout); } else if (it.key() < fromLine) { m_lineLayouts.insert(it.key(), it.value()); } else { //gets deleted when oldMap goes but invalidate it just in case const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout(); } } } else { for (int i = fromLine; i <= toLine; ++i) if (m_lineLayouts.contains(i)) { const_cast<KateLineLayoutPtr&>(m_lineLayouts[i])->setLayoutDirty(); m_lineLayouts.remove(i); } } } void KateLayoutCache::clear( ) { m_textLayouts.clear(); m_lineLayouts.clear(); m_startPos = KTextEditor::Cursor(-1,-1); } void KateLayoutCache::setViewWidth( int width ) { bool wider = width > m_viewWidth; m_viewWidth = width; m_lineLayouts.clear(); m_startPos = KTextEditor::Cursor(-1,-1); // Only get rid of layouts that we have to if (wider) { QMapIterator<int, KateLineLayoutPtr> it = m_lineLayouts; while (it.hasNext()) { it.next(); if (it.value()->viewLineCount() > 1) const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout(); } } else { QMapIterator<int, KateLineLayoutPtr> it = m_lineLayouts; while (it.hasNext()) { it.next(); if (it.value()->viewLineCount() > 1 || it.value()->width() > m_viewWidth) const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout(); } } } bool KateLayoutCache::wrap( ) const { return m_wrap; } void KateLayoutCache::setWrap( bool wrap ) { m_wrap = wrap; clear(); } void KateLayoutCache::relayoutLines( int startRealLine, int endRealLine ) { for (int i = startRealLine; i <= endRealLine; ++i) { QMap<int, KateLineLayoutPtr>::iterator it = m_lineLayouts.find(i); if (it != m_lineLayouts.end()) (*it)->setLayoutDirty(); } } #include "katelayoutcache.moc" <|endoftext|>
<commit_before>f1c55491-327f-11e5-8fba-9cf387a8033e<commit_msg>f1cb8e82-327f-11e5-839c-9cf387a8033e<commit_after>f1cb8e82-327f-11e5-839c-9cf387a8033e<|endoftext|>
<commit_before>/** * @file llsearcheditor.cpp * @brief LLSearchEditor implementation * * $LicenseInfo:firstyear=2001&license=viewergpl$ * * Copyright (c) 2001-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ // Text editor widget to let users enter a single line. #include "linden_common.h" #include "llsearcheditor.h" LLSearchEditor::LLSearchEditor(const LLSearchEditor::Params& p) : LLUICtrl(p), mSearchButton(NULL), mClearButton(NULL) { S32 srch_btn_top = p.search_button.top_pad + p.search_button.rect.height; S32 srch_btn_right = p.search_button.rect.width + p.search_button.left_pad; LLRect srch_btn_rect(p.search_button.left_pad, srch_btn_top, srch_btn_right, p.search_button.top_pad); S32 text_pad_left = p.text_pad_left; if (p.search_button_visible) text_pad_left += srch_btn_rect.getWidth(); // Set up line editor. LLLineEditor::Params line_editor_params(p); line_editor_params.name("filter edit box"); line_editor_params.rect(getLocalRect()); line_editor_params.follows.flags(FOLLOWS_ALL); line_editor_params.text_pad_left(text_pad_left); line_editor_params.revert_on_esc(false); line_editor_params.commit_callback.function(boost::bind(&LLUICtrl::onCommit, this)); line_editor_params.keystroke_callback(boost::bind(&LLSearchEditor::handleKeystroke, this)); mSearchEditor = LLUICtrlFactory::create<LLLineEditor>(line_editor_params); mSearchEditor->setPassDelete(TRUE); addChild(mSearchEditor); if (p.search_button_visible) { // Set up search button. LLButton::Params srch_btn_params(p.search_button); srch_btn_params.name(std::string("search button")); srch_btn_params.rect(srch_btn_rect) ; srch_btn_params.follows.flags(FOLLOWS_LEFT|FOLLOWS_TOP); srch_btn_params.tab_stop(false); srch_btn_params.click_callback.function(boost::bind(&LLUICtrl::onCommit, this)); mSearchButton = LLUICtrlFactory::create<LLButton>(srch_btn_params); mSearchEditor->addChild(mSearchButton); } if (p.clear_button_visible) { // Set up clear button. LLButton::Params clr_btn_params(p.clear_button); clr_btn_params.name(std::string("clear button")); S32 clr_btn_top = clr_btn_params.rect.bottom + clr_btn_params.rect.height; S32 clr_btn_right = getRect().getWidth() - clr_btn_params.pad_right; S32 clr_btn_left = clr_btn_right - clr_btn_params.rect.width; LLRect clear_btn_rect(clr_btn_left, clr_btn_top, clr_btn_right, p.clear_button.rect.bottom); clr_btn_params.rect(clear_btn_rect) ; clr_btn_params.follows.flags(FOLLOWS_RIGHT|FOLLOWS_TOP); clr_btn_params.tab_stop(false); clr_btn_params.click_callback.function(boost::bind(&LLSearchEditor::onClearButtonClick, this, _2)); mClearButton = LLUICtrlFactory::create<LLButton>(clr_btn_params); mSearchEditor->addChild(mClearButton); } } //virtual void LLSearchEditor::draw() { if (mClearButton) mClearButton->setVisible(!mSearchEditor->getWText().empty()); LLUICtrl::draw(); } //virtual void LLSearchEditor::setValue(const LLSD& value ) { mSearchEditor->setValue(value); } //virtual LLSD LLSearchEditor::getValue() const { return mSearchEditor->getValue(); } //virtual BOOL LLSearchEditor::setTextArg( const std::string& key, const LLStringExplicit& text ) { return mSearchEditor->setTextArg(key, text); } //virtual BOOL LLSearchEditor::setLabelArg( const std::string& key, const LLStringExplicit& text ) { return mSearchEditor->setLabelArg(key, text); } //virtual void LLSearchEditor::setLabel( const LLStringExplicit &new_label ) { mSearchEditor->setLabel(new_label); } //virtual void LLSearchEditor::clear() { if (mSearchEditor) { mSearchEditor->clear(); } } //virtual void LLSearchEditor::setFocus( BOOL b ) { if (mSearchEditor) { mSearchEditor->setFocus(b); } } void LLSearchEditor::onClearButtonClick(const LLSD& data) { setText(LLStringUtil::null); mSearchEditor->doDelete(); // force keystroke callback } void LLSearchEditor::handleKeystroke() { if (mKeystrokeCallback) { mKeystrokeCallback(this, getValue()); } } <commit_msg>Fixed normal bug EXT-5468 - Lists from people panel are not refreshed after filter field has been reseted by (x).<commit_after>/** * @file llsearcheditor.cpp * @brief LLSearchEditor implementation * * $LicenseInfo:firstyear=2001&license=viewergpl$ * * Copyright (c) 2001-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ // Text editor widget to let users enter a single line. #include "linden_common.h" #include "llsearcheditor.h" LLSearchEditor::LLSearchEditor(const LLSearchEditor::Params& p) : LLUICtrl(p), mSearchButton(NULL), mClearButton(NULL) { S32 srch_btn_top = p.search_button.top_pad + p.search_button.rect.height; S32 srch_btn_right = p.search_button.rect.width + p.search_button.left_pad; LLRect srch_btn_rect(p.search_button.left_pad, srch_btn_top, srch_btn_right, p.search_button.top_pad); S32 text_pad_left = p.text_pad_left; if (p.search_button_visible) text_pad_left += srch_btn_rect.getWidth(); // Set up line editor. LLLineEditor::Params line_editor_params(p); line_editor_params.name("filter edit box"); line_editor_params.rect(getLocalRect()); line_editor_params.follows.flags(FOLLOWS_ALL); line_editor_params.text_pad_left(text_pad_left); line_editor_params.revert_on_esc(false); line_editor_params.commit_callback.function(boost::bind(&LLUICtrl::onCommit, this)); line_editor_params.keystroke_callback(boost::bind(&LLSearchEditor::handleKeystroke, this)); mSearchEditor = LLUICtrlFactory::create<LLLineEditor>(line_editor_params); mSearchEditor->setPassDelete(TRUE); addChild(mSearchEditor); if (p.search_button_visible) { // Set up search button. LLButton::Params srch_btn_params(p.search_button); srch_btn_params.name(std::string("search button")); srch_btn_params.rect(srch_btn_rect) ; srch_btn_params.follows.flags(FOLLOWS_LEFT|FOLLOWS_TOP); srch_btn_params.tab_stop(false); srch_btn_params.click_callback.function(boost::bind(&LLUICtrl::onCommit, this)); mSearchButton = LLUICtrlFactory::create<LLButton>(srch_btn_params); mSearchEditor->addChild(mSearchButton); } if (p.clear_button_visible) { // Set up clear button. LLButton::Params clr_btn_params(p.clear_button); clr_btn_params.name(std::string("clear button")); S32 clr_btn_top = clr_btn_params.rect.bottom + clr_btn_params.rect.height; S32 clr_btn_right = getRect().getWidth() - clr_btn_params.pad_right; S32 clr_btn_left = clr_btn_right - clr_btn_params.rect.width; LLRect clear_btn_rect(clr_btn_left, clr_btn_top, clr_btn_right, p.clear_button.rect.bottom); clr_btn_params.rect(clear_btn_rect) ; clr_btn_params.follows.flags(FOLLOWS_RIGHT|FOLLOWS_TOP); clr_btn_params.tab_stop(false); clr_btn_params.click_callback.function(boost::bind(&LLSearchEditor::onClearButtonClick, this, _2)); mClearButton = LLUICtrlFactory::create<LLButton>(clr_btn_params); mSearchEditor->addChild(mClearButton); } } //virtual void LLSearchEditor::draw() { if (mClearButton) mClearButton->setVisible(!mSearchEditor->getWText().empty()); LLUICtrl::draw(); } //virtual void LLSearchEditor::setValue(const LLSD& value ) { mSearchEditor->setValue(value); } //virtual LLSD LLSearchEditor::getValue() const { return mSearchEditor->getValue(); } //virtual BOOL LLSearchEditor::setTextArg( const std::string& key, const LLStringExplicit& text ) { return mSearchEditor->setTextArg(key, text); } //virtual BOOL LLSearchEditor::setLabelArg( const std::string& key, const LLStringExplicit& text ) { return mSearchEditor->setLabelArg(key, text); } //virtual void LLSearchEditor::setLabel( const LLStringExplicit &new_label ) { mSearchEditor->setLabel(new_label); } //virtual void LLSearchEditor::clear() { if (mSearchEditor) { mSearchEditor->clear(); } } //virtual void LLSearchEditor::setFocus( BOOL b ) { if (mSearchEditor) { mSearchEditor->setFocus(b); } } void LLSearchEditor::onClearButtonClick(const LLSD& data) { mSearchEditor->selectAll(); mSearchEditor->doDelete(); // force keystroke callback } void LLSearchEditor::handleKeystroke() { if (mKeystrokeCallback) { mKeystrokeCallback(this, getValue()); } } <|endoftext|>
<commit_before>/* * Copyright 2011 Marco Martin <mart@kde.org> * Copyright 2014 Aleix Pol Gonzalez <aleixpol@blue-systems.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, 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 Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "desktopicon.h" #include <QSGSimpleTextureNode> #include <qquickwindow.h> #include <QIcon> #include <QBitmap> #include <QSGTexture> #include <QDebug> #include <QSGSimpleTextureNode> #include <QSGTexture> #include <QSharedPointer> #include <QtQml> #include <QQuickImageProvider> #include <QGuiApplication> class ManagedTextureNode : public QSGSimpleTextureNode { Q_DISABLE_COPY(ManagedTextureNode) public: ManagedTextureNode(); void setTexture(QSharedPointer<QSGTexture> texture); private: QSharedPointer<QSGTexture> m_texture; }; ManagedTextureNode::ManagedTextureNode() {} void ManagedTextureNode::setTexture(QSharedPointer<QSGTexture> texture) { m_texture = texture; QSGSimpleTextureNode::setTexture(texture.data()); } typedef QHash<qint64, QHash<QWindow*, QWeakPointer<QSGTexture> > > TexturesCache; struct ImageTexturesCachePrivate { TexturesCache cache; }; class ImageTexturesCache { public: ImageTexturesCache(); ~ImageTexturesCache(); /** * @returns the texture for a given @p window and @p image. * * If an @p image id is the same as one already provided before, we won't create * a new texture and return a shared pointer to the existing texture. */ QSharedPointer<QSGTexture> loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options); QSharedPointer<QSGTexture> loadTexture(QQuickWindow *window, const QImage &image); private: QScopedPointer<ImageTexturesCachePrivate> d; }; ImageTexturesCache::ImageTexturesCache() : d(new ImageTexturesCachePrivate) { } ImageTexturesCache::~ImageTexturesCache() { } QSharedPointer<QSGTexture> ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options) { qint64 id = image.cacheKey(); QSharedPointer<QSGTexture> texture = d->cache.value(id).value(window).toStrongRef(); if (!texture) { auto cleanAndDelete = [this, window, id](QSGTexture* texture) { QHash<QWindow*, QWeakPointer<QSGTexture> >& textures = (d->cache)[id]; textures.remove(window); if (textures.isEmpty()) d->cache.remove(id); delete texture; }; texture = QSharedPointer<QSGTexture>(window->createTextureFromImage(image, options), cleanAndDelete); (d->cache)[id][window] = texture.toWeakRef(); } //if we have a cache in an atlas but our request cannot use an atlassed texture //create a new texture and use that //don't use removedFromAtlas() as that requires keeping a reference to the non atlased version if (!(options & QQuickWindow::TextureCanUseAtlas) && texture->isAtlasTexture()) { texture = QSharedPointer<QSGTexture>(window->createTextureFromImage(image, options)); } return texture; } QSharedPointer<QSGTexture> ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image) { return loadTexture(window, image, 0); } Q_GLOBAL_STATIC(ImageTexturesCache, s_iconImageCache) DesktopIcon::DesktopIcon(QQuickItem *parent) : QQuickItem(parent), m_smooth(false), m_changed(false), m_active(false), m_selected(false) { setFlag(ItemHasContents, true); } DesktopIcon::~DesktopIcon() { } void DesktopIcon::setSource(const QVariant &icon) { if (m_source == icon) { return; } m_source = icon; m_changed = true; update(); emit sourceChanged(); } QVariant DesktopIcon::source() const { return m_source; } void DesktopIcon::setEnabled(const bool enabled) { if (enabled == QQuickItem::isEnabled()) { return; } QQuickItem::setEnabled(enabled); m_changed = true; update(); emit enabledChanged(); } void DesktopIcon::setActive(const bool active) { if (active == m_active) { return; } m_active = active; m_changed = true; update(); emit activeChanged(); } bool DesktopIcon::active() const { return m_active; } bool DesktopIcon::valid() const { return !m_source.isNull(); } void DesktopIcon::setSelected(const bool selected) { if (selected == m_selected) { return; } m_selected = selected; m_changed = true; update(); emit selectedChanged(); } bool DesktopIcon::selected() const { return m_selected; } int DesktopIcon::implicitWidth() const { return 32; } int DesktopIcon::implicitHeight() const { return 32; } void DesktopIcon::setSmooth(const bool smooth) { if (smooth == m_smooth) { return; } m_smooth = smooth; m_changed = true; update(); emit smoothChanged(); } bool DesktopIcon::smooth() const { return m_smooth; } QSGNode* DesktopIcon::updatePaintNode(QSGNode* node, QQuickItem::UpdatePaintNodeData* /*data*/) { if (m_source.isNull()) { delete node; return Q_NULLPTR; } if (m_changed || node == 0) { QImage img; const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()); switch(m_source.type()){ case QVariant::Pixmap: img = m_source.value<QPixmap>().toImage(); break; case QVariant::Image: img = m_source.value<QImage>(); break; case QVariant::Bitmap: img = m_source.value<QBitmap>().toImage(); break; case QVariant::Icon: img = m_source.value<QIcon>().pixmap(size, iconMode(), QIcon::On).toImage(); break; case QVariant::String: img = findIcon(size); break; case QVariant::Brush: case QVariant::Color: //perhaps fill image instead? default: break; } if (img.isNull()){ img = QImage(size, QImage::Format_Alpha8); img.fill(Qt::transparent); } if (img.size() != size){ img = img.scaled(size, Qt::IgnoreAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation ); } m_changed = false; ManagedTextureNode* mNode = dynamic_cast<ManagedTextureNode*>(node); if (!mNode) { delete node; mNode = new ManagedTextureNode; } mNode->setTexture(s_iconImageCache->loadTexture(window(), img)); mNode->setRect(QRect(QPoint(0,0), QSize(width(), height()))); node = mNode; } return node; } void DesktopIcon::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { if (newGeometry.size() != oldGeometry.size()) { m_changed = true; update(); } QQuickItem::geometryChanged(newGeometry, oldGeometry); } void DesktopIcon::handleFinished(QNetworkAccessManager* qnam, QNetworkReply* reply) { if (reply->error() == QNetworkReply::NoError) { const QUrl possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!possibleRedirectUrl.isEmpty()) { const QUrl redirectUrl = reply->url().resolved(possibleRedirectUrl); if (redirectUrl == reply->url()) { // no infinite redirections thank you very much reply->deleteLater(); return; } reply->deleteLater(); QNetworkRequest request(possibleRedirectUrl); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); QNetworkReply* newReply = qnam->get(request); connect(newReply, &QNetworkReply::readyRead, this, [this, newReply](){ handleReadyRead(newReply); }); connect(newReply, &QNetworkReply::finished, this, [this, qnam, newReply](){ handleFinished(qnam, newReply); }); return; } } } void DesktopIcon::handleReadyRead(QNetworkReply* reply) { if (reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isNull()) { QByteArray data; do { data.append(reply->read(32768)); // Because we are in the main thread, this could be potentially very expensive, so let's not block qApp->processEvents(); } while(!reply->atEnd()); m_loadedImage = QImage::fromData(data); if (m_loadedImage.isNull()) { // broken image from data, inform the user of this with some useful broken-image thing... const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()); m_loadedImage = QIcon::fromTheme("unknown").pixmap(size, iconMode(), QIcon::On).toImage(); } m_changed = true; update(); } } QImage DesktopIcon::findIcon(const QSize &size) { QImage img; QString iconSource = m_source.toString(); if (iconSource.startsWith("image://")){ QUrl iconUrl(iconSource); QString iconProviderId = iconUrl.host(); QString iconId = iconUrl.path(); QSize actualSize; QQuickImageProvider* imageProvider = dynamic_cast<QQuickImageProvider*>( qmlEngine(this)->imageProvider(iconProviderId)); if (!imageProvider) return img; switch(imageProvider->imageType()){ case QQmlImageProviderBase::Image: img = imageProvider->requestImage(iconId, &actualSize, size); case QQmlImageProviderBase::Pixmap: img = imageProvider->requestPixmap(iconId, &actualSize, size).toImage(); case QQmlImageProviderBase::Texture: case QQmlImageProviderBase::Invalid: case QQmlImageProviderBase::ImageResponse: //will have to investigate this more break; } } else if(iconSource.startsWith("http://") || iconSource.startsWith("https://")) { if(!m_loadedImage.isNull()) { return m_loadedImage.scaled(size, Qt::KeepAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation ); } QQmlEngine* engine = qmlEngine(this); QNetworkAccessManager* qnam; if (engine && (qnam = qmlEngine(this)->networkAccessManager())) { QNetworkRequest request(m_source.toUrl()); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); QNetworkReply* reply = qnam->get(request); connect(reply, &QNetworkReply::readyRead, this, [this, reply](){ handleReadyRead(reply); }); connect(reply, &QNetworkReply::finished, this, [this, qnam, reply](){ handleFinished(qnam, reply); }); } // Temporary icon while we wait for the real image to load... img = QIcon::fromTheme("image-x-icon").pixmap(size, iconMode(), QIcon::On).toImage(); } else { if (iconSource.startsWith("qrc:/")){ iconSource = iconSource.mid(3); } QIcon icon(iconSource); if (icon.availableSizes().isEmpty()) { icon = QIcon::fromTheme(iconSource); } if (!icon.availableSizes().isEmpty()){ img = icon.pixmap(size, iconMode(), QIcon::On).toImage(); } } return img; } QIcon::Mode DesktopIcon::iconMode() const { if (!isEnabled()) { return QIcon::Disabled; } else if (m_selected) { return QIcon::Selected; } else if (m_active) { return QIcon::Active; } return QIcon::Normal; } <commit_msg>repaint when app palette changes<commit_after>/* * Copyright 2011 Marco Martin <mart@kde.org> * Copyright 2014 Aleix Pol Gonzalez <aleixpol@blue-systems.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, 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 Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "desktopicon.h" #include <QSGSimpleTextureNode> #include <qquickwindow.h> #include <QIcon> #include <QBitmap> #include <QSGTexture> #include <QDebug> #include <QSGSimpleTextureNode> #include <QSGTexture> #include <QSharedPointer> #include <QtQml> #include <QQuickImageProvider> #include <QGuiApplication> class ManagedTextureNode : public QSGSimpleTextureNode { Q_DISABLE_COPY(ManagedTextureNode) public: ManagedTextureNode(); void setTexture(QSharedPointer<QSGTexture> texture); private: QSharedPointer<QSGTexture> m_texture; }; ManagedTextureNode::ManagedTextureNode() {} void ManagedTextureNode::setTexture(QSharedPointer<QSGTexture> texture) { m_texture = texture; QSGSimpleTextureNode::setTexture(texture.data()); } typedef QHash<qint64, QHash<QWindow*, QWeakPointer<QSGTexture> > > TexturesCache; struct ImageTexturesCachePrivate { TexturesCache cache; }; class ImageTexturesCache { public: ImageTexturesCache(); ~ImageTexturesCache(); /** * @returns the texture for a given @p window and @p image. * * If an @p image id is the same as one already provided before, we won't create * a new texture and return a shared pointer to the existing texture. */ QSharedPointer<QSGTexture> loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options); QSharedPointer<QSGTexture> loadTexture(QQuickWindow *window, const QImage &image); private: QScopedPointer<ImageTexturesCachePrivate> d; }; ImageTexturesCache::ImageTexturesCache() : d(new ImageTexturesCachePrivate) { } ImageTexturesCache::~ImageTexturesCache() { } QSharedPointer<QSGTexture> ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options) { qint64 id = image.cacheKey(); QSharedPointer<QSGTexture> texture = d->cache.value(id).value(window).toStrongRef(); if (!texture) { auto cleanAndDelete = [this, window, id](QSGTexture* texture) { QHash<QWindow*, QWeakPointer<QSGTexture> >& textures = (d->cache)[id]; textures.remove(window); if (textures.isEmpty()) d->cache.remove(id); delete texture; }; texture = QSharedPointer<QSGTexture>(window->createTextureFromImage(image, options), cleanAndDelete); (d->cache)[id][window] = texture.toWeakRef(); } //if we have a cache in an atlas but our request cannot use an atlassed texture //create a new texture and use that //don't use removedFromAtlas() as that requires keeping a reference to the non atlased version if (!(options & QQuickWindow::TextureCanUseAtlas) && texture->isAtlasTexture()) { texture = QSharedPointer<QSGTexture>(window->createTextureFromImage(image, options)); } return texture; } QSharedPointer<QSGTexture> ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image) { return loadTexture(window, image, 0); } Q_GLOBAL_STATIC(ImageTexturesCache, s_iconImageCache) DesktopIcon::DesktopIcon(QQuickItem *parent) : QQuickItem(parent), m_smooth(false), m_changed(false), m_active(false), m_selected(false) { setFlag(ItemHasContents, true); connect(qApp, &QGuiApplication::paletteChanged, this, [this]() { m_changed = true; update(); }); } DesktopIcon::~DesktopIcon() { } void DesktopIcon::setSource(const QVariant &icon) { if (m_source == icon) { return; } m_source = icon; m_changed = true; update(); emit sourceChanged(); } QVariant DesktopIcon::source() const { return m_source; } void DesktopIcon::setEnabled(const bool enabled) { if (enabled == QQuickItem::isEnabled()) { return; } QQuickItem::setEnabled(enabled); m_changed = true; update(); emit enabledChanged(); } void DesktopIcon::setActive(const bool active) { if (active == m_active) { return; } m_active = active; m_changed = true; update(); emit activeChanged(); } bool DesktopIcon::active() const { return m_active; } bool DesktopIcon::valid() const { return !m_source.isNull(); } void DesktopIcon::setSelected(const bool selected) { if (selected == m_selected) { return; } m_selected = selected; m_changed = true; update(); emit selectedChanged(); } bool DesktopIcon::selected() const { return m_selected; } int DesktopIcon::implicitWidth() const { return 32; } int DesktopIcon::implicitHeight() const { return 32; } void DesktopIcon::setSmooth(const bool smooth) { if (smooth == m_smooth) { return; } m_smooth = smooth; m_changed = true; update(); emit smoothChanged(); } bool DesktopIcon::smooth() const { return m_smooth; } QSGNode* DesktopIcon::updatePaintNode(QSGNode* node, QQuickItem::UpdatePaintNodeData* /*data*/) { if (m_source.isNull()) { delete node; return Q_NULLPTR; } if (m_changed || node == 0) { QImage img; const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()); switch(m_source.type()){ case QVariant::Pixmap: img = m_source.value<QPixmap>().toImage(); break; case QVariant::Image: img = m_source.value<QImage>(); break; case QVariant::Bitmap: img = m_source.value<QBitmap>().toImage(); break; case QVariant::Icon: img = m_source.value<QIcon>().pixmap(size, iconMode(), QIcon::On).toImage(); break; case QVariant::String: img = findIcon(size); break; case QVariant::Brush: case QVariant::Color: //perhaps fill image instead? default: break; } if (img.isNull()){ img = QImage(size, QImage::Format_Alpha8); img.fill(Qt::transparent); } if (img.size() != size){ img = img.scaled(size, Qt::IgnoreAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation ); } m_changed = false; ManagedTextureNode* mNode = dynamic_cast<ManagedTextureNode*>(node); if (!mNode) { delete node; mNode = new ManagedTextureNode; } mNode->setTexture(s_iconImageCache->loadTexture(window(), img)); mNode->setRect(QRect(QPoint(0,0), QSize(width(), height()))); node = mNode; } return node; } void DesktopIcon::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { if (newGeometry.size() != oldGeometry.size()) { m_changed = true; update(); } QQuickItem::geometryChanged(newGeometry, oldGeometry); } void DesktopIcon::handleFinished(QNetworkAccessManager* qnam, QNetworkReply* reply) { if (reply->error() == QNetworkReply::NoError) { const QUrl possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!possibleRedirectUrl.isEmpty()) { const QUrl redirectUrl = reply->url().resolved(possibleRedirectUrl); if (redirectUrl == reply->url()) { // no infinite redirections thank you very much reply->deleteLater(); return; } reply->deleteLater(); QNetworkRequest request(possibleRedirectUrl); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); QNetworkReply* newReply = qnam->get(request); connect(newReply, &QNetworkReply::readyRead, this, [this, newReply](){ handleReadyRead(newReply); }); connect(newReply, &QNetworkReply::finished, this, [this, qnam, newReply](){ handleFinished(qnam, newReply); }); return; } } } void DesktopIcon::handleReadyRead(QNetworkReply* reply) { if (reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isNull()) { QByteArray data; do { data.append(reply->read(32768)); // Because we are in the main thread, this could be potentially very expensive, so let's not block qApp->processEvents(); } while(!reply->atEnd()); m_loadedImage = QImage::fromData(data); if (m_loadedImage.isNull()) { // broken image from data, inform the user of this with some useful broken-image thing... const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()); m_loadedImage = QIcon::fromTheme("unknown").pixmap(size, iconMode(), QIcon::On).toImage(); } m_changed = true; update(); } } QImage DesktopIcon::findIcon(const QSize &size) { QImage img; QString iconSource = m_source.toString(); if (iconSource.startsWith("image://")){ QUrl iconUrl(iconSource); QString iconProviderId = iconUrl.host(); QString iconId = iconUrl.path(); QSize actualSize; QQuickImageProvider* imageProvider = dynamic_cast<QQuickImageProvider*>( qmlEngine(this)->imageProvider(iconProviderId)); if (!imageProvider) return img; switch(imageProvider->imageType()){ case QQmlImageProviderBase::Image: img = imageProvider->requestImage(iconId, &actualSize, size); case QQmlImageProviderBase::Pixmap: img = imageProvider->requestPixmap(iconId, &actualSize, size).toImage(); case QQmlImageProviderBase::Texture: case QQmlImageProviderBase::Invalid: case QQmlImageProviderBase::ImageResponse: //will have to investigate this more break; } } else if(iconSource.startsWith("http://") || iconSource.startsWith("https://")) { if(!m_loadedImage.isNull()) { return m_loadedImage.scaled(size, Qt::KeepAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation ); } QQmlEngine* engine = qmlEngine(this); QNetworkAccessManager* qnam; if (engine && (qnam = qmlEngine(this)->networkAccessManager())) { QNetworkRequest request(m_source.toUrl()); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); QNetworkReply* reply = qnam->get(request); connect(reply, &QNetworkReply::readyRead, this, [this, reply](){ handleReadyRead(reply); }); connect(reply, &QNetworkReply::finished, this, [this, qnam, reply](){ handleFinished(qnam, reply); }); } // Temporary icon while we wait for the real image to load... img = QIcon::fromTheme("image-x-icon").pixmap(size, iconMode(), QIcon::On).toImage(); } else { if (iconSource.startsWith("qrc:/")){ iconSource = iconSource.mid(3); } QIcon icon(iconSource); if (icon.availableSizes().isEmpty()) { icon = QIcon::fromTheme(iconSource); } if (!icon.availableSizes().isEmpty()){ img = icon.pixmap(size, iconMode(), QIcon::On).toImage(); } } return img; } QIcon::Mode DesktopIcon::iconMode() const { if (!isEnabled()) { return QIcon::Disabled; } else if (m_selected) { return QIcon::Selected; } else if (m_active) { return QIcon::Active; } return QIcon::Normal; } <|endoftext|>
<commit_before>#include "Copy.h" namespace dale { namespace Operation { bool Copy(Context *ctx, Function *fn, ParseResult *pr, ParseResult *pr_ret) { /* If this is a setf function, then don't copy, even if it can * be done. This is because, if the setf function is (e.g.) * the same as the current function, you'll end up with * non-terminating recursion. It would be possible to limit * this to the same function only, but you could have mutual * recursion - it would be better for the author to do all of * this manually, rather than complicating things. */ pr->copyTo(pr_ret); if (fn->is_setf_fn) { return true; } if (pr->do_not_copy_with_setf) { return true; } /* If the parseresult has already been copied, then don't copy * it again (pointless). todo: if you are having copy etc. * problems, this is likely to be the issue. */ if (pr->freshly_copied) { return true; } std::vector<Type *> types; Type *copy_type = ctx->tr->getPointerType(pr->type); types.push_back(copy_type); types.push_back(copy_type); Function *over_setf = ctx->getFunction("setf-copy", &types, NULL, 0); if (!over_setf) { return true; } llvm::IRBuilder<> builder(pr->block); llvm::Value *new_ptr1 = llvm::cast<llvm::Value>( builder.CreateAlloca(ctx->toLLVMType(pr->type, NULL, false)) ); llvm::Value *new_ptr2 = llvm::cast<llvm::Value>( builder.CreateAlloca(ctx->toLLVMType(pr->type, NULL, false)) ); builder.CreateStore(pr->value, new_ptr2); std::vector<llvm::Value *> call_args; call_args.push_back(new_ptr1); call_args.push_back(new_ptr2); builder.CreateCall( over_setf->llvm_function, llvm::ArrayRef<llvm::Value*>(call_args)); llvm::Value *result = builder.CreateLoad(new_ptr1); pr_ret->set(pr->block, pr->type, result); pr_ret->freshly_copied = 1; return true; } } } <commit_msg>[master] tidying<commit_after>#include "Copy.h" namespace dale { namespace Operation { bool Copy(Context *ctx, Function *fn, ParseResult *pr, ParseResult *pr_ret) { pr->copyTo(pr_ret); /* If this is a setf function, then don't copy, even if it can be * done. This is because, if the setf function is (e.g.) the same * as the current function, there will be non-terminating * recursion. It would be possible to limit this to the same * function only, but you could have mutual recursion; it would be * better for the author to do all of this manually, rather than * complicating things. (It's very possible that this will change * in the future.) */ if (fn->is_setf_fn) { return true; } if (pr->do_not_copy_with_setf) { return true; } /* If the parse result has already been copied, then don't copy * it again, since there's no point. */ if (pr->freshly_copied) { return true; } Type *copy_type = ctx->tr->getPointerType(pr->type); std::vector<Type *> types; types.push_back(copy_type); types.push_back(copy_type); Function *over_setf = ctx->getFunction("setf-copy", &types, NULL, 0); if (!over_setf) { return true; } llvm::IRBuilder<> builder(pr->block); llvm::Type *llvm_pr_type = ctx->toLLVMType(pr->type, NULL, false); llvm::Value *result_ptr = llvm::cast<llvm::Value>(builder.CreateAlloca(llvm_pr_type)); llvm::Value *value_ptr = llvm::cast<llvm::Value>(builder.CreateAlloca(llvm_pr_type)); builder.CreateStore(pr->value, value_ptr); std::vector<llvm::Value *> call_args; call_args.push_back(result_ptr); call_args.push_back(value_ptr); builder.CreateCall( over_setf->llvm_function, llvm::ArrayRef<llvm::Value*>(call_args) ); llvm::Value *result = builder.CreateLoad(result_ptr); pr_ret->set(pr->block, pr->type, result); pr_ret->freshly_copied = 1; return true; } } } <|endoftext|>
<commit_before>9aa4fd2e-2747-11e6-9829-e0f84713e7b8<commit_msg>Stuff changed<commit_after>9adb5ea1-2747-11e6-bc21-e0f84713e7b8<|endoftext|>
<commit_before>#include<cmath> #include<exhaust.hpp> #include<lua_cmds.hpp> #include<eap_resources.hpp> exhaust::exhaust(std::string lua_file) : algorithm(lua_file) { } void exhaust::setup_algo_params() { try { algorithm::setup_algo_params(); m_nec_input = boost::format(eap::run_directory + "ind%09d"); } catch (...) { throw; } } void exhaust::run() { try { std::vector<position_ptr> placements; std::cout<<"***creating individuals\n"; recur_placements(placements, 0); evaluate(); std::sort(m_pop.begin(), m_pop.end(), eap::gain_fitness_sort); m_max_gain = m_pop.back()->m_gain_fitness; std::sort(m_pop.begin(), m_pop.end(), eap::coupling_fitness_sort); m_min_coup = m_pop.front()->m_coupling_fitness; m_max_coup = m_pop.back()->m_coupling_fitness + std::abs(m_min_coup); for (individual_ptr i_ind : m_pop) { i_ind->m_coupling_fitness += std::abs(m_min_coup); if (i_ind->m_coupling_fitness < 0) throw eap::InvalidStateException("Invalid coupling calculation\n"); i_ind->m_coupling_fitness /= m_max_coup; i_ind->m_gain_fitness /= m_max_gain; i_ind->m_fitness = cal_fitness(i_ind); } std::sort(m_pop.begin(), m_pop.end(), eap::fitness_sort); std::cout<<"best "<<m_pop[0]->m_fitness<<"\n"; save_norm(eap::run_directory); save_population(eap::run_directory, m_pop); save_best_nec(eap::run_directory, m_pop[0]); } catch (...) { throw; } } void exhaust::evaluate() { try { if (m_run_simulator) run_simulation(0); //argument doesn't signify anything here boost::format nec_output(eap::run_directory + "ind%09da%02d.out"); for (unsigned int i=0; i<m_pop.size(); ++i) { for (unsigned int j=0; j<m_ant_configs.size(); ++j) { evaluation_ptr p_eval(new evaluation); m_pop[i]->m_evals.push_back(p_eval); unsigned int read = read_radiation(str(nec_output % i % j), p_eval); if (read != (num_polar() * m_step_freq)) throw eap::InvalidStateException("Problem with output in " + str(nec_output % i % j)); m_pop[i]->m_one_ant_on_fitness.push_back(compare(m_free_inds[j]->m_evals[0], m_pop[i]->m_evals[j])); m_pop[i]->m_gain_fitness += m_pop[i]->m_one_ant_on_fitness[j]; } m_pop[i]->m_coupling_fitness = read_coupling(str(nec_output % i % m_ant_configs.size()), m_ant_configs.size()); if (m_pop[i]->m_coupling_fitness == 0.0f) throw eap::InvalidStateException("coupling bad\n"); m_pop[i]->m_fitness = cal_fitness(m_pop[i]); } } catch (...) { throw; } } void exhaust::run_simulation(unsigned int id) { try { std::cout<<"***running simulation for exhaustive\n"; std::string cmd("ls " + eap::run_directory + "*.nec | parallel -j+0 ./nec2++.exe -i {}"); system(cmd.c_str()); std::cout<<"***completed simulation for exhaustive\n"; } catch (...) { throw; } } void exhaust::recur_placements(std::vector<position_ptr> &placements, unsigned int i) { if(m_ant_configs.size() == placements.size()) { m_pop.push_back(create_individual(str(m_nec_input % m_pop.size())+"a%02d.nec", placements)); return; } for (unsigned int j=0; j<m_ant_configs[i]->m_positions.size(); j++) { if(!overlap(placements, m_ant_configs[i]->m_positions[j])) { placements.push_back(m_ant_configs[i]->m_positions[j]); recur_placements(placements, i+1); placements.pop_back(); } } } exhaust::~exhaust(void) { } <commit_msg>replacing ls since exhaustive fails for large files<commit_after>#include<cmath> #include<exhaust.hpp> #include<lua_cmds.hpp> #include<eap_resources.hpp> exhaust::exhaust(std::string lua_file) : algorithm(lua_file) { } void exhaust::setup_algo_params() { try { algorithm::setup_algo_params(); m_nec_input = boost::format(eap::run_directory + "ind%09d"); } catch (...) { throw; } } void exhaust::run() { try { std::vector<position_ptr> placements; std::cout<<"***creating individuals\n"; recur_placements(placements, 0); evaluate(); std::sort(m_pop.begin(), m_pop.end(), eap::gain_fitness_sort); m_max_gain = m_pop.back()->m_gain_fitness; std::sort(m_pop.begin(), m_pop.end(), eap::coupling_fitness_sort); m_min_coup = m_pop.front()->m_coupling_fitness; m_max_coup = m_pop.back()->m_coupling_fitness + std::abs(m_min_coup); for (individual_ptr i_ind : m_pop) { i_ind->m_coupling_fitness += std::abs(m_min_coup); if (i_ind->m_coupling_fitness < 0) throw eap::InvalidStateException("Invalid coupling calculation\n"); i_ind->m_coupling_fitness /= m_max_coup; i_ind->m_gain_fitness /= m_max_gain; i_ind->m_fitness = cal_fitness(i_ind); } std::sort(m_pop.begin(), m_pop.end(), eap::fitness_sort); std::cout<<"best "<<m_pop[0]->m_fitness<<"\n"; save_norm(eap::run_directory); save_population(eap::run_directory, m_pop); save_best_nec(eap::run_directory, m_pop[0]); } catch (...) { throw; } } void exhaust::evaluate() { try { if (m_run_simulator) run_simulation(0); //argument doesn't signify anything here boost::format nec_output(eap::run_directory + "ind%09da%02d.out"); for (unsigned int i=0; i<m_pop.size(); ++i) { for (unsigned int j=0; j<m_ant_configs.size(); ++j) { evaluation_ptr p_eval(new evaluation); m_pop[i]->m_evals.push_back(p_eval); unsigned int read = read_radiation(str(nec_output % i % j), p_eval); if (read != (num_polar() * m_step_freq)) throw eap::InvalidStateException("Problem with output in " + str(nec_output % i % j)); m_pop[i]->m_one_ant_on_fitness.push_back(compare(m_free_inds[j]->m_evals[0], m_pop[i]->m_evals[j])); m_pop[i]->m_gain_fitness += m_pop[i]->m_one_ant_on_fitness[j]; } m_pop[i]->m_coupling_fitness = read_coupling(str(nec_output % i % m_ant_configs.size()), m_ant_configs.size()); if (m_pop[i]->m_coupling_fitness == 0.0f) throw eap::InvalidStateException("coupling bad\n"); m_pop[i]->m_fitness = cal_fitness(m_pop[i]); } } catch (...) { throw; } } void exhaust::run_simulation(unsigned int id) { try { std::cout<<"***running simulation for exhaustive\n"; std::string cmd("find " + eap::run_directory + " -iname \"*.nec\" | parallel -j+0 ./nec2++.exe -i {}"); system(cmd.c_str()); std::cout<<"***completed simulation for exhaustive\n"; } catch (...) { throw; } } void exhaust::recur_placements(std::vector<position_ptr> &placements, unsigned int i) { if(m_ant_configs.size() == placements.size()) { m_pop.push_back(create_individual(str(m_nec_input % m_pop.size())+"a%02d.nec", placements)); return; } for (unsigned int j=0; j<m_ant_configs[i]->m_positions.size(); j++) { if(!overlap(placements, m_ant_configs[i]->m_positions[j])) { placements.push_back(m_ant_configs[i]->m_positions[j]); recur_placements(placements, i+1); placements.pop_back(); } } } exhaust::~exhaust(void) { } <|endoftext|>
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #ifndef PARASOLS_GUARD_GRAPH_GRAPH_HH #define PARASOLS_GUARD_GRAPH_GRAPH_HH 1 #include <vector> #include <string> #include <type_traits> #include <cstdint> namespace parasols { /** * A graph, with an adjaceny matrix representation. We only provide the * operations we actually need. * * Indices start at 0. */ class Graph { public: /** * The adjaceny matrix type. Shouldn't really be public, but we * snoop around inside it when doing message passing. */ using AdjacencyMatrix = std::vector<std::uint8_t>; private: int _size = 0; AdjacencyMatrix _adjacency; bool _add_one_for_output; /** * Return the appropriate offset into _adjacency for the edge (a, * b). */ auto _position(int a, int b) const -> AdjacencyMatrix::size_type; public: /** * \param initial_size can be 0, if resize() is called afterwards. * * \param add_one_for_output is true if the graph should be * displayed 1-indexed (this affects vertex_name, but vertex * numbers are still 0-indexed). */ Graph(int initial_size, bool add_one_for_output); Graph(const Graph &) = default; /** * Number of vertices. */ auto size() const -> int; /** * Change our size. Must be called before adding an edge, and must * not be called afterwards. */ auto resize(int size) -> void; /** * Add an edge from a to b (and from b to a). */ auto add_edge(int a, int b) -> void; /** * Are vertices a and b adjacent? */ auto adjacent(int a, int b) const -> bool; /** * What is the degree of a given vertex? */ auto degree(int a) const -> int; /** * Format a vertex for outputting. * * Some graphs are 0-indexed, some are 1-indexed. Some might even * have named vertices. This turns a vertex number (0, size - 1) * into a string for human consumption. */ auto vertex_name(int a) const -> std::string; /** * Turn a string name into a vertex number. * * Some graphs are 0-indexed, some are 1-indexed. Some might even * have named vertices. This turns a vertex name into a 0-indexed * integer. */ auto vertex_number(const std::string &) const -> int; /** * The adjaceny matrix. Shouldn't really be public, but we snoop * around inside it when doing message passing. */ auto adjaceny_matrix() -> AdjacencyMatrix & { return _adjacency; } /** * Add one for output? */ auto add_one_for_output() const -> bool { return _add_one_for_output; } }; enum class GraphOptions { None = 0, AllowLoops = 1 }; inline bool test(GraphOptions a, GraphOptions b) { return static_cast<std::underlying_type<GraphOptions>::type>(a) & static_cast<std::underlying_type<GraphOptions>::type>(b); } } #endif <commit_msg>Default ctor<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #ifndef PARASOLS_GUARD_GRAPH_GRAPH_HH #define PARASOLS_GUARD_GRAPH_GRAPH_HH 1 #include <vector> #include <string> #include <type_traits> #include <cstdint> namespace parasols { /** * A graph, with an adjaceny matrix representation. We only provide the * operations we actually need. * * Indices start at 0. */ class Graph { public: /** * The adjaceny matrix type. Shouldn't really be public, but we * snoop around inside it when doing message passing. */ using AdjacencyMatrix = std::vector<std::uint8_t>; private: int _size = 0; AdjacencyMatrix _adjacency; bool _add_one_for_output; /** * Return the appropriate offset into _adjacency for the edge (a, * b). */ auto _position(int a, int b) const -> AdjacencyMatrix::size_type; public: /** * \param initial_size can be 0, if resize() is called afterwards. * * \param add_one_for_output is true if the graph should be * displayed 1-indexed (this affects vertex_name, but vertex * numbers are still 0-indexed). */ Graph(int initial_size, bool add_one_for_output); Graph(const Graph &) = default; explicit Graph() = default; /** * Number of vertices. */ auto size() const -> int; /** * Change our size. Must be called before adding an edge, and must * not be called afterwards. */ auto resize(int size) -> void; /** * Add an edge from a to b (and from b to a). */ auto add_edge(int a, int b) -> void; /** * Are vertices a and b adjacent? */ auto adjacent(int a, int b) const -> bool; /** * What is the degree of a given vertex? */ auto degree(int a) const -> int; /** * Format a vertex for outputting. * * Some graphs are 0-indexed, some are 1-indexed. Some might even * have named vertices. This turns a vertex number (0, size - 1) * into a string for human consumption. */ auto vertex_name(int a) const -> std::string; /** * Turn a string name into a vertex number. * * Some graphs are 0-indexed, some are 1-indexed. Some might even * have named vertices. This turns a vertex name into a 0-indexed * integer. */ auto vertex_number(const std::string &) const -> int; /** * The adjaceny matrix. Shouldn't really be public, but we snoop * around inside it when doing message passing. */ auto adjaceny_matrix() -> AdjacencyMatrix & { return _adjacency; } /** * Add one for output? */ auto add_one_for_output() const -> bool { return _add_one_for_output; } }; enum class GraphOptions { None = 0, AllowLoops = 1 }; inline bool test(GraphOptions a, GraphOptions b) { return static_cast<std::underlying_type<GraphOptions>::type>(a) & static_cast<std::underlying_type<GraphOptions>::type>(b); } } #endif <|endoftext|>
<commit_before>c74762e6-4b02-11e5-81ce-28cfe9171a43<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>c75857d7-4b02-11e5-91c6-28cfe9171a43<|endoftext|>
<commit_before>#include <iostream> #include <string> #include <stdexcept> #include <GL/glew.h> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <QApplication> #include <QMainWindow> #include <QMenu> #include <QAction> #include <QKeyEvent> #include <QHBoxLayout> #include <dependency_graph/graph.h> #include <dependency_graph/node_base.inl> #include <dependency_graph/datablock.inl> #include <dependency_graph/metadata.inl> #include <dependency_graph/attr.inl> #include <qt_node_editor/node.h> #include <qt_node_editor/connected_edge.h> #include <qt_node_editor/graph_widget.h> #include <possumwood_sdk/app.h> #include <possumwood_sdk/gl.h> #include "adaptor.h" #include "main_window.h" #include "gl_init.h" #include "common.h" namespace po = boost::program_options; using std::cout; using std::endl; using std::flush; int main(int argc, char* argv[]) { // // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("scene", po::value<std::string>(), "open a scene file") ; // process the options po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { cout << desc << "\n"; return 1; } /////////////////////////////// // create the possumwood application possumwood::App papp; { // load all plugins into an RAII container PluginsRAII plugins; GL_CHECK_ERR; { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); // way higher than currently supported - will fall back to highest format.setVersion(6, 0); format.setProfile(QSurfaceFormat::CoreProfile); #ifndef NDEBUG format.setOption(QSurfaceFormat::DebugContext); #endif format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); QSurfaceFormat::setDefaultFormat(format); } // create the application object QApplication app(argc, argv); // nice scaling on High DPI displays is support in Qt 5.6+ #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif GL_CHECK_ERR; // make a main window MainWindow win; win.setWindowIcon(QIcon(":icons/app.png")); win.showMaximized(); GL_CHECK_ERR; std::cout << "OpenGL version supported by this platform is " << glGetString(GL_VERSION) << std::endl; GL_CHECK_ERR; // open the scene file, if specified on the command line if(vm.count("scene")) possumwood::App::instance().loadFile(boost::filesystem::path(vm["scene"].as<std::string>())); GL_CHECK_ERR; // and start the main application loop app.exec(); GL_CHECK_ERR; } return 0; } <commit_msg>Removed glut include from main.cpp to fix snap builds<commit_after>#include <iostream> #include <string> #include <stdexcept> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <QApplication> #include <QMainWindow> #include <QMenu> #include <QAction> #include <QKeyEvent> #include <QHBoxLayout> #include <dependency_graph/graph.h> #include <dependency_graph/node_base.inl> #include <dependency_graph/datablock.inl> #include <dependency_graph/metadata.inl> #include <dependency_graph/attr.inl> #include <qt_node_editor/node.h> #include <qt_node_editor/connected_edge.h> #include <qt_node_editor/graph_widget.h> #include <possumwood_sdk/app.h> #include <possumwood_sdk/gl.h> #include "adaptor.h" #include "main_window.h" #include "gl_init.h" #include "common.h" namespace po = boost::program_options; using std::cout; using std::endl; using std::flush; int main(int argc, char* argv[]) { // // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("scene", po::value<std::string>(), "open a scene file") ; // process the options po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { cout << desc << "\n"; return 1; } /////////////////////////////// // create the possumwood application possumwood::App papp; { // load all plugins into an RAII container PluginsRAII plugins; GL_CHECK_ERR; { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); // way higher than currently supported - will fall back to highest format.setVersion(6, 0); format.setProfile(QSurfaceFormat::CoreProfile); #ifndef NDEBUG format.setOption(QSurfaceFormat::DebugContext); #endif format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); QSurfaceFormat::setDefaultFormat(format); } // create the application object QApplication app(argc, argv); // nice scaling on High DPI displays is support in Qt 5.6+ #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif GL_CHECK_ERR; // make a main window MainWindow win; win.setWindowIcon(QIcon(":icons/app.png")); win.showMaximized(); GL_CHECK_ERR; std::cout << "OpenGL version supported by this platform is " << glGetString(GL_VERSION) << std::endl; GL_CHECK_ERR; // open the scene file, if specified on the command line if(vm.count("scene")) possumwood::App::instance().loadFile(boost::filesystem::path(vm["scene"].as<std::string>())); GL_CHECK_ERR; // and start the main application loop app.exec(); GL_CHECK_ERR; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2010-2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2006 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: Ali Saidi */ #include "arch/arm/linux/atag.hh" #include "arch/arm/linux/system.hh" #include "arch/arm/isa_traits.hh" #include "arch/arm/utility.hh" #include "arch/generic/linux/threadinfo.hh" #include "base/loader/dtb_object.hh" #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "cpu/base.hh" #include "cpu/pc_event.hh" #include "cpu/thread_context.hh" #include "debug/Loader.hh" #include "kern/linux/events.hh" #include "mem/fs_translating_port_proxy.hh" #include "mem/physical.hh" #include "sim/stat_control.hh" using namespace ArmISA; using namespace Linux; LinuxArmSystem::LinuxArmSystem(Params *p) : ArmSystem(p), enableContextSwitchStatsDump(p->enable_context_switch_stats_dump), kernelPanicEvent(NULL), kernelOopsEvent(NULL) { if (p->panic_on_panic) { kernelPanicEvent = addKernelFuncEventOrPanic<PanicPCEvent>( "panic", "Kernel panic in simulated kernel"); } else { #ifndef NDEBUG kernelPanicEvent = addKernelFuncEventOrPanic<BreakPCEvent>("panic"); #endif } if (p->panic_on_oops) { kernelOopsEvent = addKernelFuncEventOrPanic<PanicPCEvent>( "oops_exit", "Kernel oops in guest"); } // With ARM udelay() is #defined to __udelay uDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>( "__udelay", "__udelay", 1000, 0); // constant arguments to udelay() have some precomputation done ahead of // time. Constant comes from code. constUDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>( "__const_udelay", "__const_udelay", 1000, 107374); secDataPtrAddr = 0; secDataAddr = 0; penReleaseAddr = 0; kernelSymtab->findAddress("__secondary_data", secDataPtrAddr); kernelSymtab->findAddress("secondary_data", secDataAddr); kernelSymtab->findAddress("pen_release", penReleaseAddr); secDataPtrAddr &= ~ULL(0x7F); secDataAddr &= ~ULL(0x7F); penReleaseAddr &= ~ULL(0x7F); } bool LinuxArmSystem::adderBootUncacheable(Addr a) { Addr block = a & ~ULL(0x7F); if (block == secDataPtrAddr || block == secDataAddr || block == penReleaseAddr) return true; return false; } void LinuxArmSystem::initState() { // Moved from the constructor to here since it relies on the // address map being resolved in the interconnect // Call the initialisation of the super class ArmSystem::initState(); // Load symbols at physical address, we might not want // to do this permanently, for but early bootup work // it is helpful. if (params()->early_kernel_symbols) { kernel->loadGlobalSymbols(kernelSymtab, loadAddrMask); kernel->loadGlobalSymbols(debugSymbolTable, loadAddrMask); } // Setup boot data structure Addr addr = 0; // Check if the kernel image has a symbol that tells us it supports // device trees. bool kernel_has_fdt_support = kernelSymtab->findAddress("unflatten_device_tree", addr); bool dtb_file_specified = params()->dtb_filename != ""; if (kernel_has_fdt_support && dtb_file_specified) { // Kernel supports flattened device tree and dtb file specified. // Using Device Tree Blob to describe system configuration. inform("Loading DTB file: %s\n", params()->dtb_filename); ObjectFile *dtb_file = createObjectFile(params()->dtb_filename, true); if (!dtb_file) { fatal("couldn't load DTB file: %s\n", params()->dtb_filename); } DtbObject *_dtb_file = dynamic_cast<DtbObject*>(dtb_file); if (_dtb_file) { if (!_dtb_file->addBootCmdLine(params()->boot_osflags.c_str(), params()->boot_osflags.size())) { warn("couldn't append bootargs to DTB file: %s\n", params()->dtb_filename); } } else { warn("dtb_file cast failed; couldn't append bootargs " "to DTB file: %s\n", params()->dtb_filename); } dtb_file->setTextBase(params()->atags_addr); dtb_file->loadSections(physProxy); delete dtb_file; } else { // Using ATAGS // Warn if the kernel supports FDT and we haven't specified one if (kernel_has_fdt_support) { assert(!dtb_file_specified); warn("Kernel supports device tree, but no DTB file specified\n"); } // Warn if the kernel doesn't support FDT and we have specified one if (dtb_file_specified) { assert(!kernel_has_fdt_support); warn("DTB file specified, but no device tree support in kernel\n"); } AtagCore ac; ac.flags(1); // read-only ac.pagesize(8192); ac.rootdev(0); AddrRangeList atagRanges = physmem.getConfAddrRanges(); if (atagRanges.size() != 1) { fatal("Expected a single ATAG memory entry but got %d\n", atagRanges.size()); } AtagMem am; am.memSize(atagRanges.begin()->size()); am.memStart(atagRanges.begin()->start()); AtagCmdline ad; ad.cmdline(params()->boot_osflags); DPRINTF(Loader, "boot command line %d bytes: %s\n", ad.size() <<2, params()->boot_osflags.c_str()); AtagNone an; uint32_t size = ac.size() + am.size() + ad.size() + an.size(); uint32_t offset = 0; uint8_t *boot_data = new uint8_t[size << 2]; offset += ac.copyOut(boot_data + offset); offset += am.copyOut(boot_data + offset); offset += ad.copyOut(boot_data + offset); offset += an.copyOut(boot_data + offset); DPRINTF(Loader, "Boot atags was %d bytes in total\n", size << 2); DDUMP(Loader, boot_data, size << 2); physProxy.writeBlob(params()->atags_addr, boot_data, size << 2); delete[] boot_data; } for (int i = 0; i < threadContexts.size(); i++) { threadContexts[i]->setIntReg(0, 0); threadContexts[i]->setIntReg(1, params()->machine_type); threadContexts[i]->setIntReg(2, params()->atags_addr); } } LinuxArmSystem::~LinuxArmSystem() { if (uDelaySkipEvent) delete uDelaySkipEvent; if (constUDelaySkipEvent) delete constUDelaySkipEvent; if (dumpStatsPCEvent) delete dumpStatsPCEvent; } LinuxArmSystem * LinuxArmSystemParams::create() { return new LinuxArmSystem(this); } void LinuxArmSystem::startup() { if (enableContextSwitchStatsDump) { dumpStatsPCEvent = addKernelFuncEvent<DumpStatsPCEvent>("__switch_to"); if (!dumpStatsPCEvent) panic("dumpStatsPCEvent not created!"); std::string task_filename = "tasks.txt"; taskFile = simout.create(name() + "." + task_filename); for (int i = 0; i < _numContexts; i++) { ThreadContext *tc = threadContexts[i]; uint32_t pid = tc->getCpuPtr()->getPid(); if (pid != Request::invldPid) { mapPid(tc, pid); tc->getCpuPtr()->taskId(taskMap[pid]); } } } } void LinuxArmSystem::mapPid(ThreadContext *tc, uint32_t pid) { // Create a new unique identifier for this pid std::map<uint32_t, uint32_t>::iterator itr = taskMap.find(pid); if (itr == taskMap.end()) { uint32_t map_size = taskMap.size(); if (map_size > ContextSwitchTaskId::MaxNormalTaskId + 1) { warn_once("Error out of identifiers for cache occupancy stats"); taskMap[pid] = ContextSwitchTaskId::Unknown; } else { taskMap[pid] = map_size; } } } /** This function is called whenever the the kernel function * "__switch_to" is called to change running tasks. * * r0 = task_struct of the previously running process * r1 = task_info of the previously running process * r2 = task_info of the next process to run */ void DumpStatsPCEvent::process(ThreadContext *tc) { Linux::ThreadInfo ti(tc); Addr task_descriptor = tc->readIntReg(2); uint32_t pid = ti.curTaskPID(task_descriptor); uint32_t tgid = ti.curTaskTGID(task_descriptor); std::string next_task_str = ti.curTaskName(task_descriptor); // Streamline treats pid == -1 as the kernel process. // Also pid == 0 implies idle process (except during Linux boot) int32_t mm = ti.curTaskMm(task_descriptor); bool is_kernel = (mm == 0); if (is_kernel && (pid != 0)) { pid = -1; tgid = -1; next_task_str = "kernel"; } LinuxArmSystem* sys = dynamic_cast<LinuxArmSystem *>(tc->getSystemPtr()); if (!sys) { panic("System is not LinuxArmSystem while getting Linux process info!"); } std::map<uint32_t, uint32_t>& taskMap = sys->taskMap; // Create a new unique identifier for this pid sys->mapPid(tc, pid); // Set cpu task id, output process info, and dump stats tc->getCpuPtr()->taskId(taskMap[pid]); tc->getCpuPtr()->setPid(pid); std::ostream* taskFile = sys->taskFile; // Task file is read by cache occupancy plotting script or // Streamline conversion script. ccprintf(*taskFile, "tick=%lld %d cpu_id=%d next_pid=%d next_tgid=%d next_task=%s\n", curTick(), taskMap[pid], tc->cpuId(), (int) pid, (int) tgid, next_task_str); taskFile->flush(); // Dump and reset statistics Stats::schedStatEvent(true, true, curTick(), 0); } <commit_msg>arm: Accomodate function name changes in newer linux kernels<commit_after>/* * Copyright (c) 2010-2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2006 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: Ali Saidi */ #include "arch/arm/linux/atag.hh" #include "arch/arm/linux/system.hh" #include "arch/arm/isa_traits.hh" #include "arch/arm/utility.hh" #include "arch/generic/linux/threadinfo.hh" #include "base/loader/dtb_object.hh" #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "cpu/base.hh" #include "cpu/pc_event.hh" #include "cpu/thread_context.hh" #include "debug/Loader.hh" #include "kern/linux/events.hh" #include "mem/fs_translating_port_proxy.hh" #include "mem/physical.hh" #include "sim/stat_control.hh" using namespace ArmISA; using namespace Linux; LinuxArmSystem::LinuxArmSystem(Params *p) : ArmSystem(p), enableContextSwitchStatsDump(p->enable_context_switch_stats_dump), kernelPanicEvent(NULL), kernelOopsEvent(NULL) { if (p->panic_on_panic) { kernelPanicEvent = addKernelFuncEventOrPanic<PanicPCEvent>( "panic", "Kernel panic in simulated kernel"); } else { #ifndef NDEBUG kernelPanicEvent = addKernelFuncEventOrPanic<BreakPCEvent>("panic"); #endif } if (p->panic_on_oops) { kernelOopsEvent = addKernelFuncEventOrPanic<PanicPCEvent>( "oops_exit", "Kernel oops in guest"); } // With ARM udelay() is #defined to __udelay // newer kernels use __loop_udelay and __loop_const_udelay symbols uDelaySkipEvent = addKernelFuncEvent<UDelayEvent>( "__loop_udelay", "__udelay", 1000, 0); if(!uDelaySkipEvent) uDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>( "__udelay", "__udelay", 1000, 0); // constant arguments to udelay() have some precomputation done ahead of // time. Constant comes from code. constUDelaySkipEvent = addKernelFuncEvent<UDelayEvent>( "__loop_const_udelay", "__const_udelay", 1000, 107374); if(!constUDelaySkipEvent) constUDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>( "__const_udelay", "__const_udelay", 1000, 107374); secDataPtrAddr = 0; secDataAddr = 0; penReleaseAddr = 0; kernelSymtab->findAddress("__secondary_data", secDataPtrAddr); kernelSymtab->findAddress("secondary_data", secDataAddr); kernelSymtab->findAddress("pen_release", penReleaseAddr); secDataPtrAddr &= ~ULL(0x7F); secDataAddr &= ~ULL(0x7F); penReleaseAddr &= ~ULL(0x7F); } bool LinuxArmSystem::adderBootUncacheable(Addr a) { Addr block = a & ~ULL(0x7F); if (block == secDataPtrAddr || block == secDataAddr || block == penReleaseAddr) return true; return false; } void LinuxArmSystem::initState() { // Moved from the constructor to here since it relies on the // address map being resolved in the interconnect // Call the initialisation of the super class ArmSystem::initState(); // Load symbols at physical address, we might not want // to do this permanently, for but early bootup work // it is helpful. if (params()->early_kernel_symbols) { kernel->loadGlobalSymbols(kernelSymtab, loadAddrMask); kernel->loadGlobalSymbols(debugSymbolTable, loadAddrMask); } // Setup boot data structure Addr addr = 0; // Check if the kernel image has a symbol that tells us it supports // device trees. bool kernel_has_fdt_support = kernelSymtab->findAddress("unflatten_device_tree", addr); bool dtb_file_specified = params()->dtb_filename != ""; if (kernel_has_fdt_support && dtb_file_specified) { // Kernel supports flattened device tree and dtb file specified. // Using Device Tree Blob to describe system configuration. inform("Loading DTB file: %s\n", params()->dtb_filename); ObjectFile *dtb_file = createObjectFile(params()->dtb_filename, true); if (!dtb_file) { fatal("couldn't load DTB file: %s\n", params()->dtb_filename); } DtbObject *_dtb_file = dynamic_cast<DtbObject*>(dtb_file); if (_dtb_file) { if (!_dtb_file->addBootCmdLine(params()->boot_osflags.c_str(), params()->boot_osflags.size())) { warn("couldn't append bootargs to DTB file: %s\n", params()->dtb_filename); } } else { warn("dtb_file cast failed; couldn't append bootargs " "to DTB file: %s\n", params()->dtb_filename); } dtb_file->setTextBase(params()->atags_addr); dtb_file->loadSections(physProxy); delete dtb_file; } else { // Using ATAGS // Warn if the kernel supports FDT and we haven't specified one if (kernel_has_fdt_support) { assert(!dtb_file_specified); warn("Kernel supports device tree, but no DTB file specified\n"); } // Warn if the kernel doesn't support FDT and we have specified one if (dtb_file_specified) { assert(!kernel_has_fdt_support); warn("DTB file specified, but no device tree support in kernel\n"); } AtagCore ac; ac.flags(1); // read-only ac.pagesize(8192); ac.rootdev(0); AddrRangeList atagRanges = physmem.getConfAddrRanges(); if (atagRanges.size() != 1) { fatal("Expected a single ATAG memory entry but got %d\n", atagRanges.size()); } AtagMem am; am.memSize(atagRanges.begin()->size()); am.memStart(atagRanges.begin()->start()); AtagCmdline ad; ad.cmdline(params()->boot_osflags); DPRINTF(Loader, "boot command line %d bytes: %s\n", ad.size() <<2, params()->boot_osflags.c_str()); AtagNone an; uint32_t size = ac.size() + am.size() + ad.size() + an.size(); uint32_t offset = 0; uint8_t *boot_data = new uint8_t[size << 2]; offset += ac.copyOut(boot_data + offset); offset += am.copyOut(boot_data + offset); offset += ad.copyOut(boot_data + offset); offset += an.copyOut(boot_data + offset); DPRINTF(Loader, "Boot atags was %d bytes in total\n", size << 2); DDUMP(Loader, boot_data, size << 2); physProxy.writeBlob(params()->atags_addr, boot_data, size << 2); delete[] boot_data; } for (int i = 0; i < threadContexts.size(); i++) { threadContexts[i]->setIntReg(0, 0); threadContexts[i]->setIntReg(1, params()->machine_type); threadContexts[i]->setIntReg(2, params()->atags_addr); } } LinuxArmSystem::~LinuxArmSystem() { if (uDelaySkipEvent) delete uDelaySkipEvent; if (constUDelaySkipEvent) delete constUDelaySkipEvent; if (dumpStatsPCEvent) delete dumpStatsPCEvent; } LinuxArmSystem * LinuxArmSystemParams::create() { return new LinuxArmSystem(this); } void LinuxArmSystem::startup() { if (enableContextSwitchStatsDump) { dumpStatsPCEvent = addKernelFuncEvent<DumpStatsPCEvent>("__switch_to"); if (!dumpStatsPCEvent) panic("dumpStatsPCEvent not created!"); std::string task_filename = "tasks.txt"; taskFile = simout.create(name() + "." + task_filename); for (int i = 0; i < _numContexts; i++) { ThreadContext *tc = threadContexts[i]; uint32_t pid = tc->getCpuPtr()->getPid(); if (pid != Request::invldPid) { mapPid(tc, pid); tc->getCpuPtr()->taskId(taskMap[pid]); } } } } void LinuxArmSystem::mapPid(ThreadContext *tc, uint32_t pid) { // Create a new unique identifier for this pid std::map<uint32_t, uint32_t>::iterator itr = taskMap.find(pid); if (itr == taskMap.end()) { uint32_t map_size = taskMap.size(); if (map_size > ContextSwitchTaskId::MaxNormalTaskId + 1) { warn_once("Error out of identifiers for cache occupancy stats"); taskMap[pid] = ContextSwitchTaskId::Unknown; } else { taskMap[pid] = map_size; } } } /** This function is called whenever the the kernel function * "__switch_to" is called to change running tasks. * * r0 = task_struct of the previously running process * r1 = task_info of the previously running process * r2 = task_info of the next process to run */ void DumpStatsPCEvent::process(ThreadContext *tc) { Linux::ThreadInfo ti(tc); Addr task_descriptor = tc->readIntReg(2); uint32_t pid = ti.curTaskPID(task_descriptor); uint32_t tgid = ti.curTaskTGID(task_descriptor); std::string next_task_str = ti.curTaskName(task_descriptor); // Streamline treats pid == -1 as the kernel process. // Also pid == 0 implies idle process (except during Linux boot) int32_t mm = ti.curTaskMm(task_descriptor); bool is_kernel = (mm == 0); if (is_kernel && (pid != 0)) { pid = -1; tgid = -1; next_task_str = "kernel"; } LinuxArmSystem* sys = dynamic_cast<LinuxArmSystem *>(tc->getSystemPtr()); if (!sys) { panic("System is not LinuxArmSystem while getting Linux process info!"); } std::map<uint32_t, uint32_t>& taskMap = sys->taskMap; // Create a new unique identifier for this pid sys->mapPid(tc, pid); // Set cpu task id, output process info, and dump stats tc->getCpuPtr()->taskId(taskMap[pid]); tc->getCpuPtr()->setPid(pid); std::ostream* taskFile = sys->taskFile; // Task file is read by cache occupancy plotting script or // Streamline conversion script. ccprintf(*taskFile, "tick=%lld %d cpu_id=%d next_pid=%d next_tgid=%d next_task=%s\n", curTick(), taskMap[pid], tc->cpuId(), (int) pid, (int) tgid, next_task_str); taskFile->flush(); // Dump and reset statistics Stats::schedStatEvent(true, true, curTick(), 0); } <|endoftext|>
<commit_before>#include <vector> #include <iostream> #include <SFML/Graphics.hpp> #include "Body.hpp" #define SIZE 6 #define BASE_LINE 2 // #define ACCEL 9.82 using namespace sf; using namespace std; bool operator!=(const Body& a, const Body& b); int main() { RenderWindow window(VideoMode(800, 600), ""); // Drawable elements vector<Body> planets; VertexArray line(Lines, 2); CircleShape base_line(BASE_LINE); // Logic vars Clock timer; float delta_t(0); bool running = true; bool is_placing = false; // Some inits line[0].color = Color::Blue; line[1].color = Color::Green; base_line.setFillColor(Color::Blue); while (running) { Event evt; while (window.pollEvent(evt)) { if (evt.type == Event::Closed) { running = false; } if (evt.type == Event::KeyPressed) { if (evt.key.code == Keyboard::Escape) { running = false; } } if (evt.type == Event::MouseButtonPressed) { is_placing = true; line[0].position = Vector2f(evt.mouseButton.x, evt.mouseButton.y); line[1].position = Vector2f(evt.mouseButton.x, evt.mouseButton.y); base_line.setPosition(evt.mouseButton.x - BASE_LINE, evt.mouseButton.y - BASE_LINE); } if (evt.type == Event::MouseMoved) { if (is_placing) { line[1].position = Vector2f(evt.mouseMove.x, evt.mouseMove.y); } } if (evt.type == Event::MouseButtonReleased) { if (is_placing) { Vector2f position(line[0].position.x - SIZE, line[0].position.y - SIZE); Body p(position, SIZE, line[1].position - line[0].position); cout << "New Body at: " << (line[1].position - line[0].position).x << ';' << (line[1].position - line[0].position).y << endl; planets.push_back(p); } is_placing = false; } } window.clear(); // Delta T delta_t = timer.restart().asSeconds(); // Vector Preview - wow - need an arrow if (is_placing) { window.draw(line); window.draw(base_line); } // Planets if (planets.size()) { for (Body& b : planets) { b.move(delta_t); } } if (planets.size() > 1) { for (unsigned int i = 0; i < planets.size(); i++) { for (unsigned int j = 0; j < planets.size();j++) { if (i != j) { planets[i].applyGravityOf(planets[j], delta_t); } } } } for (Body& b : planets) { b.draw(window); } window.display(); } return 0; } <commit_msg>Added keyboards toggles<commit_after>#include <vector> #include <iostream> #include <SFML/Graphics.hpp> #include "Body.hpp" #define MASS 10 #define BASE_LINE 2 using namespace sf; using namespace std; int main() { RenderWindow window(VideoMode(800, 600), "Gravity Simulation by Johan"); // Drawable elements vector<Body> planets; VertexArray line(Lines, 2); CircleShape base_line(BASE_LINE); // Logic vars Clock timer; float delta_t(0); int mass(MASS); bool running = true; bool is_placing = false; bool trace = false; // Some inits line[0].color = Color::Blue; line[1].color = Color::Green; base_line.setFillColor(Color::Blue); while (running) { Event evt; while (window.pollEvent(evt)) { if (evt.type == Event::Closed) { running = false; } if (evt.type == Event::KeyPressed) { if (evt.key.code == Keyboard::Escape) { running = false; } switch (evt.key.code) // TODO: +- mass; toggle "clear()"; pause; { case Keyboard::Add: mass += 100; break; case Keyboard::Subtract: mass -= 100; break; case Keyboard::T: trace = !trace; break; case Keyboard::Space: is_placing = false; break; default: break; } } if (evt.type == Event::MouseButtonPressed) { is_placing = true; line[0].position = Vector2f(evt.mouseButton.x, evt.mouseButton.y); line[1].position = Vector2f(evt.mouseButton.x, evt.mouseButton.y); base_line.setPosition(evt.mouseButton.x - BASE_LINE, evt.mouseButton.y - BASE_LINE); } if (evt.type == Event::MouseMoved) { if (is_placing) { line[1].position = Vector2f(evt.mouseMove.x, evt.mouseMove.y); } } if (evt.type == Event::MouseButtonReleased) { if (is_placing) { Vector2f position(line[0].position.x - MASS, line[0].position.y - MASS); Body p(position, MASS, line[1].position - line[0].position); // cout << "New Body at: " << (line[1].position - line[0].position).x << ';' // << (line[1].position - line[0].position).y << endl; planets.push_back(p); } is_placing = false; } } if (!trace) { window.clear(); } // Delta T delta_t = timer.restart().asSeconds(); // Vector Preview - wow - need an arrow - hard if (is_placing) { window.draw(line); window.draw(base_line); } // Planets if (planets.size()) { for (Body& b : planets) { b.move(delta_t); } } if (planets.size() > 1) { for (unsigned int i = 0; i < planets.size(); i++) { for (unsigned int j = 0; j < planets.size();j++) { if (i != j) { planets[i].applyGravityOf(planets[j], delta_t); } } } } for (Body& b : planets) { b.draw(window); } window.display(); } return 0; } <|endoftext|>
<commit_before>10828038-2e4f-11e5-b509-28cfe91dbc4b<commit_msg>1089e666-2e4f-11e5-bedc-28cfe91dbc4b<commit_after>1089e666-2e4f-11e5-bedc-28cfe91dbc4b<|endoftext|>
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "arch/io/event_watcher.hpp" #include "arch/runtime/thread_pool.hpp" linux_event_watcher_t::linux_event_watcher_t(fd_t f, linux_event_callback_t *eh) : fd(f), error_handler(eh), in_watcher(NULL), out_watcher(NULL), #ifdef __linux rdhup_watcher(NULL), #endif old_mask(0) { /* At first, only register for error events */ linux_thread_pool_t::thread->queue.watch_resource(fd, 0, this); } linux_event_watcher_t::~linux_event_watcher_t() { linux_thread_pool_t::thread->queue.forget_resource(fd, this); } linux_event_watcher_t::watch_t::watch_t(linux_event_watcher_t *p, int e) : parent(p), event(e) { rassert(!*parent->get_watch_slot(event), "something's already watching that event."); *parent->get_watch_slot(event) = this; parent->remask(); } linux_event_watcher_t::watch_t::~watch_t() { rassert(*parent->get_watch_slot(event) == this); *parent->get_watch_slot(event) = NULL; parent->remask(); } bool linux_event_watcher_t::is_watching(int event) { assert_thread(); return *get_watch_slot(event) == NULL; } linux_event_watcher_t::watch_t **linux_event_watcher_t::get_watch_slot(int event) { switch (event) { case poll_event_in: return &in_watcher; case poll_event_out: return &out_watcher; #ifdef __linux case poll_event_rdhup: return &rdhup_watcher; #endif default: crash("bad event"); } } void linux_event_watcher_t::remask() { int new_mask = 0; if (in_watcher) new_mask |= poll_event_in; if (out_watcher) new_mask |= poll_event_out; #ifdef __linux if (rdhup_watcher) new_mask |= poll_event_rdhup; #endif if (new_mask != old_mask) { linux_thread_pool_t::thread->queue.adjust_resource(fd, new_mask, this); } old_mask = new_mask; } void linux_event_watcher_t::on_event(int event) { int error_mask = poll_event_err | poll_event_hup; #ifdef __linux error_mask |= poll_event_rdhup; #endif guarantee((event & (error_mask | old_mask)) == event, "Unexpected event received (from operating system?)."); if (event & error_mask) { #ifdef __linux // TODO(OSX): Should we not call on_event(event & error_mask) in any case? if ((event & poll_event_rdhup) && rdhup_watcher) { if (!rdhup_watcher->is_pulsed()) rdhup_watcher->pulse(); } else { error_handler->on_event(event & error_mask); } #else error_handler->on_event(event & error_mask); #endif // __linux /* The error handler might have cancelled some watches, which would cause `remask()` to be run. We filter again to maintain the invariant that `event` only contains events that we are watching for. */ event &= old_mask; } if (event & poll_event_in) { rassert(in_watcher); if (!in_watcher->is_pulsed()) in_watcher->pulse(); } if (event & poll_event_out) { rassert(out_watcher); if (!out_watcher->is_pulsed()) out_watcher->pulse(); } } <commit_msg>Made linux event watcher treat (rdhup | X) eventmasks where (X & err) || (X & hup) as error instead of rdhup.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "arch/io/event_watcher.hpp" #include "arch/runtime/thread_pool.hpp" linux_event_watcher_t::linux_event_watcher_t(fd_t f, linux_event_callback_t *eh) : fd(f), error_handler(eh), in_watcher(NULL), out_watcher(NULL), #ifdef __linux rdhup_watcher(NULL), #endif old_mask(0) { /* At first, only register for error events */ linux_thread_pool_t::thread->queue.watch_resource(fd, 0, this); } linux_event_watcher_t::~linux_event_watcher_t() { linux_thread_pool_t::thread->queue.forget_resource(fd, this); } linux_event_watcher_t::watch_t::watch_t(linux_event_watcher_t *p, int e) : parent(p), event(e) { rassert(!*parent->get_watch_slot(event), "something's already watching that event."); *parent->get_watch_slot(event) = this; parent->remask(); } linux_event_watcher_t::watch_t::~watch_t() { rassert(*parent->get_watch_slot(event) == this); *parent->get_watch_slot(event) = NULL; parent->remask(); } bool linux_event_watcher_t::is_watching(int event) { assert_thread(); return *get_watch_slot(event) == NULL; } linux_event_watcher_t::watch_t **linux_event_watcher_t::get_watch_slot(int event) { switch (event) { case poll_event_in: return &in_watcher; case poll_event_out: return &out_watcher; #ifdef __linux case poll_event_rdhup: return &rdhup_watcher; #endif default: crash("bad event"); } } void linux_event_watcher_t::remask() { int new_mask = 0; if (in_watcher) new_mask |= poll_event_in; if (out_watcher) new_mask |= poll_event_out; #ifdef __linux if (rdhup_watcher) new_mask |= poll_event_rdhup; #endif if (new_mask != old_mask) { linux_thread_pool_t::thread->queue.adjust_resource(fd, new_mask, this); } old_mask = new_mask; } void linux_event_watcher_t::on_event(int event) { int error_mask = poll_event_err | poll_event_hup; #ifdef __linux error_mask |= poll_event_rdhup; #endif guarantee((event & (error_mask | old_mask)) == event, "Unexpected event received (from operating system?)."); if (event & error_mask) { #ifdef __linux if (event & ~poll_event_rdhup) { error_handler->on_event(event & error_mask); } else { rassert(event & poll_event_rdhup); if (!rdhup_watcher->is_pulsed()) rdhup_watcher->pulse(); } #else error_handler->on_event(event & error_mask); #endif // __linux /* The error handler might have cancelled some watches, which would cause `remask()` to be run. We filter again to maintain the invariant that `event` only contains events that we are watching for. */ event &= old_mask; } if (event & poll_event_in) { rassert(in_watcher); if (!in_watcher->is_pulsed()) in_watcher->pulse(); } if (event & poll_event_out) { rassert(out_watcher); if (!out_watcher->is_pulsed()) out_watcher->pulse(); } } <|endoftext|>
<commit_before>da0004fd-2e4e-11e5-826a-28cfe91dbc4b<commit_msg>da070a38-2e4e-11e5-b482-28cfe91dbc4b<commit_after>da070a38-2e4e-11e5-b482-28cfe91dbc4b<|endoftext|>
<commit_before>/* * Copyright (c) 2011 Google * 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 */ #ifndef __ARCH_RISCV_INTERRUPT_HH__ #define __ARCH_RISCV_INTERRUPT_HH__ #include <bitset> #include <memory> #include "arch/riscv/faults.hh" #include "arch/riscv/registers.hh" #include "base/logging.hh" #include "cpu/thread_context.hh" #include "debug/Interrupt.hh" #include "params/RiscvInterrupts.hh" #include "sim/sim_object.hh" class BaseCPU; class ThreadContext; namespace RiscvISA { /* * This is based on version 1.10 of the RISC-V privileged ISA reference, * chapter 3.1.14. */ class Interrupts : public SimObject { private: BaseCPU * cpu; std::bitset<NumInterruptTypes> ip; std::bitset<NumInterruptTypes> ie; public: typedef RiscvInterruptsParams Params; const Params * params() const { return dynamic_cast<const Params *>(_params); } Interrupts(Params * p) : SimObject(p), cpu(nullptr), ip(0), ie(0) {} void setCPU(BaseCPU * _cpu) { cpu = _cpu; } std::bitset<NumInterruptTypes> globalMask(ThreadContext *tc) const { INTERRUPT mask; STATUS status = tc->readMiscReg(MISCREG_STATUS); if (status.mie) mask.mei = mask.mti = mask.msi = 1; if (status.sie) mask.sei = mask.sti = mask.ssi = 1; if (status.uie) mask.uei = mask.uti = mask.usi = 1; return std::bitset<NumInterruptTypes>(mask); } bool checkInterrupt(int num) const { return ip[num] && ie[num]; } bool checkInterrupts(ThreadContext *tc) const { return (ip & ie & globalMask(tc)).any(); } Fault getInterrupt(ThreadContext *tc) const { assert(checkInterrupts(tc)); std::bitset<NumInterruptTypes> mask = globalMask(tc); for (int c = 0; c < NumInterruptTypes; c++) if (checkInterrupt(c) && mask[c]) return std::make_shared<InterruptFault>(c); return NoFault; } void updateIntrInfo(ThreadContext *tc) {} void post(int int_num, int index) { DPRINTF(Interrupt, "Interrupt %d:%d posted\n", int_num, index); ip[int_num] = true; } void clear(int int_num, int index) { DPRINTF(Interrupt, "Interrupt %d:%d cleared\n", int_num, index); ip[int_num] = false; } void clearAll() { DPRINTF(Interrupt, "All interrupts cleared\n"); ip = 0; } uint64_t readIP() const { return (uint64_t)ip.to_ulong(); } uint64_t readIE() const { return (uint64_t)ie.to_ulong(); } void setIP(const uint64_t& val) { ip = val; } void setIE(const uint64_t& val) { ie = val; } void serialize(CheckpointOut &cp) const { SERIALIZE_SCALAR(ip.to_ulong()); SERIALIZE_SCALAR(ie.to_ulong()); } void unserialize(CheckpointIn &cp) { long reg; UNSERIALIZE_SCALAR(reg); ip = reg; UNSERIALIZE_SCALAR(reg); ie = reg; } }; } // namespace RiscvISA #endif // __ARCH_RISCV_INTERRUPT_HH__ <commit_msg>arch-riscv: Initialize interrupt mask<commit_after>/* * Copyright (c) 2011 Google * 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 */ #ifndef __ARCH_RISCV_INTERRUPT_HH__ #define __ARCH_RISCV_INTERRUPT_HH__ #include <bitset> #include <memory> #include "arch/riscv/faults.hh" #include "arch/riscv/registers.hh" #include "base/logging.hh" #include "cpu/thread_context.hh" #include "debug/Interrupt.hh" #include "params/RiscvInterrupts.hh" #include "sim/sim_object.hh" class BaseCPU; class ThreadContext; namespace RiscvISA { /* * This is based on version 1.10 of the RISC-V privileged ISA reference, * chapter 3.1.14. */ class Interrupts : public SimObject { private: BaseCPU * cpu; std::bitset<NumInterruptTypes> ip; std::bitset<NumInterruptTypes> ie; public: typedef RiscvInterruptsParams Params; const Params * params() const { return dynamic_cast<const Params *>(_params); } Interrupts(Params * p) : SimObject(p), cpu(nullptr), ip(0), ie(0) {} void setCPU(BaseCPU * _cpu) { cpu = _cpu; } std::bitset<NumInterruptTypes> globalMask(ThreadContext *tc) const { INTERRUPT mask = 0; STATUS status = tc->readMiscReg(MISCREG_STATUS); if (status.mie) mask.mei = mask.mti = mask.msi = 1; if (status.sie) mask.sei = mask.sti = mask.ssi = 1; if (status.uie) mask.uei = mask.uti = mask.usi = 1; return std::bitset<NumInterruptTypes>(mask); } bool checkInterrupt(int num) const { return ip[num] && ie[num]; } bool checkInterrupts(ThreadContext *tc) const { return (ip & ie & globalMask(tc)).any(); } Fault getInterrupt(ThreadContext *tc) const { assert(checkInterrupts(tc)); std::bitset<NumInterruptTypes> mask = globalMask(tc); for (int c = 0; c < NumInterruptTypes; c++) if (checkInterrupt(c) && mask[c]) return std::make_shared<InterruptFault>(c); return NoFault; } void updateIntrInfo(ThreadContext *tc) {} void post(int int_num, int index) { DPRINTF(Interrupt, "Interrupt %d:%d posted\n", int_num, index); ip[int_num] = true; } void clear(int int_num, int index) { DPRINTF(Interrupt, "Interrupt %d:%d cleared\n", int_num, index); ip[int_num] = false; } void clearAll() { DPRINTF(Interrupt, "All interrupts cleared\n"); ip = 0; } uint64_t readIP() const { return (uint64_t)ip.to_ulong(); } uint64_t readIE() const { return (uint64_t)ie.to_ulong(); } void setIP(const uint64_t& val) { ip = val; } void setIE(const uint64_t& val) { ie = val; } void serialize(CheckpointOut &cp) const { SERIALIZE_SCALAR(ip.to_ulong()); SERIALIZE_SCALAR(ie.to_ulong()); } void unserialize(CheckpointIn &cp) { long reg; UNSERIALIZE_SCALAR(reg); ip = reg; UNSERIALIZE_SCALAR(reg); ie = reg; } }; } // namespace RiscvISA #endif // __ARCH_RISCV_INTERRUPT_HH__ <|endoftext|>
<commit_before>e41689eb-313a-11e5-ba23-3c15c2e10482<commit_msg>e41d6cbd-313a-11e5-9865-3c15c2e10482<commit_after>e41d6cbd-313a-11e5-9865-3c15c2e10482<|endoftext|>
<commit_before>2093fdf4-585b-11e5-ab9f-6c40088e03e4<commit_msg>209d34c8-585b-11e5-aa20-6c40088e03e4<commit_after>209d34c8-585b-11e5-aa20-6c40088e03e4<|endoftext|>
<commit_before>68a20e88-5216-11e5-a588-6c40088e03e4<commit_msg>68ab1c94-5216-11e5-88eb-6c40088e03e4<commit_after>68ab1c94-5216-11e5-88eb-6c40088e03e4<|endoftext|>
<commit_before>988ea114-35ca-11e5-8d44-6c40088e03e4<commit_msg>98956e9a-35ca-11e5-bc0b-6c40088e03e4<commit_after>98956e9a-35ca-11e5-bc0b-6c40088e03e4<|endoftext|>
<commit_before>//===-- RegisterScavenging.cpp - Machine register scavenging --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the machine register scavenger. It can provide // information, such as unused registers, at any point in a machine basic block. // It also provides a mechanism to make registers available by evicting them to // spill slots. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "reg-scavenging" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/STLExtras.h" using namespace llvm; /// setUsed - Set the register and its sub-registers as being used. void RegScavenger::setUsed(unsigned Reg) { RegsAvailable.reset(Reg); for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); unsigned SubReg = *SubRegs; ++SubRegs) RegsAvailable.reset(SubReg); } bool RegScavenger::isAliasUsed(unsigned Reg) const { if (isUsed(Reg)) return true; for (const unsigned *R = TRI->getAliasSet(Reg); *R; ++R) if (isUsed(*R)) return true; return false; } void RegScavenger::initRegState() { ScavengedReg = 0; ScavengedRC = NULL; ScavengeRestore = NULL; // All registers started out unused. RegsAvailable.set(); // Reserved registers are always used. RegsAvailable ^= ReservedRegs; if (!MBB) return; // Live-in registers are in use. for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(), E = MBB->livein_end(); I != E; ++I) setUsed(*I); // Pristine CSRs are also unavailable. BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB); for (int I = PR.find_first(); I>0; I = PR.find_next(I)) setUsed(I); } void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) { MachineFunction &MF = *mbb->getParent(); const TargetMachine &TM = MF.getTarget(); TII = TM.getInstrInfo(); TRI = TM.getRegisterInfo(); MRI = &MF.getRegInfo(); assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) && "Target changed?"); // Self-initialize. if (!MBB) { NumPhysRegs = TRI->getNumRegs(); RegsAvailable.resize(NumPhysRegs); // Create reserved registers bitvector. ReservedRegs = TRI->getReservedRegs(MF); // Create callee-saved registers bitvector. CalleeSavedRegs.resize(NumPhysRegs); const unsigned *CSRegs = TRI->getCalleeSavedRegs(); if (CSRegs != NULL) for (unsigned i = 0; CSRegs[i]; ++i) CalleeSavedRegs.set(CSRegs[i]); } MBB = mbb; initRegState(); Tracking = false; } void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) { BV.set(Reg); for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++) BV.set(*R); } void RegScavenger::addRegWithAliases(BitVector &BV, unsigned Reg) { BV.set(Reg); for (const unsigned *R = TRI->getAliasSet(Reg); *R; R++) BV.set(*R); } void RegScavenger::forward() { // Move ptr forward. if (!Tracking) { MBBI = MBB->begin(); Tracking = true; } else { assert(MBBI != MBB->end() && "Already past the end of the basic block!"); MBBI = llvm::next(MBBI); } assert(MBBI != MBB->end() && "Already at the end of the basic block!"); MachineInstr *MI = MBBI; if (MI == ScavengeRestore) { ScavengedReg = 0; ScavengedRC = NULL; ScavengeRestore = NULL; } if (MI->isDebugValue()) return; // Find out which registers are early clobbered, killed, defined, and marked // def-dead in this instruction. // FIXME: The scavenger is not predication aware. If the instruction is // predicated, conservatively assume "kill" markers do not actually kill the // register. Similarly ignores "dead" markers. bool isPred = TII->isPredicated(MI); BitVector EarlyClobberRegs(NumPhysRegs); BitVector KillRegs(NumPhysRegs); BitVector DefRegs(NumPhysRegs); BitVector DeadRegs(NumPhysRegs); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg || isReserved(Reg)) continue; if (MO.isUse()) { // Ignore undef uses. if (MO.isUndef()) continue; // Two-address operands implicitly kill. if (!isPred && (MO.isKill() || MI->isRegTiedToDefOperand(i))) addRegWithSubRegs(KillRegs, Reg); } else { assert(MO.isDef()); if (!isPred && MO.isDead()) addRegWithSubRegs(DeadRegs, Reg); else addRegWithSubRegs(DefRegs, Reg); if (MO.isEarlyClobber()) addRegWithAliases(EarlyClobberRegs, Reg); } } // Verify uses and defs. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (!MO.isReg() || MO.isUndef()) continue; unsigned Reg = MO.getReg(); if (!Reg || isReserved(Reg)) continue; if (MO.isUse()) { if (!isUsed(Reg)) { // Check if it's partial live: e.g. // D0 = insert_subreg D0<undef>, S0 // ... D0 // The problem is the insert_subreg could be eliminated. The use of // D0 is using a partially undef value. This is not *incorrect* since // S1 is can be freely clobbered. // Ideally we would like a way to model this, but leaving the // insert_subreg around causes both correctness and performance issues. bool SubUsed = false; for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); unsigned SubReg = *SubRegs; ++SubRegs) if (isUsed(SubReg)) { SubUsed = true; break; } assert(SubUsed && "Using an undefined register!"); } assert((!EarlyClobberRegs.test(Reg) || MI->isRegTiedToDefOperand(i)) && "Using an early clobbered register!"); } else { assert(MO.isDef()); #if 0 // FIXME: Enable this once we've figured out how to correctly transfer // implicit kills during codegen passes like the coalescer. assert((KillRegs.test(Reg) || isUnused(Reg) || isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) && "Re-defining a live register!"); #endif } } // Commit the changes. setUnused(KillRegs); setUnused(DeadRegs); setUsed(DefRegs); } void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) { if (includeReserved) used = ~RegsAvailable; else used = ~RegsAvailable & ~ReservedRegs; } unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const { for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E; ++I) if (!isAliasUsed(*I)) { DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) << "\n"); return *I; } return 0; } /// getRegsAvailable - Return all available registers in the register class /// in Mask. BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) { BitVector Mask(TRI->getNumRegs()); for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E; ++I) if (!isAliasUsed(*I)) Mask.set(*I); return Mask; } /// findSurvivorReg - Return the candidate register that is unused for the /// longest after StargMII. UseMI is set to the instruction where the search /// stopped. /// /// No more than InstrLimit instructions are inspected. /// unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI, BitVector &Candidates, unsigned InstrLimit, MachineBasicBlock::iterator &UseMI) { int Survivor = Candidates.find_first(); assert(Survivor > 0 && "No candidates for scavenging"); MachineBasicBlock::iterator ME = MBB->getFirstTerminator(); assert(StartMI != ME && "MI already at terminator"); MachineBasicBlock::iterator RestorePointMI = StartMI; MachineBasicBlock::iterator MI = StartMI; bool inVirtLiveRange = false; for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) { if (MI->isDebugValue()) { ++InstrLimit; // Don't count debug instructions continue; } bool isVirtKillInsn = false; bool isVirtDefInsn = false; // Remove any candidates touched by instruction. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (!MO.isReg() || MO.isUndef() || !MO.getReg()) continue; if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) { if (MO.isDef()) isVirtDefInsn = true; else if (MO.isKill()) isVirtKillInsn = true; continue; } Candidates.reset(MO.getReg()); for (const unsigned *R = TRI->getAliasSet(MO.getReg()); *R; R++) Candidates.reset(*R); } // If we're not in a virtual reg's live range, this is a valid // restore point. if (!inVirtLiveRange) RestorePointMI = MI; // Update whether we're in the live range of a virtual register if (isVirtKillInsn) inVirtLiveRange = false; if (isVirtDefInsn) inVirtLiveRange = true; // Was our survivor untouched by this instruction? if (Candidates.test(Survivor)) continue; // All candidates gone? if (Candidates.none()) break; Survivor = Candidates.find_first(); } // If we ran off the end, that's where we want to restore. if (MI == ME) RestorePointMI = ME; assert (RestorePointMI != StartMI && "No available scavenger restore location!"); // We ran out of candidates, so stop the search. UseMI = RestorePointMI; return Survivor; } unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC, MachineBasicBlock::iterator I, int SPAdj) { // Consider all allocatable registers in the register class initially BitVector Candidates = TRI->getAllocatableSet(*I->getParent()->getParent(), RC); // Exclude all the registers being used by the instruction. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { MachineOperand &MO = I->getOperand(i); if (MO.isReg() && MO.getReg() != 0 && !TargetRegisterInfo::isVirtualRegister(MO.getReg())) Candidates.reset(MO.getReg()); } // Try to find a register that's unused if there is one, as then we won't // have to spill. Search explicitly rather than masking out based on // RegsAvailable, as RegsAvailable does not take aliases into account. // That's what getRegsAvailable() is for. BitVector Available = getRegsAvailable(RC); if ((Candidates & Available).any()) Candidates &= Available; // Find the register whose use is furthest away. MachineBasicBlock::iterator UseMI; unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI); // If we found an unused register there is no reason to spill it. if (!isAliasUsed(SReg)) { DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n"); return SReg; } assert(ScavengedReg == 0 && "Scavenger slot is live, unable to scavenge another register!"); // Avoid infinite regress ScavengedReg = SReg; // If the target knows how to save/restore the register, let it do so; // otherwise, use the emergency stack spill slot. if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) { // Spill the scavenged register before I. assert(ScavengingFrameIndex >= 0 && "Cannot scavenge register without an emergency spill slot!"); TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI); MachineBasicBlock::iterator II = prior(I); TRI->eliminateFrameIndex(II, SPAdj, this); // Restore the scavenged register before its use (or first terminator). TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI); II = prior(UseMI); TRI->eliminateFrameIndex(II, SPAdj, this); } ScavengeRestore = prior(UseMI); // Doing this here leads to infinite regress. // ScavengedReg = SReg; ScavengedRC = RC; DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) << "\n"); return SReg; } <commit_msg>Handle <def,undef> in the second loop as well.<commit_after>//===-- RegisterScavenging.cpp - Machine register scavenging --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the machine register scavenger. It can provide // information, such as unused registers, at any point in a machine basic block. // It also provides a mechanism to make registers available by evicting them to // spill slots. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "reg-scavenging" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/STLExtras.h" using namespace llvm; /// setUsed - Set the register and its sub-registers as being used. void RegScavenger::setUsed(unsigned Reg) { RegsAvailable.reset(Reg); for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); unsigned SubReg = *SubRegs; ++SubRegs) RegsAvailable.reset(SubReg); } bool RegScavenger::isAliasUsed(unsigned Reg) const { if (isUsed(Reg)) return true; for (const unsigned *R = TRI->getAliasSet(Reg); *R; ++R) if (isUsed(*R)) return true; return false; } void RegScavenger::initRegState() { ScavengedReg = 0; ScavengedRC = NULL; ScavengeRestore = NULL; // All registers started out unused. RegsAvailable.set(); // Reserved registers are always used. RegsAvailable ^= ReservedRegs; if (!MBB) return; // Live-in registers are in use. for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(), E = MBB->livein_end(); I != E; ++I) setUsed(*I); // Pristine CSRs are also unavailable. BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB); for (int I = PR.find_first(); I>0; I = PR.find_next(I)) setUsed(I); } void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) { MachineFunction &MF = *mbb->getParent(); const TargetMachine &TM = MF.getTarget(); TII = TM.getInstrInfo(); TRI = TM.getRegisterInfo(); MRI = &MF.getRegInfo(); assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) && "Target changed?"); // Self-initialize. if (!MBB) { NumPhysRegs = TRI->getNumRegs(); RegsAvailable.resize(NumPhysRegs); // Create reserved registers bitvector. ReservedRegs = TRI->getReservedRegs(MF); // Create callee-saved registers bitvector. CalleeSavedRegs.resize(NumPhysRegs); const unsigned *CSRegs = TRI->getCalleeSavedRegs(); if (CSRegs != NULL) for (unsigned i = 0; CSRegs[i]; ++i) CalleeSavedRegs.set(CSRegs[i]); } MBB = mbb; initRegState(); Tracking = false; } void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) { BV.set(Reg); for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++) BV.set(*R); } void RegScavenger::addRegWithAliases(BitVector &BV, unsigned Reg) { BV.set(Reg); for (const unsigned *R = TRI->getAliasSet(Reg); *R; R++) BV.set(*R); } void RegScavenger::forward() { // Move ptr forward. if (!Tracking) { MBBI = MBB->begin(); Tracking = true; } else { assert(MBBI != MBB->end() && "Already past the end of the basic block!"); MBBI = llvm::next(MBBI); } assert(MBBI != MBB->end() && "Already at the end of the basic block!"); MachineInstr *MI = MBBI; if (MI == ScavengeRestore) { ScavengedReg = 0; ScavengedRC = NULL; ScavengeRestore = NULL; } if (MI->isDebugValue()) return; // Find out which registers are early clobbered, killed, defined, and marked // def-dead in this instruction. // FIXME: The scavenger is not predication aware. If the instruction is // predicated, conservatively assume "kill" markers do not actually kill the // register. Similarly ignores "dead" markers. bool isPred = TII->isPredicated(MI); BitVector EarlyClobberRegs(NumPhysRegs); BitVector KillRegs(NumPhysRegs); BitVector DefRegs(NumPhysRegs); BitVector DeadRegs(NumPhysRegs); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg || isReserved(Reg)) continue; if (MO.isUse()) { // Ignore undef uses. if (MO.isUndef()) continue; // Two-address operands implicitly kill. if (!isPred && (MO.isKill() || MI->isRegTiedToDefOperand(i))) addRegWithSubRegs(KillRegs, Reg); } else { assert(MO.isDef()); if (!isPred && MO.isDead()) addRegWithSubRegs(DeadRegs, Reg); else addRegWithSubRegs(DefRegs, Reg); if (MO.isEarlyClobber()) addRegWithAliases(EarlyClobberRegs, Reg); } } // Verify uses and defs. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg || isReserved(Reg)) continue; if (MO.isUse()) { if (MO.isUndef()) continue; if (!isUsed(Reg)) { // Check if it's partial live: e.g. // D0 = insert_subreg D0<undef>, S0 // ... D0 // The problem is the insert_subreg could be eliminated. The use of // D0 is using a partially undef value. This is not *incorrect* since // S1 is can be freely clobbered. // Ideally we would like a way to model this, but leaving the // insert_subreg around causes both correctness and performance issues. bool SubUsed = false; for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); unsigned SubReg = *SubRegs; ++SubRegs) if (isUsed(SubReg)) { SubUsed = true; break; } assert(SubUsed && "Using an undefined register!"); } assert((!EarlyClobberRegs.test(Reg) || MI->isRegTiedToDefOperand(i)) && "Using an early clobbered register!"); } else { assert(MO.isDef()); #if 0 // FIXME: Enable this once we've figured out how to correctly transfer // implicit kills during codegen passes like the coalescer. assert((KillRegs.test(Reg) || isUnused(Reg) || isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) && "Re-defining a live register!"); #endif } } // Commit the changes. setUnused(KillRegs); setUnused(DeadRegs); setUsed(DefRegs); } void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) { if (includeReserved) used = ~RegsAvailable; else used = ~RegsAvailable & ~ReservedRegs; } unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const { for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E; ++I) if (!isAliasUsed(*I)) { DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) << "\n"); return *I; } return 0; } /// getRegsAvailable - Return all available registers in the register class /// in Mask. BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) { BitVector Mask(TRI->getNumRegs()); for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E; ++I) if (!isAliasUsed(*I)) Mask.set(*I); return Mask; } /// findSurvivorReg - Return the candidate register that is unused for the /// longest after StargMII. UseMI is set to the instruction where the search /// stopped. /// /// No more than InstrLimit instructions are inspected. /// unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI, BitVector &Candidates, unsigned InstrLimit, MachineBasicBlock::iterator &UseMI) { int Survivor = Candidates.find_first(); assert(Survivor > 0 && "No candidates for scavenging"); MachineBasicBlock::iterator ME = MBB->getFirstTerminator(); assert(StartMI != ME && "MI already at terminator"); MachineBasicBlock::iterator RestorePointMI = StartMI; MachineBasicBlock::iterator MI = StartMI; bool inVirtLiveRange = false; for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) { if (MI->isDebugValue()) { ++InstrLimit; // Don't count debug instructions continue; } bool isVirtKillInsn = false; bool isVirtDefInsn = false; // Remove any candidates touched by instruction. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (!MO.isReg() || MO.isUndef() || !MO.getReg()) continue; if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) { if (MO.isDef()) isVirtDefInsn = true; else if (MO.isKill()) isVirtKillInsn = true; continue; } Candidates.reset(MO.getReg()); for (const unsigned *R = TRI->getAliasSet(MO.getReg()); *R; R++) Candidates.reset(*R); } // If we're not in a virtual reg's live range, this is a valid // restore point. if (!inVirtLiveRange) RestorePointMI = MI; // Update whether we're in the live range of a virtual register if (isVirtKillInsn) inVirtLiveRange = false; if (isVirtDefInsn) inVirtLiveRange = true; // Was our survivor untouched by this instruction? if (Candidates.test(Survivor)) continue; // All candidates gone? if (Candidates.none()) break; Survivor = Candidates.find_first(); } // If we ran off the end, that's where we want to restore. if (MI == ME) RestorePointMI = ME; assert (RestorePointMI != StartMI && "No available scavenger restore location!"); // We ran out of candidates, so stop the search. UseMI = RestorePointMI; return Survivor; } unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC, MachineBasicBlock::iterator I, int SPAdj) { // Consider all allocatable registers in the register class initially BitVector Candidates = TRI->getAllocatableSet(*I->getParent()->getParent(), RC); // Exclude all the registers being used by the instruction. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { MachineOperand &MO = I->getOperand(i); if (MO.isReg() && MO.getReg() != 0 && !TargetRegisterInfo::isVirtualRegister(MO.getReg())) Candidates.reset(MO.getReg()); } // Try to find a register that's unused if there is one, as then we won't // have to spill. Search explicitly rather than masking out based on // RegsAvailable, as RegsAvailable does not take aliases into account. // That's what getRegsAvailable() is for. BitVector Available = getRegsAvailable(RC); if ((Candidates & Available).any()) Candidates &= Available; // Find the register whose use is furthest away. MachineBasicBlock::iterator UseMI; unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI); // If we found an unused register there is no reason to spill it. if (!isAliasUsed(SReg)) { DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n"); return SReg; } assert(ScavengedReg == 0 && "Scavenger slot is live, unable to scavenge another register!"); // Avoid infinite regress ScavengedReg = SReg; // If the target knows how to save/restore the register, let it do so; // otherwise, use the emergency stack spill slot. if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) { // Spill the scavenged register before I. assert(ScavengingFrameIndex >= 0 && "Cannot scavenge register without an emergency spill slot!"); TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI); MachineBasicBlock::iterator II = prior(I); TRI->eliminateFrameIndex(II, SPAdj, this); // Restore the scavenged register before its use (or first terminator). TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI); II = prior(UseMI); TRI->eliminateFrameIndex(II, SPAdj, this); } ScavengeRestore = prior(UseMI); // Doing this here leads to infinite regress. // ScavengedReg = SReg; ScavengedRC = RC; DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) << "\n"); return SReg; } <|endoftext|>
<commit_before>fcbc2398-585a-11e5-a685-6c40088e03e4<commit_msg>fcc4f6ee-585a-11e5-8ac0-6c40088e03e4<commit_after>fcc4f6ee-585a-11e5-8ac0-6c40088e03e4<|endoftext|>
<commit_before>7473286e-5216-11e5-bad4-6c40088e03e4<commit_msg>7479c4a8-5216-11e5-95fe-6c40088e03e4<commit_after>7479c4a8-5216-11e5-95fe-6c40088e03e4<|endoftext|>
<commit_before>d570907e-35ca-11e5-b6f2-6c40088e03e4<commit_msg>d5775a12-35ca-11e5-87e4-6c40088e03e4<commit_after>d5775a12-35ca-11e5-87e4-6c40088e03e4<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtDeclarative 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 either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** 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.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qscriptvalueiterator.h" #include "qdebug.h" #include "qtimer.h" #include "qevent.h" #include "qdir.h" #include "qcoreapplication.h" #include "qfontdatabase.h" #include "qicon.h" #include "qurl.h" #include "qboxlayout.h" #include "qbasictimer.h" #include "qmlbindablevalue.h" #include "qml.h" #include "qfxitem.h" #include "qperformancelog.h" #include "qfxperf.h" #include "qfxview.h" #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcontext.h> #include <QtDeclarative/qmldebugger.h> QT_BEGIN_NAMESPACE DEFINE_BOOL_CONFIG_OPTION(itemTreeDump, ITEMTREE_DUMP); DEFINE_BOOL_CONFIG_OPTION(qmlDebugger, QML_DEBUGGER); static QVariant stringToPixmap(const QString &str) { //XXX need to use correct paths return QVariant(QPixmap(str)); } static QVariant stringToIcon(const QString &str) { //XXX need to use correct paths return QVariant(QIcon(str)); } static QVariant stringToKeySequence(const QString &str) { return QVariant::fromValue(QKeySequence(str)); } static QVariant stringToUrl(const QString &str) { return QVariant(QUrl(str)); } class QFxViewPrivate { public: QFxViewPrivate(QFxView *w) : q(w), root(0), component(0) {} QFxView *q; QFxItem *root; QUrl source; QString qml; QmlEngine engine; QmlComponent *component; QBasicTimer resizetimer; QSize initialSize; void init(); }; /*! \class QFxView \brief The QFxView class provides a widget for displaying a Qt Declarative user interface. QFxView currently provides a minimal interface for displaying QML files, and connecting between QML and C++ Qt objects. Typical usage: \code ... QFxView *view = new QFxView(this); vbox->addWidget(view); QUrl url(fileName); view->setUrl(url); ... view->execute(); ... \endcode */ /*! \fn QFxView::QFxView(QWidget *parent) Constructs a QFxView with the given \a parent. */ QFxView::QFxView(QWidget *parent) : QSimpleCanvas(parent), d(new QFxViewPrivate(this)) { setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); d->init(); } /*! \fn QFxView::QFxView(QSimpleCanvas::CanvasMode mode, QWidget *parent) \internal Constructs a QFxView with the given \a parent. The canvas \a mode can be QSimpleCanvas::GraphicsView or QSimpleCanvas::SimpleCanvas. */ QFxView::QFxView(QSimpleCanvas::CanvasMode mode, QWidget *parent) : QSimpleCanvas(mode, parent), d(new QFxViewPrivate(this)) { setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); d->init(); } void QFxViewPrivate::init() { // XXX: These need to be put in a central location for this kind of thing qRegisterMetaType<QFxAnchorLine>("QFxAnchorLine"); QmlMetaType::registerCustomStringConverter(QVariant::Pixmap, &stringToPixmap); QmlMetaType::registerCustomStringConverter(QVariant::Icon, &stringToIcon); QmlMetaType::registerCustomStringConverter(QVariant::KeySequence, &stringToKeySequence); QmlMetaType::registerCustomStringConverter(QVariant::Url, &stringToUrl); #ifdef Q_ENABLE_PERFORMANCE_LOG QFxPerfTimer<QFxPerf::FontDatabase> perf; #endif QFontDatabase database; } /*! The destructor clears the view's \l {QFxItem} {items} and deletes the internal representation. \sa clearItems() */ QFxView::~QFxView() { clearItems(); delete d; d = 0; } /*! Sets the source to the \a url. The QML string is set to empty. */ void QFxView::setUrl(const QUrl& url) { d->source = url; d->qml = QString(); } /*! Sets the source to the URL from the \a filename, and sets the QML string to \a qml. */ void QFxView::setQml(const QString &qml, const QString &filename) { d->source = QUrl::fromLocalFile(filename); d->qml = qml; } /*! Returns the QML string. */ QString QFxView::qml() const { return d->qml; } /*! Returns a pointer to the QmlEngine used for instantiating QML Components. */ QmlEngine* QFxView::engine() { return &d->engine; } /*! This function returns the root of the context hierarchy. Each QML component is instantiated in a QmlContext. QmlContext's are essential for passing data to QML components. In QML, contexts are arranged hierarchically and this hierarchy is managed by the QmlEngine. */ QmlContext* QFxView::rootContext() { return d->engine.rootContext(); } /*! Displays the Qt Declarative user interface. */ void QFxView::execute() { if (d->qml.isEmpty()) { d->component = new QmlComponent(&d->engine, d->source, this); } else { d->component = new QmlComponent(&d->engine, d->qml.toUtf8(), d->source); } if (!d->component->isLoading()) { continueExecute(); } else { connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute())); } } /*! \internal */ void QFxView::printErrorLine(const QmlError &error) { QUrl url = error.url(); if (error.line() > 0 && error.column() > 0 && url.scheme() == QLatin1String("file")) { QString file = url.toLocalFile(); QFile f(file); if (f.open(QIODevice::ReadOnly)) { QByteArray data = f.readAll(); QTextStream stream(data, QIODevice::ReadOnly); const QString code = stream.readAll(); const QStringList lines = code.split(QLatin1Char('\n')); if (lines.count() >= error.line()) { const QString &line = lines.at(error.line() - 1); qWarning() << qPrintable(line); int column = qMax(0, error.column() - 1); column = qMin(column, line.length()); QByteArray ind; ind.reserve(column); for (int i = 0; i < column; ++i) { const QChar ch = line.at(i); if (ch.isSpace()) ind.append(ch.unicode()); else ind.append(' '); } ind.append('^'); qWarning() << ind.constData(); } } } } /*! \internal */ void QFxView::continueExecute() { disconnect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute())); if (!d->component){ qWarning() << "Error in loading" << d->source; return; } if(d->component->isError()) { QList<QmlError> errors = d->component->errors(); foreach (const QmlError &error, errors) { qWarning() << error; } return; } QObject *obj = d->component->create(); if(d->component->isError()) { QList<QmlError> errors = d->component->errors(); foreach (const QmlError &error, errors) { qWarning() << error; } return; } if (obj) { if (QFxItem *item = qobject_cast<QFxItem *>(obj)) { item->QSimpleCanvasItem::setParent(QSimpleCanvas::root()); if (itemTreeDump()) item->dump(); if(qmlDebugger()) { QmlDebugger *debugger = new QmlDebugger; debugger->setDebugObject(item); debugger->setCanvas(this); debugger->show(); raise(); debugger->raise(); } QPerformanceLog::displayData(); QPerformanceLog::clear(); d->root = item; connect(item, SIGNAL(widthChanged()), this, SLOT(sizeChanged())); connect(item, SIGNAL(heightChanged()), this, SLOT(sizeChanged())); emit sceneResized(QSize(d->root->width(),d->root->height())); } else if (QWidget *wid = qobject_cast<QWidget *>(obj)) { window()->setAttribute(Qt::WA_OpaquePaintEvent, false); window()->setAttribute(Qt::WA_NoSystemBackground, false); if (!layout()) { setLayout(new QVBoxLayout); } else if (layout()->count()) { // Hide the QGraphicsView in GV mode. QLayoutItem *item = layout()->itemAt(0); if (item->widget()) item->widget()->hide(); } layout()->addWidget(wid); emit sceneResized(wid->size()); } } } /*! \fn void QFxView::sceneResized(QSize size) This signal is emitted when the view is resized to \a size. */ /*! \internal */ void QFxView::sizeChanged() { // delay, so we catch both width and height changing. d->resizetimer.start(0,this); } /*! If the \l {QTimerEvent} {timer event} \a e is this view's resize timer, sceneResized() is emitted. */ void QFxView::timerEvent(QTimerEvent* e) { if (e->timerId() == d->resizetimer.timerId()) { if (d->root) emit sceneResized(QSize(d->root->width(),d->root->height())); d->resizetimer.stop(); updateGeometry(); } } /*! The size hint is the size of the root item. */ QSize QFxView::sizeHint() const { if (!d->root) { if (d->initialSize.width() <= 0) d->initialSize.setWidth(d->root->width()); if (d->initialSize.height() <= 0) d->initialSize.setHeight(d->root->height()); } return d->initialSize; } /*! Creates a \l{QmlComponent} {component} from the \a qml string, and returns it as an \l {QFxItem} {item}. If the \a parent item is provided, it becomes the new item's parent. \a parent should be in this view's item hierarchy. */ QFxItem* QFxView::addItem(const QString &qml, QFxItem* parent) { if (!d->root) return 0; QmlComponent component(&d->engine, qml.toUtf8(), QUrl()); if(d->component->isError()) { QList<QmlError> errors = d->component->errors(); foreach (const QmlError &error, errors) { qWarning() << error; } return 0; } QObject *obj = component.create(); if(d->component->isError()) { QList<QmlError> errors = d->component->errors(); foreach (const QmlError &error, errors) { qWarning() << error; } return 0; } if (obj){ QFxItem *item = static_cast<QFxItem *>(obj); if (!parent) parent = d->root; item->setItemParent(parent); return item; } return 0; } /*! Deletes the view's \l {QFxItem} {items} and the \l {QmlEngine} {QML engine's} Component cache. */ void QFxView::reset() { clearItems(); d->engine.clearComponentCache(); } /*! Deletes the view's \l {QFxItem} {items}. */ void QFxView::clearItems() { if (!d->root) return; delete d->root; d->root = 0; } /*! Returns the view's root \l {QFxItem} {item}. */ QFxItem *QFxView::root() const { return d->root; } /*! This function handles the \l {QResizeEvent} {resize event} \a e. */ void QFxView::resizeEvent(QResizeEvent *e) { if (d->root) { d->root->setWidth(width()); d->root->setHeight(height()); } QSimpleCanvas::resizeEvent(e); } /*! \fn void QFxView::focusInEvent(QFocusEvent *e) This virtual function does nothing with the event \a e in this class. */ void QFxView::focusInEvent(QFocusEvent *) { // Do nothing (do not call QWidget::update()) } /*! \fn void QFxView::focusOutEvent(QFocusEvent *e) This virtual function does nothing with the event \a e in this class. */ void QFxView::focusOutEvent(QFocusEvent *) { // Do nothing (do not call QWidget::update()) } /*! \internal */ void QFxView::dumpRoot() { root()->dump(); } QT_END_NAMESPACE <commit_msg>fix bug 253385 fix<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtDeclarative 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 either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** 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.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qscriptvalueiterator.h" #include "qdebug.h" #include "qtimer.h" #include "qevent.h" #include "qdir.h" #include "qcoreapplication.h" #include "qfontdatabase.h" #include "qicon.h" #include "qurl.h" #include "qboxlayout.h" #include "qbasictimer.h" #include "qmlbindablevalue.h" #include "qml.h" #include "qfxitem.h" #include "qperformancelog.h" #include "qfxperf.h" #include "qfxview.h" #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcontext.h> #include <QtDeclarative/qmldebugger.h> QT_BEGIN_NAMESPACE DEFINE_BOOL_CONFIG_OPTION(itemTreeDump, ITEMTREE_DUMP); DEFINE_BOOL_CONFIG_OPTION(qmlDebugger, QML_DEBUGGER); static QVariant stringToPixmap(const QString &str) { //XXX need to use correct paths return QVariant(QPixmap(str)); } static QVariant stringToIcon(const QString &str) { //XXX need to use correct paths return QVariant(QIcon(str)); } static QVariant stringToKeySequence(const QString &str) { return QVariant::fromValue(QKeySequence(str)); } static QVariant stringToUrl(const QString &str) { return QVariant(QUrl(str)); } class QFxViewPrivate { public: QFxViewPrivate(QFxView *w) : q(w), root(0), component(0) {} QFxView *q; QFxItem *root; QUrl source; QString qml; QmlEngine engine; QmlComponent *component; QBasicTimer resizetimer; QSize initialSize; void init(); }; /*! \class QFxView \brief The QFxView class provides a widget for displaying a Qt Declarative user interface. QFxView currently provides a minimal interface for displaying QML files, and connecting between QML and C++ Qt objects. Typical usage: \code ... QFxView *view = new QFxView(this); vbox->addWidget(view); QUrl url(fileName); view->setUrl(url); ... view->execute(); ... \endcode */ /*! \fn QFxView::QFxView(QWidget *parent) Constructs a QFxView with the given \a parent. */ QFxView::QFxView(QWidget *parent) : QSimpleCanvas(parent), d(new QFxViewPrivate(this)) { setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); d->init(); } /*! \fn QFxView::QFxView(QSimpleCanvas::CanvasMode mode, QWidget *parent) \internal Constructs a QFxView with the given \a parent. The canvas \a mode can be QSimpleCanvas::GraphicsView or QSimpleCanvas::SimpleCanvas. */ QFxView::QFxView(QSimpleCanvas::CanvasMode mode, QWidget *parent) : QSimpleCanvas(mode, parent), d(new QFxViewPrivate(this)) { setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); d->init(); } void QFxViewPrivate::init() { // XXX: These need to be put in a central location for this kind of thing qRegisterMetaType<QFxAnchorLine>("QFxAnchorLine"); QmlMetaType::registerCustomStringConverter(QVariant::Pixmap, &stringToPixmap); QmlMetaType::registerCustomStringConverter(QVariant::Icon, &stringToIcon); QmlMetaType::registerCustomStringConverter(QVariant::KeySequence, &stringToKeySequence); QmlMetaType::registerCustomStringConverter(QVariant::Url, &stringToUrl); #ifdef Q_ENABLE_PERFORMANCE_LOG QFxPerfTimer<QFxPerf::FontDatabase> perf; #endif QFontDatabase database; } /*! The destructor clears the view's \l {QFxItem} {items} and deletes the internal representation. \sa clearItems() */ QFxView::~QFxView() { clearItems(); delete d; d = 0; } /*! Sets the source to the \a url. The QML string is set to empty. */ void QFxView::setUrl(const QUrl& url) { d->source = url; d->qml = QString(); } /*! Sets the source to the URL from the \a filename, and sets the QML string to \a qml. */ void QFxView::setQml(const QString &qml, const QString &filename) { d->source = QUrl::fromLocalFile(filename); d->qml = qml; } /*! Returns the QML string. */ QString QFxView::qml() const { return d->qml; } /*! Returns a pointer to the QmlEngine used for instantiating QML Components. */ QmlEngine* QFxView::engine() { return &d->engine; } /*! This function returns the root of the context hierarchy. Each QML component is instantiated in a QmlContext. QmlContext's are essential for passing data to QML components. In QML, contexts are arranged hierarchically and this hierarchy is managed by the QmlEngine. */ QmlContext* QFxView::rootContext() { return d->engine.rootContext(); } /*! Displays the Qt Declarative user interface. */ void QFxView::execute() { if (d->qml.isEmpty()) { d->component = new QmlComponent(&d->engine, d->source, this); } else { d->component = new QmlComponent(&d->engine, d->qml.toUtf8(), d->source); } if (!d->component->isLoading()) { continueExecute(); } else { connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute())); } } /*! \internal */ void QFxView::printErrorLine(const QmlError &error) { QUrl url = error.url(); if (error.line() > 0 && error.column() > 0 && url.scheme() == QLatin1String("file")) { QString file = url.toLocalFile(); QFile f(file); if (f.open(QIODevice::ReadOnly)) { QByteArray data = f.readAll(); QTextStream stream(data, QIODevice::ReadOnly); const QString code = stream.readAll(); const QStringList lines = code.split(QLatin1Char('\n')); if (lines.count() >= error.line()) { const QString &line = lines.at(error.line() - 1); qWarning() << qPrintable(line); int column = qMax(0, error.column() - 1); column = qMin(column, line.length()); QByteArray ind; ind.reserve(column); for (int i = 0; i < column; ++i) { const QChar ch = line.at(i); if (ch.isSpace()) ind.append(ch.unicode()); else ind.append(' '); } ind.append('^'); qWarning() << ind.constData(); } } } } /*! \internal */ void QFxView::continueExecute() { disconnect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute())); if (!d->component){ qWarning() << "Error in loading" << d->source; return; } if(d->component->isError()) { QList<QmlError> errors = d->component->errors(); foreach (const QmlError &error, errors) { qWarning() << error; } return; } QObject *obj = d->component->create(); if(d->component->isError()) { QList<QmlError> errors = d->component->errors(); foreach (const QmlError &error, errors) { qWarning() << error; } return; } if (obj) { if (QFxItem *item = qobject_cast<QFxItem *>(obj)) { item->QSimpleCanvasItem::setParent(QSimpleCanvas::root()); if (itemTreeDump()) item->dump(); if(qmlDebugger()) { QmlDebugger *debugger = new QmlDebugger; debugger->setDebugObject(item); debugger->setCanvas(this); debugger->show(); raise(); debugger->raise(); } QPerformanceLog::displayData(); QPerformanceLog::clear(); d->root = item; connect(item, SIGNAL(widthChanged()), this, SLOT(sizeChanged())); connect(item, SIGNAL(heightChanged()), this, SLOT(sizeChanged())); emit sceneResized(QSize(d->root->width(),d->root->height())); } else if (QWidget *wid = qobject_cast<QWidget *>(obj)) { window()->setAttribute(Qt::WA_OpaquePaintEvent, false); window()->setAttribute(Qt::WA_NoSystemBackground, false); if (!layout()) { setLayout(new QVBoxLayout); } else if (layout()->count()) { // Hide the QGraphicsView in GV mode. QLayoutItem *item = layout()->itemAt(0); if (item->widget()) item->widget()->hide(); } layout()->addWidget(wid); emit sceneResized(wid->size()); } } } /*! \fn void QFxView::sceneResized(QSize size) This signal is emitted when the view is resized to \a size. */ /*! \internal */ void QFxView::sizeChanged() { // delay, so we catch both width and height changing. d->resizetimer.start(0,this); } /*! If the \l {QTimerEvent} {timer event} \a e is this view's resize timer, sceneResized() is emitted. */ void QFxView::timerEvent(QTimerEvent* e) { if (e->timerId() == d->resizetimer.timerId()) { if (d->root) emit sceneResized(QSize(d->root->width(),d->root->height())); d->resizetimer.stop(); updateGeometry(); } } /*! The size hint is the size of the root item. */ QSize QFxView::sizeHint() const { if (d->root) { if (d->initialSize.width() <= 0) d->initialSize.setWidth(d->root->width()); if (d->initialSize.height() <= 0) d->initialSize.setHeight(d->root->height()); } return d->initialSize; } /*! Creates a \l{QmlComponent} {component} from the \a qml string, and returns it as an \l {QFxItem} {item}. If the \a parent item is provided, it becomes the new item's parent. \a parent should be in this view's item hierarchy. */ QFxItem* QFxView::addItem(const QString &qml, QFxItem* parent) { if (!d->root) return 0; QmlComponent component(&d->engine, qml.toUtf8(), QUrl()); if(d->component->isError()) { QList<QmlError> errors = d->component->errors(); foreach (const QmlError &error, errors) { qWarning() << error; } return 0; } QObject *obj = component.create(); if(d->component->isError()) { QList<QmlError> errors = d->component->errors(); foreach (const QmlError &error, errors) { qWarning() << error; } return 0; } if (obj){ QFxItem *item = static_cast<QFxItem *>(obj); if (!parent) parent = d->root; item->setItemParent(parent); return item; } return 0; } /*! Deletes the view's \l {QFxItem} {items} and the \l {QmlEngine} {QML engine's} Component cache. */ void QFxView::reset() { clearItems(); d->engine.clearComponentCache(); } /*! Deletes the view's \l {QFxItem} {items}. */ void QFxView::clearItems() { if (!d->root) return; delete d->root; d->root = 0; } /*! Returns the view's root \l {QFxItem} {item}. */ QFxItem *QFxView::root() const { return d->root; } /*! This function handles the \l {QResizeEvent} {resize event} \a e. */ void QFxView::resizeEvent(QResizeEvent *e) { if (d->root) { d->root->setWidth(width()); d->root->setHeight(height()); } QSimpleCanvas::resizeEvent(e); } /*! \fn void QFxView::focusInEvent(QFocusEvent *e) This virtual function does nothing with the event \a e in this class. */ void QFxView::focusInEvent(QFocusEvent *) { // Do nothing (do not call QWidget::update()) } /*! \fn void QFxView::focusOutEvent(QFocusEvent *e) This virtual function does nothing with the event \a e in this class. */ void QFxView::focusOutEvent(QFocusEvent *) { // Do nothing (do not call QWidget::update()) } /*! \internal */ void QFxView::dumpRoot() { root()->dump(); } QT_END_NAMESPACE <|endoftext|>
<commit_before>/* * main.cpp * * Created on: Oct 13, 2017 * Author: austinhoffmann */ #include <iostream> #include <unordered_map> #include "./rapidXML/rapidxml_utils.hpp" #include "./rapidXML/rapidxml.hpp" #include "Object.h" #include "Room.h" #include "Container.hpp" #include <sstream> #include <iterator> #include "helper.hpp" int main(int argc, char* argv[]) { if(argc != 2) { std::cout << "Zork usage: ./Zork [filename]" << std::endl; return 0; } //create a c-string that will be parsed by rapidxml using the input file rapidxml::file<>ifile(argv[1]); //create a DOM model of the input file that is parsed rapidxml::xml_document<> doc; doc.parse<0>(ifile.data()); //create an unordered map to store all of our Room objects std::unordered_map<std::string, Room> roomMap; //Map node is the first child of the XML overall tree rapidxml::xml_node<>* mapNode = doc.first_node("map"); //Room creation rapidxml::xml_node<>* node = mapNode->first_node("room"); if(node == nullptr) { std::cout << "Could not find a valid room with the XML parser" <<std::endl; return 0; } //keep creating rooms while we have new ones while(node) { //create Room Room room(node); //Add room to unordered map roomMap.insert(std::make_pair(room.get_name(), room)); //Get next room node node = node->next_sibling("room"); } //End Room Creation //Container creation node = mapNode->first_node("container"); std::unordered_map<std::string, Container> containerMap; while(node) { Container container(node); containerMap.insert(std::make_pair(container.get_name(), container)); node = node->next_sibling("container"); } //End Container creation //Item creation node = mapNode->first_node("item"); std::unordered_map<std::string, Item> itemMap; while(node) { Item item(node); itemMap.insert(std::make_pair(item.get_name(), item)); node = node->next_sibling("item"); } //End item Creation //Create the player's inventory auto inventory = Container(); //END OF SETUP //START OF GAMEPLAY //Find the Entrance to start the game auto search = roomMap.find("Entrance"); auto currentRoom = search->second; std::cout << currentRoom.get_description() << std::endl; //Start game bool exit_condition = false; while(exit_condition == false) { //Get user input std::string input; std::getline(std::cin, input); //n, s, e, w if(input == "n" || input == "s" || input == "e" || input == "w") { currentRoom = currentRoom.movement(input, roomMap); } //open exit else if(input == "open exit") { exit_condition = currentRoom.exit_check(); } //i else if(input == "i") { inventory.open_container(); } //open (container) else if(input.substr(0,4) == "open") { std::string containerName = input.substr(5); bool found = currentRoom.find_container(containerName); if(found) { auto containerSearch = containerMap.find(containerName); auto container = containerSearch->second; container.open_container(); } else { std::cout << "Error: that container is not in this room" << std::endl; } } //put (item) in (container) else if(input.substr(0,3) == "put") { std::istringstream iss{input}; std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; bool found = inventory.find_item(tokens[1]); if(found) { bool containerFound = currentRoom.find_container(tokens[3]); if(containerFound) { auto containerSearch = containerMap.find(tokens[3]); auto container = containerSearch->second; container.add_item(tokens[1]); //update container stored in the map for future lookup update_map<Container>(container, containerMap); inventory.remove_item(tokens[1]); std::cout << "Item " << tokens[1] << " added to " << tokens[3] << std::endl; } else { std::cout << "Error: that container is not in this room" << std::endl; } } else { std::cout << "Error: you dont have " << tokens[1] << " in your inventory" << std::endl; } } //take (item) else if(input.substr(0,4) == "take") { std::string itemName = input.substr(5); bool found = currentRoom.find_item(itemName, containerMap); if(found) { inventory.add_item(itemName); currentRoom.remove_item(itemName, containerMap); update_map<Room>(currentRoom, roomMap); std::cout << "Item " << itemName << " added to inventory" << std::endl; } else { std::cout << "Error: that item is not in the current room" << std::endl; } } else { std::cout << "Invalid Command" << std::endl; } } return 0; } <commit_msg>Add support for drop item<commit_after>/* * main.cpp * * Created on: Oct 13, 2017 * Author: austinhoffmann */ #include <iostream> #include <unordered_map> #include "./rapidXML/rapidxml_utils.hpp" #include "./rapidXML/rapidxml.hpp" #include "Object.h" #include "Room.h" #include "Container.hpp" #include <sstream> #include <iterator> #include "helper.hpp" int main(int argc, char* argv[]) { if(argc != 2) { std::cout << "Zork usage: ./Zork [filename]" << std::endl; return 0; } //create a c-string that will be parsed by rapidxml using the input file rapidxml::file<>ifile(argv[1]); //create a DOM model of the input file that is parsed rapidxml::xml_document<> doc; doc.parse<0>(ifile.data()); //create an unordered map to store all of our Room objects std::unordered_map<std::string, Room> roomMap; //Map node is the first child of the XML overall tree rapidxml::xml_node<>* mapNode = doc.first_node("map"); //Room creation rapidxml::xml_node<>* node = mapNode->first_node("room"); if(node == nullptr) { std::cout << "Could not find a valid room with the XML parser" <<std::endl; return 0; } //keep creating rooms while we have new ones while(node) { //create Room Room room(node); //Add room to unordered map roomMap.insert(std::make_pair(room.get_name(), room)); //Get next room node node = node->next_sibling("room"); } //End Room Creation //Container creation node = mapNode->first_node("container"); std::unordered_map<std::string, Container> containerMap; while(node) { Container container(node); containerMap.insert(std::make_pair(container.get_name(), container)); node = node->next_sibling("container"); } //End Container creation //Item creation node = mapNode->first_node("item"); std::unordered_map<std::string, Item> itemMap; while(node) { Item item(node); itemMap.insert(std::make_pair(item.get_name(), item)); node = node->next_sibling("item"); } //End item Creation //Create the player's inventory auto inventory = Container(); //END OF SETUP //START OF GAMEPLAY //Find the Entrance to start the game auto search = roomMap.find("Entrance"); auto currentRoom = search->second; std::cout << currentRoom.get_description() << std::endl; //Start game bool exit_condition = false; while(exit_condition == false) { //Get user input std::string input; std::getline(std::cin, input); //n, s, e, w if(input == "n" || input == "s" || input == "e" || input == "w") { currentRoom = currentRoom.movement(input, roomMap); } //open exit else if(input == "open exit") { exit_condition = currentRoom.exit_check(); } //i else if(input == "i") { inventory.open_container(); } //open (container) else if(input.substr(0,4) == "open" && input.size() > 5) { std::string containerName = input.substr(5); bool found = currentRoom.find_container(containerName); if(found) { auto containerSearch = containerMap.find(containerName); auto container = containerSearch->second; container.open_container(); } else { std::cout << "Error: that container is not in this room" << std::endl; } } //put (item) in (container) else if(input.substr(0,3) == "put" && input.size() > 3) { std::istringstream iss{input}; std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; if(tokens.size() == 4) { bool found = inventory.find_item(tokens[1]); if(found) { bool containerFound = currentRoom.find_container(tokens[3]); if(containerFound) { auto containerSearch = containerMap.find(tokens[3]); auto container = containerSearch->second; container.add_item(tokens[1]); //update container stored in the map for future lookup update_map<Container>(container, containerMap); inventory.remove_item(tokens[1]); std::cout << "Item " << tokens[1] << " added to " << tokens[3] << std::endl; } else { std::cout << "Error: that container is not in this room" << std::endl; } } else { std::cout << "Error: you dont have " << tokens[1] << " in your inventory" << std::endl; } } else { std::cout << "Invalid command" << std::endl; } } //take (item) else if(input.substr(0,4) == "take" && input.size() > 4) { std::string itemName = input.substr(5); bool found = currentRoom.find_item(itemName, containerMap); if(found) { inventory.add_item(itemName); currentRoom.remove_item(itemName, containerMap); update_map<Room>(currentRoom, roomMap); std::cout << "Item " << itemName << " added to inventory" << std::endl; } else { std::cout << "Error: that item is not in the current room" << std::endl; } } //drop (item) else if(input.substr(0,4) == "drop" && input.size() > 5) { std::string itemName = input.substr(5); bool found = inventory.find_item(itemName); if(found) { inventory.remove_item(itemName); currentRoom.add_item(itemName); update_map<Room>(currentRoom, roomMap); std::cout << itemName << " dropped" << std::endl; } else { std::cout << "Error: you do not have " << itemName << " in your inventory" << std::endl; } } else { std::cout << "Invalid Command" << std::endl; } } return 0; } <|endoftext|>
<commit_before>#include "job_evaluator.h" #include "job_exception.h" #include "../config/job_metadata.h" #include "../fileman/fallback_file_manager.h" #include "../fileman/prefixed_file_manager.h" #include "../helpers/config.h" job_evaluator::job_evaluator(std::shared_ptr<spdlog::logger> logger, std::shared_ptr<worker_config> config, std::shared_ptr<file_manager_interface> remote_fm, std::shared_ptr<file_manager_interface> cache_fm, fs::path working_directory, std::shared_ptr<progress_callback_interface> progr_callback) : working_directory_(working_directory), job_(nullptr), job_results_(), remote_fm_(remote_fm), cache_fm_(cache_fm), logger_(logger), config_(config), progress_callback_(progr_callback) { if (logger_ == nullptr) { logger_ = helpers::create_null_logger(); } init_progress_callback(); } void job_evaluator::init_progress_callback() { if (progress_callback_ == nullptr) { progress_callback_ = std::make_shared<empty_progress_callback>(); } } void job_evaluator::download_submission() { logger_->info("Trying to download submission archive..."); // create directory for downloaded archive fs::path archive_url = archive_url_; try { fs::create_directories(archive_path_); } catch (fs::filesystem_error &e) { throw job_exception(std::string("Cannot create archive directory for submission archives: ") + e.what()); } // download a file archive_name_ = archive_url.filename(); remote_fm_->get_file(archive_url.string(), (archive_path_ / archive_name_).string()); logger_->info("Submission archive downloaded succesfully."); progress_callback_->job_archive_downloaded(job_id_); return; } void job_evaluator::prepare_submission() { logger_->info("Preparing submission for usage..."); // decompress downloaded archive try { fs::create_directories(submission_path_); archivator::decompress((archive_path_ / archive_name_).string(), submission_path_.string()); } catch (archive_exception &e) { throw job_exception("Downloaded submission cannot be decompressed: " + std::string(e.what())); } // copy source codes to source code folder try { // stem().stem() is removing the .tar.bz2 ending (maybe working with just .zip ending too) fs::path tmp_path = submission_path_ / archive_name_.stem().stem(); // source_path_ is automaticaly created in copy_directory() helpers::copy_directory(tmp_path, source_path_); fs::permissions(source_path_, fs::add_perms | fs::group_write | fs::others_write); } catch (helpers::filesystem_exception &e) { throw job_exception("Error copying source files to source code path: " + std::string(e.what())); } try { fs::create_directories(results_path_); } catch (fs::filesystem_error &e) { throw job_exception("Result folder cannot be created: " + std::string(e.what())); } try { fs::create_directories(job_temp_dir_); } catch (fs::filesystem_error &e) { throw job_exception("Cannot create directories: " + std::string(e.what())); } logger_->info("Submission prepared."); return; } void job_evaluator::build_job() { namespace fs = boost::filesystem; logger_->info("Building job..."); // find job-config.yml to load configuration fs::path config_path(source_path_); config_path /= "job-config.yml"; if (!fs::exists(config_path)) { throw job_exception("Job configuration not found"); } // load configuration to object logger_->info("Loading job configuration from yaml..."); YAML::Node conf; try { conf = YAML::LoadFile(config_path.string()); } catch (YAML::Exception &e) { throw job_exception("Job configuration not loaded correctly: " + std::string(e.what())); } logger_->info("Yaml job configuration loaded properly."); // copy job config to results archive try { fs::copy_file(config_path, results_path_); } catch (fs::filesystem_error &e) { logger_->warn("Copying of job-config.yml file to results archive failed."); } // build job_metadata structure std::shared_ptr<job_metadata> job_meta = nullptr; try { job_meta = helpers::build_job_metadata(conf); } catch (helpers::config_exception &e) { throw job_unrecoverable_exception("Job configuration loading problem: " + std::string(e.what())); } // check job invariant, identifiers from broker and in configuration has to be the same if (job_id_ != job_meta->job_id) { throw job_unrecoverable_exception("Job identification from broker and in configuration are different"); } // construct manager which is used in task factory auto task_fileman = std::make_shared<fallback_file_manager>( cache_fm_, std::make_shared<prefixed_file_manager>(remote_fm_, job_meta->file_server_url + "/")); auto factory = std::make_shared<task_factory>(task_fileman); // ... and construct job itself job_ = std::make_shared<job>( job_meta, config_, job_temp_dir_, source_path_, results_path_, factory, progress_callback_); logger_->info("Job building done."); return; } void job_evaluator::run_job() { logger_->info("Ready for evaluation..."); job_results_ = job_->run(); logger_->info("Job evaluated."); } void job_evaluator::init_submission_paths() { source_path_ = working_directory_ / "eval" / std::to_string(config_->get_worker_id()) / job_id_; submission_path_ = working_directory_ / "submissions" / std::to_string(config_->get_worker_id()) / job_id_; archive_path_ = working_directory_ / "downloads" / std::to_string(config_->get_worker_id()) / job_id_; // set temporary directory for tasks in job job_temp_dir_ = working_directory_ / "temp" / std::to_string(config_->get_worker_id()) / job_id_; results_path_ = working_directory_ / "results" / std::to_string(config_->get_worker_id()) / job_id_; } void job_evaluator::cleanup_submission() { // cleanup source code directory after job evaluation try { if (fs::exists(source_path_)) { logger_->info("Cleaning up source code directory..."); fs::remove_all(source_path_); } } catch (fs::filesystem_error &e) { logger_->warn("Source code directory not cleaned properly: {}", e.what()); } // delete submission decompressed directory try { if (fs::exists(submission_path_)) { logger_->info("Cleaning up decompressed submission directory..."); fs::remove_all(submission_path_); } } catch (fs::filesystem_error &e) { logger_->warn("Submission directory not cleaned properly: {}", e.what()); } // delete downloaded archive directory try { if (fs::exists(archive_path_)) { logger_->info("Cleaning up directory containing downloaded archive..."); fs::remove_all(archive_path_); } } catch (fs::filesystem_error &e) { logger_->warn("Archive directory not cleaned properly: {}", e.what()); } // delete temp directory try { if (fs::exists(job_temp_dir_)) { logger_->info("Cleaning up temp directory for tasks..."); fs::remove_all(job_temp_dir_); } } catch (fs::filesystem_error &e) { logger_->warn("Temp directory not cleaned properly: {}", e.what()); } // and finally delete created results directory try { if (fs::exists(results_path_)) { logger_->info("Cleaning up directory containing created results..."); fs::remove_all(results_path_); } } catch (fs::filesystem_error &e) { logger_->warn("Results directory not cleaned properly: {}", e.what()); } return; } void job_evaluator::cleanup_variables() { try { archive_url_ = ""; archive_name_ = ""; archive_path_ = ""; submission_path_ = ""; source_path_ = ""; results_path_ = ""; result_url_ = ""; job_id_ = ""; job_ = nullptr; } catch (std::exception &e) { logger_->error("Error in deinicialization of evaluator: {}", e.what()); } } void job_evaluator::prepare_evaluator() { init_submission_paths(); cleanup_submission(); } void job_evaluator::cleanup_evaluator() { if (config_->get_cleanup_submission() == true) { cleanup_submission(); } cleanup_variables(); } void job_evaluator::push_result() { logger_->info("Trying to upload results of job..."); // just checkout for errors if (job_ == nullptr) { logger_->error("Pointer to job is null."); return; } // define path to result yaml file and archived result fs::path result_yaml = results_path_ / "result.yml"; fs::path archive_path = results_path_ / "result.zip"; logger_->info("Building yaml results file..."); // build yaml tree YAML::Node res; res["job-id"] = job_id_; res["hw-group"] = config_->get_hwgroup(); for (auto &i : job_results_) { YAML::Node node; node["task-id"] = i.first; switch (i.second->status) { case task_status::OK: node["status"] = "OK"; break; case task_status::FAILED: node["status"] = "FAILED"; break; case task_status::SKIPPED: node["status"] = "SKIPPED"; break; } if (!i.second->error_message.empty()) { node["error_message"] = i.second->error_message; } if (!i.second->output_stdout.empty() || !i.second->output_stderr.empty()) { YAML::Node output_node; if (!i.second->output_stdout.empty()) { output_node["stdout"] = i.second->output_stdout; } if (!i.second->output_stderr.empty()) { output_node["stderr"] = i.second->output_stderr; } node["output"] = output_node; } auto &sandbox = i.second->sandbox_status; if (sandbox != nullptr) { YAML::Node subnode; subnode["exitcode"] = sandbox->exitcode; subnode["time"] = sandbox->time; subnode["wall-time"] = sandbox->wall_time; subnode["memory"] = sandbox->memory; subnode["max-rss"] = sandbox->max_rss; switch (sandbox->status) { case isolate_status::OK: subnode["status"] = "OK"; break; case isolate_status::RE: subnode["status"] = "RE"; break; case isolate_status::SG: subnode["status"] = "SG"; break; case isolate_status::TO: subnode["status"] = "TO"; break; case isolate_status::XX: subnode["status"] = "XX"; break; } subnode["exitsig"] = sandbox->exitsig; subnode["killed"] = sandbox->killed; subnode["message"] = sandbox->message; subnode["csw-voluntary"] = sandbox->csw_voluntary; subnode["csw-forced"] = sandbox->csw_forced; node["sandbox_results"] = subnode; } res["results"].push_back(node); } // open output stream and write constructed yaml std::ofstream out(result_yaml.string()); out << res; out.close(); logger_->info("Yaml result file written succesfully."); // compress given result.yml file logger_->info("Compression of results file..."); try { archivator::compress(results_path_.string(), archive_path.string()); } catch (archive_exception &e) { logger_->error("Results file not archived properly: {}", e.what()); return; } logger_->info("Compression done."); // send archived result to file server remote_fm_->put_file(archive_path.string(), result_url_); logger_->info("Job results uploaded succesfully."); progress_callback_->job_results_uploaded(job_id_); return; } eval_response job_evaluator::evaluate(eval_request request) { logger_->info("Request for job evaluation arrived to worker"); logger_->info("Job ID of incoming job is: {}", request.job_id); // set all needed variables for evaluation job_id_ = request.job_id; archive_url_ = request.job_url; result_url_ = request.result_url; // prepare response which will be sent to broker eval_response_holder response(request.job_id, "OK"); prepare_evaluator(); try { download_submission(); prepare_submission(); build_job(); run_job(); push_result(); progress_callback_->job_finished(job_id_); } catch (job_unrecoverable_exception &e) { logger_->error("Job evaluator encountered unrecoverable error: {}", e.what()); progress_callback_->job_build_failed(job_id_); progress_callback_->job_finished(job_id_); response.set_result("FAILED", e.what()); } catch (std::exception &e) { logger_->error("Job evaluator encountered internal error: {}", e.what()); progress_callback_->job_aborted(job_id_); response.set_result("INTERNAL_ERROR", e.what()); } logger_->info("Job ({}) ended.", job_id_); cleanup_evaluator(); return response.get_eval_response(); } <commit_msg>Fix copying job-config to results<commit_after>#include "job_evaluator.h" #include "job_exception.h" #include "../config/job_metadata.h" #include "../fileman/fallback_file_manager.h" #include "../fileman/prefixed_file_manager.h" #include "../helpers/config.h" job_evaluator::job_evaluator(std::shared_ptr<spdlog::logger> logger, std::shared_ptr<worker_config> config, std::shared_ptr<file_manager_interface> remote_fm, std::shared_ptr<file_manager_interface> cache_fm, fs::path working_directory, std::shared_ptr<progress_callback_interface> progr_callback) : working_directory_(working_directory), job_(nullptr), job_results_(), remote_fm_(remote_fm), cache_fm_(cache_fm), logger_(logger), config_(config), progress_callback_(progr_callback) { if (logger_ == nullptr) { logger_ = helpers::create_null_logger(); } init_progress_callback(); } void job_evaluator::init_progress_callback() { if (progress_callback_ == nullptr) { progress_callback_ = std::make_shared<empty_progress_callback>(); } } void job_evaluator::download_submission() { logger_->info("Trying to download submission archive..."); // create directory for downloaded archive fs::path archive_url = archive_url_; try { fs::create_directories(archive_path_); } catch (fs::filesystem_error &e) { throw job_exception(std::string("Cannot create archive directory for submission archives: ") + e.what()); } // download a file archive_name_ = archive_url.filename(); remote_fm_->get_file(archive_url.string(), (archive_path_ / archive_name_).string()); logger_->info("Submission archive downloaded succesfully."); progress_callback_->job_archive_downloaded(job_id_); return; } void job_evaluator::prepare_submission() { logger_->info("Preparing submission for usage..."); // decompress downloaded archive try { fs::create_directories(submission_path_); archivator::decompress((archive_path_ / archive_name_).string(), submission_path_.string()); } catch (archive_exception &e) { throw job_exception("Downloaded submission cannot be decompressed: " + std::string(e.what())); } // copy source codes to source code folder try { // stem().stem() is removing the .tar.bz2 ending (maybe working with just .zip ending too) fs::path tmp_path = submission_path_ / archive_name_.stem().stem(); // source_path_ is automaticaly created in copy_directory() helpers::copy_directory(tmp_path, source_path_); fs::permissions(source_path_, fs::add_perms | fs::group_write | fs::others_write); } catch (helpers::filesystem_exception &e) { throw job_exception("Error copying source files to source code path: " + std::string(e.what())); } try { fs::create_directories(results_path_); } catch (fs::filesystem_error &e) { throw job_exception("Result folder cannot be created: " + std::string(e.what())); } try { fs::create_directories(job_temp_dir_); } catch (fs::filesystem_error &e) { throw job_exception("Cannot create directories: " + std::string(e.what())); } logger_->info("Submission prepared."); return; } void job_evaluator::build_job() { namespace fs = boost::filesystem; logger_->info("Building job..."); // find job-config.yml to load configuration fs::path config_path(source_path_); config_path /= "job-config.yml"; if (!fs::exists(config_path)) { throw job_exception("Job configuration not found"); } // load configuration to object logger_->info("Loading job configuration from yaml..."); YAML::Node conf; try { conf = YAML::LoadFile(config_path.string()); } catch (YAML::Exception &e) { throw job_exception("Job configuration not loaded correctly: " + std::string(e.what())); } logger_->info("Yaml job configuration loaded properly."); // copy job config to results archive try { fs::copy_file(config_path, (fs::path(results_path_) / fs::path("job-config.yml")).string()); } catch (fs::filesystem_error &e) { logger_->warn("Copying of job-config.yml file to results archive failed: {}", e.what()); } // build job_metadata structure std::shared_ptr<job_metadata> job_meta = nullptr; try { job_meta = helpers::build_job_metadata(conf); } catch (helpers::config_exception &e) { throw job_unrecoverable_exception("Job configuration loading problem: " + std::string(e.what())); } // check job invariant, identifiers from broker and in configuration has to be the same if (job_id_ != job_meta->job_id) { throw job_unrecoverable_exception("Job identification from broker and in configuration are different"); } // construct manager which is used in task factory auto task_fileman = std::make_shared<fallback_file_manager>( cache_fm_, std::make_shared<prefixed_file_manager>(remote_fm_, job_meta->file_server_url + "/")); auto factory = std::make_shared<task_factory>(task_fileman); // ... and construct job itself job_ = std::make_shared<job>( job_meta, config_, job_temp_dir_, source_path_, results_path_, factory, progress_callback_); logger_->info("Job building done."); return; } void job_evaluator::run_job() { logger_->info("Ready for evaluation..."); job_results_ = job_->run(); logger_->info("Job evaluated."); } void job_evaluator::init_submission_paths() { source_path_ = working_directory_ / "eval" / std::to_string(config_->get_worker_id()) / job_id_; submission_path_ = working_directory_ / "submissions" / std::to_string(config_->get_worker_id()) / job_id_; archive_path_ = working_directory_ / "downloads" / std::to_string(config_->get_worker_id()) / job_id_; // set temporary directory for tasks in job job_temp_dir_ = working_directory_ / "temp" / std::to_string(config_->get_worker_id()) / job_id_; results_path_ = working_directory_ / "results" / std::to_string(config_->get_worker_id()) / job_id_; } void job_evaluator::cleanup_submission() { // cleanup source code directory after job evaluation try { if (fs::exists(source_path_)) { logger_->info("Cleaning up source code directory..."); fs::remove_all(source_path_); } } catch (fs::filesystem_error &e) { logger_->warn("Source code directory not cleaned properly: {}", e.what()); } // delete submission decompressed directory try { if (fs::exists(submission_path_)) { logger_->info("Cleaning up decompressed submission directory..."); fs::remove_all(submission_path_); } } catch (fs::filesystem_error &e) { logger_->warn("Submission directory not cleaned properly: {}", e.what()); } // delete downloaded archive directory try { if (fs::exists(archive_path_)) { logger_->info("Cleaning up directory containing downloaded archive..."); fs::remove_all(archive_path_); } } catch (fs::filesystem_error &e) { logger_->warn("Archive directory not cleaned properly: {}", e.what()); } // delete temp directory try { if (fs::exists(job_temp_dir_)) { logger_->info("Cleaning up temp directory for tasks..."); fs::remove_all(job_temp_dir_); } } catch (fs::filesystem_error &e) { logger_->warn("Temp directory not cleaned properly: {}", e.what()); } // and finally delete created results directory try { if (fs::exists(results_path_)) { logger_->info("Cleaning up directory containing created results..."); fs::remove_all(results_path_); } } catch (fs::filesystem_error &e) { logger_->warn("Results directory not cleaned properly: {}", e.what()); } return; } void job_evaluator::cleanup_variables() { try { archive_url_ = ""; archive_name_ = ""; archive_path_ = ""; submission_path_ = ""; source_path_ = ""; results_path_ = ""; result_url_ = ""; job_id_ = ""; job_ = nullptr; } catch (std::exception &e) { logger_->error("Error in deinicialization of evaluator: {}", e.what()); } } void job_evaluator::prepare_evaluator() { init_submission_paths(); cleanup_submission(); } void job_evaluator::cleanup_evaluator() { if (config_->get_cleanup_submission() == true) { cleanup_submission(); } cleanup_variables(); } void job_evaluator::push_result() { logger_->info("Trying to upload results of job..."); // just checkout for errors if (job_ == nullptr) { logger_->error("Pointer to job is null."); return; } // define path to result yaml file and archived result fs::path result_yaml = results_path_ / "result.yml"; fs::path archive_path = results_path_ / "result.zip"; logger_->info("Building yaml results file..."); // build yaml tree YAML::Node res; res["job-id"] = job_id_; res["hw-group"] = config_->get_hwgroup(); for (auto &i : job_results_) { YAML::Node node; node["task-id"] = i.first; switch (i.second->status) { case task_status::OK: node["status"] = "OK"; break; case task_status::FAILED: node["status"] = "FAILED"; break; case task_status::SKIPPED: node["status"] = "SKIPPED"; break; } if (!i.second->error_message.empty()) { node["error_message"] = i.second->error_message; } if (!i.second->output_stdout.empty() || !i.second->output_stderr.empty()) { YAML::Node output_node; if (!i.second->output_stdout.empty()) { output_node["stdout"] = i.second->output_stdout; } if (!i.second->output_stderr.empty()) { output_node["stderr"] = i.second->output_stderr; } node["output"] = output_node; } auto &sandbox = i.second->sandbox_status; if (sandbox != nullptr) { YAML::Node subnode; subnode["exitcode"] = sandbox->exitcode; subnode["time"] = sandbox->time; subnode["wall-time"] = sandbox->wall_time; subnode["memory"] = sandbox->memory; subnode["max-rss"] = sandbox->max_rss; switch (sandbox->status) { case isolate_status::OK: subnode["status"] = "OK"; break; case isolate_status::RE: subnode["status"] = "RE"; break; case isolate_status::SG: subnode["status"] = "SG"; break; case isolate_status::TO: subnode["status"] = "TO"; break; case isolate_status::XX: subnode["status"] = "XX"; break; } subnode["exitsig"] = sandbox->exitsig; subnode["killed"] = sandbox->killed; subnode["message"] = sandbox->message; subnode["csw-voluntary"] = sandbox->csw_voluntary; subnode["csw-forced"] = sandbox->csw_forced; node["sandbox_results"] = subnode; } res["results"].push_back(node); } // open output stream and write constructed yaml std::ofstream out(result_yaml.string()); out << res; out.close(); logger_->info("Yaml result file written succesfully."); // compress given result.yml file logger_->info("Compression of results file..."); try { archivator::compress(results_path_.string(), archive_path.string()); } catch (archive_exception &e) { logger_->error("Results file not archived properly: {}", e.what()); return; } logger_->info("Compression done."); // send archived result to file server remote_fm_->put_file(archive_path.string(), result_url_); logger_->info("Job results uploaded succesfully."); progress_callback_->job_results_uploaded(job_id_); return; } eval_response job_evaluator::evaluate(eval_request request) { logger_->info("Request for job evaluation arrived to worker"); logger_->info("Job ID of incoming job is: {}", request.job_id); // set all needed variables for evaluation job_id_ = request.job_id; archive_url_ = request.job_url; result_url_ = request.result_url; // prepare response which will be sent to broker eval_response_holder response(request.job_id, "OK"); prepare_evaluator(); try { download_submission(); prepare_submission(); build_job(); run_job(); push_result(); progress_callback_->job_finished(job_id_); } catch (job_unrecoverable_exception &e) { logger_->error("Job evaluator encountered unrecoverable error: {}", e.what()); progress_callback_->job_build_failed(job_id_); progress_callback_->job_finished(job_id_); response.set_result("FAILED", e.what()); } catch (std::exception &e) { logger_->error("Job evaluator encountered internal error: {}", e.what()); progress_callback_->job_aborted(job_id_); response.set_result("INTERNAL_ERROR", e.what()); } logger_->info("Job ({}) ended.", job_id_); cleanup_evaluator(); return response.get_eval_response(); } <|endoftext|>
<commit_before>86936fd2-2d15-11e5-af21-0401358ea401<commit_msg>86936fd3-2d15-11e5-af21-0401358ea401<commit_after>86936fd3-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>6aeb67f4-2fa5-11e5-a6ed-00012e3d3f12<commit_msg>6aed3cb4-2fa5-11e5-9e93-00012e3d3f12<commit_after>6aed3cb4-2fa5-11e5-9e93-00012e3d3f12<|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id: ValuePrinter.cpp 46307 2012-10-04 06:53:23Z axel $ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/StoredValueRef.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/ValuePrinter.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclCXX.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Support/raw_ostream.h" using namespace cling; using namespace clang; using namespace llvm; StoredValueRef::StoredValue::StoredValue(Interpreter& interp, QualType clangTy, const llvm::Type* llvm_Ty) : Value(GenericValue(), clangTy, llvm_Ty), m_Interp(interp), m_Mem(0){ if (clangTy->isIntegralOrEnumerationType() || clangTy->isRealFloatingType() || clangTy->hasPointerRepresentation()) { return; }; if (const MemberPointerType* MPT = clangTy->getAs<MemberPointerType>()) { if (MPT->isMemberDataPointer()) { return; } } m_Mem = m_Buf; const uint64_t size = (uint64_t) getAllocSizeInBytes(); if (size > sizeof(m_Buf)) { m_Mem = new char[size]; } setGV(llvm::PTOGV(m_Mem)); } StoredValueRef::StoredValue::~StoredValue() { // Destruct the object, then delete the memory if needed. Destruct(); if (m_Mem != m_Buf) delete [] m_Mem; } void* StoredValueRef::StoredValue::GetDtorWrapperPtr(CXXRecordDecl* CXXRD) { std::string funcname; { llvm::raw_string_ostream namestr(funcname); namestr << "__cling_StoredValue_Destruct_" << CXXRD; } void* dtorWrapperPtr = m_Interp.getAddressOfGlobal(funcname.c_str()); if (dtorWrapperPtr) return dtorWrapperPtr; std::string code("extern \"C\" void "); std::string typeName = getClangType().getAsString(); code += funcname + "(void*obj){((" + typeName + "*)obj)->~" + typeName +"();}"; m_Interp.declare(code); return m_Interp.getAddressOfGlobal(funcname.c_str()); } void StoredValueRef::StoredValue::Destruct() { // If applicable, call addr->~Type() to destruct the object. // template <typename T> void destr(T* obj = 0) { (T)obj->~T(); } // |-FunctionDecl destr 'void (struct XB *)' // |-TemplateArgument type 'struct XB' // |-ParmVarDecl obj 'struct XB *' // `-CompoundStmt // `-CXXMemberCallExpr 'void' // `-MemberExpr '<bound member function type>' ->~XB // `-ImplicitCastExpr 'struct XB *' <LValueToRValue> // `-DeclRefExpr 'struct XB *' lvalue ParmVar 'obj' 'struct XB *' const RecordType* RT = dyn_cast<RecordType>(getClangType()); if (!RT) return; CXXRecordDecl* CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()); if (!CXXRD || CXXRD->hasTrivialDestructor()) return; CXXRD = CXXRD->getCanonicalDecl(); void* funcPtr = GetDtorWrapperPtr(CXXRD); if (!funcPtr) return; typedef void (*DtorWrapperFunc_t)(void* obj); DtorWrapperFunc_t wrapperFuncPtr = (DtorWrapperFunc_t) funcPtr; (*wrapperFuncPtr)(getAs<void*>()); } long long StoredValueRef::StoredValue::getAllocSizeInBytes() const { const ASTContext& ctx = m_Interp.getCI()->getASTContext(); return (long long) ctx.getTypeSizeInChars(getClangType()).getQuantity(); } void StoredValueRef::dump() const { ASTContext& ctx = m_Value->m_Interp.getCI()->getASTContext(); valuePrinterInternal::StreamStoredValueRef(llvm::errs(), this, ctx); } StoredValueRef StoredValueRef::allocate(Interpreter& interp, QualType t, const llvm::Type* llvmTy) { return new StoredValue(interp, t, llvmTy); } StoredValueRef StoredValueRef::bitwiseCopy(Interpreter& interp, const Value& value) { StoredValue* SValue = new StoredValue(interp, value.getClangType(), value.getLLVMType()); if (SValue->m_Mem) { const char* src = (const char*)value.getGV().PointerVal; // It's not a pointer. LLVM stores a char[5] (i.e. 5 x i8) as an i40, // so use that instead. We don't keep it as an int; instead, we "allocate" // it as a "proper" char[5] in the m_Mem. "Allocate" because it uses the // m_Buf, so no actual allocation happens. uint64_t IntVal = value.getGV().IntVal.getSExtValue(); if (!src) src = (const char*)&IntVal; memcpy(SValue->m_Mem, src, SValue->getAllocSizeInBytes()); } else { SValue->setGV(value.getGV()); } return SValue; } <commit_msg>Use TypeName::GetFullyQualifiedName; no dtor on const.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id: ValuePrinter.cpp 46307 2012-10-04 06:53:23Z axel $ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/StoredValueRef.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/ValuePrinter.h" #include "cling/Utils/AST.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclCXX.h" #include "clang/Frontend/CompilerInstance.h" using namespace cling; using namespace clang; using namespace llvm; StoredValueRef::StoredValue::StoredValue(Interpreter& interp, QualType clangTy, const llvm::Type* llvm_Ty) : Value(GenericValue(), clangTy, llvm_Ty), m_Interp(interp), m_Mem(0){ if (clangTy->isIntegralOrEnumerationType() || clangTy->isRealFloatingType() || clangTy->hasPointerRepresentation()) { return; }; if (const MemberPointerType* MPT = clangTy->getAs<MemberPointerType>()) { if (MPT->isMemberDataPointer()) { return; } } m_Mem = m_Buf; const uint64_t size = (uint64_t) getAllocSizeInBytes(); if (size > sizeof(m_Buf)) { m_Mem = new char[size]; } setGV(llvm::PTOGV(m_Mem)); } StoredValueRef::StoredValue::~StoredValue() { // Destruct the object, then delete the memory if needed. Destruct(); if (m_Mem != m_Buf) delete [] m_Mem; } void* StoredValueRef::StoredValue::GetDtorWrapperPtr(CXXRecordDecl* CXXRD) { std::string funcname; { llvm::raw_string_ostream namestr(funcname); namestr << "__cling_StoredValue_Destruct_" << CXXRD; } void* dtorWrapperPtr = m_Interp.getAddressOfGlobal(funcname.c_str()); if (dtorWrapperPtr) return dtorWrapperPtr; std::string code("extern \"C\" void "); std::string typeName = utils::TypeName::GetFullyQualifiedName(getClangType(), CXXRD->getASTContext()); code += funcname + "(void* obj){((" + typeName + "*)obj)->~" + typeName +"();}"; m_Interp.declare(code); return m_Interp.getAddressOfGlobal(funcname.c_str()); } void StoredValueRef::StoredValue::Destruct() { // If applicable, call addr->~Type() to destruct the object. // template <typename T> void destr(T* obj = 0) { (T)obj->~T(); } // |-FunctionDecl destr 'void (struct XB *)' // |-TemplateArgument type 'struct XB' // |-ParmVarDecl obj 'struct XB *' // `-CompoundStmt // `-CXXMemberCallExpr 'void' // `-MemberExpr '<bound member function type>' ->~XB // `-ImplicitCastExpr 'struct XB *' <LValueToRValue> // `-DeclRefExpr 'struct XB *' lvalue ParmVar 'obj' 'struct XB *' if (getClangType.isConst()) return; const RecordType* RT = dyn_cast<RecordType>(getClangType()); if (!RT) return; CXXRecordDecl* CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()); if (!CXXRD || CXXRD->hasTrivialDestructor()) return; CXXRD = CXXRD->getCanonicalDecl(); void* funcPtr = GetDtorWrapperPtr(CXXRD); if (!funcPtr) return; typedef void (*DtorWrapperFunc_t)(void* obj); DtorWrapperFunc_t wrapperFuncPtr = (DtorWrapperFunc_t) funcPtr; (*wrapperFuncPtr)(getAs<void*>()); } long long StoredValueRef::StoredValue::getAllocSizeInBytes() const { const ASTContext& ctx = m_Interp.getCI()->getASTContext(); return (long long) ctx.getTypeSizeInChars(getClangType()).getQuantity(); } void StoredValueRef::dump() const { ASTContext& ctx = m_Value->m_Interp.getCI()->getASTContext(); valuePrinterInternal::StreamStoredValueRef(llvm::errs(), this, ctx); } StoredValueRef StoredValueRef::allocate(Interpreter& interp, QualType t, const llvm::Type* llvmTy) { return new StoredValue(interp, t, llvmTy); } StoredValueRef StoredValueRef::bitwiseCopy(Interpreter& interp, const Value& value) { StoredValue* SValue = new StoredValue(interp, value.getClangType(), value.getLLVMType()); if (SValue->m_Mem) { const char* src = (const char*)value.getGV().PointerVal; // It's not a pointer. LLVM stores a char[5] (i.e. 5 x i8) as an i40, // so use that instead. We don't keep it as an int; instead, we "allocate" // it as a "proper" char[5] in the m_Mem. "Allocate" because it uses the // m_Buf, so no actual allocation happens. uint64_t IntVal = value.getGV().IntVal.getSExtValue(); if (!src) src = (const char*)&IntVal; memcpy(SValue->m_Mem, src, SValue->getAllocSizeInBytes()); } else { SValue->setGV(value.getGV()); } return SValue; } <|endoftext|>
<commit_before>#include "aquila/global.h" #include "aquila/source/generator/SquareGenerator.h" #include "aquila/source/SignalSource.h" #include "aquila/transform/FftFactory.h" #include "aquila/tools/TextPlot.h" #include "aquila/source/WaveFile.h" #include <algorithm> #include <functional> #include <memory> #include <iostream> #include <cstdlib> using namespace std; const std::size_t SIZE = 512; void findMax(Aquila::SpectrumType spectrum, Aquila::FrequencyType sampleFreq) { std::size_t halfLength = spectrum.size() / 2; std::vector<double> absSpectrum(halfLength); double max = 0; int peak_freq = 0; for (std::size_t i = 0; i < halfLength; ++i) { absSpectrum[i] = std::abs(spectrum[i]); //cout << i*(sampleFreq/halfLength)<< " amp " <<absSpectrum[i] << endl; if(absSpectrum[i] > max){ max = absSpectrum[i]; peak_freq = i*(sampleFreq/halfLength)/2; } } cout << "peak freq for input with sample size: "<< halfLength*2 << " which needs to be pow of 2" <<endl; cout <<peak_freq << " Hz max amp:" << max << endl; //plot(absSpectrum); } void freqOfindex(std::size_t start, Aquila::WaveFile wav){ Aquila::FrequencyType sampleFreq = wav.getSampleFrequency(); vector<Aquila::SampleType> chunk; for (std::size_t i =start; i< start+SIZE; ++i) { chunk.push_back(wav.sample(i)); } Aquila::SignalSource data(chunk, sampleFreq); Aquila::TextPlot plt("input wave"); auto fft = Aquila::FftFactory::getFft(SIZE); cout << "\n\nSignal spectrum of "<<start<< endl; Aquila::SpectrumType spectrum = fft->fft(data.toArray()); plt.setTitle("Signal spectrum of "+ std::to_string(start)); findMax(spectrum, sampleFreq); // plt.plotSpectrum(spectrum); } int main(int argc, char *argv[]) { if (argc < 2) { std::cout << "Usage: main <FILENAME>" << std::endl; return 1; } Aquila::WaveFile wav(argv[1]); const std::size_t END = wav.getSamplesCount(); std::size_t start = 0; while(start < END && wav.sample(start) <= 1000 ) start++; //220500 = 5*44100 // cout << END <<endl; // cout << start; for(int x = start; x < END; x+=END/5) freqOfindex(x, wav); return 0; } <commit_msg>only searh high freq<commit_after>#include "aquila/global.h" #include "aquila/source/generator/SquareGenerator.h" #include "aquila/source/SignalSource.h" #include "aquila/transform/FftFactory.h" #include "aquila/tools/TextPlot.h" #include "aquila/source/WaveFile.h" #include <algorithm> #include <functional> #include <memory> #include <iostream> #include <cstdlib> using namespace std; const std::size_t SIZE = 512; void findMax(Aquila::SpectrumType spectrum, Aquila::FrequencyType sampleFreq) { std::size_t halfLength = spectrum.size() / 2; std::vector<double> absSpectrum(halfLength); double max = 0; int peak_freq = 0; int start = 15000/((sampleFreq/halfLength)/2); for (std::size_t i = start; i < halfLength; ++i) { absSpectrum[i] = std::abs(spectrum[i]); // cout << i*(sampleFreq/halfLength)<< " amp " <<absSpectrum[i] << endl; if(absSpectrum[i] > max){ max = absSpectrum[i]; peak_freq = i*(sampleFreq/halfLength)/2; } } cout << "peak freq for input with sample size: "<< halfLength*2 << " which needs to be pow of 2" <<endl; cout <<peak_freq << " Hz max amp:" << max << endl; //plot(absSpectrum); } void freqOfindex(std::size_t start, Aquila::WaveFile wav){ Aquila::FrequencyType sampleFreq = wav.getSampleFrequency(); vector<Aquila::SampleType> chunk; for (std::size_t i =start; i< start+SIZE; ++i) { chunk.push_back(wav.sample(i)); } Aquila::SignalSource data(chunk, sampleFreq); Aquila::TextPlot plt("input wave"); auto fft = Aquila::FftFactory::getFft(SIZE); cout << "\n\nSignal spectrum of "<<start<< endl; Aquila::SpectrumType spectrum = fft->fft(data.toArray()); plt.setTitle("Signal spectrum of "+ std::to_string(start)); findMax(spectrum, sampleFreq); // plt.plotSpectrum(spectrum); } int main(int argc, char *argv[]) { if (argc < 2) { std::cout << "Usage: main <FILENAME>" << std::endl; return 1; } Aquila::WaveFile wav(argv[1]); const std::size_t END = wav.getSamplesCount(); std::size_t start = 0; while(start < END && wav.sample(start) <= 1000 ) start++; //220500 = 5*44100 // cout << END <<endl; // cout << start; for(int x = start; x < END; x+=END/5) freqOfindex(x, wav); return 0; } <|endoftext|>
<commit_before>c7c2d31e-2e4e-11e5-a207-28cfe91dbc4b<commit_msg>c7c9f663-2e4e-11e5-aa96-28cfe91dbc4b<commit_after>c7c9f663-2e4e-11e5-aa96-28cfe91dbc4b<|endoftext|>
<commit_before>c8d5ad6e-2e4e-11e5-926f-28cfe91dbc4b<commit_msg>c8dcb7ba-2e4e-11e5-95d4-28cfe91dbc4b<commit_after>c8dcb7ba-2e4e-11e5-95d4-28cfe91dbc4b<|endoftext|>
<commit_before>64844e94-2fa5-11e5-82c2-00012e3d3f12<commit_msg>6485fc42-2fa5-11e5-a4ee-00012e3d3f12<commit_after>6485fc42-2fa5-11e5-a4ee-00012e3d3f12<|endoftext|>
<commit_before>2bbc9f74-5216-11e5-b5e7-6c40088e03e4<commit_msg>2bc3bec6-5216-11e5-ab67-6c40088e03e4<commit_after>2bc3bec6-5216-11e5-ab67-6c40088e03e4<|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <QtGui/QApplication> #include "mainwindow.h" #include "FLViz.h" #ifndef EX_USAGE #define EX_USAGE 64 #endif /* Debugging */ extern int flag_D; /* Tutaj spodziewamy si komunikatw o bdach */ extern const char *errmsg[]; /* Jak uywa tego programu */ static void usage(const char *prog) { fprintf(stderr, "%s [-d] [-D] [-h] [-s] [-o <file>] [-v] [-g] <file>\n", prog); fprintf(stderr, "-d\twyrzu format zrenderowany\n"); fprintf(stderr, "-D\twcz debugging\n"); fprintf(stderr, "-h\thelp (pomoc)\n"); fprintf(stderr, "-s\ttryb symulacji\n"); fprintf(stderr, "-o <file>\tustaw plik wyjciowy\n"); fprintf(stderr, "-v\tszczegowe wypisywanie komunikatw\n"); fprintf(stderr, "-g\tnie uruchamiaj interfejsu graficznego\n"); exit(EX_USAGE); } /* * FLViz */ int main(int argc, char **argv) { QApplication *a; struct FA *fa; FILE *fp; int o; int flag_v = 0; int flag_d = 0; char *prog = argv[0]; char *in_fn = NULL; int error = 0; int flag_s = 0; int flag_g = 0; int i; int word; char *ofname = NULL; while ((o = getopt(argc, argv, "dDghosv")) != -1) switch (o) { case 'd': flag_d++; break; case 'D': flag_D++; break; case 'h': usage(argv[0]); break; case 's': flag_s++; break; case 'o': ofname = optarg; break; case 'v': flag_v++; break; case 'g': flag_g++; break; default: fprintf(stderr, "Unknown option\n"); exit(EX_USAGE); } argc -= optind; argv += optind; /* Podanie g udpala interfejs tekstowy */ if (!flag_g) { a = new QApplication(argc, argv); MainWindow w; w.show(); error = a->exec(); return (error); } if (argc == 0) usage(prog); /* * To samo co w graficznym interfejsie. * Tworzymy graf i w zalenoci od trybu, wyrzucamy * go w dogodnej formie */ in_fn = argv[0]; fp = fopen(in_fn, "r"); ASSERT(fp != NULL && "Couldn't open file"); error = FA_create(&fa, fp); if (error != 0) { printf("Error = %d, MSG: %s\n", error, errmsg[-error]); exit(1); } FA_ASSERT(fa); if (ofname == NULL) ofname = "outfile.FLViz"; /* Tryb symulacji */ if (flag_s) { if (flag_d) FA_dump_dot(fa, ofname); for (;;) { FA_dump(fa); printf("-- Podaj indeks sowa automatu --\n"); i = scanf("%d", &word); if (i != 1) break; FA_trans(fa, word); if (flag_d) FA_dump_dot(fa, ofname); } exit(EXIT_SUCCESS); } if (flag_d) { FA_dump_dot(fa, ofname); exit(EXIT_SUCCESS); } FA_dump(fa); FA_free(fa); exit(EXIT_SUCCESS); } <commit_msg>Add assert.h and make QApplication not error out.<commit_after>#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <QApplication> #include "mainwindow.h" #include "FLViz.h" #ifndef EX_USAGE #define EX_USAGE 64 #endif /* Debugging */ extern int flag_D; /* Tutaj spodziewamy si komunikatw o bdach */ extern const char *errmsg[]; /* Jak uywa tego programu */ static void usage(const char *prog) { fprintf(stderr, "%s [-d] [-D] [-h] [-s] [-o <file>] [-v] [-g] <file>\n", prog); fprintf(stderr, "-d\twyrzu format zrenderowany\n"); fprintf(stderr, "-D\twcz debugging\n"); fprintf(stderr, "-h\thelp (pomoc)\n"); fprintf(stderr, "-s\ttryb symulacji\n"); fprintf(stderr, "-o <file>\tustaw plik wyjciowy\n"); fprintf(stderr, "-v\tszczegowe wypisywanie komunikatw\n"); fprintf(stderr, "-g\tnie uruchamiaj interfejsu graficznego\n"); exit(EX_USAGE); } /* * FLViz */ int main(int argc, char **argv) { QApplication *a; struct FA *fa; FILE *fp; int o; int flag_v = 0; int flag_d = 0; char *prog = argv[0]; char *in_fn = NULL; int error = 0; int flag_s = 0; int flag_g = 0; int i; int word; char *ofname = NULL; while ((o = getopt(argc, argv, "dDghosv")) != -1) switch (o) { case 'd': flag_d++; break; case 'D': flag_D++; break; case 'h': usage(argv[0]); break; case 's': flag_s++; break; case 'o': ofname = optarg; break; case 'v': flag_v++; break; case 'g': flag_g++; break; default: fprintf(stderr, "Unknown option\n"); exit(EX_USAGE); } argc -= optind; argv += optind; /* Podanie g udpala interfejs tekstowy */ if (!flag_g) { a = new QApplication(argc, argv); MainWindow w; w.show(); error = a->exec(); return (error); } if (argc == 0) usage(prog); /* * To samo co w graficznym interfejsie. * Tworzymy graf i w zalenoci od trybu, wyrzucamy * go w dogodnej formie */ in_fn = argv[0]; fp = fopen(in_fn, "r"); ASSERT(fp != NULL && "Couldn't open file"); error = FA_create(&fa, fp); if (error != 0) { printf("Error = %d, MSG: %s\n", error, errmsg[-error]); exit(1); } FA_ASSERT(fa); if (ofname == NULL) ofname = "outfile.FLViz"; /* Tryb symulacji */ if (flag_s) { if (flag_d) FA_dump_dot(fa, ofname); for (;;) { FA_dump(fa); printf("-- Podaj indeks sowa automatu --\n"); i = scanf("%d", &word); if (i != 1) break; FA_trans(fa, word); if (flag_d) FA_dump_dot(fa, ofname); } exit(EXIT_SUCCESS); } if (flag_d) { FA_dump_dot(fa, ofname); exit(EXIT_SUCCESS); } FA_dump(fa); FA_free(fa); exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>99e5e475-4b02-11e5-86fc-28cfe9171a43<commit_msg>Nope, didn't work, now it does<commit_after>99f3d733-4b02-11e5-9e63-28cfe9171a43<|endoftext|>
<commit_before>b86a136b-2d3c-11e5-b139-c82a142b6f9b<commit_msg>b8bf860f-2d3c-11e5-98fa-c82a142b6f9b<commit_after>b8bf860f-2d3c-11e5-98fa-c82a142b6f9b<|endoftext|>
<commit_before>24041a02-2f67-11e5-940e-6c40088e03e4<commit_msg>240a66e8-2f67-11e5-b243-6c40088e03e4<commit_after>240a66e8-2f67-11e5-b243-6c40088e03e4<|endoftext|>
<commit_before>972e1f9a-35ca-11e5-a5e7-6c40088e03e4<commit_msg>973562a8-35ca-11e5-b062-6c40088e03e4<commit_after>973562a8-35ca-11e5-b062-6c40088e03e4<|endoftext|>
<commit_before>a530fb45-ad58-11e7-8852-ac87a332f658<commit_msg>bug fix<commit_after>a5bf95ae-ad58-11e7-8083-ac87a332f658<|endoftext|>