├── LICENSE ├── README.md ├── docs ├── AnandamideAPI.chm ├── build_doc.bat ├── images │ ├── async_blocks.png │ ├── block.png │ ├── branching_blocks.png │ ├── cycle_blocks.png │ ├── evaluator_blocks.png │ ├── function_blocks.png │ └── parametric_blocks.png └── source │ └── AnandamideAPI.cfg ├── include ├── Action.h ├── Anandamide.h ├── AnandamideAPI.h ├── AnandamideAction.h ├── AnandamideDocumentation.h ├── AnandamideDragData.h ├── AnandamideEditor.h ├── AnandamideEvent.h ├── AnandamideInput.h ├── AnandamideLibAPI.h ├── AnandamideLibrary.h ├── AnandamideLogic.h ├── AnandamideNeurone.h ├── AnandamideOutput.h ├── AnandamideParameter.h ├── AnandamideScript.h ├── AnandamideStdLib.h ├── AnandamideTypeInfo.h ├── AnandamideUi.h ├── AnandamideVariable.h ├── Array.h ├── Map.h ├── MathCore.h ├── Renderer.h ├── Resource.h └── Str.h ├── project ├── AnandamideAPI.pro ├── resources.qrc └── types │ ├── array.png │ ├── eye.png │ ├── function.png │ ├── pinion.png │ ├── undefined.png │ └── variable.png └── src ├── Anandamide ├── Anandamide.cpp ├── AnandamideAction.cpp ├── AnandamideDragData.cpp ├── AnandamideEditor.cpp ├── AnandamideEvent.cpp ├── AnandamideInput.cpp ├── AnandamideLibrary.cpp ├── AnandamideLogic.cpp ├── AnandamideNeurone.cpp ├── AnandamideOutput.cpp ├── AnandamideParameter.cpp ├── AnandamideScript.cpp ├── AnandamideStdLib.cpp ├── AnandamideTypeInfo.cpp ├── AnandamideUi.cpp └── AnandamideVariable.cpp ├── Common ├── Str.cpp ├── Xml.cpp └── Xml.h ├── Math └── MathCore.cpp ├── Misc ├── Camera2d.cpp ├── Camera2d.h ├── Grid.cpp └── Grid.h └── Renderer └── Renderer.cpp /README.md: -------------------------------------------------------------------------------- 1 | # AnandamideAPI 2 | Anandamide script is flexible diagram-based scripting language. Powerful library system provides flexible add-on support for your application and allows simple and fast feature development. Based on simple idea, this programming language is easy for understanding of basic principles and leads to lower cost of developemet for the business logic of your application. 3 | 4 | for runtime please, look at 5 | https://github.com/Evil-Spirit/AnandamideEditor 6 | 7 | ![Screenshot](docs/images/branching_blocks.png) 8 | 9 | -------------------------------------------------------------------------------- /docs/AnandamideAPI.chm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/docs/AnandamideAPI.chm -------------------------------------------------------------------------------- /docs/build_doc.bat: -------------------------------------------------------------------------------- 1 | ..\..\..\depend\\Doxygen\bin\doxygen.exe ..\docs\source\AnandamideAPI.cfg 2 | rem pause 3 | -------------------------------------------------------------------------------- /docs/images/async_blocks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/docs/images/async_blocks.png -------------------------------------------------------------------------------- /docs/images/block.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/docs/images/block.png -------------------------------------------------------------------------------- /docs/images/branching_blocks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/docs/images/branching_blocks.png -------------------------------------------------------------------------------- /docs/images/cycle_blocks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/docs/images/cycle_blocks.png -------------------------------------------------------------------------------- /docs/images/evaluator_blocks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/docs/images/evaluator_blocks.png -------------------------------------------------------------------------------- /docs/images/function_blocks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/docs/images/function_blocks.png -------------------------------------------------------------------------------- /docs/images/parametric_blocks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/docs/images/parametric_blocks.png -------------------------------------------------------------------------------- /include/Action.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ActionH 26 | #define ActionH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "Array.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | // 35 | // namespace Common 36 | // 37 | //------------------------------------------------------------------------------ 38 | 39 | namespace Common { 40 | 41 | class Event; 42 | 43 | //-------------------------------------------------------------------------- 44 | // 45 | // class Action 46 | // 47 | //-------------------------------------------------------------------------- 48 | 49 | class ANANDAMIDE_API Action { 50 | 51 | public: 52 | 53 | virtual ~Action() { } 54 | 55 | virtual void *getInstance() = 0; 56 | virtual const void *getInstance() const = 0; 57 | virtual Action *clone() const = 0; 58 | virtual void run() = 0; 59 | 60 | template 61 | static Action *create(T *instance, void (T::*func)(void)); 62 | template 63 | static Action *create(T &function); 64 | 65 | }; 66 | 67 | //-------------------------------------------------------------------------- 68 | // 69 | // class Action 70 | // 71 | //-------------------------------------------------------------------------- 72 | 73 | template 74 | class ActionTemplate : public Action { 75 | 76 | typedef void (Instance::*ActionFunc)(void); 77 | 78 | Instance *instance; 79 | ActionFunc func; 80 | 81 | 82 | public: 83 | 84 | // 85 | ActionTemplate(Instance *instance_, ActionFunc func_) { 86 | instance = instance_; 87 | func = func_; 88 | } 89 | 90 | // 91 | virtual void run() { 92 | (instance->*func)(); 93 | } 94 | 95 | // 96 | virtual void *getInstance() { 97 | return instance; 98 | } 99 | 100 | // 101 | virtual const void *getInstance() const { 102 | return instance; 103 | } 104 | 105 | // 106 | virtual Action *clone() const { 107 | return new ActionTemplate(instance, func); 108 | } 109 | 110 | }; 111 | 112 | template 113 | class ActionFunction : public Action { 114 | 115 | T function; 116 | 117 | public: 118 | 119 | // 120 | ActionFunction(T &function) : function(function) { 121 | } 122 | 123 | // 124 | virtual void run() { 125 | function(); 126 | } 127 | 128 | // 129 | virtual void *getInstance() { 130 | return nullptr; 131 | } 132 | 133 | // 134 | virtual const void *getInstance() const { 135 | return nullptr; 136 | } 137 | 138 | // 139 | virtual Action *clone() const { 140 | return new ActionFunction (const_cast (function)); 141 | } 142 | 143 | }; 144 | 145 | //-------------------------------------------------------------------------- 146 | 147 | template 148 | Action *Action::create(T *instance, void (T::*func)(void)) { 149 | return new ActionTemplate (instance, func); 150 | } 151 | 152 | template 153 | Action *Action::create(T &function) 154 | { 155 | return new ActionFunction (function); 156 | } 157 | 158 | } 159 | 160 | #endif 161 | 162 | //------------------------------------------------------------------------------ 163 | -------------------------------------------------------------------------------- /include/Anandamide.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef AnandamideH 26 | #define AnandamideH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | 32 | ///----------------------------------------------------------------------------- 33 | /// 34 | /// \brief Пространство имен библиотеки AnandamideAPI 35 | /// 36 | ///----------------------------------------------------------------------------- 37 | 38 | namespace Anandamide { 39 | 40 | ///------------------------------------------------------------------------- 41 | /// 42 | /// \class Messager 43 | /// 44 | /// \brief Класс для вывода предупреждений и сообщений об ошибках компиляции 45 | /// и времени выполнения скриптов. 46 | /// \details Используется для вывода ошибок компиляции 47 | /// и времени выполнения скрипта. 48 | ///
Для того, чтобы ошибки выводились с помощью пользовательских функций 49 | /// (например: qDebug(), printf, Log::message(), и т. д.), необходимо: 50 | /// 1. Наследовать класс Message 51 | /// 2. Перегрузить функции message, warning, error 52 | /// 3. Создать экземпляр наследника класса Message 53 | /// 4. Установить текущий Messager функцией setMessager 54 | /// 55 | ///------------------------------------------------------------------------- 56 | 57 | class ANANDAMIDE_API Messager { 58 | public: 59 | virtual ~Messager(); 60 | 61 | /// \brief Функция вывода информационного сообщения 62 | /// \param text выводимый текст 63 | virtual void message(const char *text); 64 | 65 | /// \brief Функция вывода предупреждающего сообщения 66 | /// \param text выводимый текст 67 | virtual void warning(const char *text); 68 | 69 | /// \brief Функция вывода сообщения об ошибке 70 | /// \param text выводимый текст 71 | virtual void error(const char *text); 72 | }; 73 | 74 | /// 75 | /// \brief вывод сообщения об ошибке, используя текущий Messager 76 | /// \param message выводимый текст 77 | /// 78 | ANANDAMIDE_API void errorMessage(const char *message); 79 | 80 | /// \brief вывод предупреждающего сообщения, используя текущий Messager 81 | /// \param message выводимый текст 82 | ANANDAMIDE_API void warningMessage(const char *message); 83 | 84 | /// \brief вывод информационного сообщения, используя текущий Messager 85 | /// \param message выводимый текст 86 | ANANDAMIDE_API void messageMessage(const char *message); 87 | 88 | /// \brief установка текущего Messager`а 89 | /// \param messager выводимый текст 90 | ANANDAMIDE_API void setMessager(Messager *messager); 91 | 92 | class Input; 93 | ANANDAMIDE_API void errorPointerMessage(Input* input); 94 | } 95 | 96 | //------------------------------------------------------------------------------ 97 | 98 | #endif 99 | 100 | //------------------------------------------------------------------------------ 101 | -------------------------------------------------------------------------------- /include/AnandamideAPI.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "AnandamideLibAPI.h" 26 | #include "AnandamideNeurone.h" 27 | #include "AnandamideLogic.h" 28 | #include "AnandamideScript.h" 29 | #include "AnandamideEditor.h" 30 | #include "AnandamideLibrary.h" 31 | #include "Anandamide.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | -------------------------------------------------------------------------------- /include/AnandamideAction.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ANANDAMIDEACTION_H 26 | #define ANANDAMIDEACTION_H 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "Array.h" 32 | #include "Action.h" 33 | #include "AnandamideEvent.h" 34 | #include "MathCore.h" 35 | 36 | //------------------------------------------------------------------------------ 37 | 38 | namespace Anandamide { 39 | 40 | class Event; 41 | class Neurone; 42 | class Neurone; 43 | class LogicEditor; 44 | 45 | ///------------------------------------------------------------------------- 46 | /// 47 | /// \class Action 48 | /// 49 | /// \brief Класс действий блоков 50 | /// 51 | ///------------------------------------------------------------------------- 52 | 53 | class ANANDAMIDE_API Action { 54 | 55 | private: 56 | 57 | friend class Event; 58 | friend class Neurone; 59 | friend class LogicEditor; 60 | 61 | mutable Array events; 62 | Common::Action *action; 63 | Neurone *neurone; 64 | 65 | void addEvent(Event *event); 66 | void removeEvent(Event *event); 67 | 68 | void setNeurone(Neurone *neurone); 69 | 70 | public: 71 | 72 | Action(); 73 | ~Action(); 74 | 75 | /// 76 | /// \brief Получение указателя на блок, к которому принадлежит данное действие 77 | /// \return указатель на блок, к которому принадлежит данное событие 78 | /// 79 | Neurone *getNeurone(); 80 | 81 | /// 82 | /// \brief Константная версия получения указателя на блок, к которому принадлежит данное действие 83 | /// \return указатель на блок, к которому принадлежит данное событие 84 | /// 85 | const Neurone *getNeurone() const; 86 | 87 | /// 88 | /// \brief run Запуск действия 89 | /// \param event событие, запустившее действие 90 | /// 91 | void run(); 92 | 93 | /// 94 | /// \brief Установка функции, которая вызывается при вызове данного действия 95 | /// \param action функция 96 | /// 97 | void setAction(Common::Action *action); 98 | 99 | /// 100 | /// \brief Получение имени данного действия 101 | /// \return имя действия 102 | /// 103 | const char *getName() const; 104 | 105 | }; 106 | 107 | } 108 | 109 | #endif // ANANDAMIDEACTION_H 110 | -------------------------------------------------------------------------------- /include/AnandamideDocumentation.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | /*! 26 | \mainpage Документация AnandamideAPI 27 | 28 | \section intro Введение 29 | 30 | Библиотека AnandamideAPI служит для работы с объектами скриптового языка Anandamide. Функции и классы этой 31 | библиотеки служат для создания, редактирования и запуска скриптовых программ на основе блочного представления. 32 | 33 | \section blocks Блоки 34 | 35 | Блок является основной составляющей скриптового языка. Блоки могут быть связаны между собой для осуществления контроля 36 | потока исполнения и потока данных. 37 | 38 | \image html block.png "Составляющие блока" 39 | 40 | \section program_flow Потоки исполенения. 41 | 42 | Блок может содержать действия (actions) и события (events). Эти сущности обеспечивают управление ходом выполенения программы 43 | (передачу управления другому блоку, ветвления, циклы). Обычно программа начинает свое выполенение с определенного места (точка входа). 44 | Дальнейшее поведение программы зависит от того, на какой блок поступает поток исполенения. В зависимости от внутренней логики блока, 45 | его действия (входящий поток исполения) могут порождать одно или несколько событий (исходящий поток исполенения). 46 | Одно или множество событий одного блока могут быть связаны с одним или несколькими действиями другого блока. Если одно 47 | событие блока связано с несколькими действиями, то порядок их выполнения не определен. Для однозначного определения порядка 48 | необходимо пользоваться специальными разветвлящими блоками (Sequence). Одно действие блока может активироваться от произвольного 49 | количества событий. 50 | 51 | \subsection flow_function Функциональные блоки (Functions) 52 | Обычно большинство блоков содержат только одно действие (in) и одно событие (out), которое вызывается после того, как 53 | логика работы блока завершена. Такие блоки являются полным аналогом функций или процедур из языков программирования. 54 | 55 | \image html function_blocks.png "Функциональные блоки Message" 56 | 57 | \subsection flow_branching Блоки ветвлений (Branching) 58 | Блоки могут содержать один вход и несколко выходов, которые могут активироваться в зависимости от входных параметров или иных условий. 59 | Такие блоки обеспечивают ветвление. 60 | 61 | \image html branching_blocks.png "Блок условного ветвления If" 62 | 63 | \subsection flow_cycles Блоки циклов (Cycles) 64 | Блоки могут вызывать одно событие несколько раз, за счет чего обеспечиваются реализация циклов. 65 | 66 | \image html cycle_blocks.png "Блок цикла For" 67 | 68 | \subsection flow_events Блоки асинхронных событий (Async Events) 69 | Блоки могут вызывать событие вне зависимости от входных действий или параметров, асинхронно. 70 | 71 | \image html async_blocks.png "Блок асинхронных событий нажатия/отпускания клавиши" 72 | 73 | \section data_flow Потоки данных. 74 | 75 | Блок может содержать входные (input), выходные (output) и внутренние (parameters) параметры. 76 | Эти параметры могут иметь различный тип принимаемого или возвращаемого значения. 77 | В визуальном редакторе скриптов на основе блоков эти параметры имеют различный цвет отображения и пиктограммы. 78 | Один выходной параметр может быть связан с несколькими входными параметрами, но один входной параметр может 79 | быть связан только с одним выходным. Если входной параметр не имеет связи с источником данных (выходным параметром), 80 | ему может быть присвоено значение по умолчанию, которое может быть задано при выделении блока в визуальном редакторе. 81 | Так же при выделении блока могут быть заданы скрытые параметры блока, которые могут влиять на количество действий, 82 | событий, входных или выходных параметров и прочую логику поведения блока. 83 | 84 | \subsection flow_evaluators Блоки вычислений (Evaluators) 85 | Блоки могут не иметь ни входящих, ни исходящих потоков исполенения. Эти блоки в неявном виде имеют действие, которое 86 | происходит при запросе выходного параметра. Это действие должно обеспечивать вычисление и установку нового значения 87 | требуемого выходного параметра. Такие блоки могут быть ислользованы для вычисления значений математических выражений. 88 | Такое поведение используется для того, чтобы исключить двойное соединение блоков (параллельное соединение потока 89 | исполнения и потока данных) 90 | 91 | \image html evaluator_blocks.png "Вычислительные блоки операций сложения, умножения и деления" 92 | 93 | \subsection flow_parameters Блоки с переменных числом выводов (Parametric Blocks) 94 | 95 | Внутренние параметры могут быть использованы для того, чтобы задавать количество выводов блоков. 96 | 97 | \image html parametric_blocks.png "Блок с переменным числом событий Switch" 98 | 99 | \section data_types Типы данных. 100 | 101 | Входные, выходные и скрытые параметры блоков могут харанить и передавать различные данные заданного типа. Некоторые блоки 102 | передают и принимают значения любого типа (Variable). 103 | 104 | \subsection base_types Базовые типы данных 105 | Существует несколько системных типов данных, которые вшиты в систему переменных (Variable). 106 | - int - целое 107 | - float - число с плавающей точкой одинарной точности 108 | - double - число с плавающей точкой двойной точности 109 | - string - строка символов 110 | - Enum - тип перечисления 111 | - Variable - универсальный тип, который может сохранять любой тип данных 112 | 113 | Каждый типа данных имеет визуальные аттрибуты (цвет и пиктограмму) для облегчения визуальной идентификации типа в 114 | редакторе блочных скриптов. 115 | 116 | \subsection user_types Пользовательские типы данных 117 | Библиотека AnandamideAPI поддерживает регистрацию пользовательских типов данных, в том числе автоматическое пробрасывание 118 | функций конвертации в строковое представление а так же внтутритиповых операторов сравнения (больше и равно), сложения, 119 | вычитания, умножения и деления. 120 | Поддерживается регистрация элементов типов-перечислений. 121 | 122 | \section using_library Использование библиотеки AnandamideAPI. 123 | 124 | \subsection libraries Создание библиотеки пользовательских типов и блоков. 125 | 126 | Для создания произвольной логики на языке блочного скрипта используются различные блоки. Стандартная библиотека блоков 127 | содержит основные функции для создания циклов, ветвлений и некоторых операций. Для расширения набора блоков, из которых 128 | состоят скрипты имеется механизм внешних библиотек. Внешние библиотеки создаются в виде динамических библиотек *.dll. 129 | Для создания библиотеки необходимо настроить проект на сборку динамической библиотеки (*.dll). Для того, чтобы такая 130 | динамическая библиотека могла подключаться к AnandamideAPI, должны соблюдаться следующие условия: 131 | 1. Внешнаяя билблиотека должна использовать AnandamideAPI 132 | 2. В библиотеке должна быть объявлена функция регистрации библиотеки в виде: 133 | \code {.cpp} 134 | extern "C" __declspec(dllexport) void anandamideDefineLibrary(Anandamide::Library *library); 135 | \endcode 136 | 137 | Внутри функции регистрации библиотеки должно происходить заполнение полей объекта library.
138 | Для того, чтобы объвить имя библиотеки, необходимо выполнить следующее: 139 | 140 | \code {.cpp} 141 | void anandamideDefineLibrary(Anandamide::Library *library) { 142 | // задаем имя "Sample" 143 | library->setName("Sample"); 144 | ... 145 | } 146 | \endcode 147 | 148 | \subsection type_libraries Регистрация библиотечных типов. 149 | 150 | Для того, чтобы пользовательский тип был загеристрирован для использования в библотеке, необходимо выполнить следующие 151 | условия: 152 | 153 | 1. Необходимо присвоить пользовательскому типу уникальный идентификатор, который позволит однозначно идентифицировать 154 | тип. Обязательно необходимо делать это в заголовочном файле, после того, как необходимый тип был объявлен.
155 | \code {.cpp} 156 | // Например, имеем следующий тип данных: 157 | class UBER_API UberType { 158 | public: 159 | virtual ~UberType(); 160 | 161 | virtual int getValue() const; 162 | 163 | }; 164 | 165 | // Ниже в заголовочном файле необходимо зарегистрировать идентификатор типа: 166 | DEFINE_TYPEID(UberType , 109901) 167 | 168 | // Таким образом, требуемый тип будет зарегистрирован 169 | \endcode 170 | 171 | 2. Нужно зарегистрировать данный тип и присвоить ему визуальное оформление (цвет и пиктограмму). 172 | Для этого внутри функции регистрации библиотеки необходимо сделать слудующее: 173 | \code {.cpp} 174 | void anandamideDefineLibrary(Anandamide::Library *library) { 175 | ... 176 | library->addType (0.7f, 0.5f, 0.7f, ADD_IMG(":/types/types/variable.png")); 177 | ... 178 | } 179 | \endcode 180 | 181 | Для регистрации типов-перечислений используется следующий синтаксис: 182 | 183 | 184 | \code {.cpp} 185 | // объявление типа перечисления 186 | enum CompareOperation { 187 | IF_EQUAL, 188 | IF_NOTEQUAL, 189 | IF_GREATER, 190 | IF_GEQUAL, 191 | IF_LESS, 192 | IF_LEQUAL, 193 | }; 194 | 195 | // начало регистрации типа перечисления 196 | ENUM_BEGIN(CompareOperation) 197 | 198 | // регистрация элементов типа перечисления 199 | ENUM_ITEM_NAMED(IF_EQUAL, "==") 200 | ENUM_ITEM_NAMED(IF_NOTEQUAL, "!=") 201 | ENUM_ITEM_NAMED(IF_GREATER, ">") 202 | ENUM_ITEM_NAMED(IF_GEQUAL, ">=") 203 | ENUM_ITEM_NAMED(IF_LESS, "<") 204 | ENUM_ITEM_NAMED(IF_LEQUAL, "<=") 205 | 206 | // конец регистрации типа перечисления и присвоение идентификатора 207 | ENUM_END(CompareOperation, 550000) 208 | \endcode 209 | 210 | Если название элемента перечисления должно совпадать с символом элемента перечисления, для регистрации элемента 211 | можно воспользоваться упрощенной формой: 212 | 213 | \code {.cpp} 214 | // начало регистрации типа перечисления 215 | ENUM_BEGIN(CompareOperation) 216 | 217 | // регистрация элементов типа перечисления 218 | ENUM_ITEM(IF_EQUAL) 219 | ENUM_ITEM(IF_NOTEQUAL) 220 | ENUM_ITEM(IF_GREATER) 221 | ENUM_ITEM(IF_GEQUAL) 222 | ENUM_ITEM(IF_LESS) 223 | ENUM_ITEM(IF_LEQUAL) 224 | 225 | // конец регистрации типа перечисления и присвоение идентификатора 226 | ENUM_END(CompareOperation, 550000) 227 | \endcode 228 | 229 | \subsection block_libraries Регистрация библиотечных блоков. 230 | 231 | Библиотеки могут содержать произвольное количество блоков, которые дополнительно могут быть классифицированны по группам 232 | (kinds). Есть три основных способа создания новых блоков - создание блоков из обычных функций, создание блоков из 233 | членов класса и создание произвольных блоков. 234 | 235 | \subsection function_lib_blocks Создание блоков из функций. 236 | AnandamideAPI содержит механизм автоматического создания новых блоков из обычных функций с использованием всего одной строчки кода. 237 | Для создания такого блока, необходимо сделать следующее: 238 | 1. Создать функцию, на основе которой требуется создать блок: 239 | \code {.cpp} 240 | int arraySize(VariableArray array) { 241 | return array->count(); 242 | } 243 | \endcode 244 | 245 | 2. Убедиться, что типы данных, которые использует функция, уже зарегистрированы в какой-либо библиотеке. 246 | \code {.cpp} 247 | typedef Array VariableArrayData; 248 | DEFINE_TYPEID(VariableArray , 330022) 249 | \endcode 250 | 251 | 3. Зарегистрировать функциональный блок в библиотеке. 252 | \code {.cpp} 253 | void anandamideDefineLibrary(Anandamide::Library *library) { 254 | ... 255 | library->addFunction("Std/Array(kind)", "arraySize(Id)", "arraySize(BlockHeader)", &arraySizeFuncPtr, "size(return_value_name)", {"array(input_parameter_names)"}); 256 | ... 257 | } 258 | \endcode 259 | 260 | \subsection member_lib_blocks Создание блоков из членов класса. 261 | 262 | Функция уже реализована, и вы можете обраться к разработчику, чтобы получить дополнительную информацию. 263 | 264 | \subsection user_lib_blocks Создание блоков с произвольной логикой. 265 | 266 | Если необходимо создать блок с такой логикой работы, какую нельзя реализовать с помощью функциональных блоков, 267 | необходимо выполнить следующие шаги: 268 | 269 | 1. Объявить класс-наследник от Neurone 270 | \code {.cpp} 271 | class If : public Neurone { 272 | ... 273 | }; 274 | \endcode 275 | 2. Перегрузить статческую функцию Anandamide::Neurone::define() и заполнить стуктуру Anandamide::NeuroneDef. Это необходимо для того, чтобы 276 | в редакторе блоков можно было получить полную информацию о блоке без фактического создания работающего блока. 277 | Иногда требуется непосредственное создание блока в редакторе без замещения его блоком-пустышкой. Это необходимо 278 | для создания блоков, вид которых зависит от параметров. 279 | \code {.cpp} 280 | static void define(NeuroneDef *def) { 281 | 282 | // задать группу-классификацию для блока 283 | def->setKind("FlowControl"); 284 | 285 | // установка флага создания настоящего блока вместо блока-пустышки в редакторе скриптов 286 | def->setCreateDummy(false); 287 | 288 | // добавление скрытый параметр, который отвечает за операцию сравнения 289 | def->addParameter ("op", "=="); 290 | 291 | // добавление входных параметров a, b 292 | def->addInput ("a", "0"); 293 | def->addInput ("b", "0"); 294 | 295 | // добавление событий ветвления 296 | def->addEvent("then"); 297 | def->addEvent("else"); 298 | 299 | // добавление действия запуска операции сравнения 300 | def->addAction("check"); 301 | } 302 | \endcode 303 | 3. Перегрузить виртуальные функции и реализовать логику работы блока 304 | (например, Anandamide::Neurone::onInit(), Anandamide::Neurone::hasCaption(), Anandamide::Neurone::onGetCaption()) 305 | \code {.cpp} 306 | // Функция, которая автоматически вызывается при создании нового экземпляра блока. 307 | // К моменту вызова этой функции все компоненты блока, описанные в NeuroneDef будут автоматичеки созданы 308 | void onInit(Libraries *libraries) override { 309 | 310 | // Получение параметра блока 311 | p_op = getParameter("op"); 312 | 313 | // Получение входных параметров блока 314 | i_a = getInput("a"); 315 | i_b = getInput("b"); 316 | 317 | // Получение событий блока 318 | e_then = getEvent("then"); 319 | e_else = getEvent("else"); 320 | 321 | // Связь действия и функции, которая вызвается при активации этого действия 322 | getAction("check")->setAction(Common::Action::create(this, &If::in)); 323 | } 324 | 325 | // Функция, которая автоматически вызвается для определения, имеет ли текущий блок вторую строку заголовка. 326 | bool hasCaption() override { 327 | return true; 328 | } 329 | 330 | // Функция, которая автоматически вызывается для получения второй строки заголовка блока. 331 | Str onGetCaption() override { 332 | return format("a %s b", p_op->getValue().getStr()); 333 | } 334 | 335 | // реализация логики действия "check" 336 | void in() { 337 | CompareOperation op = VariableToType (p_op->getValue()).value; 338 | 339 | if (check(i_a->getValue(), i_b->getValue(), op)) { 340 | e_then->run(); 341 | } else { 342 | e_else->run(); 343 | } 344 | } 345 | \endcode 346 | 4. Зарегистрировать класс блока в библиотеке 347 | \code {.cpp} 348 | void anandamideDefineLibrary(Anandamide::Library *library) { 349 | ... 350 | library->addTemplate ("If"); 351 | ... 352 | } 353 | \endcode 354 | 355 | \subsection variables Работа с универсальным типом данных Variable. 356 | 357 | Для харанения и передачи данных в библиотеке AnandamideAPI вводится тип данных Variable, который способен хранить 358 | данные любого типа. Для базовых типов данных (int, float, double, const char *, Enum, etc) возможна атоматическая 359 | конвертация между этими типами.
360 | 361 | Для того, чтобы в рамках реализации произвольных блоков работать с различными типами данных, необходимо использовать 362 | шаблонные классы, обеспечивающие конвертацию Variable в различные типы (Anandamide::VariableToType): 363 | 364 | \code {.cpp} 365 | class SomeBlock : public Neurone { 366 | ... 367 | void init() { 368 | int some_param_int = VariableToType (getParameter(0).getValue()).value; 369 | Str some_param_string = VariableToType (getParameter(1).getValue()).value; 370 | double some_param_double = VariableToType (getParameter(2).getValue()).value; 371 | } 372 | ... 373 | }; 374 | \endcode 375 | 376 | Для конвертации различных типов в Variable необходимо пользоваться шаблонными классами Anandamide::TypeToVariable: 377 | \code {.cpp} 378 | class GetDoubleResult : public Neurone { 379 | 380 | ... 381 | // 382 | void in() { 383 | 384 | double a = VariableToType (getInput(0).getValue()).value; 385 | double b = VariableToType (getInput(1).getValue()).value; 386 | double c = VariableToType (getInput(2).getValue()).value; 387 | 388 | getOutput(0).setValue(TypeToVariable(a + b * c).value); 389 | 390 | out->run(); 391 | } 392 | ... 393 | }; 394 | \endcode 395 | 396 | */ 397 | -------------------------------------------------------------------------------- /include/AnandamideDragData.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Sergey Almighty 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef DragDataH 26 | #define DragDataH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "AnandamideNeurone.h" 32 | #include "AnandamideScript.h" 33 | #include "QString" 34 | #include "QMap" 35 | #include "QVector" 36 | #include "QMimeData" 37 | 38 | //------------------------------------------------------------------------------ 39 | 40 | namespace Anandamide { 41 | 42 | //-------------------------------------------------------------------------- 43 | // 44 | // class DragData 45 | // 46 | //-------------------------------------------------------------------------- 47 | 48 | class ANANDAMIDE_API BlockDragDataContent { 49 | public: 50 | QString type; 51 | QString library; 52 | QString instance; 53 | 54 | QString metaType; 55 | QString ownerName; 56 | QString itemValue; 57 | 58 | QMap params; 59 | QMap inputs; 60 | }; 61 | 62 | class ANANDAMIDE_API BlockDragData { 63 | 64 | public: 65 | 66 | QVector contents; 67 | BlockDragDataContent content; 68 | 69 | BlockDragData(); 70 | ~BlockDragData(); 71 | 72 | void addToMimeData(QMimeData* data); 73 | bool fillFromMimedata(const QMimeData *data); 74 | 75 | QMimeData *toMimeData(); 76 | bool fromMimeData(const QMimeData *data); 77 | void fillNeurone(Neurone *neurone); 78 | 79 | static void fillBlocksNum(QMimeData *data, int num); 80 | 81 | void print(); 82 | }; 83 | } 84 | 85 | //------------------------------------------------------------------------------ 86 | 87 | #endif 88 | 89 | //------------------------------------------------------------------------------ 90 | -------------------------------------------------------------------------------- /include/AnandamideEditor.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef AnandamideEditorH 26 | #define AnandamideEditorH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "AnandamideLogic.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | namespace Anandamide { 36 | 37 | //-------------------------------------------------------------------------- 38 | 39 | class Camera2d; 40 | class Grid; 41 | class Renderer; 42 | 43 | //-------------------------------------------------------------------------- 44 | // 45 | // class LogicEditor 46 | // 47 | //-------------------------------------------------------------------------- 48 | 49 | class ANANDAMIDE_API LogicEditor { 50 | 51 | enum { 52 | SELECT, 53 | MOVE, 54 | SELECT_RECT, 55 | LINK_EVENT_ACTION, 56 | LINK_OUTPUT_INPUT 57 | }; 58 | 59 | Logic *logic; 60 | 61 | int edit_state; 62 | Vector2f move; 63 | vec3 free_point; 64 | BBox rect; 65 | 66 | Grid *grid; 67 | Camera2d *camera; 68 | Common::Action *on_selection_changed; 69 | Common::Action *on_link_create_block; 70 | bool blockGroupSelection; 71 | int pasteShift; 72 | bool setGroupFlag; 73 | bool editableFlag; 74 | 75 | protected: 76 | 77 | Neurone *link_event; 78 | Neurone *link_action; 79 | 80 | int link_event_index; 81 | int link_action_index; 82 | 83 | Neurone *link_input; 84 | Neurone *link_output; 85 | 86 | int link_input_index; 87 | int link_output_index; 88 | 89 | Link picked_link; 90 | Link selected_link; 91 | 92 | Neurone *selected; 93 | Neurone *hovered; 94 | NeuroneGroup *selectedGroup; 95 | 96 | virtual void onRemoveNode(Neurone *node); 97 | virtual void onSelectNode(Neurone *node); 98 | virtual void onLinkCreateBlock(float x, float y); 99 | 100 | public: 101 | 102 | LogicEditor(); 103 | ~LogicEditor(); 104 | 105 | void reset(); 106 | void render(Renderer *renderer, int w, int h, bool flag); 107 | 108 | //событие изменения логики сценария 109 | void onChangeLogic(); 110 | //событие изменения месторасположения блоков 111 | void onChangeLocation(); 112 | 113 | virtual void clear(); 114 | void undoLinks(); 115 | void createEventActionLinks(); 116 | void createOutputInputLinks(); 117 | 118 | virtual void removeNode(int index); 119 | virtual void removeNode(Neurone *node); 120 | bool removeSelected(); 121 | bool cloneSelected(); 122 | void copyAsXml(Str &xml_str); 123 | bool pasteAsXml(const Str &xml_str, int x = 0, int y = 0); 124 | void copyGroupContentsToLogic(NeuroneGroup* srcGroup, Logic* destLogic); 125 | void postPrepareLogic(Logic* destLogic); 126 | void createGroupFromLogic(Neurone* logicNode); 127 | 128 | void mouseDown(int X_, int Y_, int b, bool ctrl = false, bool blockLink = false); 129 | void mouseUp(int X, int Y, int b, bool ctrl = false); 130 | void mouseMove(int X, int Y); 131 | void mouseWheel(float delta, bool shift = false); 132 | 133 | void selectNode(Neurone *node); 134 | void hoverNode(Neurone *node); 135 | 136 | void runOnSelection(); 137 | Neurone *getSelectedNode(); 138 | void clearSelection(); 139 | void focusNode(Neurone *node); 140 | 141 | Neurone *create(const char *name, const char *library = "", const char *instance = ""); 142 | void place(Neurone *node); 143 | void setLogic(Logic *logic_); 144 | Logic *getLogic(); 145 | void nullLogic(); 146 | 147 | vec3 getCursorPos(); 148 | float getCameraPosX(); 149 | float getCameraPosY(); 150 | float getCameraZoom(); 151 | void setupCamera(Renderer *renderer, float width, float h); 152 | 153 | void setOnSelectionChanged(Common::Action *action); 154 | Common::Action *getOnSelectionChanged(); 155 | 156 | Str getInfo(int x, int y); 157 | Link selectLink(const vec3 &point); 158 | Link& getPickedLink(); 159 | void clearLinks(); 160 | 161 | Neurone* getNodeByPos(int X, int Y); 162 | Action* getActionByPos(int X, int Y); 163 | 164 | bool canCreateNewGroup(); 165 | bool createNewGroup(); 166 | NeuroneGroup* getSelectedGroup(); 167 | NeuroneGroup* getGroupOfSelectedNodes(); 168 | bool removeSelectedFromGroup(); 169 | 170 | NeuroneGroup* getGroupByPos(int X, int Y); 171 | bool removeGroup(NeuroneGroup* group); 172 | bool removeGroupWithNodes(NeuroneGroup* group); 173 | int getGroupsCount(); 174 | bool addToGroupPrepare(); 175 | void addToGroupCancel(); 176 | bool isAddToGroupMode(); 177 | bool addSelectedToGroup(NeuroneGroup* group); 178 | bool addSelectedToGroupByPos(int X, int Y); 179 | 180 | bool canPopupMenu(); 181 | bool isSomethingSelected(); 182 | int getSelectedGroupsCount(); 183 | void makeLogicFromGroup(NeuroneGroup* group); 184 | bool canMakeGroupFromLogic(); 185 | void makeGroupFromLogic(Neurone* node); 186 | 187 | vec3 getCameraPos() const; 188 | void setCameraPos(vec3 pos); 189 | 190 | void createEventLink(Neurone* node, int index); 191 | void createActionLink(Neurone* node, int index); 192 | void createOutputLink(Neurone* node, int index); 193 | void createInputLink(Neurone* node, int index); 194 | 195 | void setEditable(bool editable); 196 | }; 197 | } 198 | 199 | //------------------------------------------------------------------------------ 200 | 201 | #endif 202 | 203 | //------------------------------------------------------------------------------ 204 | -------------------------------------------------------------------------------- /include/AnandamideEvent.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ANANDAMIDEEVENT_H 26 | #define ANANDAMIDEEVENT_H 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "Array.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | namespace Anandamide { 36 | 37 | class Action; 38 | class Neurone; 39 | 40 | ///------------------------------------------------------------------------- 41 | /// 42 | /// \class Event 43 | /// 44 | /// \brief Класс событий блоков 45 | /// 46 | ///-------------------------------------------------------------------------- 47 | 48 | class ANANDAMIDE_API Event { 49 | 50 | friend class Neurone; 51 | 52 | Array actions; 53 | Neurone *neurone; 54 | 55 | void setNeurone(Neurone *neurone); 56 | 57 | public: 58 | 59 | Event(); 60 | ~Event(); 61 | 62 | /// 63 | /// \brief Запуск всех Action, с которыми связано событие 64 | /// 65 | void run(); 66 | 67 | /// 68 | /// \brief Добавление связи с Action при генерации данного события 69 | /// \param action действие, которые вызывается при генерации данного события 70 | /// 71 | void addAction(Action *action); 72 | 73 | /// 74 | /// \brief Удаление действия по индексу 75 | /// \param index индекс удаляемого действия 76 | /// 77 | void removeAction(int index); 78 | 79 | /// 80 | /// \brief Удаление связи с Action при генерации данного события 81 | /// \param action указатель на действие 82 | /// 83 | void removeAction(Action *action); 84 | 85 | /// 86 | /// \brief Получение количества действий, с которыми связано данное событие 87 | /// \return 88 | /// 89 | int getActionsCount() const; 90 | 91 | 92 | /// 93 | /// \brief Получение действия, с которым связано данное событие по индексу 94 | /// \param i индекс действия 95 | /// \return действие с индексом i 96 | /// 97 | Action &getAction(int i); 98 | 99 | /// 100 | /// \brief Константная версия получения действия, с которым связано данное событие по индексу 101 | /// \param i индекс действия 102 | /// \return действие с индексом i 103 | /// 104 | const Action &getAction(int i) const; 105 | 106 | /// 107 | /// \brief Получение блока, в котором содержится данное событие 108 | /// \return указатель на блок, в которм содержится данное событие 109 | /// 110 | Neurone *getNeurone(); 111 | 112 | /// 113 | /// \brief Константная версия получения блока, в котором содержится данное событие 114 | /// \return указатель на блок, в которм содержится данное событие 115 | /// 116 | const Neurone *getNeurone() const; 117 | 118 | /// 119 | /// \brief Получнеие имени даного события 120 | /// \return имя события 121 | /// 122 | const char *getName() const; 123 | 124 | }; 125 | 126 | } 127 | 128 | #endif // ANANDAMIDEEVENT_H 129 | -------------------------------------------------------------------------------- /include/AnandamideInput.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ANANDAMIDEINPUT_H 26 | #define ANANDAMIDEINPUT_H 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "AnandamideVariable.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | namespace Anandamide { 35 | 36 | class Output; 37 | class Neurone; 38 | class TypeDef; 39 | 40 | ///------------------------------------------------------------------------- 41 | /// 42 | /// \class Input 43 | /// 44 | /// \brief Класс входных параметров блоков 45 | /// 46 | ///------------------------------------------------------------------------- 47 | 48 | class ANANDAMIDE_API Input { 49 | 50 | friend class Neurone; 51 | 52 | Variable default_value; 53 | Output *source; 54 | Neurone *neurone; 55 | 56 | void setNeurone(Neurone *neurone); 57 | 58 | float pos_x; 59 | float pos_y; 60 | float dir_x; 61 | float dir_y; 62 | 63 | public: 64 | 65 | Input(const Variable &default_value_); 66 | 67 | /// 68 | /// \brief Получение значения входного параметра 69 | /// \return значение переменной по умолчанию в случае, если не задан выходной параметр, иначе значение выходного параметра 70 | /// 71 | const Variable &getValue() const; 72 | 73 | /// 74 | /// \brief Установка значения по умолчанию, которое будет получено в случае, если данный входной параметр не связан с выходным параметром 75 | /// \param default_value_ 76 | /// 77 | void setValue(const Variable &default_value_); 78 | 79 | /// 80 | /// \brief Получение переменной 81 | /// \return переменная 82 | /// 83 | Variable &getVariable(); 84 | 85 | /// 86 | /// \brief Получение переменной-значения по умолчанию 87 | /// \return переменная-значение по умолчанию 88 | /// 89 | Variable &getDefaultValue(); 90 | 91 | /// 92 | /// \brief Константная версия получения переменной-значения по умолчанию 93 | /// \return переменная-значение по умолчанию 94 | /// 95 | const Variable &getDefaultValue() const; 96 | 97 | /// 98 | /// \brief Получение источника (выходного параметра), с которым связан данный входной параметр 99 | /// \return выходной параметр, с которым связан данный входной параметр 100 | /// 101 | Output *getSource(); 102 | 103 | /// 104 | /// \brief Константная версия получения источника (выходного параметра), с которым связан данный входной параметр 105 | /// \return выходной параметр, с которым связан данный входной параметр 106 | /// 107 | const Output *getSource() const; 108 | 109 | /// 110 | /// \brief setSource 111 | /// \param source_ 112 | /// 113 | void setSource(Output *source_); 114 | 115 | /// 116 | /// \brief Получение имени данного входного параметра 117 | /// \return имя входного параметра 118 | /// 119 | const char *getName() const; 120 | 121 | /// 122 | /// \brief Получение блока, в котором содержится данный входной параметр 123 | /// \return указатель на блок, в которм содержится данный входной параметр 124 | /// 125 | Neurone *getNeurone(); 126 | 127 | /// 128 | /// \brief Константная версия получения блока, в котором содержится данный входной параметр 129 | /// \return указатель на блок, в которм содержится данный входной параметр 130 | /// 131 | const Neurone *getNeurone() const; 132 | 133 | /// 134 | /// \brief Получение определения типа для переменной данного входного параметра 135 | /// \return определение типа 136 | /// 137 | const TypeDef *getTypeDef() const; 138 | 139 | float getPosX() const; 140 | float getPosY() const; 141 | void setPos(float x, float y); 142 | 143 | float getDirX() const; 144 | float getDirY() const; 145 | void setDir(float x, float y); 146 | 147 | }; 148 | 149 | } 150 | 151 | #endif // ANANDAMIDEINPUT_H 152 | -------------------------------------------------------------------------------- /include/AnandamideLibAPI.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ANANDAMIDEAPI_GLOBAL_H 26 | #define ANANDAMIDEAPI_GLOBAL_H 27 | #if _WIN32 28 | #ifdef ANANDAMIDEAPI_LIBRARY 29 | #define ANANDAMIDE_API __declspec(dllexport) 30 | #else 31 | #define ANANDAMIDE_API __declspec(dllimport) 32 | #endif 33 | #else 34 | #ifdef ANANDAMIDEAPI_LIBRARY 35 | #define ANANDAMIDE_API __attribute__((visibility("default"))) 36 | #else 37 | #define ANANDAMIDE_API __attribute__((visibility("default"))) 38 | #endif 39 | #endif 40 | 41 | #define ANANDAMIDE_UNUSED(x) (void)x 42 | 43 | #pragma warning(disable:4996 4100 4804) 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /include/AnandamideOutput.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ANANDAMIDEOUTPUT_H 26 | #define ANANDAMIDEOUTPUT_H 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "Action.h" 31 | #include "AnandamideLibAPI.h" 32 | #include "AnandamideVariable.h" 33 | 34 | //------------------------------------------------------------------------------ 35 | 36 | namespace Anandamide { 37 | 38 | class Neurone; 39 | class TypeDef; 40 | 41 | ///------------------------------------------------------------------------- 42 | /// 43 | /// \class Output 44 | /// 45 | /// \brief Класс выходных параметров блоков 46 | /// 47 | ///------------------------------------------------------------------------- 48 | 49 | class ANANDAMIDE_API Output { 50 | 51 | Variable value; 52 | Neurone *instance; 53 | Common::Action *on_get_value; 54 | 55 | public: 56 | 57 | /// 58 | /// \brief Конструктор для создания нового выходного параметра 59 | /// \param neurone блок, для которого создается выходной параметр 60 | /// 61 | Output(Neurone *neurone); 62 | 63 | /// 64 | /// \brief Конструктор для создания нового выходного параметра 65 | /// \param neurone блок, для которого создается выходной параметр 66 | /// \param value значение по умолчанию 67 | /// 68 | Output(Neurone *neurone, const Variable &value); 69 | 70 | ~Output(); 71 | 72 | /// 73 | /// \brief Получение значения выходного параметра 74 | /// \return переменная-значение выходного параметра 75 | /// 76 | const Variable &getValue() const; 77 | 78 | /// 79 | /// \brief Установить значение выходного параметра 80 | /// \param value новое значение выходного параметра 81 | /// 82 | void setValue(const Variable &value); 83 | 84 | /// 85 | /// \brief Получение переменной выходного параметра 86 | /// \return ссылка на переменную выходного параметра 87 | /// 88 | Variable &getVariable(); 89 | 90 | /// 91 | /// \brief Получение блока, к которому принадлежит текущий выходной параметр 92 | /// \return указатель на блок, к которому принадлежит текущий выходной параметр 93 | /// 94 | Neurone *getInstance(); 95 | 96 | /// 97 | /// \brief Константная версия получения блока, к которому принадлежит текущий выходной параметр 98 | /// \return указатель на блок, к которому принадлежит текущий выходной параметр 99 | /// 100 | const Neurone *getInstance() const; 101 | 102 | /// 103 | /// \brief Установка функции, которая будет вызываться при получении значения параметра 104 | /// \param action функция, которая будет вызвана, когда запрашивается значение выходного параметра через getValue() 105 | /// 106 | void setOnGetValueAction(Common::Action *action); 107 | 108 | /// 109 | /// \brief Установка функции, которая будет вызываться при получении значения параметра 110 | /// \return функцию, которая вызвается, когда запрашивается значение выходного параметра через getValue() 111 | /// 112 | Common::Action *getOnGetValueAction(); 113 | 114 | /// 115 | /// \brief Получение имени выходного параметра 116 | /// \return имя выходного параметра 117 | /// 118 | const char *getName() const; 119 | 120 | /// 121 | /// \brief Получение определения для типа выходнго параметра 122 | /// \return определение для типа выходного параметра 123 | /// 124 | const TypeDef *getTypeDef() const; 125 | }; 126 | 127 | } 128 | 129 | #endif // ANANDAMIDEOUTPUT_H 130 | -------------------------------------------------------------------------------- /include/AnandamideParameter.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ANANDAMIDEPARAMETER_H 26 | #define ANANDAMIDEPARAMETER_H 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "AnandamideVariable.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | namespace Anandamide { 36 | 37 | ///------------------------------------------------------------------------- 38 | /// 39 | /// \class Parameter 40 | /// 41 | /// \brief Класс параметров блоков 42 | /// 43 | ///------------------------------------------------------------------------- 44 | 45 | class ANANDAMIDE_API Parameter { 46 | 47 | Variable value; 48 | 49 | public: 50 | 51 | /// 52 | /// \brief Конструктор класса параметра 53 | /// \param value значение параметра 54 | /// 55 | Parameter(const Variable &value); 56 | 57 | /// 58 | /// \brief Получение значения параметра 59 | /// \return переменную-значение параметра 60 | /// 61 | const Variable &getValue() const; 62 | 63 | /// 64 | /// \brief Установка значения параметра 65 | /// \param новое значение параметра 66 | /// 67 | void setValue(const Variable &value); 68 | 69 | /// 70 | /// \brief Получение ссылки на переменную, в которой хранится значение параметра 71 | /// \return ссылку на переменную, в которой хранится значение параметра 72 | /// 73 | Variable &getVariable(); 74 | 75 | }; 76 | 77 | } 78 | 79 | #endif // ANANDAMIDEPARAMETER_H 80 | -------------------------------------------------------------------------------- /include/AnandamideScript.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ANANDAMIDE_SCRIPT_H 26 | #define ANANDAMIDE_SCRIPT_H 27 | 28 | #include "AnandamideLibAPI.h" 29 | #include "AnandamideLogic.h" 30 | #include "Array.h" 31 | #include "Str.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | namespace Anandamide { 36 | 37 | class Xml; 38 | class Logic; 39 | class Neurone; 40 | class Libraries; 41 | 42 | enum ScriptCompileState { 43 | SCS_NOT_COMPILED, 44 | SCS_COMPILED_OK, 45 | SCS_COMPILED_FAILED 46 | }; 47 | 48 | ///------------------------------------------------------------------------------ 49 | /// 50 | /// @class Script 51 | /// 52 | /// @brief Класс скрипта. 53 | /// Класс Script служит для загрузки, компиляции и запуска скриптов 54 | /// 55 | ///------------------------------------------------------------------------------ 56 | 57 | class ANANDAMIDE_API Script { 58 | 59 | friend class Logic; 60 | friend class ScriptLibrary; 61 | 62 | Array logics; 63 | Logic *main; 64 | Libraries *libraries; 65 | 66 | bool is_shutdown; 67 | Action *shutdown_action; 68 | 69 | void *user_data; 70 | const Xml *loading; 71 | 72 | void preLoadLogic(const char *name_str); 73 | Str name; 74 | Str id; 75 | Str fileName; 76 | ScriptCompileState scriptCompileState; 77 | 78 | protected: 79 | 80 | Script(); 81 | virtual ~Script(); 82 | void generateId(); 83 | 84 | public: 85 | 86 | /// 87 | /// \brief Получение занимаемого размера памяти 88 | /// \return размер в байтах 89 | /// 90 | virtual unsigned long long getSize(); 91 | 92 | const char *getId() const; 93 | 94 | /// 95 | /// \brief Функция создания экземпляра класса Script 96 | /// \return новый экземпляр класса Script 97 | /// 98 | static Script *create(); 99 | 100 | Script* clone(); 101 | 102 | /// 103 | /// \brief Уничтожение экземпляра класса Script 104 | /// 105 | void destroy(); 106 | 107 | /// 108 | /// \brief Очистка содержимого скрипта (блоков, загруженных библиотек, уничтожение скомпилированного скрита) 109 | /// 110 | void clear(); 111 | 112 | /// 113 | /// \brief Компиляция скрипта 114 | /// \return true, если операция успешна 115 | /// 116 | bool compile(); 117 | 118 | /// 119 | /// \brief getCompileState возвращает состояние скомпилированности сценария 120 | /// \return 121 | /// 122 | ScriptCompileState getCompileState() const; 123 | 124 | /// 125 | /// \brief Запуск скрипта (запуск Action "entry" у блока \"Main\"). 126 | /// \return true, если операция успешна 127 | /// 128 | bool run(); 129 | 130 | /// 131 | /// \brief Установка коллбэк-функции, выполняющейся при завершении скрипта 132 | /// \param action коллбэк-функция 133 | /// 134 | void setShutdownAction(Action *action); 135 | 136 | /// 137 | /// \brief Завершение скрипта. 138 | /// 139 | void shutdown(); 140 | 141 | /// 142 | /// \brief Проверка на завершение работы 143 | /// \return состояние завершенности скрипта 144 | /// 145 | bool isShutdown() const; 146 | 147 | /// 148 | /// \brief Вызов update() у всех блоков 149 | /// \param dt время в секундах, прошедшее с предыдущего момента вызова update() 150 | /// 151 | void update(float dt); 152 | 153 | /// 154 | /// \brief Создание "нового" скрипта (очистка и создание блока "Main" и Action "entry") 155 | /// 156 | void newScript(); 157 | 158 | /// 159 | /// \brief Получение количества исходных скриптовых блоков 160 | /// \return количество исходных скриптовых блоков внутри скрипта 161 | /// 162 | int getLogicsCount(); 163 | 164 | /// 165 | /// \brief Получение скомпилированного главного блока. 166 | /// \return скомпилированный главный блок \"Main\". В случае, если скрипт не скопмпилирован, вернет NULL. 167 | /// 168 | Logic *getMain(); 169 | 170 | /// 171 | /// \brief Получение имени блока по индексу 172 | /// \param i индекс блока 173 | /// \return исходный скриптовых блок с индексом i 174 | /// 175 | Logic *getLogic(int i); 176 | 177 | /// 178 | /// \brief Добавление нового исходного блока в скрипт. 179 | /// \param name имя нового блока. 180 | /// \return новый исходный блок или NULL в случае, если исходный блок с таким именем уже существует. 181 | /// 182 | Logic *addLogic(const char *name); 183 | 184 | /// 185 | /// \brief Добавление существующего исходного блока в скрипт 186 | /// \param logic существующий исходный блок 187 | /// \return false, если блок не был добавлен по причине того, что блок с таким именем уже существует 188 | /// 189 | bool addLogic(Logic *logic); 190 | 191 | /// 192 | /// \brief Поиск исходного блока по имени 193 | /// \param name_str имя исходного блока 194 | /// \return найденный исходный блок, либо NULL в случае, если исходный блок не найден 195 | /// 196 | Logic *findLogic(const char *name_str); 197 | 198 | /// 199 | /// \brief Поиск исходного блока по имени и получение его индекса 200 | /// \param name имя исходного блока 201 | /// \return индекс найденного исходного блока, либо -1 в случае, если исходный блок не найден 202 | /// 203 | int indexOfLogic(const char *name); 204 | 205 | /// 206 | /// \brief Удаление исходного блока 207 | /// \param logic исходный блок, который следует удалить 208 | /// 209 | void removeLogic(Logic *logic); 210 | 211 | /// 212 | /// \brief Создание блока (создается либо новый скриптовый блок из этого скрипта, либо блок из библиотеки) 213 | /// \param type имя типа блока 214 | /// \param dummy флаг создания блока-пустышки 215 | /// \return новый созданный блок, либо NULL в случае неудачи 216 | /// 217 | Neurone *createNeurone(const char *type, const char *library, bool dummy = false, Neurone* dummyNode = NULL); 218 | 219 | /// 220 | /// \brief Чтение скрипта из формата Xml 221 | /// \param xml объект Xml 222 | /// \param version версия файла 223 | /// \return false, в случае возникновения ошибок 224 | /// 225 | bool readXml(const Xml *xml, int version, const char* scriptFileName); 226 | 227 | /// 228 | /// \brief readXmlLibraries Чтение библиотек скрипта из формата Xml (этап 1) 229 | /// \param xml объект Xml 230 | /// \param version версия файла 231 | /// \return false, в случае возникновения ошибок 232 | /// 233 | bool readXmlLibraries(const Xml *xml, int version, const char* scriptFileName); 234 | 235 | /// 236 | /// \brief readXmlLogics Чтение логик скрипта из формата Xml (этап 2) 237 | /// \param xml объект Xml 238 | /// \param version версия файла 239 | /// \return false, в случае возникновения ошибок 240 | /// 241 | bool readXmlLogics(const Xml *xml, int version); 242 | 243 | /// 244 | /// \brief Запись скрипта в формат Xml 245 | /// \param xml объект Xml 246 | /// 247 | void writeXml(Xml *xml, const char *script_file = NULL) const; 248 | 249 | /// 250 | /// \brief Запись скприта в файл 251 | /// \param name имя файла 252 | /// 253 | void save(const char *name); 254 | 255 | /// 256 | /// \brief Загрузка скрипта из файла 257 | /// \param name имя файла 258 | /// \return false, в случае возникновения ошибок 259 | /// 260 | bool load(const char *filename); 261 | 262 | /// 263 | /// \brief loadLibraries загрузка библиотек из файла AND (этап 1) 264 | /// \param filename 265 | /// \return false, в случае возникновения ошибок 266 | /// 267 | bool loadLibraries(const char *filename); 268 | 269 | /// 270 | /// \brief loadLogics загрузка логик из файла AND (этап 2) 271 | /// \param filename 272 | /// \return false, в случае возникновения ошибок 273 | /// 274 | bool loadLogics(const char *filename); 275 | 276 | bool loadScriptName(const char *filename); 277 | 278 | /// 279 | /// \brief Получение загруженных библиотек 280 | /// \return загруженные библиотеки скрипта 281 | /// 282 | Libraries *getLibraries(); 283 | 284 | /// 285 | /// \brief Получение имени скрипта 286 | /// \return имя скрипта 287 | /// 288 | const char *getName() const; 289 | 290 | /// 291 | /// \brief Установка нового имени скрипта. В случае, если скрипт используется как библиотека, 292 | /// имя скрипта будет являться именем библиотеки. 293 | /// \param name новое имя скрипта 294 | /// 295 | void setName(const char *name); 296 | 297 | /// 298 | /// \brief Установка пользовательских данных скрипта. 299 | /// \param пользовательский данные 300 | /// 301 | void setUserData(void *data); 302 | 303 | /// 304 | /// \brief Получение пользовательских данных скрипта 305 | /// \return пользовательский данные 306 | /// 307 | void *getUserData() const; 308 | 309 | void renameNodes(const char* oldName, const char* newName); 310 | 311 | void removeLibraryNodes(Anandamide::Library* lib); 312 | }; 313 | 314 | } 315 | 316 | #endif // ANANDAMIDESCRIPT_H 317 | -------------------------------------------------------------------------------- /include/AnandamideStdLib.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ANANDAMIDESTDLIB_H 26 | #define ANANDAMIDESTDLIB_H 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "AnandamideLibrary.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | namespace Anandamide { 36 | ANANDAMIDE_API VariableArray arrayCreate(); 37 | ANANDAMIDE_API int arraySize(VariableArray array); 38 | ANANDAMIDE_API void arrayAppend(VariableArray array, const Variable &v); 39 | ANANDAMIDE_API void arrayAppend(VariableArray array_dst, VariableArray array_src); 40 | ANANDAMIDE_API int arrayIndexOf(VariableArray array, const Variable &v); 41 | ANANDAMIDE_API void arrayResize(VariableArray array, int size); 42 | ANANDAMIDE_API const Variable &arrayGet(VariableArray array, int index); 43 | ANANDAMIDE_API void arraySet(VariableArray array, int index, const Variable &value); 44 | ANANDAMIDE_API void arrayRemove(VariableArray array, int index); 45 | ANANDAMIDE_API void arrayClear(VariableArray array); 46 | 47 | ANANDAMIDE_API VariableMap mapCreate(); 48 | ANANDAMIDE_API int mapSize(VariableMap map); 49 | ANANDAMIDE_API void mapAppend(VariableMap map, const Variable &key, const Variable &v); 50 | ANANDAMIDE_API const Variable &mapGet(VariableMap map, const Variable &key); 51 | ANANDAMIDE_API const Variable &mapGet(VariableMap map, int index); 52 | ANANDAMIDE_API const Variable &mapKey(VariableMap map, int index); 53 | ANANDAMIDE_API bool mapContains(VariableMap map, const Variable &key); 54 | ANANDAMIDE_API void mapRemove(VariableMap map, const Variable &key); 55 | ANANDAMIDE_API void mapClear(VariableMap map); 56 | } 57 | 58 | enum CompareOperation { 59 | IF_EQUAL, 60 | IF_NOTEQUAL, 61 | IF_GREATER, 62 | IF_GEQUAL, 63 | IF_LESS, 64 | IF_LEQUAL, 65 | }; 66 | 67 | ENUM_BEGIN(CompareOperation) 68 | ENUM_ITEM_NAMED(IF_EQUAL, "==") 69 | ENUM_ITEM_NAMED(IF_NOTEQUAL, "!=") 70 | ENUM_ITEM_NAMED(IF_GREATER, ">") 71 | ENUM_ITEM_NAMED(IF_GEQUAL, ">=") 72 | ENUM_ITEM_NAMED(IF_LESS, "<") 73 | ENUM_ITEM_NAMED(IF_LEQUAL, "<=") 74 | ENUM_END(CompareOperation, 2000) 75 | 76 | 77 | ENUM_BEGIN(Qt::GlobalColor); 78 | ENUM_ITEM(Qt::white); 79 | ENUM_ITEM(Qt::black); 80 | ENUM_ITEM(Qt::red); 81 | ENUM_ITEM(Qt::darkRed); 82 | ENUM_ITEM(Qt::green); 83 | ENUM_ITEM(Qt::darkGreen); 84 | ENUM_ITEM(Qt::blue); 85 | ENUM_ITEM(Qt::darkBlue); 86 | ENUM_ITEM(Qt::cyan); 87 | ENUM_ITEM(Qt::darkCyan); 88 | ENUM_ITEM(Qt::magenta); 89 | ENUM_ITEM(Qt::darkMagenta); 90 | ENUM_ITEM(Qt::yellow); 91 | ENUM_ITEM(Qt::darkYellow); 92 | ENUM_ITEM(Qt::gray); 93 | ENUM_ITEM(Qt::darkGray); 94 | ENUM_ITEM(Qt::lightGray); 95 | ENUM_END(Qt::GlobalColor, 1210) 96 | 97 | typedef void (*ConsoleMessageCallback)(const char*); 98 | typedef void (*ConsoleMessageExtCallback)(const char*, bool, Qt::GlobalColor, bool, bool); 99 | 100 | ANANDAMIDE_API void setMsgFunction(ConsoleMessageCallback callBack); 101 | ANANDAMIDE_API void setMsgExtFunction(ConsoleMessageExtCallback callBack); 102 | 103 | #endif // ANANDAMIDESTDLIB_H 104 | -------------------------------------------------------------------------------- /include/AnandamideUi.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Georgy Kostarev 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // kostarevgi@gmail.com 10 | // 11 | // AnandamideAPI is free software: you can redistribute it and/or modify 12 | // it under the terms of the GNU General Public License as published by 13 | // the Free Software Foundation, either version 3 of the License, or 14 | // (at your option) any later version. 15 | // 16 | // AnandamideAPI is distributed in the hope that it will be useful, 17 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | // GNU General Public License for more details. 20 | // 21 | // You should have received a copy of the GNU General Public License 22 | // along with AnandamideAPI. If not, see . 23 | // 24 | //------------------------------------------------------------------------------ 25 | 26 | #ifndef ANANDAMIDEUILIB_H 27 | #define ANANDAMIDEUILIB_H 28 | 29 | #include "AnandamideLibrary.h" 30 | 31 | class QObject; 32 | struct QMetaObject; 33 | 34 | namespace Anandamide { 35 | 36 | 37 | ///------------------------------------------------------------------ 38 | /// 39 | /// @class ObjectLibrary 40 | /// @brief Класс библиотеки Qt объекта 41 | /// 42 | ///------------------------------------------------------------------ 43 | 44 | 45 | class ANANDAMIDE_API QObjectLibrary : public Library 46 | { 47 | 48 | Str filename; 49 | QObject *object; 50 | QObjectLibrary(QObject *object, const Str &filename); 51 | 52 | public: 53 | 54 | ~QObjectLibrary() override; 55 | 56 | /// 57 | /// \brief Функция для создания библиотеки из .ui файла 58 | /// \param filename имя файла 59 | /// \return библиотеку объекта 60 | /// 61 | static QObjectLibrary *create(const char *filename); 62 | 63 | /// 64 | /// \brief Функция для создания библиотеки из экземпляра объекта 65 | /// \param object объект 66 | /// \return библиотеку объекта 67 | /// 68 | static QObjectLibrary *create(QObject *object); 69 | 70 | /// 71 | /// \brief Функция для автоматического экспорта объекта в любую библиотеку 72 | /// \param library библиотека 73 | /// \param object объект 74 | /// 75 | static void parseDefs(Library *library, QObject *object); 76 | 77 | /// 78 | /// \brief Функция для автоматического экспорта методов и свойств мета-объекта в любую библиотеку 79 | /// \param library библиотека 80 | /// \param metaobject мета-объект 81 | /// 82 | static void parseDefs(Library *library, const QMetaObject *metaobject); 83 | 84 | void setFileName(const char *filename) override; 85 | const char *getFileName() const override; 86 | const char *getLibFileName() const override; 87 | }; 88 | 89 | typedef QObjectLibrary Ui; 90 | 91 | /// 92 | /// @macro Макрос, для определения типов, экспортируемых при помощи механизма QObjectLibrary 93 | /// @note используется вместо DEFINE_TYPEID 94 | /// 95 | #define DEFINE_TYPEID_OBJECT(TYPE, INDEX) \ 96 | DEFINE_TYPEID(TYPE, INDEX) \ 97 | Q_DECLARE_METATYPE(TYPE) \ 98 | namespace Anandamide { \ 99 | template <> \ 100 | class VariableToType { \ 101 | public: \ 102 | TYPE value; \ 103 | VariableToType(const Variable &v) { \ 104 | auto value_ = QVariant(QMetaType::type(v.getType().name()), v.getDataPtr()); \ 105 | if (!value_.isValid() || !value_.canConvert(qMetaTypeId ())) { \ 106 | warningMessage(format("Undefined conversion between <%s> and <%s> types. Check DEFINE_TYPEID_OBJECT macro.", v.getType().name(), #TYPE)); \ 107 | return; \ 108 | } \ 109 | value_.convert(qMetaTypeId ()); \ 110 | value = value_.value (); \ 111 | } \ 112 | }; \ 113 | namespace __DEFS { \ 114 | struct __DEFINE_TYPE_##INDEX { inline __DEFINE_TYPE_##INDEX() { qRegisterMetaType (); } }; \ 115 | static __DEFINE_TYPE_##INDEX __TYPE_DEFINITION_##INDEX; \ 116 | } \ 117 | } 118 | } 119 | 120 | #endif // ANANDAMIDEUILIB_H 121 | -------------------------------------------------------------------------------- /include/Array.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ArrayH 26 | #define ArrayH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | //#include "MathCore.h" 31 | #include "AnandamideLibAPI.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | #include 36 | #include 37 | 38 | //------------------------------------------------------------------------------ 39 | 40 | #define CHECK_RANGE(index) { \ 41 | static char error[0x200]; \ 42 | if (index >= size || index < 0) { \ 43 | sprintf(error, "Array <%s> : index out of bounds (index = %d, count = %d)", typeid(Class).name(), index, size); \ 44 | throw (const char *)error; \ 45 | } \ 46 | } 47 | namespace Anandamide { 48 | 49 | template 50 | class ANANDAMIDE_API Array { 51 | 52 | int size; 53 | int capacity; 54 | bool own; 55 | 56 | protected: 57 | 58 | Class **items; 59 | 60 | void setCapacity(int newCapacity, bool own) { 61 | if (own) { 62 | while (size > newCapacity) { 63 | delete items[--size]; 64 | } 65 | } else { 66 | if (size > newCapacity) size = newCapacity; 67 | } 68 | 69 | capacity = newCapacity; 70 | Class **newItems = new Class *[capacity]; 71 | for (int i=0; i nC) 103 | remove(size - 1); 104 | } 105 | */ 106 | 107 | virtual void clear() { 108 | if (size <= 0) return; 109 | 110 | setCapacity(0, own); 111 | 112 | delete []items; 113 | capacity = 0; 114 | size = 0; 115 | items = 0; 116 | } 117 | 118 | virtual void destroy() { 119 | if (size <= 0) return; 120 | 121 | setCapacity(0, true); 122 | 123 | delete []items; 124 | capacity = 0; 125 | size = 0; 126 | items = 0; 127 | } 128 | 129 | Class &operator[](int index) { 130 | CHECK_RANGE(index); 131 | return *items[index]; 132 | } 133 | 134 | const Class &operator[](int index) const { 135 | CHECK_RANGE(index); 136 | return *items[index]; 137 | } 138 | 139 | Class &last() { 140 | CHECK_RANGE(size - 1); 141 | return *items[size - 1]; 142 | } 143 | 144 | const Class &last() const { 145 | CHECK_RANGE(size - 1); 146 | return *items[size - 1]; 147 | } 148 | 149 | Class &append(Class *e) { 150 | 151 | if (size + 1 > capacity) { 152 | setCapacity(size + 51, own); 153 | } 154 | items[size] = e; 155 | size ++; 156 | return *items[size - 1]; 157 | } 158 | 159 | int seek(const Class *e) const { 160 | for (int i=0; iafter; i--) { 197 | items[i + 1] = items[i]; 198 | } 199 | items[after + 1] = e; 200 | } 201 | 202 | void insertAt(Class *e, int at) { 203 | append(e); 204 | if(at == size - 1) return; 205 | for (int i = size - 1; i>at; i--) { 206 | items[i] = items[i - 1]; 207 | } 208 | items[at] = e; 209 | } 210 | 211 | 212 | virtual void remove(int index) { 213 | CHECK_RANGE(size - 1); 214 | 215 | if (own) delete items[index]; 216 | 217 | for (int i=index; i 100) { 222 | setCapacity(size + 50, own); 223 | } 224 | } 225 | 226 | void remove(const Class *e) { 227 | int index = seek(e); 228 | if (index != -1) { 229 | remove(index); 230 | } 231 | } 232 | 233 | bool is(int index) const { 234 | return items[index] != NULL; 235 | } 236 | 237 | /* Array &operator= (const Array &o) { 238 | clear(); 239 | own = o.own; 240 | if (own) { 241 | } else { 242 | for (int i=0; i. 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef MapH 26 | #define MapH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "Array.h" 31 | #include 32 | 33 | namespace Anandamide { 34 | 35 | //------------------------------------------------------------------------------ 36 | // 37 | // class Map 38 | // 39 | //------------------------------------------------------------------------------ 40 | 41 | template 42 | class ANANDAMIDE_API Map { 43 | 44 | class Item { 45 | 46 | friend class Map ; 47 | 48 | Key *key; 49 | Value *value; 50 | int index; 51 | 52 | public: 53 | 54 | 55 | // 56 | Item(int i, Key *k = NULL, Value *v = NULL) { 57 | index = i; 58 | key = k; 59 | value = v; 60 | } 61 | 62 | // 63 | virtual ~Item() { 64 | delete key; 65 | } 66 | 67 | // 68 | Key &getKey() { return *key; } 69 | Value &getValue() { return *value; } 70 | 71 | const Key &getKey() const { return *key; } 72 | const Value &getValue() const { return *value; } 73 | 74 | bool operator == (const Item &o) const { return *key == *o.key; } 75 | bool operator == (const Key &o) const { return *key == o; } 76 | 77 | }; 78 | 79 | Array items; 80 | Array index_items; 81 | bool own; 82 | 83 | public: 84 | 85 | // 86 | Map() : own(true), index_items(false) { } 87 | 88 | // 89 | Map(bool own_) : own(own_), index_items(false) { } 90 | 91 | // 92 | ~Map() { 93 | if(own) { 94 | for(int i = 0; i < items.count(); ++i) { 95 | //qDebug() << items[i].getKey() << typeid(items[i].getKey()).raw_name() << /*items[i].getValue() <<*/ typeid(items[i].getValue()).raw_name(); 96 | delete items[i].value; 97 | } 98 | } 99 | 100 | } 101 | 102 | // 103 | bool isOwn() { 104 | return own; 105 | } 106 | 107 | // 108 | Value *get(const Key &key) { 109 | int i = indexOf(key); 110 | if(i < 0) return NULL; 111 | return items[i].value; 112 | } 113 | 114 | const Value *get(const Key &key) const { 115 | int i = indexOf(key); 116 | if(i < 0) return NULL; 117 | return items[i].value; 118 | } 119 | 120 | Value get(const Key &key, const Value &def) const { 121 | Value *v = get(key); 122 | if(v != NULL) return *v; 123 | return def; 124 | } 125 | 126 | 127 | // ! здесь нужно заменять имеющееся значение. 128 | Item *append(Key *key, Value *value) { 129 | 130 | int i = indexOf(*key); 131 | 132 | if (i >= 0) { 133 | if(own) delete items[i].value; 134 | items[i].value = value; 135 | return &items[i]; 136 | } 137 | 138 | int first = 0; 139 | int last = items.count(); 140 | 141 | // We know that we must insert within the closed interval [first,last] 142 | while(first != last) { 143 | int mid = (first + last) / 2; 144 | const Key &k = *items[mid].key; 145 | if(k > *key) { 146 | last = mid; 147 | } else { 148 | first = mid + 1; 149 | } 150 | } 151 | 152 | Item *item = new Item(index_items.count(), key, value); 153 | index_items.append(item); 154 | items.insertAt(item, first); 155 | return item; 156 | } 157 | 158 | 159 | int count() const { return index_items.count(); } 160 | 161 | const Item &operator[](int index) const { return index_items[index]; } 162 | Item &operator[](int index) { return index_items[index]; } 163 | 164 | void remove(int index) { 165 | int i = indexOf(*index_items[index].key); 166 | if(i < 0) return; 167 | if(own) delete items[i].value; 168 | items.remove(i); 169 | index_items.remove(index); 170 | for(int j = index; j < index_items.count(); ++j) { 171 | index_items[j].index = j; 172 | } 173 | } 174 | 175 | void remove(const Key &key) { 176 | int i = indexOf(key); 177 | if(i < 0) return; 178 | if(own) delete items[i].value; 179 | index_items.remove(items[i].index); 180 | for(int j = items[i].index; j < index_items.count(); ++j) { 181 | index_items[j].index = j; 182 | } 183 | items.remove(i); 184 | } 185 | 186 | bool rename(const Key &key, const Key &new_key) { 187 | if(get(new_key) != NULL) return false; 188 | 189 | int i = indexOf(key); 190 | if(i < 0) return false; 191 | 192 | // store data 193 | Value *value = items[i].value; 194 | int old_index = items[i].index; 195 | 196 | // remove old item 197 | items.remove(i); 198 | 199 | // append new item 200 | Item *new_item = append(new Key(new_key), value); 201 | index_items.remove(index_items.count() - 1); 202 | 203 | // reindex 204 | index_items.remove(old_index); 205 | index_items.insertAt(new_item, old_index); 206 | new_item->index = old_index; 207 | 208 | return true; 209 | } 210 | 211 | void clear() { 212 | items.clear(); 213 | index_items.clear(); 214 | } 215 | 216 | int seek(const Value *value) const { 217 | for (int i=0; i key) { 244 | last = mid - 1; // and first stays the same 245 | } else { 246 | first = mid + 1; // and last stays the same 247 | } 248 | } 249 | return -1; 250 | } 251 | 252 | bool isOwner() { 253 | return own; 254 | } 255 | 256 | 257 | }; 258 | 259 | } 260 | //------------------------------------------------------------------------------ 261 | 262 | #endif 263 | 264 | //------------------------------------------------------------------------------ 265 | -------------------------------------------------------------------------------- /include/MathCore.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef MathCoreH 26 | #define MathCoreH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | #define PI 3.14159265358979323846f 36 | 37 | #define DEGTORAD 0.01745329251994329576f 38 | #define RADTODEG 57.2957795130823209071f 39 | 40 | #define EPSILON 1.0e-6f 41 | 42 | //------------------------------------------------------------------------------ 43 | 44 | namespace Anandamide { 45 | class vec3; 46 | class BBox; 47 | class Str; 48 | } 49 | 50 | //------------------------------------------------------------------------------ 51 | 52 | namespace math { 53 | 54 | //-------------------------------------------------------------------------- 55 | 56 | ANANDAMIDE_API float abs(float a); 57 | ANANDAMIDE_API float sqrt(float a); 58 | ANANDAMIDE_API float cos(float a); 59 | ANANDAMIDE_API float sin(float a); 60 | ANANDAMIDE_API void sincos(float alpha, float &sn, float &cs); 61 | ANANDAMIDE_API int random(int __num); 62 | 63 | template static T min_(const T &a, const T &b) { return (a < b) ? a : b; } 64 | template static T max_(const T &a, const T &b) { return (a > b) ? a : b; } 65 | template static void swap(T &a, T &b) { T temp = a; a = b; b = temp; } 66 | template static T lerp(const T &a, const T &b, float k) { return a + (b - a) * k; } 67 | 68 | //-------------------------------------------------------------------------- 69 | 70 | } 71 | 72 | //------------------------------------------------------------------------------ 73 | 74 | namespace Anandamide { 75 | 76 | //------------------------------------------------------------------------------ 77 | 78 | class ANANDAMIDE_API vec3 { 79 | 80 | public: 81 | 82 | //-------------------------------------------------------------------------- 83 | 84 | union { 85 | struct { float x, y, z; }; 86 | struct { float r, g, b; }; 87 | struct { float v[3]; }; 88 | }; 89 | 90 | //-------------------------------------------------------------------------- 91 | 92 | inline vec3() : x(0.0f), y(0.0f), z(0.0f) {} 93 | inline vec3(float nx, float ny, float nz) : x(nx), y(ny), z(nz) {} 94 | inline vec3(const vec3 &v) : x(v.x), y(v.y), z(v.z) {} 95 | 96 | //-------------------------------------------------------------------------- 97 | 98 | inline vec3 &operator= (const vec3 &v) { x = v.x; y = v.y; z = v.z; return *this; } 99 | inline vec3 operator- () const { return vec3(-x, -y, -z); } 100 | inline vec3 operator+ () const { return vec3(x, y, z); } 101 | 102 | //-------------------------------------------------------------------------- 103 | 104 | inline vec3 operator+ (const vec3 &v) const { return vec3(x + v.x, y + v.y, z + v.z); } 105 | inline vec3 operator- (const vec3 &v) const { return vec3(x - v.x, y - v.y, z - v.z); } 106 | inline vec3 operator* (const vec3 &v) const { return vec3(x * v.x, y * v.y, z * v.z); } 107 | inline vec3 operator/ (const vec3 &v) const { return vec3(x / v.x, y / v.y, z / v.z); } 108 | inline vec3 operator* (float a) const { return vec3(x * a, y * a, z * a); } 109 | inline vec3 operator/ (float a) const { return vec3(x / a, y / a, z / a); } 110 | 111 | //-------------------------------------------------------------------------- 112 | 113 | inline vec3 &operator+= (const vec3 &v) { x += v.x; y += v.y; z += v.z; return *this; } 114 | inline vec3 &operator-= (const vec3 &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } 115 | inline vec3 &operator/= (const vec3 &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } 116 | inline vec3 &operator*= (const vec3 &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } 117 | inline vec3 &operator*= (float a) { x *= a; y *= a; z *= a; return *this; } 118 | inline vec3 &operator/= (float a) { x /= a; y /= a; z /= a; return *this; } 119 | 120 | //-------------------------------------------------------------------------- 121 | 122 | inline float &operator[] (int i) { return v[i]; } 123 | inline float operator[] (int i) const { return v[i]; } 124 | 125 | //-------------------------------------------------------------------------- 126 | 127 | inline bool operator== (const vec3 &v) const { return ::math::abs(x - v.x) <= EPSILON && ::math::abs(y - v.y) <= EPSILON && ::math::abs(z - v.z) <= EPSILON; } 128 | inline bool operator!= (const vec3 &v) const { return ::math::abs(x - v.x) > EPSILON || ::math::abs(y - v.y) > EPSILON || ::math::abs(z - v.z) > EPSILON; } 129 | 130 | //-------------------------------------------------------------------------- 131 | 132 | inline bool operator> (const vec3 &v) const { return (x - v.x) > EPSILON && (y - v.y) > EPSILON && (z - v.z) > EPSILON; } 133 | inline bool operator< (const vec3 &v) const { return (x - v.x) < -EPSILON && (y - v.y) < -EPSILON && (z - v.z) < -EPSILON; } 134 | inline bool operator>= (const vec3 &v) const { return (x - v.x) >= -EPSILON && (y - v.y) >= -EPSILON && (z - v.z) >= -EPSILON; } 135 | inline bool operator<= (const vec3 &v) const { return (x - v.x) <= EPSILON && (y - v.y) <= EPSILON && (z - v.z) <= EPSILON; } 136 | 137 | inline bool isZero() const { return ::math::abs(x) < EPSILON && ::math::abs(y) < EPSILON && ::math::abs(z) < EPSILON; } 138 | inline bool isOne() const { return ::math::abs(x - 1.0f) < EPSILON && ::math::abs(y - 1.0f) < EPSILON && ::math::abs(z - 1.0f) < EPSILON; } 139 | 140 | //-------------------------------------------------------------------------- 141 | 142 | inline float length() const { return ::math::sqrt(x * x + y * y + z * z); } 143 | inline float lengthSquared() const { return x * x + y * y + z * z; } 144 | 145 | inline bool equals(const vec3 &v, float eps = EPSILON) const { return ::math::abs(x - v.x) <= eps && ::math::abs(y - v.y) <= eps && ::math::abs(z - v.z) <= eps; } 146 | 147 | //-------------------------------------------------------------------------- 148 | 149 | inline void normalize(); 150 | 151 | //-------------------------------------------------------------------------- 152 | 153 | void operator<<(const Str &str); 154 | void operator>>(Str &str) const; 155 | 156 | }; 157 | 158 | inline vec3 normalize(const vec3 &v) { 159 | 160 | float len = v.length(); 161 | if (::math::abs(len) > EPSILON) { 162 | float inv = 1.0f / len; 163 | return vec3(v.x * inv, v.y * inv, v.z * inv); 164 | } else { 165 | return v; 166 | } 167 | } 168 | 169 | //-------------------------------------------------------------------------- 170 | 171 | inline float dot(const vec3 &a, const vec3 &b) { 172 | return 173 | a.x * b.x + 174 | a.y * b.y + 175 | a.z * b.z; 176 | } 177 | 178 | //-------------------------------------------------------------------------- 179 | 180 | inline vec3 cross(const vec3 &a, const vec3 &b) { 181 | 182 | return vec3( 183 | a.y * b.z - b.y * a.z, 184 | a.z * b.x - b.z * a.x, 185 | a.x * b.y - b.x * a.y 186 | ); 187 | } 188 | 189 | //-------------------------------------------------------------------------- 190 | 191 | inline vec3 interp(const vec3 &v1, const vec3 &v2, float t) { 192 | return v1 + (v2 - v1) * t; 193 | } 194 | 195 | //------------------------------------------------------------------------------ 196 | 197 | template 198 | class ANANDAMIDE_API Vector2x { 199 | 200 | public: 201 | 202 | union { 203 | struct { T x, y; }; 204 | struct { T v[2]; }; 205 | }; 206 | 207 | Vector2x(T nx = 0, T ny = 0) : x(nx), y(ny) {} 208 | 209 | T &operator[] (int i) { return v[i]; } 210 | T operator[] (int i) const { return v[i]; } 211 | 212 | }; 213 | 214 | //------------------------------------------------------------------------------ 215 | 216 | template 217 | class ANANDAMIDE_API Vector4x { 218 | 219 | public: 220 | 221 | union { 222 | struct { T x, y, z, w; }; 223 | struct { T r, g, b, a; }; 224 | struct { T v[4]; }; 225 | }; 226 | 227 | Vector4x(T nx = 0, T ny = 0, T nz = 0, T nw = 0) : x(nx), y(ny), z(nz), w(nw) {} 228 | 229 | T &operator[] (int i) { return v[i]; } 230 | T operator[] (int i) const { return v[i]; } 231 | 232 | }; 233 | 234 | //------------------------------------------------------------------------------ 235 | 236 | namespace math { 237 | vec3 abs(const vec3 &a); 238 | } 239 | 240 | typedef Vector2x Vector2f; 241 | typedef Vector4x Vector4f; 242 | 243 | //------------------------------------------------------------------------------ 244 | 245 | class Quaternion; 246 | 247 | //------------------------------------------------------------------------------ 248 | 249 | class ANANDAMIDE_API Matrix { 250 | 251 | public: 252 | 253 | union { 254 | struct { float data[4][4]; }; 255 | struct { float v[16]; }; 256 | }; 257 | 258 | Matrix(); 259 | 260 | void identity(); 261 | bool inverse(); 262 | void transpose(); 263 | 264 | void basis(const vec3 &, const vec3 &, const vec3 &, const vec3 &); 265 | 266 | Matrix operator* (const Matrix &) const; 267 | vec3 operator* (const vec3 &) const; 268 | Vector4f operator* (const Vector4f &) const; 269 | 270 | bool operator== (const Matrix &o); 271 | bool operator!= (const Matrix &o); 272 | 273 | bool equals(const Matrix &o, float eps = EPSILON); 274 | static Matrix rotateX(float); 275 | static Matrix rotateY(float); 276 | static Matrix rotateZ(float); 277 | static Matrix translate(const vec3 &); 278 | static Matrix scale(const vec3 &); 279 | 280 | vec3 getPos() const; 281 | void setPos(const vec3 &pos); 282 | void setScale(const vec3 &scale); 283 | 284 | void mult(const Matrix &m); 285 | void multOrder(const Matrix &m); 286 | void normalize(); 287 | void decompose(vec3 &pos, Quaternion &rot, vec3 &scale); 288 | 289 | Vector4f getRow(int i) const; 290 | Vector4f getColumn(int i) const; 291 | 292 | operator float *() { return (float *)data; } 293 | operator const float *() const { return (const float *)data; } 294 | 295 | }; 296 | 297 | //------------------------------------------------------------------------------ 298 | 299 | class Line { 300 | 301 | public: 302 | 303 | vec3 src; 304 | vec3 dst; 305 | 306 | Line() { } 307 | Line(const vec3 &s, const vec3 &d) : src(s), dst(d) { } 308 | 309 | inline vec3 getDirection() const { return (dst - src); } 310 | }; 311 | 312 | //------------------------------------------------------------------------------ 313 | 314 | class ANANDAMIDE_API Plane { 315 | 316 | public: 317 | vec3 normal; 318 | float dist; 319 | 320 | Plane() : normal(0.0f, 0.0f, 1.0f), dist(0.0f) {} 321 | Plane(const vec3 &n, float d) : normal(n), dist(d) {} 322 | Plane(const vec3 &, const vec3 &); 323 | 324 | vec3 getOrigin(); 325 | void setOrigin(const vec3 &); 326 | 327 | void normalize(); 328 | friend Plane normalize(const Plane &); 329 | //bool trace(const Line &, TracePoint &, bool = false, bool = false) const; 330 | }; 331 | 332 | //------------------------------------------------------------------------------ 333 | 334 | #undef min 335 | #undef max 336 | 337 | class ANANDAMIDE_API BBox { 338 | 339 | public: 340 | 341 | vec3 min; 342 | vec3 max; 343 | 344 | BBox() { } 345 | BBox(const vec3 &mn, const vec3 &mx); 346 | 347 | vec3 getOrigin() const { return min + (max - min) * 0.5f; } 348 | vec3 getExtents() const { return (max - min) * 0.5; } 349 | 350 | vec3 getVertex(int) const; 351 | Plane getPlane(int) const; 352 | 353 | //bool trace(const Line &, TracePoint &, bool = false, bool = false) const; 354 | void include(const vec3 &, float = 0.0f); 355 | 356 | }; 357 | 358 | //------------------------------------------------------------------------------ 359 | 360 | class ANANDAMIDE_API Frustum { 361 | 362 | Plane planes[6]; 363 | 364 | int viewport[4]; 365 | Matrix modelview; 366 | Matrix projection; 367 | 368 | void invalidate(); 369 | 370 | public: 371 | 372 | Frustum(); 373 | Frustum(const float *mv, const float *p, int *vp) { set(mv, p, vp); } 374 | void set(const float *mv, const float *p, int *vp); 375 | 376 | const Matrix &getModelview() const { return modelview; } 377 | const Matrix &getProjection() const { return projection; } 378 | 379 | const int *getViewport() const { return viewport; } 380 | const Plane &getPlane(int i) const { return planes[i]; } 381 | 382 | void setModelview(const Matrix &); 383 | void setProjection(const Matrix &); 384 | 385 | void setViewport(int *); 386 | 387 | }; 388 | 389 | //------------------------------------------------------------------------------ 390 | 391 | bool overlaps(const BBox &, const BBox &); 392 | 393 | //------------------------------------------------------------------------------ 394 | 395 | } 396 | 397 | namespace Nutmeg { 398 | 399 | const char *intToStr(int i); 400 | const char *floatToStr(float i); 401 | const char *doubleToStr(double i); 402 | const char *vectorToStr(const Anandamide::vec3 &v); 403 | const char *quaternionToStr(const Anandamide::Quaternion &q); 404 | const char *matrixToStr(const Anandamide::Matrix &m); 405 | 406 | inline const char *toString(int i) { return intToStr(i); } 407 | inline const char *toString(float f) { return floatToStr(f); } 408 | inline const char *toString(double f) { return doubleToStr(f); } 409 | inline const char *toString(const Anandamide::vec3 &v) { return vectorToStr(v); } 410 | inline const char *toString(const Anandamide::Quaternion &q) { return quaternionToStr(q); } 411 | inline const char *toString(const Anandamide::Matrix &m) { return matrixToStr(m); } 412 | 413 | int strToInt(const char *str); 414 | float strToFloat(const char *str); 415 | double strToDouble(const char *str); 416 | Anandamide::vec3 strToVector(const char *str); 417 | Anandamide::Quaternion strToQuaternion(const char *str); 418 | Anandamide::Matrix strToMatrix(const char *str); 419 | 420 | void fromString(const char *str, int &i); 421 | void fromString(const char *str, float &f); 422 | void fromString(const char *str, double &f); 423 | void fromString(const char *str, Anandamide::vec3 &v); 424 | void fromString(const char *str, Anandamide::Quaternion &q); 425 | void fromString(const char *str, Anandamide::Matrix &m); 426 | 427 | } 428 | 429 | //------------------------------------------------------------------------------ 430 | 431 | #endif 432 | 433 | //------------------------------------------------------------------------------ 434 | -------------------------------------------------------------------------------- /include/Renderer.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef RendererH 26 | #define RendererH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "MathCore.h" 32 | #include 33 | 34 | //------------------------------------------------------------------------------ 35 | 36 | class QPainter; 37 | class QImage; 38 | class QPixmap; 39 | 40 | namespace Anandamide { 41 | 42 | class ANANDAMIDE_API Renderer { 43 | 44 | bool initialized; 45 | 46 | float fontSize; 47 | 48 | Matrix modelMatrix; 49 | Matrix viewMatrix; 50 | Matrix modelviewMatrix; 51 | Matrix projectionMatrix; 52 | 53 | double dModelviewMatrix[16]; 54 | double dProjectionMatrix[16]; 55 | 56 | int width; 57 | int height; 58 | 59 | vec3 up; 60 | vec3 right; 61 | vec3 currentColor; 62 | vec3 ambientColor; 63 | vec3 cameraPos; 64 | 65 | float currentAlpha; 66 | float pointSize; 67 | bool lineSmooth; 68 | 69 | QPainter *painter; 70 | 71 | static QMap staticImages; 72 | static void addStaticImage(const QString& filename); 73 | static QImage* getStaticImage(const QString& filename); 74 | 75 | public: 76 | 77 | static void initStaticImages(); 78 | static void doneStaticImages(); 79 | 80 | Renderer(); 81 | virtual ~Renderer(); 82 | 83 | void setPainter(QPainter *painter) { 84 | this->painter = painter; 85 | } 86 | 87 | QPainter *getPainter() { 88 | return painter; 89 | } 90 | 91 | //-------------------------------------------------------------------------- 92 | // common 93 | //-------------------------------------------------------------------------- 94 | 95 | virtual void init(); 96 | 97 | //-------------------------------------------------------------------------- 98 | // base 99 | //-------------------------------------------------------------------------- 100 | 101 | virtual void color(float r, float g, float b, float a = 1.0f); 102 | virtual void color(const vec3 &, float a = 1.0f); 103 | 104 | virtual vec3 getColor() const; 105 | 106 | //-------------------------------------------------------------------------- 107 | // 108 | //-------------------------------------------------------------------------- 109 | 110 | virtual void clear(bool = true, bool = true, const vec3 &c = vec3(0.0f, 0.0f, 0.0f)); 111 | virtual void begin(); 112 | virtual void end(); 113 | 114 | //-------------------------------------------------------------------------- 115 | // 2d mode 116 | //-------------------------------------------------------------------------- 117 | 118 | //virtual void set2d(int w = -1, int h = -1); 119 | virtual void setResolution(int w, int h); 120 | virtual int getWidth() const; 121 | virtual int getHeight() const; 122 | virtual void rect(float x, float y, float w, float h); 123 | virtual void rectLine(float x, float y, float w, float h); 124 | void rect3d(float x, float y, float w, float h, bool selected = false); 125 | virtual void rectFill(float x, float y, float w, float h); 126 | 127 | virtual void linkSpline(const vec3 &p0, const vec3 &p1, const vec3 &c0, const vec3 &c1, bool selected = false, int num = -1); 128 | 129 | /// 130 | /// \brief linkSpline Drawing link spline with user-defined angles [use in CustomNeurone] 131 | /// \param a0 src angle 132 | /// \param a1 dst angle 133 | /// 134 | virtual void linkSpline(const vec3 &p0, const vec3 &p1, float a0, float a1, const vec3 &c0, const vec3 &c1, bool selected, int num); 135 | virtual void linkSpline(const vec3 &p0, const vec3 &p1, const vec3 &d0, const vec3 &d1, const vec3 &c0, const vec3 &c1, bool selected = false, int num = -1); 136 | 137 | static bool selectSpline(const vec3 &p0, const vec3 &p1, const vec3 &by, float radius); 138 | static bool selectSpline(const vec3 &p0, const vec3 &p1, const vec3 &d0, const vec3 &d1, const vec3 &by, float radius); 139 | static bool selectSpline(const vec3 &p0, const vec3 &p1, float a0, float a1, const vec3 &by, float radius); 140 | 141 | virtual void drawImage(float x, float y, float w, float h, const QImage &image); 142 | virtual void drawStaticImage(float x, float y, float w, float h, const QString &image_name); 143 | 144 | void clearPolygonPoints(); 145 | void addPolygonPoint(float x, float y); 146 | void polygonDraw(); 147 | 148 | void text(float x, float y, const char *text, ...); 149 | void textInRect(float left, float top, float width, float height, int flags, const char *text, ...); 150 | float textWidth(const char *text, ...); 151 | float textHeight(const char *text, ...); 152 | 153 | void textBold(float x, float y, const char *text, ...); 154 | void textBoldInRect(float left, float top, float width, float height, int flags, const char *text, ...); 155 | float textBoldWidth(const char *text, ...); 156 | float textBoldHeight(const char *text, ...); 157 | 158 | void textToWidth(float left, float width, float topCenter, bool leftToRight, const char *text, ...); 159 | float getTextPointSizeByWidth(float width, const char *text, ...); 160 | float textWidth(float textSize, const char *text, ...); 161 | float textHeight(float textSize, const char *text, ...); 162 | void text(float textSize, float x, float y, const char *text, ...); 163 | 164 | //-------------------------------------------------------------------------- 165 | // 3d mode 166 | //-------------------------------------------------------------------------- 167 | 168 | //virtual void set3d(); 169 | 170 | virtual void render(const Line &); 171 | 172 | //-------------------------------------------------------------------------- 173 | // resources 174 | //-------------------------------------------------------------------------- 175 | 176 | virtual void setMatrix(const Matrix &); 177 | virtual const Matrix &getMatrix() const; 178 | 179 | virtual void setViewMatrix(const Matrix &); 180 | virtual const Matrix &getViewMatrix() const; 181 | 182 | int *getViewport(); 183 | void setFrustum(const Frustum &f); 184 | virtual void getFrustum(Frustum &f); 185 | 186 | virtual vec3 unproject(const vec3 &v, const Frustum &f); 187 | virtual vec3 project(const vec3 &v, const Frustum &f); 188 | 189 | }; 190 | 191 | //------------------------------------------------------------------------------ 192 | } 193 | 194 | #endif 195 | -------------------------------------------------------------------------------- /include/Resource.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef ResourceH 26 | #define ResourceH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "Str.h" 31 | #include "Map.h" 32 | #include "Xml.h" 33 | #include 34 | 35 | //------------------------------------------------------------------------------ 36 | // 37 | // namespace Nutmeg 38 | // 39 | //------------------------------------------------------------------------------ 40 | 41 | namespace Anandamide { 42 | 43 | //-------------------------------------------------------------------------- 44 | 45 | class ResourceItemBase; 46 | class ResourceManBase; 47 | template class ResourceMan; 48 | 49 | //-------------------------------------------------------------------------- 50 | // 51 | // class ResourceItemBase 52 | // 53 | //-------------------------------------------------------------------------- 54 | 55 | class ResourceItemBase { 56 | 57 | public: 58 | 59 | Str name; 60 | Str file_name; 61 | 62 | int ref_count; 63 | int time_stamp; 64 | int file_size; 65 | float loading_time; 66 | 67 | ResourceItemBase() { 68 | ref_count = 0; 69 | time_stamp = 0; 70 | file_size = 0; 71 | loading_time = 0.0f; 72 | } 73 | 74 | virtual ~ResourceItemBase() { } 75 | 76 | }; 77 | 78 | //-------------------------------------------------------------------------- 79 | // 80 | // class ResourceItem 81 | // 82 | //-------------------------------------------------------------------------- 83 | 84 | template 85 | class ResourceItem : public ResourceItemBase { 86 | 87 | public: 88 | 89 | T *data; 90 | 91 | ResourceItem(T *data_) { 92 | data = data_; 93 | } 94 | 95 | virtual ~ResourceItem() { 96 | delete data; 97 | } 98 | 99 | }; 100 | 101 | //-------------------------------------------------------------------------- 102 | // 103 | // class Resource 104 | // 105 | //-------------------------------------------------------------------------- 106 | 107 | template 108 | class Resource { 109 | 110 | friend class ResourceMan ; 111 | 112 | static ResourceMan &manager() { 113 | static ResourceMan value(new T()); 114 | return value; 115 | } 116 | 117 | ResourceItem *resource_item; 118 | 119 | Resource(ResourceItem *resource_item_) : resource_item(NULL) { 120 | resource_item = resource_item_; 121 | assert(resource_item != NULL); 122 | resource_item->ref_count ++; 123 | } 124 | 125 | public: 126 | 127 | Resource() : resource_item(NULL) { 128 | resource_item = manager().getDefaultResourceItem(); 129 | resource_item->ref_count ++; 130 | } 131 | 132 | // 133 | Resource(const Resource &o) { 134 | resource_item = o.resource_item; 135 | resource_item->ref_count ++; 136 | } 137 | 138 | // 139 | Resource(const char *name) { 140 | resource_item = NULL; 141 | *this = manager().load(name); 142 | } 143 | 144 | // 145 | ~Resource() { 146 | if (resource_item == NULL) return; 147 | resource_item->ref_count --; 148 | manager().freeUnused(); 149 | } 150 | 151 | bool is() const { 152 | return resource_item != NULL && resource_item->data != NULL; 153 | } 154 | 155 | bool isDefault() const { 156 | return resource_item->data == manager().getDefaultResource(); 157 | } 158 | 159 | void load(const char *name) { 160 | *this = manager().load(name); 161 | } 162 | 163 | Resource &operator=(const Resource &o) { 164 | if (&o == this) return *this; 165 | if (resource_item != NULL) resource_item->ref_count --; 166 | resource_item = o.resource_item; 167 | resource_item->ref_count ++; 168 | manager().freeUnused(); 169 | return *this; 170 | } 171 | 172 | // 173 | const T *operator->() const { 174 | if (resource_item == NULL || resource_item->data == NULL) { 175 | return manager().getDefaultResourceItem()->data; 176 | } 177 | return resource_item->data; 178 | } 179 | 180 | // 181 | const T &get() const { 182 | if (resource_item == NULL || resource_item->data == NULL) { 183 | return *manager().getDefaultResourceItem()->data; 184 | } 185 | return *resource_item->data; 186 | } 187 | 188 | // 189 | operator const T &() const { 190 | if (resource_item == NULL) { 191 | ResourceItem *&item = const_cast *&> (resource_item); 192 | item = manager().getDefaultResourceItem(); 193 | item->ref_count ++; 194 | } 195 | 196 | if (resource_item->data == NULL) { 197 | return *manager().getDefaultResourceItem()->data; 198 | } 199 | 200 | return *resource_item->data; 201 | }; 202 | 203 | bool operator==(const Resource &o) const { 204 | return resource_item == o.resource_item; 205 | } 206 | 207 | // 208 | const char *getName() const { 209 | if (resource_item == NULL) { 210 | ResourceItem *&item = const_cast *&> (resource_item); 211 | item = manager().getDefaultResourceItem(); 212 | item->ref_count ++; 213 | } 214 | return resource_item->name; 215 | } 216 | 217 | // 218 | void writeXml(const char *name, Xml *xml) const { 219 | if (resource_item == NULL) { 220 | ResourceItem *&item = const_cast *&> (resource_item); 221 | item = manager().getDefaultResourceItem(); 222 | item->ref_count ++; 223 | } 224 | xml->setChildData(name, resource_item->file_name); 225 | } 226 | 227 | void readXml(const char *name, const Xml *xml) { 228 | Str file; 229 | xml->getChildData(name, file); 230 | load(file); 231 | } 232 | 233 | static ResourceMan &getManager() { 234 | return manager(); 235 | } 236 | 237 | void setDefault() { 238 | *this = manager().load(manager().getDefaultResourceItem()->name); 239 | } 240 | 241 | int getRefsCount() const { 242 | if (resource_item != NULL) { 243 | return resource_item->ref_count; 244 | } else { 245 | return 0; 246 | } 247 | } 248 | 249 | }; 250 | 251 | //-------------------------------------------------------------------------- 252 | // 253 | // class ResourceMan 254 | // 255 | //-------------------------------------------------------------------------- 256 | 257 | template 258 | class ResourceMan { 259 | 260 | Map > items; 261 | T *default_resource; 262 | ResourceItem *default_item; 263 | 264 | ResourceItem *getItemByName(const char *id) { 265 | return items.get(id); 266 | } 267 | 268 | bool freeing; 269 | bool free_unused; 270 | 271 | public: 272 | 273 | // 274 | ResourceMan(T *def_res) { 275 | 276 | default_resource = def_res; 277 | assert(default_resource != NULL); 278 | 279 | default_item = new ResourceItem (default_resource); 280 | default_item->name = "default"; 281 | items.append(new Str(default_item->name), default_item); 282 | 283 | freeing = false; 284 | free_unused = true; 285 | } 286 | 287 | Resource load(const char *name) { 288 | 289 | ResourceItem *item = getItemByName(name); 290 | if (item == NULL) { 291 | T *data = T::loadResource(name); 292 | if(data == NULL) return default_item; 293 | item = new ResourceItem (data); 294 | item->name = name; 295 | items.append(new Str(name), item); 296 | } 297 | 298 | return Resource (item); 299 | } 300 | 301 | Resource create(const char *name, T *resource) { 302 | ResourceItem *item = items.get(name); 303 | 304 | if (item == NULL) { 305 | item = new ResourceItem (resource); 306 | item->file_name = ""; 307 | item->name = name; 308 | item->data = resource; 309 | items.append(new Str(item->name), item); 310 | } 311 | 312 | return Resource (item); 313 | } 314 | 315 | int getItemsCount() const { 316 | return items.count(); 317 | } 318 | 319 | const ResourceItem &getItem(int index) const { 320 | return items[index].getValue(); 321 | } 322 | 323 | const ResourceItem *getItemByName(const char *id) const { 324 | return items.get(id); 325 | } 326 | 327 | T *getDefaultResource() { 328 | return default_resource; 329 | } 330 | 331 | ResourceItem *getDefaultResourceItem() { 332 | return default_item; 333 | } 334 | 335 | void freeUnused() { 336 | if (free_unused == false) return; 337 | if (freeing == true) return; 338 | 339 | bool found = true; 340 | 341 | freeing = true; 342 | while (found) { 343 | found = false; 344 | for (int i=1; i &getItem(int i) { 357 | return items[i].getValue(); 358 | } 359 | 360 | bool isRemoveUnused() { 361 | return free_unused; 362 | } 363 | 364 | void setRemoveUnused(bool state) { 365 | free_unused = state; 366 | if (free_unused) freeUnused(); 367 | } 368 | 369 | }; 370 | 371 | } 372 | 373 | //------------------------------------------------------------------------------ 374 | 375 | #endif 376 | 377 | //------------------------------------------------------------------------------ 378 | -------------------------------------------------------------------------------- /include/Str.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef StrH 26 | #define StrH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "Array.h" 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | namespace Anandamide { 36 | 37 | //-------------------------------------------------------------------------- 38 | 39 | class ANANDAMIDE_API Str { 40 | 41 | char *data; 42 | int fsize; 43 | 44 | void newSize(int size); 45 | 46 | public: 47 | 48 | Str(); 49 | Str(int size); 50 | Str(const char *str); 51 | Str(const Str &str); 52 | ~Str(); 53 | 54 | void set(const char *str); 55 | void clear(); 56 | void setSize(int size); 57 | int size() const; 58 | 59 | operator char *(); 60 | operator const char *() const; 61 | 62 | const char *str() const; 63 | 64 | char &operator[](int i); 65 | char operator[](int i) const; 66 | 67 | Str &operator= (const char *str); 68 | Str &operator= (const Str &str); 69 | bool operator== (const char *str) const; 70 | bool operator== (const Str &str) const; 71 | bool operator!= (const char *str) const; 72 | bool operator!= (const Str &str) const; 73 | Str operator+ (const char *str) const; 74 | Str operator+ (char c) const; 75 | 76 | bool operator> (const Str &o) const; 77 | bool operator> (const char *str) const; 78 | 79 | const char *format(const char *fmt, ...); 80 | 81 | void del(int p, int n = 1); 82 | void ins(int ps, const char *s); 83 | void ins(int ps, char s); 84 | 85 | int getInt() const; 86 | float getFloat() const; 87 | int getDigits() const; 88 | Str getLetters() const; 89 | 90 | void split(char c, Array &strings) const; 91 | int find(const char *str) const; 92 | 93 | void toLowerCase(); 94 | Str getLowerCase() const; 95 | 96 | void replace(const char *f, const char *r); 97 | 98 | }; 99 | 100 | //-------------------------------------------------------------------------- 101 | 102 | ANANDAMIDE_API const char *format(const char *fmt, ...); 103 | 104 | //-------------------------------------------------------------------------- 105 | 106 | template class ANANDAMIDE_API Array ; 107 | 108 | //-------------------------------------------------------------------------- 109 | 110 | } 111 | //------------------------------------------------------------------------------ 112 | 113 | #endif 114 | 115 | //------------------------------------------------------------------------------ 116 | -------------------------------------------------------------------------------- /project/AnandamideAPI.pro: -------------------------------------------------------------------------------- 1 | #------------------------------------------------- 2 | # 3 | # Project created by QtCreator 2014-11-17T17:37:55 4 | # 5 | #------------------------------------------------- 6 | 7 | QT -= core gui 8 | QT += opengl uitools widgets 9 | 10 | DESTDIR = ../lib/ 11 | DLLDESTDIR = ../bin/ 12 | 13 | #CONFIG+=x64 14 | #DEFINES+=x64 15 | 16 | DOXYGEN_BIN = $$quote(..\\..\\..\\depend\\Doxygen\\bin\\doxygen.exe) 17 | DOXYGEN_CFG = $$quote(..\\docs\\source\\AnandamideAPI.cfg) 18 | 19 | defineReplace(compileDoc){ 20 | exists($${DOXYGEN_BIN}){ 21 | exists($${DOXYGEN_CFG}){ 22 | return ($$quote(cmd /c $$escape_expand(\")$${DOXYGEN_BIN}$$escape_expand(\") $$1 $$escape_expand(\n\t))) 23 | }else{ 24 | message(NOT EXIST DOXYGEN_CFG) 25 | } 26 | }else{ 27 | message(NOT EXIST DOXYGEN_BIN) 28 | } 29 | } 30 | 31 | BIN_DIR = $$quote(..\\bin\\) 32 | LIB_DIR = $$quote(..\\lib\\) 33 | #TARGET = AnandamideAPI 34 | TEMPLATE = lib 35 | 36 | DEFINES+=ANANDAMIDEAPI_LIBRARY 37 | 38 | INCLUDEPATH += ../include 39 | INCLUDEPATH += ../src/Anandamide 40 | INCLUDEPATH += ../src/Common 41 | INCLUDEPATH += ../src/Engine 42 | INCLUDEPATH += ../src/Math 43 | INCLUDEPATH += ../src/Renderer 44 | INCLUDEPATH += ../src/Misc 45 | 46 | SOURCES += \ 47 | ../src/Misc/Camera2d.cpp \ 48 | ../src/Misc/Grid.cpp \ 49 | ../src/Anandamide/Anandamide.cpp \ 50 | ../src/Anandamide/AnandamideAction.cpp \ 51 | ../src/Anandamide/AnandamideEditor.cpp \ 52 | ../src/Anandamide/AnandamideEvent.cpp \ 53 | ../src/Anandamide/AnandamideInput.cpp \ 54 | ../src/Anandamide/AnandamideLibrary.cpp \ 55 | ../src/Anandamide/AnandamideLogic.cpp \ 56 | ../src/Anandamide/AnandamideNeurone.cpp \ 57 | ../src/Anandamide/AnandamideOutput.cpp \ 58 | ../src/Anandamide/AnandamideParameter.cpp \ 59 | ../src/Anandamide/AnandamideScript.cpp \ 60 | ../src/Anandamide/AnandamideVariable.cpp \ 61 | ../src/Common/Str.cpp \ 62 | ../src/Common/Xml.cpp \ 63 | ../src/Math/MathCore.cpp \ 64 | ../src/Renderer/Renderer.cpp \ 65 | ../src/Anandamide/AnandamideStdLib.cpp \ 66 | ../src/Anandamide/AnandamideTypeInfo.cpp \ 67 | ../src/Anandamide/AnandamideUi.cpp \ 68 | ../src/Anandamide/AnandamideDragData.cpp 69 | 70 | HEADERS +=\ 71 | ../src/Misc/Camera2d.h \ 72 | ../src/Misc/Grid.h \ 73 | ../src/Common/Xml.h \ 74 | ../include/AnandamideAPI.h \ 75 | ../include/Action.h \ 76 | ../include/Anandamide.h \ 77 | ../include/AnandamideAction.h \ 78 | ../include/AnandamideEditor.h \ 79 | ../include/AnandamideEvent.h \ 80 | ../include/AnandamideInput.h \ 81 | ../include/AnandamideLibAPI.h \ 82 | ../include/AnandamideLibrary.h \ 83 | ../include/AnandamideLogic.h \ 84 | ../include/AnandamideNeurone.h \ 85 | ../include/AnandamideOutput.h \ 86 | ../include/AnandamideParameter.h \ 87 | ../include/AnandamideScript.h \ 88 | ../include/AnandamideStdLib.h \ 89 | ../include/AnandamideVariable.h \ 90 | ../include/Array.h \ 91 | ../include/Map.h \ 92 | ../include/MathCore.h \ 93 | ../include/Str.h \ 94 | ../include/Renderer.h \ 95 | ../include/AnandamideTypeInfo.h \ 96 | ../include/AnandamideDocumentation.h \ 97 | ../include/Resource.h \ 98 | ../include/AnandamideUi.h \ 99 | ../include/AnandamideDragData.h 100 | 101 | QMAKE_CXXFLAGS += -std=c++11 102 | 103 | CONFIG(debug, debug|release) { 104 | 105 | DEFINES+=DEBUG 106 | 107 | CONFIG(x64, x64|x32) { 108 | TARGET = AnandamideAPI_x64d 109 | } else { 110 | TARGET = AnandamideAPI_x86d 111 | } 112 | #LIBS += -lopengl32 113 | 114 | message($${TARGET}) 115 | } else { 116 | #QMAKE_CXXFLAGS += /Ot /Oy- /GL /MP 117 | CONFIG(x64, x64|x32) { 118 | TARGET = AnandamideAPI_x64 119 | } else { 120 | TARGET = AnandamideAPI_x86 121 | } 122 | # LIBS += -lopengl32 123 | 124 | message($${TARGET}) 125 | } 126 | 127 | unix { 128 | target.path = /usr/lib 129 | INSTALLS += target 130 | } 131 | 132 | RESOURCES += \ 133 | resources.qrc 134 | -------------------------------------------------------------------------------- /project/resources.qrc: -------------------------------------------------------------------------------- 1 | 2 | 3 | types/eye.png 4 | types/function.png 5 | types/pinion.png 6 | types/variable.png 7 | types/array.png 8 | types/undefined.png 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /project/types/array.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/project/types/array.png -------------------------------------------------------------------------------- /project/types/eye.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/project/types/eye.png -------------------------------------------------------------------------------- /project/types/function.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/project/types/function.png -------------------------------------------------------------------------------- /project/types/pinion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/project/types/pinion.png -------------------------------------------------------------------------------- /project/types/undefined.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/project/types/undefined.png -------------------------------------------------------------------------------- /project/types/variable.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Evil-Spirit/AnandamideAPI/64b6f8fadc9770c93e7665a505290ea95f2fe570/project/types/variable.png -------------------------------------------------------------------------------- /src/Anandamide/Anandamide.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "Anandamide.h" 26 | 27 | #include "AnandamideScript.h" 28 | 29 | //------------------------------------------------------------------------------ 30 | 31 | #include 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | namespace Anandamide { 36 | 37 | Messager default_messager; 38 | Messager *messager = &default_messager; 39 | 40 | Messager::~Messager() { 41 | 42 | } 43 | 44 | void Messager::message(const char *text) { 45 | qDebug() << text; 46 | } 47 | 48 | void Messager::warning(const char *text) { 49 | qDebug() << "Warning: " << text; 50 | } 51 | 52 | void Messager::error(const char *text) { 53 | qDebug() << "Error: " << text; 54 | } 55 | 56 | void errorMessage(const char *text) { 57 | qDebug() << text; 58 | if(messager != NULL) messager->error(text); 59 | } 60 | 61 | void warningMessage(const char *text) { 62 | qDebug() << text; 63 | if(messager != NULL) messager->warning(text); 64 | } 65 | 66 | void messageMessage(const char *text) { 67 | if(messager != NULL) messager->message(text); 68 | } 69 | 70 | void setMessager(Anandamide::Messager *m) { 71 | messager = m; 72 | if(messager == NULL) messager = &default_messager; 73 | } 74 | 75 | void errorPointerMessage(Input *input) 76 | { 77 | errorMessage(format("ERROR: input pointer is NULL (Script \"%s\", Logic \"%s\", Block \"%s\", Input \"%s\")", 78 | input->getNeurone()->getLogic()->getScript()->getName(), 79 | input->getNeurone()->getLogic()->getName(), 80 | input->getNeurone()->getType(), 81 | input->getName())); 82 | } 83 | 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/Anandamide/AnandamideAction.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "AnandamideAction.h" 26 | 27 | #include "AnandamideEvent.h" 28 | #include "AnandamideNeurone.h" 29 | 30 | namespace Anandamide { 31 | 32 | Action::~Action() { 33 | while (events.count() > 0) { 34 | events[0].removeAction(this); 35 | } 36 | delete action; 37 | } 38 | 39 | Neurone *Action::getNeurone() { 40 | return neurone; 41 | } 42 | 43 | const Neurone *Action::getNeurone() const { 44 | return neurone; 45 | } 46 | 47 | void Action::run() { 48 | if(action == NULL) return; 49 | action->run(); 50 | } 51 | 52 | void Action::setAction(Common::Action *action) { 53 | delete this->action; 54 | this->action = action; 55 | } 56 | 57 | const char *Action::getName() const { 58 | if(neurone == NULL) return ""; 59 | int i = neurone->indexOf(this); 60 | if(i < 0) return ""; 61 | return neurone->getActionName(i); 62 | } 63 | 64 | void Action::addEvent(Event *event) { 65 | if (events.seek(event) >= 0) return; 66 | events.append(event); 67 | } 68 | 69 | void Action::removeEvent(Event *event) { 70 | events.remove(event); 71 | } 72 | 73 | void Action::setNeurone(Neurone *neurone) { 74 | this->neurone = neurone; 75 | } 76 | 77 | Action::Action() : events(false) { 78 | action = NULL; 79 | neurone = NULL; 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/Anandamide/AnandamideDragData.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Sergey Almighty 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "AnandamideDragData.h" 26 | #include "AnandamideLibrary.h" 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include 31 | //------------------------------------------------------------------------------ 32 | 33 | namespace Anandamide { 34 | 35 | BlockDragData::BlockDragData() {} 36 | 37 | BlockDragData::~BlockDragData() {} 38 | 39 | void BlockDragData::addToMimeData(QMimeData *data) 40 | { 41 | if(!data->hasFormat("AnandamideBlock")) { 42 | QByteArray bytes2; 43 | data->setData("AnandamideBlock", bytes2); 44 | } 45 | 46 | QByteArray bytes = data->data("AnandamideBlock"); 47 | 48 | QByteArray bytes3; 49 | QDataStream out(&bytes3, QIODevice::WriteOnly); 50 | out << content.type; 51 | out << content.library; 52 | out << content.instance; 53 | out << content.params; 54 | out << content.inputs; 55 | 56 | bytes += bytes3; 57 | 58 | data->setData("AnandamideBlock", bytes); 59 | } 60 | 61 | bool BlockDragData::fillFromMimedata(const QMimeData *data) 62 | { 63 | bool res = false; 64 | 65 | if(data->hasFormat("AnandamideBlock") && data->hasFormat("AnandamideBlockNum")) { 66 | QByteArray bytes2 = data->data("AnandamideBlockNum"); 67 | QDataStream in2(&bytes2, QIODevice::ReadOnly); 68 | int num = 0; 69 | in2 >> num; 70 | 71 | QByteArray bytes = data->data("AnandamideBlock"); 72 | QDataStream in(&bytes, QIODevice::ReadOnly); 73 | 74 | contents.clear(); 75 | for(int i=0; i> content.type; 77 | in >> content.library; 78 | in >> content.instance; 79 | in >> content.params; 80 | in >> content.inputs; 81 | 82 | contents.append(content); 83 | } 84 | } 85 | 86 | return res; 87 | } 88 | 89 | QMimeData *BlockDragData::toMimeData() 90 | { 91 | QMimeData *data = new QMimeData; 92 | 93 | data->setText("This is a Drug & Drop"); 94 | 95 | QByteArray bytes; 96 | QDataStream out(&bytes, QIODevice::WriteOnly); 97 | out << content.type; 98 | out << content.library; 99 | out << content.instance; 100 | out << content.params; 101 | out << content.inputs; 102 | 103 | data->setData("AnandamideBlock", bytes); 104 | 105 | return data; 106 | } 107 | 108 | bool BlockDragData::fromMimeData(const QMimeData *data) 109 | { 110 | bool res = false; 111 | 112 | if(data->hasFormat("AnandamideBlock")) { 113 | QByteArray bytes = data->data("AnandamideBlock"); 114 | 115 | QDataStream in(&bytes, QIODevice::ReadOnly); 116 | in >> content.type; 117 | in >> content.library; 118 | in >> content.instance; 119 | in >> content.params; 120 | in >> content.inputs; 121 | } 122 | 123 | return res; 124 | } 125 | 126 | void BlockDragData::fillNeurone(Neurone *neurone) { 127 | if(content.type == "ObjectBlock") { 128 | neurone->getParameter("name")->setValue(Anandamide::Variable(content.instance.toLocal8Bit().constData())); 129 | neurone->getParameter("ownerName")->setValue(Anandamide::Variable(content.ownerName.toLocal8Bit().constData())); 130 | } else if(content.type == "SignalBlock" || content.metaType == "Signals") { 131 | neurone->getParameter("name")->setValue(Anandamide::Variable(content.instance.toLocal8Bit().constData())); 132 | neurone->getParameter("signal")->setValue(Anandamide::Variable(content.itemValue.toLocal8Bit().constData())); 133 | neurone->getParameter("ownerName")->setValue(Anandamide::Variable(content.ownerName.toLocal8Bit().constData())); 134 | } else if(content.metaType == "Slots") { 135 | neurone->getParameter("name")->setValue(Anandamide::Variable(content.instance.toLocal8Bit().constData())); 136 | neurone->getParameter("slot")->setValue(Anandamide::Variable(content.itemValue.toLocal8Bit().constData())); 137 | neurone->getParameter("ownerName")->setValue(Anandamide::Variable(content.ownerName.toLocal8Bit().constData())); 138 | } else if(content.metaType == "Methods") { 139 | neurone->getParameter("name")->setValue(Anandamide::Variable(content.instance.toLocal8Bit().constData())); 140 | neurone->getParameter("slot")->setValue(Anandamide::Variable(content.itemValue.toLocal8Bit().constData())); 141 | neurone->getParameter("ownerName")->setValue(Anandamide::Variable(content.ownerName.toLocal8Bit().constData())); 142 | } else if(content.metaType == "Properties") { 143 | neurone->getParameter("name")->setValue(Anandamide::Variable(content.instance.toLocal8Bit().constData())); 144 | neurone->getParameter("property")->setValue(Anandamide::Variable(content.itemValue.toLocal8Bit().constData())); 145 | neurone->getParameter("ownerName")->setValue(Anandamide::Variable(content.ownerName.toLocal8Bit().constData())); 146 | } else { 147 | foreach(auto key, content.params.keys()) { 148 | Parameter *param = neurone->getParameter(key.toLocal8Bit().constData()); 149 | if(param) param->setValue(Anandamide::Variable(content.params[key].toLocal8Bit().constData())); 150 | } 151 | foreach(auto key, content.inputs.keys()) { 152 | Input *input = neurone->getInput(key.toLocal8Bit().constData()); 153 | if(input) input->setValue(Anandamide::Variable(content.inputs[key].toLocal8Bit().constData())); 154 | } 155 | neurone->invalidate(); 156 | } 157 | } 158 | 159 | void BlockDragData::fillBlocksNum(QMimeData *data, int num) 160 | { 161 | data->setText("I`m Sexy Guy"); 162 | QByteArray bytes; 163 | QDataStream out(&bytes, QIODevice::WriteOnly); 164 | out << num; 165 | data->setData("AnandamideBlockNum", bytes); 166 | } 167 | 168 | void BlockDragData::print() 169 | { 170 | qDebug() << __FUNCTION__ << "type=" << content.type; 171 | qDebug() << __FUNCTION__ << "library=" << content.library; 172 | qDebug() << __FUNCTION__ << "instance=" << content.instance; 173 | qDebug() << __FUNCTION__ << "====params"; 174 | foreach(auto key, content.params.keys()) { 175 | qDebug() << key << content.params[key]; 176 | } 177 | qDebug() << __FUNCTION__ << "====inputs"; 178 | foreach(auto key, content.inputs.keys()) { 179 | qDebug() << key << content.inputs[key]; 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/Anandamide/AnandamideEvent.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "AnandamideEvent.h" 26 | 27 | #include "AnandamideAction.h" 28 | #include "AnandamideNeurone.h" 29 | 30 | namespace Anandamide { 31 | 32 | void Event::setNeurone(Neurone *neurone) { 33 | this->neurone = neurone; 34 | } 35 | 36 | Event::Event() : actions(false) { 37 | neurone = NULL; 38 | } 39 | 40 | Event::~Event() { 41 | for (int i=0; i= 0) return; 55 | 56 | action->addEvent(this); 57 | actions.append(action); 58 | } 59 | 60 | void Event::removeAction(int index) { 61 | actions[index].removeEvent(this); 62 | actions.remove(index); 63 | } 64 | 65 | void Event::removeAction(Action *action) { 66 | int index = actions.seek(action); 67 | if (index < 0) return; 68 | removeAction(index); 69 | } 70 | 71 | int Event::getActionsCount() const { 72 | return actions.count(); 73 | } 74 | 75 | Action &Event::getAction(int i) { 76 | return actions[i]; 77 | } 78 | 79 | const Action &Event::getAction(int i) const { 80 | return actions[i]; 81 | } 82 | 83 | Neurone *Event::getNeurone() { 84 | return neurone; 85 | } 86 | 87 | const Neurone *Event::getNeurone() const { 88 | return neurone; 89 | } 90 | 91 | const char *Event::getName() const { 92 | if(neurone == NULL) return ""; 93 | int i = neurone->indexOf(this); 94 | if(i < 0) return ""; 95 | return neurone->getEventName(i); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/Anandamide/AnandamideInput.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "AnandamideInput.h" 26 | 27 | #include "AnandamideOutput.h" 28 | #include "AnandamideNeurone.h" 29 | #include "AnandamideLibrary.h" 30 | #include "AnandamideLogic.h" 31 | #include "AnandamideScript.h" 32 | 33 | namespace Anandamide { 34 | 35 | void Input::setNeurone(Neurone *neurone) { 36 | this->neurone = neurone; 37 | } 38 | 39 | Input::Input(const Variable &default_value_) { 40 | default_value = default_value_; 41 | source = NULL; 42 | } 43 | 44 | const Variable &Input::getValue() const { 45 | if (source != NULL) return source->getValue(); 46 | return default_value; 47 | } 48 | 49 | void Input::setValue(const Variable &default_value_) { 50 | default_value = default_value_; 51 | } 52 | 53 | const Output *Input::getSource() const { 54 | return source; 55 | } 56 | 57 | Output *Input::getSource() { 58 | return source; 59 | } 60 | 61 | void Input::setSource(Output *source_) { 62 | source = source_; 63 | } 64 | 65 | const char *Input::getName() const { 66 | if(neurone == NULL) return ""; 67 | int i = neurone->indexOf(this); 68 | if(i < 0) return ""; 69 | return neurone->getInputName(i); 70 | } 71 | 72 | Neurone *Input::getNeurone() { 73 | return neurone; 74 | } 75 | 76 | const Neurone *Input::getNeurone() const { 77 | return neurone; 78 | } 79 | 80 | const TypeDef *Input::getTypeDef() const { 81 | return neurone->getLogic()->getScript()->getLibraries()->getTypeDef(default_value.getType()); 82 | } 83 | 84 | float Input::getPosX() const { 85 | return pos_x; 86 | } 87 | 88 | float Input::getPosY() const { 89 | return pos_y; 90 | } 91 | 92 | void Input::setPos(float x, float y) { 93 | pos_x = x; 94 | pos_y = y; 95 | } 96 | 97 | float Input::getDirX() const { 98 | return pos_x; 99 | } 100 | 101 | float Input::getDirY() const { 102 | return pos_y; 103 | } 104 | 105 | void Input::setDir(float x, float y) { 106 | dir_x = x; 107 | dir_y = y; 108 | } 109 | 110 | Variable &Input::getVariable() { 111 | return default_value; 112 | } 113 | 114 | Variable &Input::getDefaultValue() { 115 | return default_value; 116 | } 117 | 118 | const Variable &Input::getDefaultValue() const { 119 | return default_value; 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/Anandamide/AnandamideOutput.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "AnandamideOutput.h" 26 | #include "AnandamideNeurone.h" 27 | #include "AnandamideLibrary.h" 28 | #include "AnandamideLogic.h" 29 | #include "AnandamideScript.h" 30 | 31 | namespace Anandamide { 32 | 33 | Output::Output(Neurone *instance_) { 34 | instance = instance_; 35 | on_get_value = NULL; 36 | } 37 | 38 | Output::Output(Neurone *instance_, const Variable &value_) { 39 | instance = instance_; 40 | value = value_; 41 | on_get_value = NULL; 42 | } 43 | 44 | Output::~Output() { 45 | delete on_get_value; 46 | } 47 | 48 | const Variable &Output::getValue() const { 49 | if (on_get_value != NULL) on_get_value->run(); 50 | return value; 51 | } 52 | 53 | void Output::setValue(const Variable &value_) { 54 | value = value_; 55 | } 56 | 57 | Neurone *Output::getInstance() { 58 | return instance; 59 | } 60 | 61 | const Neurone *Output::getInstance() const { 62 | return instance; 63 | } 64 | 65 | Variable &Output::getVariable() { 66 | return value; 67 | } 68 | 69 | void Output::setOnGetValueAction(Common::Action *action) { 70 | on_get_value = action; 71 | } 72 | 73 | Common::Action *Output::getOnGetValueAction() { 74 | return on_get_value; 75 | } 76 | 77 | const char *Output::getName() const { 78 | if(instance == NULL) return ""; 79 | int i = instance->indexOf(this); 80 | if(i < 0) return ""; 81 | return instance->getOutputName(i); 82 | } 83 | 84 | const TypeDef *Output::getTypeDef() const { 85 | return instance->getLogic()->getScript()->getLibraries()->getTypeDef(value.getType()); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/Anandamide/AnandamideParameter.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "AnandamideParameter.h" 26 | 27 | namespace Anandamide { 28 | 29 | Parameter::Parameter(const Anandamide::Variable &value_) { 30 | value = value_; 31 | } 32 | 33 | const Variable &Parameter::getValue() const { 34 | return value; 35 | } 36 | 37 | void Parameter::setValue(const Variable &value_) { 38 | value = value_; 39 | } 40 | 41 | Variable &Parameter::getVariable() { 42 | return value; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/Anandamide/AnandamideScript.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "AnandamideScript.h" 26 | #include "AnandamideLogic.h" 27 | #include "AnandamideLibrary.h" 28 | #include "AnandamideStdLib.h" 29 | #include "Xml.h" 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | namespace Anandamide { 38 | 39 | Script::Script() { 40 | user_data = NULL; 41 | main = NULL; 42 | loading = NULL; 43 | is_shutdown = false; 44 | shutdown_action = NULL; 45 | scriptCompileState = SCS_NOT_COMPILED; 46 | libraries = new Libraries(); 47 | clear(); 48 | generateId(); 49 | } 50 | 51 | Script *Script::create() { 52 | return new Script(); 53 | } 54 | 55 | Script *Script::clone() { 56 | Script* res = Script::create(); 57 | res->setName(this->getName()); 58 | Xml xml("script"); 59 | writeXml(&xml, this->fileName.str()); 60 | res->readXml(&xml, 1, this->fileName.str()); 61 | return res; 62 | } 63 | 64 | void Script::destroy() { 65 | delete this; 66 | } 67 | 68 | Script::~Script() { 69 | logics.clear(); 70 | delete main; 71 | main = NULL; 72 | delete libraries; 73 | libraries = NULL; 74 | delete shutdown_action; 75 | shutdown_action = NULL; 76 | // TypeDef::clearDefImages(); 77 | } 78 | 79 | void Script::generateId() { 80 | id.set(QUuid::createUuid().toString().toLocal8Bit().constData()); 81 | } 82 | 83 | unsigned long long Script::getSize() { 84 | qDebug() << __FUNCTION__ << name; 85 | 86 | unsigned long long res = 0; 87 | res += sizeof(*this); 88 | 89 | for(int i=0; igetSize(); 91 | } 92 | if(main) { 93 | qDebug() << __FUNCTION__ << "*COMPILED MAIN"; 94 | unsigned long long main_size = 0; 95 | main_size = main->getSize(); 96 | qDebug() << __FUNCTION__ << "*COMPILED MAIN SIZE" << main_size; 97 | res += main_size; 98 | } 99 | 100 | res += name.size(); 101 | res += id.size(); 102 | res += fileName.size(); 103 | 104 | unsigned long long libs_size = 0; 105 | if(libraries) libs_size += libraries->getSize(); 106 | 107 | res += libs_size; 108 | 109 | qDebug() << __FUNCTION__ << name << "libs" << libs_size; 110 | 111 | qDebug() << __FUNCTION__ << name << "size" << res; 112 | 113 | //Libraries *libraries; 114 | 115 | return res; 116 | } 117 | 118 | const char *Script::getId() const { 119 | return id.str(); 120 | } 121 | 122 | void Script::clear() { 123 | name = ""; 124 | logics.clear(); 125 | delete main; 126 | main = NULL; 127 | loading = NULL; 128 | libraries->clear(); 129 | libraries->loadLibrary("AnandamideAPI"); 130 | } 131 | 132 | void Script::newScript() { 133 | clear(); 134 | Logic *main_def = new Logic(this); 135 | 136 | ActionNeurone *action = new ActionNeurone("entry", main_def); 137 | action->setPos(-240, -160); 138 | Neurone *shutdown = libraries->getLibrary("Std")->getDef("Shutdown")->createNeurone(libraries); 139 | shutdown->setPos(0, -144); 140 | action->getEvent("out")->addAction(shutdown->getAction("in")); 141 | 142 | main_def->addNode(action); 143 | main_def->addNode(shutdown); 144 | main_def->setName("Main"); 145 | logics.append(main_def); 146 | } 147 | 148 | bool Script::compile() { 149 | Logic *base = findLogic("Main"); 150 | if(base == NULL) { 151 | errorMessage("Compile failed : can not find \"Main\" node."); 152 | scriptCompileState = SCS_COMPILED_FAILED; 153 | return false; 154 | } 155 | delete main; 156 | main = (Logic *)base->clone(base); 157 | is_shutdown = false; 158 | main->afterCompile(); 159 | scriptCompileState = SCS_COMPILED_OK; 160 | return true; 161 | } 162 | 163 | ScriptCompileState Script::getCompileState() const {return scriptCompileState;} 164 | 165 | bool Script::run() { 166 | if(main == NULL) { 167 | errorMessage("Run failed: script is not compiled."); 168 | return false; 169 | } 170 | 171 | Anandamide::Action *entry = main->getAction("entry"); 172 | if(entry == NULL) { 173 | errorMessage("Run failed: script action \"entry\" not found."); 174 | return false; 175 | } 176 | 177 | entry->run(); 178 | return true; 179 | } 180 | 181 | void Script::setShutdownAction(Action *action) 182 | { 183 | delete shutdown_action; 184 | shutdown_action = action; 185 | } 186 | 187 | void Script::shutdown() { 188 | warningMessage(format("Script \"%s\" is shutdown.", getName())); 189 | is_shutdown = true; 190 | if (shutdown_action) { 191 | shutdown_action->run(); 192 | } 193 | } 194 | 195 | bool Script::isShutdown() const 196 | { 197 | return is_shutdown; 198 | } 199 | 200 | void Script::update(float dt) { 201 | if(main == NULL) { 202 | errorMessage("Run failed: script is not compiled."); 203 | return; 204 | } 205 | main->update(dt); 206 | } 207 | 208 | int Script::getLogicsCount() { 209 | return logics.count(); 210 | } 211 | 212 | Logic *Script::getMain() { 213 | return main; 214 | } 215 | 216 | Logic *Script::getLogic(int i) { 217 | return &logics[i]; 218 | } 219 | 220 | Logic *Script::addLogic(const char *name) { 221 | if(findLogic(name) != NULL) return NULL; 222 | Logic *logic = new Logic(this); 223 | logic->setName(name); 224 | logics.append(logic); 225 | return logic; 226 | } 227 | 228 | bool Script::addLogic(Logic *logic) { 229 | if(findLogic(logic->getName()) != NULL) return false; 230 | logics.append(logic); 231 | return true; 232 | } 233 | 234 | Logic *Script::findLogic(const char *name_str) { 235 | Str name = name_str; 236 | for(int i=0; icreate(library, name, dummy, dummyNode); 269 | } 270 | 271 | static Str prepareFileName(const char *lib_file, const char *script_file) { 272 | QString sName = QString::fromLocal8Bit(lib_file); 273 | if(!sName.endsWith(".and")) return lib_file; 274 | if(QFileInfo(sName).isRelative()) { 275 | QDir scriptDir = QFileInfo(QString::fromLocal8Bit(script_file)).dir(); 276 | QString absLibFile = scriptDir.absoluteFilePath(sName); 277 | QDir dir("./"); 278 | QString new_name = dir.relativeFilePath(absLibFile); 279 | if(!QFileInfo(new_name).exists()) { 280 | absLibFile = dir.absoluteFilePath(sName); 281 | new_name = dir.relativeFilePath(absLibFile); 282 | } 283 | return new_name.toLocal8Bit().constData(); 284 | } 285 | return lib_file; 286 | } 287 | 288 | bool Script::readXml(const Xml *xml, int version, const char *scriptFileName) { 289 | clear(); 290 | 291 | Str newId; 292 | if(xml->getArg("id", newId)) { 293 | this->id = newId; 294 | } 295 | 296 | if(newId == Str()) { 297 | generateId(); 298 | } 299 | 300 | const Xml *xml_libs = xml->getChild("libraries"); 301 | if(xml_libs) { 302 | for(int i=0; igetChildrenCount(); i++) { 303 | const Xml *xml_lib = xml_libs->getChild(i); 304 | Str name; 305 | xml_lib->getArg("name", name); 306 | if(name == "Std") continue; 307 | if(xml_lib->isArg("plugin")) { 308 | Str plugin; 309 | xml_lib->getArg("plugin", plugin); 310 | if(!libraries->loadLibraryFormApi(plugin)) { 311 | return false; 312 | } 313 | } 314 | else 315 | if(xml_lib->isArg("file")) { 316 | Str file; 317 | xml_lib->getArg("file", file); 318 | if(!libraries->loadLibrary(prepareFileName(file, scriptFileName))) { 319 | errorMessage(format("Can not load library from file \"%s\"", file.str())); 320 | return false; 321 | } 322 | } 323 | } 324 | } 325 | 326 | QElapsedTimer timer; 327 | timer.start(); 328 | 329 | const Xml *xml_logics = xml->getChild("logics"); 330 | 331 | if(xml_logics == NULL && version == 0) { 332 | xml_logics = xml; 333 | } 334 | 335 | if(xml_logics) { 336 | loading = xml_logics; 337 | for(int i=0; igetChildrenCount(); i++) { 338 | const Xml *child = xml_logics->getChild(i); 339 | if(Str(child->getName()) != "logic") continue; 340 | Str name; 341 | child->getArg("name", name); 342 | if(findLogic(name) != NULL) { 343 | //warningMessage(format("Logic \"%s\" already exist.", name.str())); 344 | continue; 345 | } 346 | Logic *logic = new Logic(this); 347 | if(!logic->readXml(child, true)) { 348 | //return false; 349 | } 350 | logics.append(logic); 351 | } 352 | // resort 353 | for(int i=0; igetChildrenCount(); i++) { 354 | const Xml *child = xml_logics->getChild(i); 355 | if(Str(child->getName()) != "logic") continue; 356 | Str name; 357 | child->getArg("name", name); 358 | int index = indexOfLogic(name); 359 | logics.exchange(i, index); 360 | } 361 | } 362 | 363 | loading = NULL; 364 | 365 | messageMessage(format("Script \"%s\" loaded in %.2lf ms.", scriptFileName, double(timer.nsecsElapsed()) / 1e6)); 366 | return true; 367 | } 368 | 369 | bool Script::readXmlLibraries(const Xml *xml, int version, const char *scriptFileName) 370 | { 371 | clear(); 372 | 373 | Str newId; 374 | if(xml->getArg("id", newId)) 375 | this->id = newId; 376 | if(newId == Str()) 377 | generateId(); 378 | 379 | const Xml *xml_libs = xml->getChild("libraries"); 380 | if(xml_libs) { 381 | for(int i=0; igetChildrenCount(); i++) { 382 | const Xml *xml_lib = xml_libs->getChild(i); 383 | Str name; 384 | xml_lib->getArg("name", name); 385 | if(xml_lib->isArg("plugin")) { 386 | Str plugin; 387 | xml_lib->getArg("plugin", plugin); 388 | if(!libraries->loadLibraryFormApi(plugin)) { 389 | return false; 390 | } 391 | } 392 | else 393 | if(xml_lib->isArg("file")) { 394 | Str file; 395 | xml_lib->getArg("file", file); 396 | if(!libraries->loadLibrary(prepareFileName(file, scriptFileName))) { 397 | return false; 398 | } 399 | } 400 | } 401 | } 402 | 403 | return true; 404 | } 405 | 406 | bool Script::readXmlLogics(const Xml *xml, int version) 407 | { 408 | const Xml *xml_logics = xml->getChild("logics"); 409 | 410 | if(xml_logics == NULL && version == 0) { 411 | xml_logics = xml; 412 | } 413 | 414 | if(xml_logics) { 415 | loading = xml_logics; 416 | for(int i=0; igetChildrenCount(); i++) { 417 | const Xml *child = xml_logics->getChild(i); 418 | if(Str(child->getName()) != "logic") continue; 419 | Str name; 420 | child->getArg("name", name); 421 | if(findLogic(name) != NULL) { 422 | //warningMessage(format("Logic \"%s\" already exist.", name.str())); 423 | continue; 424 | } 425 | Logic *logic = new Logic(this); 426 | if(!logic->readXml(child, true)) { 427 | //return false; 428 | } 429 | logics.append(logic); 430 | } 431 | // resort 432 | for(int i=0; igetChildrenCount(); i++) { 433 | const Xml *child = xml_logics->getChild(i); 434 | if(Str(child->getName()) != "logic") continue; 435 | Str name; 436 | child->getArg("name", name); 437 | int index = indexOfLogic(name); 438 | logics.exchange(i, index); 439 | } 440 | } 441 | 442 | loading = NULL; 443 | return true; 444 | } 445 | 446 | void Script::preLoadLogic(const char *name_str) { 447 | if(loading == NULL) return; 448 | if(findLogic(name_str) != NULL) return; 449 | 450 | Str name = name_str; 451 | 452 | for(int i=0; igetChildrenCount(); i++) { 453 | const Xml *child = loading->getChild(i); 454 | if(Str(child->getName()) != "logic") continue; 455 | if(name != child->getArg("name")) continue; 456 | Logic *logic = new Logic(this); 457 | logic->readXml(child, true); 458 | logics.append(logic); 459 | } 460 | } 461 | 462 | void Script::writeXml(Xml *xml, const char *script_file) const { 463 | xml->setArg("id", id.str()); 464 | Xml *xml_libs = xml->addChild("libraries"); 465 | for(int i=0; igetLibrariesCount(); i++) { 466 | const Library *library = libraries->getLibrary(i); 467 | Xml *xml_lib = xml_libs->addChild("library"); 468 | xml_lib->setArg("name", library->getName()); 469 | QString lib_file = QString::fromLocal8Bit(library->getFileName()); 470 | if(script_file != NULL && lib_file.endsWith(".and")) { 471 | QFileInfo fi(lib_file); 472 | QDir script_dir(QFileInfo(QString::fromLocal8Bit(script_file)).dir()); 473 | lib_file = script_dir.relativeFilePath(fi.absoluteFilePath()); 474 | } 475 | xml_lib->setArg("file", lib_file.toLocal8Bit().constData()); 476 | if(Str(library->getPluginName()) != Str()) { 477 | xml_lib->setArg("plugin", library->getPluginName()); 478 | } 479 | } 480 | Xml *xml_logics = xml->addChild("logics"); 481 | for(int i=0; iaddChild("logic"); 483 | logics[i].writeXml(child); 484 | } 485 | } 486 | 487 | void Script::save(const char *filename) { 488 | Xml xml("script"); 489 | if(Str(getName()) == Str()) { 490 | setName(QFileInfo(QString::fromLocal8Bit(filename)).baseName().toLocal8Bit().constData()); 491 | } 492 | xml.setArg("name", this->name); 493 | xml.setArg("version", 1); 494 | writeXml(&xml, filename); 495 | xml.save(filename); 496 | } 497 | 498 | bool Script::load(const char *filename) { 499 | Xml xml("script"); 500 | if(!xml.load(filename)) { 501 | errorMessage(format("Can not load script file \"%s\".", filename)); 502 | return false; 503 | } 504 | this->fileName = Str(filename); 505 | int version = 0; 506 | xml.getArg("version", version); 507 | if(!readXml(&xml, version, filename)) return false; 508 | xml.getArg("name", this->name); 509 | if(name == "") { 510 | QFileInfo file_info(QString::fromLocal8Bit(filename)); 511 | name = file_info.baseName().toLocal8Bit().constData(); 512 | warningMessage(format("Don`t give up while loading name from \"%s\" file. New name will be \"%s\".", filename, name.str())); 513 | } 514 | return true; 515 | } 516 | 517 | bool Script::loadLibraries(const char *filename) 518 | { 519 | Xml xml("script"); 520 | if(!xml.load(filename)) { 521 | errorMessage(format("Can not load script file \"%s\".", filename)); 522 | return false; 523 | } 524 | int version = 0; 525 | xml.getArg("version", version); 526 | if(!readXmlLibraries(&xml, version, filename)) return false; 527 | xml.getArg("name", this->name); 528 | if(name == "") { 529 | QFileInfo file_info(QString::fromLocal8Bit(filename)); 530 | name = file_info.baseName().toLocal8Bit().constData(); 531 | warningMessage(format("Don`t give up while loading name from \"%s\" file. New name will be \"%s\".", filename, name.str())); 532 | } 533 | return true; 534 | } 535 | 536 | bool Script::loadLogics(const char *filename) 537 | { 538 | Xml xml("script"); 539 | if(!xml.load(filename)) { 540 | errorMessage(format("Can not load script file \"%s\".", filename)); 541 | return false; 542 | } 543 | int version = 0; 544 | xml.getArg("version", version); 545 | if(!readXmlLogics(&xml, version)) return false; 546 | xml.getArg("name", this->name); 547 | if(name == "") { 548 | QFileInfo file_info(QString::fromLocal8Bit(filename)); 549 | name = file_info.baseName().toLocal8Bit().constData(); 550 | warningMessage(format("Don`t give up while loading name from \"%s\" file. New name will be \"%s\".", filename, name.str())); 551 | } 552 | return true; 553 | } 554 | 555 | bool Script::loadScriptName(const char *filename) 556 | { 557 | Xml xml("script"); 558 | if(!xml.load(filename)) { 559 | errorMessage(format("Can not load script file \"%s\".", filename)); 560 | return false; 561 | } 562 | int version = 0; 563 | xml.getArg("version", version); 564 | xml.getArg("name", name); 565 | if(name == "") { 566 | QFileInfo file_info(QString::fromLocal8Bit(filename)); 567 | name = file_info.baseName().toLocal8Bit().constData(); 568 | warningMessage(format("Don`t give up while loading name from \"%s\" file. New name will be \"%s\".", filename, name.str())); 569 | } 570 | return true; 571 | } 572 | 573 | Libraries *Script::getLibraries() { 574 | return libraries; 575 | } 576 | 577 | const char *Script::getName() const { 578 | return name; 579 | } 580 | 581 | void Script::setName(const char *name) { 582 | this->name = name; 583 | } 584 | 585 | void Script::setUserData(void *data) { 586 | user_data = data; 587 | } 588 | 589 | void *Script::getUserData() const { 590 | return user_data; 591 | } 592 | 593 | void Script::renameNodes(const char *oldName, const char *newName) { 594 | for(int i = 0; i < logics.count(); ++i) { 595 | logics[i].renameNodes(oldName, newName); 596 | } 597 | } 598 | 599 | void Script::removeLibraryNodes(Library *lib) { 600 | for(int i = 0; i < logics.count(); ++i) { 601 | for(int j = 0; j < logics.getItem(i)->getNodesCount(); ++j) { 602 | Neurone* node = &logics.getItem(i)->getNode(j); 603 | if(node->getLibrary() != lib) continue; 604 | logics.getItem(i)->removeNode(j--); 605 | } 606 | for(int j = 0; j < logics.getItem(i)->getNodeGroupCount(); ++j) { 607 | NeuroneGroup* group = &logics.getItem(i)->getNodeGroup(j); 608 | if(group->getNodesCount() != 0) continue; 609 | logics.getItem(i)->removeGroup(j--); 610 | } 611 | } 612 | } 613 | 614 | } 615 | -------------------------------------------------------------------------------- /src/Anandamide/AnandamideTypeInfo.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "AnandamideTypeInfo.h" 26 | #include "Anandamide.h" 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | namespace Anandamide { 31 | 32 | //-------------------------------------------------------------------------- 33 | 34 | int nextTypeID() { 35 | static int next_id = 9000; 36 | return next_id ++; 37 | } 38 | 39 | bool checkOrAddTypeID(int id, const char *type) { 40 | static Map ids; 41 | Str *item = ids.get(id); 42 | if(item == NULL) { 43 | ids.append(new int(id), new Str(type)); 44 | return true; 45 | } 46 | if(*item == type) return true; 47 | errorMessage(format("Attempt to assign type id \"%d\" to type \"%s\", id already taken by type \"%s\".", id, type, item->str())); 48 | return false; 49 | } 50 | 51 | //-------------------------------------------------------------------------- 52 | // 53 | // сlass Enum 54 | // 55 | //-------------------------------------------------------------------------- 56 | 57 | Enum::Enum() { } 58 | 59 | Enum::~Enum() { } 60 | 61 | int Enum::getItemsCount() const { 62 | return 0; 63 | } 64 | 65 | const char *Enum::getItemName(int i) const { 66 | return NULL; 67 | } 68 | 69 | int Enum::getItemId(int i) const { 70 | return 0; 71 | } 72 | 73 | const char *Enum::getItemNameById(int id) const { 74 | return NULL; 75 | } 76 | 77 | const int *Enum::getItemIdByName(const char *name) const { 78 | return NULL; 79 | } 80 | 81 | void operator>>(const TypeInfo &t, Str &str) { 82 | str.format("%d", t.id()); 83 | } 84 | 85 | void operator<<(TypeInfo &t, const Str &str) { 86 | t.setId(str.getInt()); 87 | } 88 | 89 | //-------------------------------------------------------------------------- 90 | 91 | } 92 | 93 | #include 94 | 95 | namespace Anandamide { 96 | 97 | void operator>>(unsigned int t, Anandamide::Str &str) 98 | { 99 | str.set(QString::number(t).toLocal8Bit().constData()); 100 | } 101 | 102 | void operator<<(unsigned int &t, const Anandamide::Str &str) 103 | { 104 | t = QString::fromLocal8Bit(str.str()).toUInt(); 105 | } 106 | 107 | void operator>>(long long t, Str &str) 108 | { 109 | str.set(QString::number(t).toLocal8Bit().constData()); 110 | } 111 | 112 | void operator<<(long long &t, const Str &str) 113 | { 114 | t = QString::fromLocal8Bit(str.str()).toLongLong(); 115 | } 116 | 117 | void operator>>(unsigned long long t, Str &str) 118 | { 119 | str.set(QString::number(t).toLocal8Bit().constData()); 120 | } 121 | 122 | void operator<<(unsigned long long &t, const Str &str) 123 | { 124 | t = QString::fromLocal8Bit(str.str()).toULongLong(); 125 | } 126 | 127 | void operator>>(char t, Str &str) 128 | { 129 | str.set(QString(QChar(t)).toLocal8Bit().constData()); 130 | } 131 | 132 | void operator<<(char &t, const Str &str) 133 | { 134 | if(str.size() == 0) 135 | t = '?'; 136 | else 137 | t = str[0]; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/Common/Str.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "Str.h" 26 | 27 | //------------------------------------------------------------------------------ 28 | 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | 35 | //------------------------------------------------------------------------------ 36 | 37 | namespace Anandamide { 38 | 39 | //------------------------------------------------------------------------------ 40 | 41 | const char *format(const char *fmt, ...) { 42 | static char text[4096]; 43 | va_list ap; 44 | va_start(ap, fmt); 45 | vsnprintf(text, 4096, fmt, ap); 46 | va_end(ap); 47 | return text; 48 | } 49 | 50 | //------------------------------------------------------------------------------ 51 | 52 | void Str::newSize(int size) { 53 | static const char *empty = "\0"; 54 | if(fsize != 0) delete [] data; 55 | fsize = size; 56 | if(size == 0) { 57 | data = const_cast (empty); 58 | return; 59 | } 60 | data = new char[size + 1]; 61 | data[size] = 0; 62 | } 63 | 64 | Str::Str() : fsize(0) { newSize(0); } 65 | 66 | Str::Str(int size) : data(NULL) { newSize(size); } 67 | 68 | Str::Str(const char *str) : data(NULL) { set(str); } 69 | 70 | Str::Str(const Str &str) : data(NULL) { set(str.data); } 71 | 72 | Str::~Str() { clear(); } 73 | 74 | void Str::set(const char *str) { 75 | if (data == str) return; 76 | int new_size = 0; 77 | if (str != NULL) new_size = strlen(str); 78 | newSize(new_size); 79 | if(new_size != 0) strcpy(data, str); 80 | } 81 | 82 | void Str::setSize(int size) { 83 | if(fsize == 0) { 84 | newSize(size); 85 | return; 86 | } 87 | fsize = size; 88 | char *d = data; 89 | data = new char[size + 1]; 90 | strncpy(data, d, size); 91 | data[size] = 0; 92 | delete [] d; 93 | 94 | } 95 | 96 | void Str::clear() { 97 | newSize(0); 98 | } 99 | 100 | int Str::size() const { return fsize; } 101 | 102 | const char *Str::str() const { return data; } 103 | 104 | char Str::operator[](int i) const { return data[i]; } 105 | 106 | Str &Str::operator=(const Str &str) { set(str.data); return *this; } 107 | 108 | bool Str::operator==(const Str &str) const { return fsize == str.fsize && !strcmp(data, str.data); } 109 | 110 | bool Str::operator!=(const Str &str) const { return !operator== (str); } 111 | 112 | Str Str::operator+(char c) const { 113 | Str res(size() + 1); 114 | for (int i=0; i(const char *str) const { 123 | return strcmp(data, str) > 0; 124 | } 125 | 126 | bool Str::operator>(const Str &o) const { 127 | return strcmp(data, o.data) > 0; 128 | } 129 | 130 | const char *Str::format(const char *fmt, ...) { 131 | static char text[1024] = "\0"; 132 | va_list ap; 133 | va_start(ap, fmt); 134 | vsnprintf(text, 1024, fmt, ap); 135 | va_end(ap); 136 | set(text); 137 | return data; 138 | } 139 | 140 | void Str::del(int p, int n) { 141 | if (fsize <= 0 || n < 1 || n > fsize) return; 142 | if (p + n < fsize) { 143 | strcpy(&data[p], &data[p + n]); 144 | setSize(fsize - n); 145 | } else { 146 | setSize(p); 147 | data[fsize] = '\0'; 148 | } 149 | } 150 | 151 | void Str::ins(int ps, const char *s) { 152 | if (ps > fsize) return; 153 | 154 | int len = strlen(s); 155 | setSize(fsize + len); 156 | 157 | for (int i=fsize-len; i>=ps; i--) { 158 | data[i + len] = data[i]; 159 | } 160 | strncpy(&data[ps], s, len); 161 | } 162 | 163 | void Str::ins(int ps, char s) { 164 | if (ps > fsize) return; 165 | 166 | setSize(fsize + 1); 167 | 168 | for (int i=fsize-1; i>=ps; i--) { 169 | data[i + 1] = data[i]; 170 | } 171 | data[ps] = s; 172 | } 173 | 174 | int Str::getInt() const { 175 | return atoi(data); 176 | } 177 | 178 | float Str::getFloat() const { 179 | return float(atof(data)); 180 | } 181 | 182 | int Str::getDigits() const { 183 | Str temp; 184 | for (int i=0; i= '0' && data[i] <= '9') { 186 | temp = temp + data[i]; 187 | } 188 | } 189 | return temp.getInt(); 190 | } 191 | 192 | Str Str::getLetters() const { 193 | Str temp; 194 | for (int i=0; i '9') { 196 | temp = temp + data[i]; 197 | } 198 | } 199 | return temp; 200 | } 201 | 202 | void Str::split(char c, Anandamide::Array &strings) const { 203 | Str cur_str; 204 | for(int i=0; i. 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef XmlH 26 | #define XmlH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "AnandamideLibAPI.h" 31 | #include "Array.h" 32 | #include "Str.h" 33 | 34 | //------------------------------------------------------------------------------ 35 | namespace Anandamide { 36 | 37 | class ANANDAMIDE_API Xml { 38 | 39 | struct Arg { 40 | 41 | Str name; 42 | Str data; 43 | 44 | Arg(const char *name_, const char *data_) { 45 | name = name_; 46 | data = data_; 47 | } 48 | 49 | }; 50 | 51 | Str name; 52 | Str data; 53 | Str comment; 54 | 55 | Anandamide::Array children; 56 | Anandamide::Array args; 57 | 58 | protected: 59 | 60 | const char *parseXml(const char *str); 61 | void saveToFile(FILE *f, int depth = 0) const; 62 | 63 | public: 64 | 65 | Xml(const char *name); 66 | virtual ~Xml(); 67 | 68 | const char *getName() const; 69 | void setName(const char *name_); 70 | 71 | //-------------------------------------------------------------------------- 72 | // children 73 | //-------------------------------------------------------------------------- 74 | 75 | int getChildrenCount() const; 76 | 77 | Xml *getChild(int i); 78 | Xml *getChild(const char *child); 79 | 80 | const Xml *getChild(int i) const; 81 | const Xml *getChild(const char *child) const; 82 | 83 | Xml *addChild(Xml *xml); 84 | Xml *addChild(const char *); 85 | 86 | void removeChild(int i); 87 | void removeChild(Xml *xml); 88 | 89 | //-------------------------------------------------------------------------- 90 | // args 91 | //-------------------------------------------------------------------------- 92 | 93 | int getArgsCount() const; 94 | 95 | const char *getArg(int i) const; 96 | void setArg(int i, const char *name, const char *data); 97 | bool isArg(const char *name) const; 98 | 99 | int findArg(const char *name) const; 100 | 101 | const char *getArg(const char *name) const; 102 | 103 | bool getArg(const char *name, int &res) const; 104 | void setArg(const char *name, int data); 105 | 106 | bool getArg(const char *name, bool &res) const; 107 | void setArg(const char *name, bool data); 108 | 109 | bool getArg(const char *name, float &res) const; 110 | void setArg(const char *name, float data); 111 | 112 | bool getArg(const char *name, Str &res) const; 113 | void setArg(const char *name, const char *data); 114 | 115 | //-------------------------------------------------------------------------- 116 | // data 117 | //-------------------------------------------------------------------------- 118 | 119 | const char *getData() const; 120 | 121 | void getData(int &res) const; 122 | void setData(int data); 123 | 124 | void getData(bool &res) const; 125 | void setData(bool data); 126 | 127 | void getData(float &res) const; 128 | void setData(float data); 129 | 130 | void getData(Str &res) const; 131 | void setData(const char *data_); 132 | 133 | //-------------------------------------------------------------------------- 134 | // data 135 | //-------------------------------------------------------------------------- 136 | 137 | bool getChildData(const char *child, int &res) const; 138 | void setChildData(const char *child, int data); 139 | 140 | bool getChildData(const char *child, bool &res) const; 141 | void setChildData(const char *child, bool data); 142 | 143 | bool getChildData(const char *child, float &res) const; 144 | void setChildData(const char *child, float data); 145 | 146 | bool getChildData(const char *child, Str &res) const; 147 | void setChildData(const char *child, const char *data_); 148 | 149 | //-------------------------------------------------------------------------- 150 | // comment 151 | //-------------------------------------------------------------------------- 152 | 153 | void setComment(const char *comment); 154 | const char *getComment() const; 155 | 156 | //-------------------------------------------------------------------------- 157 | // save / load 158 | //-------------------------------------------------------------------------- 159 | 160 | bool load(const char *name); 161 | void save(const char *name) const; 162 | void saveToStr(Str &s) const; 163 | 164 | //-------------------------------------------------------------------------- 165 | 166 | Xml &operator= (const Xml &xml); 167 | 168 | // 169 | void clear(); 170 | 171 | void parse(const char *xml); 172 | 173 | }; 174 | 175 | } 176 | 177 | //------------------------------------------------------------------------------ 178 | 179 | #endif 180 | 181 | //------------------------------------------------------------------------------ 182 | -------------------------------------------------------------------------------- /src/Misc/Camera2d.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "Camera2d.h" 26 | #include "Renderer.h" 27 | #include "Anandamide.h" 28 | #include "Str.h" 29 | 30 | #include 31 | #include 32 | 33 | //------------------------------------------------------------------------------ 34 | 35 | namespace Anandamide { 36 | 37 | Camera2d::Camera2d() : scroll(false), zoom(1.0f), renderer(NULL), ratio(1.0) { } 38 | 39 | void Camera2d::setup(Renderer *renderer, float w, float h) { 40 | 41 | this->renderer = renderer; 42 | Matrix matrix; 43 | 44 | /* 45 | float zoom_s = floor(zoom * 10.0f) / 10.0f; 46 | Vector k = Vector(float(w) * zoom_s / 2.0f, float(h) * zoom_s / -2.0f, 1.0f); 47 | Vector pos_s = Vector(floor(pos.x * k.x) / k.x, floor(pos.y * k.y) / k.y, 0.0f); 48 | */ 49 | 50 | float zoom_s = getZoom(); 51 | vec3 pos_s = pos; 52 | 53 | //matrix = Matrix::getTranslate(pos) * Matrix::getScale(Vector(1.0f / float(w), -1.0f / float(h), 1.0f) / zoom) * Matrix::getTranslate(Vector(-1.0f, 1.0f, 0.0f)); 54 | 55 | /* 56 | if (math::abs(w) < EPSILON || math::abs(h) < EPSILON || math::abs(zoom_s) < EPSILON) { 57 | int stop = true; 58 | } 59 | */ 60 | 61 | matrix = Matrix::translate(pos_s) * Matrix::scale(vec3(2.0f / float(w) / zoom_s, -2.0f / float(h) / zoom_s, 1.0f)); 62 | 63 | //matrix = Matrix::getTranslate(pos) * Matrix::getScale(Vector(2.0f / float(w), -2.0f / float(h), 1.0f) / zoom)/* * Matrix::getTranslate(Vector(-1.0f, 1.0f, 0.0f))*/; 64 | renderer->setViewMatrix(matrix); 65 | renderer->getFrustum(frustum); 66 | } 67 | 68 | //------------------------------------------------------------------------------ 69 | 70 | void Camera2d::mouseDown(int x, int y) { 71 | scroll = true; 72 | click = cursor; 73 | } 74 | 75 | //------------------------------------------------------------------------------ 76 | 77 | void Camera2d::mouseUp(int x, int y) { 78 | scroll = false; 79 | } 80 | 81 | //------------------------------------------------------------------------------ 82 | 83 | bool Camera2d::mouseMove(int x, int y) { 84 | if(renderer == NULL) return false; 85 | cursor = renderer->unproject(vec3(float(x), float(y), 0.5),frustum); 86 | if (scroll) { 87 | pos += cursor - click; 88 | //click = cursor; 89 | return true; 90 | } 91 | return false; 92 | 93 | } 94 | 95 | vec3 Camera2d::fromMouse(int x, int y) { 96 | if(renderer == NULL) return vec3(); 97 | return renderer->unproject(vec3(float(x), float(y), 0.5),frustum); 98 | } 99 | 100 | //------------------------------------------------------------------------------ 101 | 102 | void Camera2d::zoomIn(float delta, bool shift) { 103 | float old_zoom = zoom; 104 | zoom += delta; 105 | if (zoom < 0.2f) zoom = 0.2f; 106 | if (zoom > 7.0f) zoom = 7.0f; 107 | if(shift) pos += (cursor + pos) * (zoom - old_zoom) * 0.65f; 108 | } 109 | 110 | vec3 Camera2d::getCursorPos() const { return cursor; } 111 | 112 | const Frustum &Camera2d::getFrustum() { return frustum; } 113 | 114 | //------------------------------------------------------------------------------ 115 | 116 | void Camera2d::setRatio(float r) { 117 | ratio = r; 118 | } 119 | 120 | float Camera2d::getZoom() const { return pow(2.0f, zoom) * 1.0f / 8.0f; } 121 | 122 | const vec3 &Camera2d::getPos() const { return pos; } 123 | 124 | void Camera2d::setPos(vec3 pos) 125 | { 126 | this->pos = pos; 127 | } 128 | 129 | void Camera2d::setTarget(vec3 t) { 130 | pos.x = -t.x; 131 | pos.y = -t.y; 132 | } 133 | 134 | bool Camera2d::getScroll() const {return scroll;} 135 | 136 | //------------------------------------------------------------------------------ 137 | 138 | void Camera2d::clear() { 139 | pos = vec3(); 140 | zoom = 3.0f; 141 | 142 | } 143 | 144 | //------------------------------------------------------------------------------ 145 | 146 | } 147 | -------------------------------------------------------------------------------- /src/Misc/Camera2d.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef Camera2dH 26 | #define Camera2dH 27 | 28 | #include "AnandamideLibAPI.h" 29 | 30 | //------------------------------------------------------------------------------ 31 | 32 | #include "MathCore.h" 33 | 34 | namespace Anandamide { 35 | 36 | class Renderer; 37 | 38 | class ANANDAMIDE_API Camera2d { 39 | 40 | vec3 click; 41 | bool scroll; 42 | vec3 pos; 43 | float zoom; 44 | float ratio; 45 | Frustum frustum; 46 | vec3 cursor; 47 | Renderer *renderer; 48 | 49 | public: 50 | 51 | Camera2d(); 52 | 53 | void setup(Renderer *renderer, float w, float h); 54 | void clear(); 55 | 56 | void mouseDown(int x, int y); 57 | void mouseUp(int x, int y); 58 | bool mouseMove(int x, int y); 59 | 60 | vec3 fromMouse(int x, int y); 61 | 62 | void zoomIn(float delta, bool shift = false); 63 | vec3 getCursorPos() const; 64 | const Frustum &getFrustum(); 65 | 66 | void setRatio(float r); 67 | float getZoom() const; 68 | const vec3 &getPos() const; 69 | void setPos(vec3 pos); 70 | void setTarget(vec3 t); 71 | 72 | bool getScroll() const; 73 | }; 74 | 75 | //------------------------------------------------------------------------------ 76 | 77 | } 78 | 79 | #endif 80 | 81 | //------------------------------------------------------------------------------ 82 | 83 | -------------------------------------------------------------------------------- /src/Misc/Grid.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #include "Grid.h" 26 | 27 | //------------------------------------------------------------------------------ 28 | 29 | namespace Anandamide { 30 | 31 | float Grid::snap(float x, float step) const { 32 | return floor(x / step + 0.5f) * step; 33 | } 34 | 35 | //------------------------------------------------------------------------------ 36 | 37 | vec3 Grid::snap(const vec3 &v, float step) const { 38 | return vec3(snap(v.x, step), snap(v.y, step), 0.5f); 39 | } 40 | 41 | //------------------------------------------------------------------------------ 42 | 43 | float Grid::snap(float x) const { 44 | return snap(x, step); 45 | } 46 | 47 | //------------------------------------------------------------------------------ 48 | 49 | vec3 Grid::snap(const vec3 &v) const { 50 | return snap(v, step); 51 | } 52 | 53 | //------------------------------------------------------------------------------ 54 | 55 | void Grid::render(Renderer *renderer, const Frustum &frustum) const { 56 | 57 | int *v; 58 | v = renderer->getViewport(); 59 | vec3 min = renderer->unproject(vec3(float(v[0]), float(v[1]), 0.5f), frustum); 60 | vec3 max = renderer->unproject(vec3(float(v[2]), float(v[3]), 0.5f), frustum); 61 | 62 | //Vector scale_v = renderer->project(Vector(1.0f, 1.0f, 0.0f), frustum) - renderer->project(Vector(0.0f, 0.0f, 0.0f), frustum); 63 | vec3 scale_v = renderer->project(min + vec3(1.0f, 1.0f, 0.0f), frustum) - renderer->project(min, frustum); 64 | //Log::message("scale_v.x %f, scale_v.y %f\n", scale_v.x, scale_v.y); 65 | float scale = ::math::min_(::math::abs(scale_v.x), ::math::abs(scale_v.y)); 66 | 67 | //return; 68 | 69 | if (::math::abs(scale) < EPSILON) { 70 | throw "Grid::render(): division by zero."; 71 | } 72 | 73 | float step = ::math::max_(1.0f, float(pow(10.0f, ceil(log10(2.0f / 3.0f / scale))))) * this->step; 74 | 75 | 76 | float ln; 77 | float z = 1.0f; 78 | 79 | ln = floor(min.y / step) * step; 80 | while (ln < max.y) { 81 | 82 | if (int(floor(ln / step + 0.5f)) == 0) { 83 | renderer->color(0.3f, 0.3f, 0.05f); 84 | z = 0.1f; 85 | } else 86 | if (int(floor(ln / step + 0.5f)) % 10 == 0 ) { 87 | renderer->color(0.3f, 0.3f, 0.3f); 88 | z = 0.2f; 89 | } else 90 | if (int(floor(ln / step + 0.5f)) % 5 == 0 ) { 91 | renderer->color(0.15f, 0.15f, 0.15f); 92 | z = 0.3f; 93 | } else { 94 | renderer->color(0.1f, 0.1f, 0.1f); 95 | z = 0.4f; 96 | } 97 | 98 | renderer->render(Line(vec3(min.x, ln, z), vec3(max.x, ln, z))); 99 | ln += step; 100 | } 101 | 102 | ln = floor(min.x / step) * step; 103 | while (ln < max.x) { 104 | 105 | if (int(floor(ln / step + 0.5f)) == 0) { 106 | renderer->color(0.3f, 0.3f, 0.05f); 107 | z = 0.1f; 108 | } else 109 | if (int(floor(ln / step + 0.5f)) % 10 == 0 ) { 110 | renderer->color(0.3f, 0.3f, 0.3f); 111 | z = 0.2f; 112 | } else 113 | if (int(floor(ln / step + 0.5f)) % 5 == 0) { 114 | renderer->color(0.15f, 0.15f, 0.15f); 115 | z = 0.3f; 116 | } else { 117 | renderer->color(0.1f, 0.1f, 0.1f); 118 | z = 0.4f; 119 | } 120 | 121 | renderer->render(Line(vec3(ln, min.y, z), vec3(ln, max.y, z))); 122 | ln += step; 123 | } 124 | 125 | 126 | } 127 | 128 | //------------------------------------------------------------------------------ 129 | 130 | } 131 | -------------------------------------------------------------------------------- /src/Misc/Grid.h: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This file is part of AnandamideAPI Script 4 | // 5 | // copyright: (c) 2010 - 2016 6 | // author: Alexey Egorov (FadeToBlack aka EvilSpirit) 7 | // mailto: anandamide@mail.ru 8 | // anandamide.script@gmail.com 9 | // 10 | // AnandamideAPI is free software: you can redistribute it and/or modify 11 | // it under the terms of the GNU General Public License as published by 12 | // the Free Software Foundation, either version 3 of the License, or 13 | // (at your option) any later version. 14 | // 15 | // AnandamideAPI is distributed in the hope that it will be useful, 16 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | // GNU General Public License for more details. 19 | // 20 | // You should have received a copy of the GNU General Public License 21 | // along with AnandamideAPI. If not, see . 22 | // 23 | //------------------------------------------------------------------------------ 24 | 25 | #ifndef GridH 26 | #define GridH 27 | 28 | //------------------------------------------------------------------------------ 29 | 30 | #include "Renderer.h" 31 | #include "MathCore.h" 32 | #include 33 | 34 | //------------------------------------------------------------------------------ 35 | 36 | namespace Anandamide { 37 | 38 | class Renderer; 39 | 40 | class Grid { 41 | 42 | public: 43 | 44 | float step; 45 | 46 | Grid() : step(0.1f) {} 47 | 48 | float snap(float x) const; 49 | vec3 snap(const vec3 &v) const; 50 | 51 | float snap(float x, float step) const; 52 | vec3 snap(const vec3 &v, float step) const; 53 | 54 | void render(Renderer *renderer, const Frustum &frustum) const; 55 | }; 56 | 57 | } 58 | //------------------------------------------------------------------------------ 59 | 60 | #endif 61 | 62 | //------------------------------------------------------------------------------ 63 | 64 | --------------------------------------------------------------------------------