id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,533,235
|
NetConfDataConfiguratorMultipart.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/multipart/NetConfDataConfiguratorMultipart.h
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTORES_CONFIG_MULTIPART_NETCONFDATACONFIGURATORMULTIPART_H_
#define SDN4CORE_NETCONF_DATASTORES_CONFIG_MULTIPART_NETCONFDATACONFIGURATORMULTIPART_H_
//SDN4CoRE
#include <sdn4core/netconf/datastores/config/base/NetConfDataConfiguratorBase.h>
#include <sdn4core/netconf/datastores/store/running/NetConfRunningDataStore.h>
namespace SDN4CoRE {
/**
* Provides a Multipart implementation for the interface of a NetConfConfigDataStore.
*
* @author Tobias Haugg, for HAW Hamburg
*/
class NetConfDataConfiguratorMultipart: public NetConfDataConfiguratorBase {
public:
~NetConfDataConfiguratorMultipart();
/**
* Creates a NetConfConfig from the current configuration data that only contains elements in the filter.
* @param filter the filter to be applied, if empty the whole config data set is returned
* @return the requested configuration data
*/
virtual NetConfConfig* getConfig(const NetConfFilter& filter) override;
/**
* Applies the changes in the config using the defaultOperation.
* @param defaultOperation Selects the default operation, one of @see ~NetConfOperation_Operation.
* @param errorOption Selects how to react on errors, one of @see ~NetConfOperation_ErrorOption.
* @param config The config to be applied
* @return true if the changes could be applied, false if an error occurred.
*/
virtual bool editConfig(int defaultOperation, int errorOption, NetConfConfig* config) override;
/**
* Validate the given config if it valid or not
* @param configSRP the configuration that should be tested
* @param defaultOperation the desired default operation that should be executed
*/
virtual bool validateConfig(NetConfConfig* config, int defaultOperation = 0) override;
protected:
virtual void initialize() override;
/**
* pointer to the runningDataStore.
* needed for accessing the validation function in order to validate nested configurations
*/
NetConfRunningDataStore* _runningDataStore;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_DATASTORES_CONFIG_MULTIPART_NETCONFDATACONFIGURATORMULTIPART_H_ */
| 3,052
|
C++
|
.h
| 60
| 45.716667
| 113
| 0.734564
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,236
|
NetConfDataConfiguratorIEEE8021Qbv.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/ieee8021qbv/NetConfDataConfiguratorIEEE8021Qbv.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTORES_CONFIG_IEEE8021QBV_NETCONFDATACONFIGURATORIEEE8021QBV_H_
#define SDN4CORE_NETCONF_DATASTORES_CONFIG_IEEE8021QBV_NETCONFDATACONFIGURATORIEEE8021QBV_H_
//Omnet
#include <omnetpp.h>
//STD
#include <map>
//CoRE4INET
#include <core4inet/linklayer/shaper/IEEE8021Qbv/gate/IEEE8021QbvGateControlList.h>
#include <sdn4core/netconf/datastores/config/base/NetConfDataConfiguratorBase.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Provides a IEEE 802.1Qbv implementation for the interface of a NetConfConfigDataStore.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfDataConfiguratorIEEE8021Qbv: public NetConfDataConfiguratorBase {
public:
/**
* Creates a NetConfConfig from the current configuration data that only contains elements in the filter.
* @param filter the filter to be applied, if empty the whole config data set is returned
* @return the requested configuration data
*/
virtual NetConfConfig* getConfig(const NetConfFilter& filter) override;
/**
* Applies the changes in the config using the defaultOperation.
* @param defaultOperation Selects the default operation, one of @see ~NetConfOperation_Operation.
* @param errorOption Selects how to react on errors, one of @see ~NetConfOperation_ErrorOption.
* @param config The config to be applied
* @return true if the changes could be applied, false if an error occurred.
*/
virtual bool editConfig(int defaultOperation, int errorOption, NetConfConfig* config) override;
/**
* Validate the given config if it valid or not
* @param configSRP the configuration that should be tested
* @param defaultOperation the desired default operation that should be executed
*/
virtual bool validateConfig(NetConfConfig* config, int defaultOperation = 0) override;
protected:
virtual void initialize() override;
/**
* Map: key port number, value IEEE8021QbvGateControlList modules in this host.
*/
std::map<int,CoRE4INET::IEEE8021QbvGateControlList*> _gateControlListModules;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_DATASTORES_CONFIG_IEEE8021QBV_NETCONFDATACONFIGURATORIEEE8021QBV_H_ */
| 2,984
|
C++
|
.h
| 63
| 44.285714
| 109
| 0.763411
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,237
|
NetConfDataConfiguratorFlowTable.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/openflow/NetConfDataConfiguratorFlowTable.h
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTORES_CONFIG_OPENFLOW_NETCONFDATACONFIGURATORFLOWTABLE_H_
#define SDN4CORE_NETCONF_DATASTORES_CONFIG_OPENFLOW_NETCONFDATACONFIGURATORFLOWTABLE_H_
//Omnet
#include <omnetpp.h>
//Openflow
#include "openflow/messages/Open_Flow_Message_m.h"
#include "openflow/openflow/switch/flowtable/OF_FlowTable.h"
//SDN4CoRE
#include <sdn4core/netconf/datastores/config/base/NetConfDataConfiguratorBase.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Provides a FlowTable implementation for the interface of a NetConfConfigDataStore.
*
* @author Tobias Haugg, for HAW Hamburg
*/
class NetConfDataConfiguratorFlowTable: public NetConfDataConfiguratorBase {
public:
/**
* Creates a NetConfConfig from the current configuration data that only contains elements in the filter.
* @param filter the filter to be applied, if empty the whole config data set is returned
* @return the requested configuration data
*/
virtual NetConfConfig* getConfig(const NetConfFilter& filter) override;
/**
* Applies the changes in the config using the defaultOperation.
* @param defaultOperation Selects the default operation, one of @see ~NetConfOperation_Operation.
* @param errorOption Selects how to react on errors, one of @see ~NetConfOperation_ErrorOption.
* @param config The config to be applied
* @return true if the changes could be applied, false if an error occurred.
*/
virtual bool editConfig(int defaultOperation, int errorOption, NetConfConfig* config) override;
/**
* Validate the given config if it valid or not
* @param configSRP the configuration that should be tested
* @param defaultOperation the desired default operation that should be executed
*/
virtual bool validateConfig(NetConfConfig* config, int defaultOperation = 0) override;
protected:
virtual void initialize() override;
/**
* The OpenFlow Flow Table containing match entries
*/
std::vector<openflow::OF_FlowTable*> _flowTables;
};
}
#endif /* SDN4CORE_NETCONF_DATASTORES_CONFIG_OPENFLOW_NETCONFDATACONFIGURATORFLOWTABLE_H_ */
| 2,902
|
C++
|
.h
| 63
| 42.936508
| 109
| 0.759292
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,238
|
NetConfDataConfiguratorDummy.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/dummy/NetConfDataConfiguratorDummy.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFCONFIGURATORDUMMY_H_
#define __SDN4CORE_NETCONFCONFIGURATORDUMMY_H_
//Omnet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/netconf/datastores/config/base/NetConfDataConfiguratorBase.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Contains the base module implementation and provides interface methods of a netconf config data store.
* NetConfConfigDataStore implementations execute netconf commands on the
* device such as get, copy and edit config commands.
* They are managed and dynamically created during runtime by
* @see~INetConfDataStoreManager modules.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfDataConfiguratorDummy : public NetConfDataConfiguratorBase
{
public:
/**
* Creates a NetConfConfig from the current configuration data that only contains elements in the filter.
* @param filter the filter to be applied, if empty the whole config data set is returned
* @return the requested configuration data
*/
virtual NetConfConfig* getConfig(const NetConfFilter& filter) override;
/**
* Applies the changes in the config using the defaultOperation.
* @param defaultOperation Selects the default operation, one of @see ~NetConfOperation_Operation.
* @param errorOption Selects how to react on errors, one of @see ~NetConfOperation_ErrorOption.
* @param config The config to be applied
* @return true if the changes could be applied, false if an error occurred.
*/
virtual bool editConfig(int defaultOperation, int errorOption, NetConfConfig* config) override;
/**
* Validate the given config if it valid or not
* @param configSRP the configuration that should be tested
* @param defaultOperation the desired default operation that should be executed
*/
virtual bool validateConfig(NetConfConfig* config, int defaultOperation = 0) override;
};
} /* namespace SDN4CoRE */
#endif
| 2,709
|
C++
|
.h
| 59
| 42.932203
| 109
| 0.755968
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,239
|
NetConfDataConfiguratorSRP.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/srp/NetConfDataConfiguratorSRP.h
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTORES_CONFIG_SRP_NETCONFDATACONFIGURATORSRP_H_
#define SDN4CORE_NETCONF_DATASTORES_CONFIG_SRP_NETCONFDATACONFIGURATORSRP_H_
//SDN4CoRE
#include <sdn4core/netconf/datastores/config/base/NetConfDataConfiguratorBase.h>
#include <sdn4core/netconf/messages/NetConfOperation_m.h>
#include <sdn4core/netconf/datastructures/srp/NetConfConfigSRP.h>
namespace SDN4CoRE {
/**
* Provides a SRP implementation for the interface of a NetConfConfigDataStore.
*
* @author Tobias Haugg, for HAW Hamburg
*/
class NetConfDataConfiguratorSRP : public NetConfDataConfiguratorBase{
public:
/**
* Creates a NetConfConfig from the current configuration data that only contains elements in the filter.
* @param filter the filter to be applied, if empty the whole config data set is returned
* @return the requested configuration data
*/
virtual NetConfConfig* getConfig(const NetConfFilter& filter) override;
/**
* Applies the changes in the config using the defaultOperation.
* @param defaultOperation Selects the default operation, one of @see ~NetConfOperation_Operation.
* @param errorOption Selects how to react on errors, one of @see ~NetConfOperation_ErrorOption.
* @param config The config to be applied
* @return true if the changes could be applied, false if an error occurred.
*/
virtual bool editConfig(int defaultOperation, int errorOption, NetConfConfig* config) override;
/**
* Validate the given config if it valid or not
* @param configSRP the configuration that should be tested
* @param defaultOperation the desired default operation that should be executed
*/
virtual bool validateConfig(NetConfConfig* config, int defaultOperation = 0) override;
protected:
virtual void initialize() override;
/**
* Reference to the SRP Table module.
*/
CoRE4INET::SRPTable* _srpTable;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_DATASTORES_CONFIG_SRP_NETCONFDATACONFIGURATORSRP_H_ */
| 2,793
|
C++
|
.h
| 59
| 44.135593
| 109
| 0.754405
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,240
|
NetConfDataConfiguratorBase.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/base/NetConfDataConfiguratorBase.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFCONFIGDATASTOREBASE_H_
#define __SDN4CORE_NETCONFCONFIGDATASTOREBASE_H_
//Omnet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfConfig.h>
#include <sdn4core/netconf/datastructures/base/NetConfFilter.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Contains the base module implementation and provides interface methods of a netconf config data store.
* NetConfConfigDataStore implementations execute netconf commands on the
* device such as get, copy and edit config commands.
* They are managed and dynamically created during runtime by
* @see~INetConfDataStoreManager modules.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfDataConfiguratorBase : public cSimpleModule
{
public:
/**
* Creates a NetConfConfig from the current configuration data that only contains elements in the filter.
* @param filter the filter to be applied, if empty the whole config data set is returned
* @return the requested configuration data
*/
virtual NetConfConfig* getConfig(const NetConfFilter& filter) = 0;
/**
* Applies the changes in the config using the defaultOperation.
* @param defaultOperation Selects the default operation, one of @see ~NetConfOperation_Operation.
* @param errorOption Selects how to react on errors, one of @see ~NetConfOperation_ErrorOption.
* @param config The config to be applied
* @return true if the changes could be applied, false if an error occurred.
*/
virtual bool editConfig(int defaultOperation, int errorOption, NetConfConfig* config) = 0;
/**
* Validate the given config if it valid or not
* @param configSRP the configuration that should be tested
* @param defaultOperation the desired default operation that should be executed
*/
virtual bool validateConfig(NetConfConfig* config, int defaultOperation = 0) = 0;
protected:
/**
*
*/
static simsignal_t editConfigOkSignal;
/**
*
*/
static simsignal_t editConfigErrorSignal;
};
} /* namespace SDN4CoRE */
#endif
| 2,882
|
C++
|
.h
| 69
| 38.463768
| 109
| 0.743214
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,241
|
NetConfServerTCP.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/server/tcp/NetConfServerTCP.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFSERVERTCP_H_
#define __SDN4CORE_NETCONFSERVERTCP_H_
#include <omnetpp.h>
#include <sdn4core/netconf/server/base/NetConfServerBase.h>
//INET
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* TCP implementation for a NetConfServer. Handles all the TCP specific functionality.
*
* A NetConf Server must be connected to device specific config and state datastores.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfServerTCP : public NetConfServerBase
{
protected:
virtual void initialize() override;
/**
* Forwards the message to the protocol specific transport layer.
* The NetConfCtrlInfo_Transport should be attached to the message.
* @param msg the message to forward
*/
virtual void sendToTransport(cMessage* msg) override;
/**
* Protocol specific implementation to open a new session.
* Checks if the session already exists, else opens a new one and adds the _nextSessionId
* Must insert the new session into the _openSessions list.
* @param msg the message to create a session for
*/
virtual NetConfServerSessionInfo* openNewSession(cMessage* msg) override;
/**
* Closes the protocol specific session and removes the session from openSessions list.
* @param sessionId the session to close
* @return true if the session was closed
*/
virtual bool closeSession(int sessionId) override;
/**
* Finds the session info for an incoming message.
* @param msg the message of a session
* @return pointer to the session info stored in _openSessions, null if none found.
*/
virtual NetConfServerSessionInfo* findSessionInfoForMsg(cMessage *msg) override;
private:
/**
* The TCP connection to NetConf clients
*/
inet::TCPSocket _serverSocket;
};
} // namespace SDN4CoRE
#endif
| 2,656
|
C++
|
.h
| 68
| 35.602941
| 93
| 0.740093
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,242
|
NetConfServerBase.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/server/base/NetConfServerBase.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFSERVER_H_
#define __SDN4CORE_NETCONFSERVER_H_
//Omnet
#include <omnetpp.h>
//STD
#include <unordered_map>
#include <vector>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfServerSessionInfo.h>
#include "sdn4core/utility/processing/ProcessingTimeSimulation.h"
#include "sdn4core/netconf/messages/NetConfMessage_m.h"
#include "sdn4core/netconf/messages/NetConfCtrlInfo_m.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* forward declaration of NetConfDataStoreManagerBase
*/
class NetConfDataStoreManagerBase;
/**
* Base implementation for a NetConfServer, communicating with a NetConf client @see~NetConfClient.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfServerBase : public ProcessingTimeSimulation
{
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
/**
* Forwards the message to the protocol specific transport layer.
* The NetConfCtrlInfo_Transport should be attached to the message.
* @param msg the message to forward
*/
virtual void sendToTransport(cMessage* msg) = 0;
/**
* Protocol specific implementation to open a new session.
* Checks if the session already exists, else opens a new one and adds the _nextSessionId
* Must insert the new session into the _openSessions list.
* @param msg the message to create a session for
*/
virtual NetConfServerSessionInfo* openNewSession(cMessage* msg) = 0;
/**
* Closes the protocol specific session and removes the session from openSessions list.
* @param sessionId the last message of the session to close
* @return true if the session was closed
*/
virtual bool closeSession(int sessionId) = 0;
/**
* Finds the session info for an incoming message.
* @param msg the message of a session
* @return pointer to the session info stored in _openSessions, null if none found.
*/
virtual NetConfServerSessionInfo* findSessionInfoForMsg(cMessage *msg) = 0;
/**
* Finds the session info for an existing session id.
* @param sessionId the id of the session to find
* @return pointer to the session info stored in _openSessions, null if none found.
*/
virtual NetConfServerSessionInfo* findSessionInfoForId(int sessionId);
/**
* @see ~ProcessingTimeSimulation::processScheduledMessage(cMessage *msg)
*/
virtual void processScheduledMessage(cMessage *msg);
/**
* Handles the hello message and replys to it.
* @param msg the incoming hello message
*/
virtual void handleHello(cMessage* msg);
/**
* Handles the close session message and replys to it.
* @param msg the incoming close session message
*/
virtual void handleCloseSession(cMessage* msg);
/**
* Handles the RPC message and forwards it to the correct store.
* @param msg the incoming RPC message
*/
virtual void handleRPC(NetConfMessage* msg);
/**
* Creates a NetConfCtrlInfo for the incoming message and sessionInfo.
* @param sessionInfo the session info for the message
* @param msg the incoming message
* @return a new NetConfCtrlInfo
*/
virtual NetConfCtrlInfo* createCtrlInfoFor(NetConfServerSessionInfo* sessionInfo, NetConfMessage* msg);
/**
* Creates an rpc reply element containing the error message.
* @param error_type Defines the conceptual layer that the error occurred.
* One of @see ~NetConf_RPCReplyElement_Error_Type
* @param error_tag Contains a string identifying the error condition.
* @param error_severity Contains an enum identifying the error severity, as
* determined by the device. One of @see ~NetConf_RPCReplyElement_Error_Severity
* @param error_app_tag Contains a string identifying the data-model-specific
* or implementation-specific error condition, if one exists.
* @return the NetConf_RPCReplyElement_Error
*/
virtual NetConf_RPCReplyElement* createRPCReplyElement_Error(
int error_type, const char * error_tag, int error_severity,
const char * error_app_tag);
/**
* Creates an rpc reply element containing OK.
* @return the NetConf_RPCReplyElement_Ok
*/
virtual NetConf_RPCReplyElement* createRPCReplyElement_Ok();
NetConfMessage_RPCReply* createRPCReply(NetConf_RPCReplyElement* element);
/**
* Network and Controller State
*/
std::vector<NetConfServerSessionInfo*> _openSessions;
/**
* The session ID to add to the next session opened with openNewSession();
*/
static int _nextSessionId;
/**
* Cached reference to the NetConf data store manager.
*/
NetConfDataStoreManagerBase* _configDataStoreManager;
/**
* Gate name (@directIn) for request inputs in data stores
*/
static const char REQUEST_FWD_GATE_NAME []; // = "requestIn";
/**
* Gate name (@directIn) for response inputs to NetConf server
*/
static const char RESPONSE_IN_GATE_NAME []; // = "responseIn";
/**
* Gate name for transport inputs
*/
static const char TRANSPORT_IN_GATE_NAME []; //= "transportIn";
/**
* Gate name for transport outputs
*/
static const char TRANSPORT_OUT_GATE_NAME []; //= "transportOut";
};
} // namespace SDN4CoRE
#endif
| 6,250
|
C++
|
.h
| 152
| 36.532895
| 109
| 0.704167
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,243
|
TransactionApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/transactionModel/TransactionApp.h
|
//
// c Mohammad Fazel Soltani, Timo Haeckel for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_TRANSACTIONAPP_H_
#define __SDN4CORE_TRANSACTIONAPP_H_
//STD
#include <map>
#include <vector>
#include <string.h>
#include <algorithm>
//SDN4CoRE
#include <sdn4core/netconf/applications/base/NetConfApplicationBase.h>
#include <sdn4core/netconf/datastructures/transactionModel/NetConfConfigCommitTimestamp.h>
//CoRE4INET
#include "core4inet/scheduler/period/Period.h"
#define SEND_TIMESTAMP_MSG_SIZE 226 * 8 // 226 Byte = 1808 bit
#define ACK_TIMESTAMP_MSG_SIZE 112 * 8 // 112 Byte = 896 bit
#define SEND_COMMIT_MSG_SIZE 108 * 8 // 108 Byte = 864 bit
#define MAX_ETHERNET_FRAME_SIZE 1530 * 8 // 1530 Byte = 12240 bit
namespace SDN4CoRE{
/**
* Contains the Transaction-App implementation of a netconf application.
* This module needs to be connected to the NetConf client.
*
* @author Mohammad Fazel Soltani, Tobias Haugg for HAW Hamburg
*/
class TransactionApp: public NetConfApplicationBase {
#define LOCK_MSG_ID "Lock"
#define COPY_CONFIG_MSG_ID "Copy Config"
#define LOCK_CANDIDATE_MSG_ID "Lock Candidate"
#define CHANGE_MSG_ID 0
#define TIMESTAMP_MSG_ID "Timestamp"
#define UNLOCK_MSG_ID "Unlock"
#define COMMIT_APPROVED_MSG_ID "Commit approved"
#define DELETE_CANDIDATE_MSG_ID "Delete Candidate Config"
#define DELETE_OLD_CONFIG_MSG_ID "Delete Old Config"
#define SELFMESSAGE_START_TRANSACTION "Start Transaction"
#define SELFMESSAGE_LAMBDA "LAMBDA_EVENT"
public:
friend class TransactionModelTest;
struct connections_less {
bool operator()(Connection_t* lhs, Connection_t* rhs) {
return lhs->remoteAddress.compare(rhs->remoteAddress.c_str())< 0;
}
};
enum Phase{
LOCK,
CHANGE,
CONFIRMATION,
UNLOCK,
DEFAULT
};
struct TransactionAppState{
static const int BeginOfTransaction = 0;
static const int WaitOnLockResponse = 1;
static const int WaitOnCandidateConfirmation = 2;
static const int WaitOnCandidateLockResponse = 3;
static const int WaitOnChangeConfirmation = 4;
static const int WaitOnCommitExecution = 5;
static const int WaitOnDeleteOldConfiguration = 6;
static const int WaitOnDeleteCandidate = 7;
static const int WaitOnUnlock = 8;
static const int ErrorState = 9;
static const int EndOfTransaction = 10;
};
struct SwitchState{
static const int SwitchAvailable = 0;
static const int SwitchLocked = 1;
static const int SwitchWithCandidate = 2;
static const int SwitchWithLockedCandidate = 3;
static const int SwitchWithChangedCandidateConfiguration = 4;
static const int SwitchCommited = 5;
static const int SwitchWithoutCandidate = 6;
static const int SwitchWithoutOldConfig = 7;
static const int SwitchUnlocked = 8;
static const int SwitchError = 9;
};
typedef struct SwitchState_s {
bool hasLockedRunning = false;
bool hasCandidate = false;
bool hasLockedCandidate = false;
bool hasConfiguration = false;
bool hasCommited = false;
bool hasError = false;
bool isInState(int state) {
switch (state) {
case SwitchState::SwitchAvailable:
if(!hasLockedRunning && !hasCandidate && !hasLockedCandidate && !hasConfiguration && !hasCommited && !hasError){
return true;
}
break;
case SwitchState::SwitchLocked:
if(hasLockedRunning && !hasError){
return true;
}
break;
case SwitchState::SwitchWithCandidate:
if(hasLockedRunning && hasCandidate && !hasLockedCandidate && !hasConfiguration && !hasCommited && !hasError){
return true;
}
break;
case SwitchState::SwitchWithLockedCandidate:
if(hasLockedRunning && hasCandidate && hasLockedCandidate && !hasConfiguration && !hasCommited && !hasError){
return true;
}
break;
case SwitchState::SwitchWithChangedCandidateConfiguration:
if(hasLockedRunning && hasCandidate && hasLockedCandidate && hasConfiguration && !hasCommited && !hasError){
return true;
}
break;
case SwitchState::SwitchCommited:
if(hasLockedRunning && hasCandidate && hasLockedCandidate && hasConfiguration && hasCommited && !hasError){
return true;
}
break;
case SwitchState::SwitchWithoutCandidate:
if(hasLockedRunning && !hasCandidate && !hasCommited){
return true;
}
break;
case SwitchState::SwitchWithoutOldConfig:
if(hasLockedRunning && !hasCandidate && hasCommited){
return true;
}
break;
case SwitchState::SwitchUnlocked:
if(!hasLockedRunning){
return true;
}
break;
case SwitchState::SwitchError:
if(hasError){
return true;
}
break;
default:
break;
}
return false;
};
} SwitchState_t;
TransactionApp() {
};
~TransactionApp(){
if(LAMBDA_EVENT != nullptr) {
auto owner = LAMBDA_EVENT->getOwner();
if (owner != nullptr && owner == this) {
delete LAMBDA_EVENT;
}
}
}
protected:
/**
* update statistics and displaystring of Switch
* @param Phase new phase
*/
void updatePhase(Phase newPhase);
/**
* finds the mentioned connection for the reply
* @param reply the NetConfMessage_RPCReply
* @return the Connection
*/
NetConfApplicationBase::Connection_t* findConnectionForReply(NetConfMessage_RPCReply* reply);
/**
* returns a vector of connection which are in the giving state
* @param state the giving state
* @return vector of connection
*/
virtual std::vector<Connection_t*> getSwitchesInState(int state);
/**
* converts a state name to a string
* @param state the giving state
* @return state name as string
*/
virtual std::string transactionAppStateToString(int state);
int getTransactionState();
/**
* the finite state machine of the transaction model
*@param msg the received message
*/
virtual void finiteStateMachine(cMessage* msg);
/**
* determines the lock order of connections
*/
virtual void determineLockOrder();
/**
* executes transition to next state
* @param state the giving state
*/
void transitionToState(int state);
/**
* checks if the received message is a msg which the transaction model can process
* @param msg the received message
* @return true if it is a message which can process the model, else false
*/
bool isFSMAlphabet(cMessage* msg);
/**
* checks if the received message is a self message to start the transaction
* @param msg the received message
* @return true if it is a message to start the transaction, else false
*/
bool isStartTransactionEvent(cMessage* msg);
/**
* checks if the received message is a rpc reply event message
* @param msg the received message
* @return true if it is a rpc reply event message , else false
*/
bool isRPCReplyEvent(cMessage* msg);
/**
* checks if it is a Lambda event message
* @param msg the received message
* @return true if it is a Lambda event message , else false
*/
bool isLambdaEvent(cMessage* msg);
/**
* the result of the transaction
* true = successful
* false = failed
*/
bool result;
/**
* the cMessage for the Lambda event
*/
cMessage* LAMBDA_EVENT;
/**
* the first state of the transaction model
*/
int transactionState = TransactionAppState::BeginOfTransaction;
/**
* map to order a connection to the switch state
*/
std::map<Connection_t*, SwitchState_t*,connections_less> switchStates;//connection_less will keep this sorted after the remote_ip
/**
* handles the message in the state BeginOfTransaction
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInBeginOfTransaction(cMessage* msg);
/**
* handles the message in the state WaitOnLockResponse
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInWaitOnLockResponse(cMessage* msg);
/**
* handles the message in the state WaitOnCandidateConfirmation
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInWaitOnCandidateConfirmation(cMessage* msg);
/**
* handles the message in the state WaitOnCandidateLockResponse
* @param msg the received message
* * @param eventHandled handled event
*/
bool handleMessageInWaitOnCandidateLockResponse(cMessage* msg);
/**
* handles the message in the state WaitOnChangeConfirmation
* @param msg the received message
* @param eventHandled handled event
*/
virtual bool handleMessageInWaitOnChangeConfirmation(cMessage* msg);
/**
* handles the message in the state WaitOnCommitExecution
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInWaitOnCommitExecution(cMessage* msg);
/**
* handles the message in the state WaitOnDeleteOldConfiguration
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInWaitOnDeleteOldConfiguration(cMessage* msg);
/**
* handles the message in the state WaitOnDeleteCandidate
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInWaitOnDeleteCandidate(cMessage* msg);
/**
* handles the message in the state WaitOnUnlock
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInWaitOnUnlock(cMessage* msg);
/**
* handles the message in the state ErrorState
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInErrorState(cMessage* msg);
/**
* checks if the event was handled
* @param eventHandled
* @return true, if event was handled else false
*/
void checkEventHandled(bool eventHandled, cMessage* msg);
virtual void initialize() override;
virtual void handleMessage(cMessage* msg) override;
/**
* intercept when all connections are ready
*/
virtual bool scheduleNextConfigurationFor(Connection_t* connection) override;
/**
* Schedules a self messsage for the next connection creation;
*/
virtual bool scheduleNextConnection() override;
/**
* schedules the start of the transaction
*/
void scheduleTransactionStart(SimTime startTime = SimTime::ZERO);
/**
* the processing time of the controller
*/
double controllerProcessingTime = 0;
/**
* Signal to emit the result of transaction
*/
simsignal_t resultOfTransaction;
/**
* Signal to emit the duration of transaction
*/
simsignal_t transactionDuration;
/**
* Signal that is emitted to count sent messages
*/
simsignal_t numSent;
/**
* Signal that is emitted to count received messages
*/
simsignal_t numReceived;
/**
* Signal that is emitted when anew phase is entered
*/
simsignal_t enterNewPhase;
};
} // namespace SDN4CoRE
#endif
| 13,067
|
C++
|
.h
| 353
| 29.203966
| 133
| 0.646157
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,244
|
TimeSynchronousTransactionApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/transactionModel/TimeSynchronousTransactionApp.h
|
//
// c Mohammad Fazel Soltani, Timo Haeckel for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_TIMESYNCHRONOUSTRANSACTIONAPP_H_
#define __SDN4CORE_TIMESYNCHRONOUSTRANSACTIONAPP_H_
//STD
#include <map>
#include <vector>
#include <string.h>
#include <algorithm>
//CoRE4INET
#include "core4inet/scheduler/period/Period.h"
//SDN4CoRE
#include <sdn4core/netconf/applications/base/NetConfApplicationBase.h>
#include <sdn4core/netconf/applications/transactionModel/TransactionApp.h>
#include <sdn4core/netconf/datastructures/transactionModel/NetConfConfigCommitTimestamp.h>
namespace SDN4CoRE{
/**
* Contains the Transaction-App implementation of a netconf application.
* This module needs to be connected to the NetConf client.
*
* @author Mohammad Fazel Soltani, Tobias Haugg for HAW Hamburg
*/
class TimeSynchronousTransactionApp: public TransactionApp {
public:
friend class TransactionModelTest;
struct TransactionAppState: public TransactionApp::TransactionAppState{
static const int WaitOnTimestampConfirmation = 11;
};
struct SwitchState: public TransactionApp::SwitchState{
const static int SwitchWithTimestamp = 10;
};
typedef struct SwitchState_s: public TransactionApp::SwitchState_s {
bool hasCommitTimeStamp = false;
bool isInState(int state) {
switch (state) {
case SwitchState::SwitchWithTimestamp:
if(hasLockedRunning && hasCandidate && hasLockedCandidate && hasConfiguration && hasCommitTimeStamp && !hasCommited && !hasError){
return true;
}
break;
default:
return TransactionApp::SwitchState_s::isInState(state);
break;
}
return false;
};
} SwitchState_t;
protected:
/**
* returns a vector of connection which are in the giving state
* @param state the giving state
* @return vector of connection
*/
std::vector<Connection_t*> getSwitchesInState(int state) override;
/**
* sets the timestamp as data for the configuration
* @param timestamp the timestamp.
* @return the Configurations
*/
Configuration_t* getCommitTimestampConfig(NetConfConfigCommitTimestamp::CommitTimestamp_t timestamp);
/**
* determines timestamp by calculation for each connection the latencies of all Ethernet frames that still to be sent
* @return the CommitTimestamp
*/
NetConfConfigCommitTimestamp::CommitTimestamp_t determineTimestamp();
/**
* converts a state name to a string
* @param state the giving state
* @return state name as string
*/
std::string transactionAppStateToString(int state)override;
/**
* the finite state machine of the transaction model
*@param msg the received message
*/
void finiteStateMachine(cMessage* msg)override;
/**
* determines the lock order of connections
*/
void determineLockOrder()override;
/**
* checks if the transaction misses the commit timestamp
* @return true if it misses the commit timestamp, else false
*/
bool checkCommitrelease();
/**
* handles the message in the state WaitOnChangeConfirmation
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInWaitOnChangeConfirmation(cMessage* msg) override;
/**
* handles the message in the state WaitOnTimestampConfirmation
* @param msg the received message
* @param eventHandled handled event
*/
bool handleMessageInWaitOnTimestampConfirmation(cMessage* msg);
virtual void initialize() override;
private:
/**
* period from scheduler
*/
CoRE4INET::Period* _period;
/**
* the commit time with cycle and period for commit execution
*/
NetConfConfigCommitTimestamp::CommitTimestamp_t _timestamp;
/**
* period to be synchronized
*/
size_t _syncPeriod = 0;
/**
* sum of the last latencies of each connection
*/
double _sumOfLastLatencies = 0;
};
} // namespace SDN4CoRE
#endif
| 4,872
|
C++
|
.h
| 132
| 31.371212
| 150
| 0.707157
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,245
|
TransactionModelTest.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/transactionModel/transactionModelTest/TransactionModelTest.h
|
//
// c Mohammad Fazel Soltani for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_TRANSACTIONMODELTEST_H_
#define __SDN4CORE_TRANSACTIONMODELTEST_H_
#include <omnetpp.h>
#include <sdn4core/netconf/applications/configparser/base/Configuration_t.h>
#include <sdn4core/netconf/applications/transactionModel/TimeSynchronousTransactionApp.h>
#include "sdn4core/netconf/applications/base/NetConfApplicationBase.h"
#include "sdn4core/netconf/datastructures/base/NetConfConfig.h"
#include "sdn4core/netconf/datastructures/base/NetConfFilter.h"
#include "sdn4core/netconf/messages/NetConfOperation_m.h"
namespace SDN4CoRE{
/*
* This class provides methods for testing the state coverage and
* transition coverage of the network-wide transaction model.
* The states are in (@TransactionApp::TransactionAppState).
* @author Mohammad Fazel Soltani, for HAW Hamburg
*/
class TransactionModelTest : public omnetpp::cSimpleModule{
private:
/**
* timesynchronous transaction app
*/
TimeSynchronousTransactionApp* _timeSynchronousTransactionApp;
/**
* test case number
*/
int _testCase;
/**
* second message to schedule second test case of commit release
*/
cMessage* _partTwoMessage;
protected:
/**
* initializes the first connection with the well-defined configurations
* @return the connection with configurations
*/
NetConfApplicationBase::Connection_t initConnectionOne();
/**
* initializes the second connection with the well-defined configurations
* @return the connection with configurations
*/
NetConfApplicationBase::Connection_t initConnectionTwo();
/**
* initializes connections and sets them as connections in the transaction model
*/
void initConnections();
/**
* resets finite state machine
*/
void resetFSM();
NetConfCtrlInfo* getControlInfo(std::string controlInfoMessageId, int sessionId);
NetConfMessage_RPCReply* getReplyOkMsg(std::string msgId, std::string controlInfoMessageId, int sessionId);
NetConfMessage_RPCReply* getReplyErrorMsg(std::string msgId, std::string controlInfoMessageId, int sessionId);
/**
* State-based test method for the following state and transition coverage:
* transitionCoverageLastCandidateFailed
* @return true if last candidate fails else false
*/
bool stateAndTransitionCoverageFailure();
/**
* State-based test method for the following state and transition coverage:
* transaction routine and all transitions to do a transaction
* @return true if it was successfull else false
*/
bool stateAndTransitionCoverageSuccesful();
/**
* State-based test method for the following transition coverage:
* first switch is already locked
* @return true if switch is already locked else false
*/
bool transitionCoverageAlreadyLocked();
/**
* State-based test method for the following transition coverage:
* next switch is already locked
* @return true if next switch is locked else false
*/
bool transitionCoverageAlreadyLockedNext();
/**
* State-based test method for the following transition coverage:
* all switches relpy that their copy config failed
* @return true if all copy config fails else false
*/
bool transitionCoverageAllCandidatesFailed();
/**
* State-based test method for the following transition coverage:
* first switch sends error-reply that copy config failed
* @return true if first switch sends error-reply that copy config fails else false
*/
bool transitionCoverageFirstCandidateFailed();
/**
* State-based test method for the following transition coverage:
* last switch sends error-reply that copy config failed
* @return true if last switch sends error-reply that copy config fails else false
*/
bool transitionCoverageLastCandidateFailed();
/**
* State-based test method for the following transition coverage:
* first change of a switch fails
* @return true if first change of a switch fails else false
*/
bool transitionCoverageFirstChangeFails();
/**
* State-based test method for the following transition coverage:
* the next change of a switch fails
* @return true if next change of a switch fails else false
*/
bool transitionCoverageNextChangeFails();
/**
* State-based test method for the following transition coverage:
* first switch reply is Timestamp-fail
* @return true if first switch reply is Timestamp-fail else false
*/
bool transitionCoverageFirstTimestampFail();
/**
* State-based test method for the following transition coverage:
* last switch reply is Timestamp-fail
* @return true if last switch reply is Timestamp-fail else false
*/
bool transitionCoverageLastTimestampFail();
/**
* State-based test method for the following transition coverage:
* commit release failed
* @return true if commit release fails else false
*/
bool transitionCoverageCommitReleaseFailed();
/**
* State-based test method for the following transition coverage:
* preparation for transitionCoverageCommitReleasePartTwo()
* @return true if first part of commit release fails else false
*/
bool transitionCoverageCommitReleasePartOne();
/**
* State-based test method for the following transition coverage:
* commit release of last switch misses commit timestamp
* @return true if second part of commit release fails else false
*/
bool transitionCoverageCommitReleasePartTwo();
protected:
virtual void initialize() override;
virtual void handleMessage(omnetpp::cMessage* msg) override;
};
} // namespace SDN4CoRE
#endif
| 6,507
|
C++
|
.h
| 158
| 36.481013
| 114
| 0.743866
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,246
|
NetConfAppConfigParserMultipart.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/multipart/NetConfAppConfigParserMultipart.h
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_MULTIPART_NETCONFAPPCONFIGPARSERMULTIPART_H_
#define SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_MULTIPART_NETCONFAPPCONFIGPARSERMULTIPART_H_
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserBase.h>
namespace SDN4CoRE {
/**
* Contains the Multipart switch specific implementation of a netconf application.
* This module needs to be connected to the NetConf client.
*
* @author Tobias Haugg, for HAW Hamburg
*/
class NetConfAppConfigParserMultipart: public NetConfAppConfigParserBase{
public:
/**
* Create config data from XML.
*/
virtual NetConfConfig* getConfigDataFor(cXMLElement* element) override;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_NETCONFAPPCONFIGPARSERMULTIPART_H_ */
| 1,553
|
C++
|
.h
| 36
| 41.333333
| 95
| 0.794176
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,247
|
NetConfAppConfigParserIEEE8021Qbv.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/ieee8021qbv/NetConfAppConfigParserIEEE8021Qbv.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFAPPCONFIGPARSERIEEE8021QBV_H_
#define __SDN4CORE_NETCONFAPPCONFIGPARSERIEEE8021QBV_H_
//Omnet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/ieee8021qbv/NetConfConfigIEEE8021Qbv.h>
#include <sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserBase.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Contains the IEEE8021Qbv switch specific implementation of a netconf application.
* This module needs to be connected to the NetConf client.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfAppConfigParserIEEE8021Qbv: public NetConfAppConfigParserBase {
public:
/**
* Create config data from XML.
*/
virtual NetConfConfig* getConfigDataFor(cXMLElement* element) override {
NetConfConfigIEEE8021Qbv* configData = new NetConfConfigIEEE8021Qbv();
cXMLElementList configsXML = element->getChildrenByTagName("config");
for (auto configXML : configsXML) {
const char* portC = configXML->getAttribute("port");
const char* gateControlList = configXML->getAttribute(
"gatecontrollist");
if (portC && gateControlList) {
NetConfConfigIEEE8021Qbv::IEEE8021QbvGateConfig_t* gateConfig =
new NetConfConfigIEEE8021Qbv::IEEE8021QbvGateConfig_t();
gateConfig->port = atoi(portC);
gateConfig->gateControlList = gateControlList;
configData->setGateConfiguration(gateConfig);
}
}
return dynamic_cast<NetConfConfig*>(configData);
}
};
} // namespace SDN4CoRE
#endif //__SDN4CORE_NETCONFAPPCONFIGPARSERIEEE8021QBV_H_
| 2,423
|
C++
|
.h
| 56
| 38.071429
| 87
| 0.731666
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,248
|
NetConfAppConfigParserOpenFlow.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/openflow/NetConfAppConfigParserOpenFlow.h
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_OPENFLOW_NETCONFAPPCONFIGPARSEROPENFLOW_H_
#define SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_OPENFLOW_NETCONFAPPCONFIGPARSEROPENFLOW_H_
//Omnet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserBase.h>
#include <sdn4core/netconf/datastructures/openflow/OF_NetConfConfigFlowMod.h>
using namespace omnetpp;
namespace SDN4CoRE{
/**
* Contains the OpenFlow switch specific implementation of a netconf application.
* This module needs to be connected to the NetConf client.
*
* @author Tobias Haugg, for HAW Hamburg
*/
class NetConfAppConfigParserOpenFlow: public NetConfAppConfigParserBase{
public:
/**
* Create config data from XML.
*/
virtual NetConfConfig* getConfigDataFor(cXMLElement* element) override;
private:
/**
* converts a string to a OF_NetConfConfigFlowMod::commands.
* @throws Cerror if the string could not be parsed
* @returns OF_NetConfConfigFlowMod::commands
*/
OF_NetConfConfigFlowMod::commands parseCommand(const char* command);
};
}
#endif /* SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_OPENFLOW_NETCONFAPPCONFIGPARSEROPENFLOW_H_ */
| 1,930
|
C++
|
.h
| 47
| 38.851064
| 98
| 0.789025
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,249
|
NetConfAppConfigParserSRPTable.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/srptable/NetConfAppConfigParserSRPTable.h
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_SRPTABLE_NETCONFAPPCONFIGPARSERSRPTABLE_H_
#define SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_SRPTABLE_NETCONFAPPCONFIGPARSERSRPTABLE_H_
//STD
#include <unordered_map>
#include <string>
//CoRE4INET
#include "core4inet/base/avb/AVBDefs.h"
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserBase.h>
namespace SDN4CoRE {
/**
* Contains the SRP switch specific implementation of a netconf application.
* This module needs to be connected to the NetConf client.
*
* @author Tobias Haugg, for HAW Hamburg
*/
class NetConfAppConfigParserSRPTable: public NetConfAppConfigParserBase{
public:
/**
* Create config data from XML.
*/
virtual NetConfConfig* getConfigDataFor(cXMLElement* element) override;
private:
/**
* map used to convert from string to enum values of type SR_CLASS
*/
std::unordered_map<std::string,CoRE4INET::SR_CLASS> stringToEnum{
{std::string("A"),CoRE4INET::SR_CLASS::A},
{std::string("B"),CoRE4INET::SR_CLASS::B},
};
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_SRPTABLE_NETCONFAPPCONFIGPARSERSRPTABLE_H_ */
| 1,926
|
C++
|
.h
| 49
| 36.938776
| 98
| 0.76697
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,250
|
Configuration_t.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/base/Configuration_t.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_BASE_CONFIGURATION_T_H_
#define SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_BASE_CONFIGURATION_T_H_
//Omnet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfConfig.h>
#include <sdn4core/netconf/datastructures/base/NetConfFilter.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Configurations to start at certain points in time.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class Configuration_t {
public:
~Configuration_t(){
if(this->data != nullptr){
delete this->data;
}
if(this->filter != nullptr){
delete this->filter;
}
}
/**
* Information on how and when to connect to server.
*/
typedef enum ConfigurationState {
ConfigurationStateWaiting = 0,
ConfigurationStateScheduled = 1,
ConfigurationStateRequested = 2,
ConfigurationStateSuccess = 3,
ConfigurationStateError = 4
} ConfigurationState_t;
static std::string connectionStateToString(ConfigurationState_t state) {
switch(state) {
case ConfigurationStateWaiting:
return "Waiting";
case ConfigurationStateScheduled:
return "Scheduled";
case ConfigurationStateRequested:
return "Requested";
case ConfigurationStateSuccess:
return "Success";
case ConfigurationStateError:
return "Error";
default: break;
}
return "Unknown";
}
/**
* Configuration message type
*/
typedef enum NetConfMessageType {
NetConfMessageType_EditConfig = 0, //edit_config
NetConfMessageType_GetConfig = 1, //get_config
NetConfMessageType_CopyConfig = 2, //copy_config
NetConfMessageType_DeleteConfig = 3, //delete_config
NetConfMessageType_Lock = 4, //lock
NetConfMessageType_Unlock = 5, //unlock
NetConfMessageType_Commit = 6, //commit
} NetConfMessageType_t;
static std::string netconfMessageTypeToString(NetConfMessageType_t state) {
switch(state) {
case NetConfMessageType_EditConfig:
return "edit_config";
case NetConfMessageType_GetConfig:
return "get_config";
case NetConfMessageType_CopyConfig:
return "copy_config";
case NetConfMessageType_DeleteConfig:
return "delete_config";
case NetConfMessageType_Lock:
return "lock";
case NetConfMessageType_Unlock:
return "unlock";
case NetConfMessageType_Commit:
return "commit";
default: break;
}
return "Unknown";
}
static int getConfigTypeFor(const char* type) {
if (!strcmp(type, "edit_config")) {
return NetConfMessageType::NetConfMessageType_EditConfig;
} else if (!strcmp(type, "get_config")) {
return NetConfMessageType::NetConfMessageType_GetConfig;
} else if (!strcmp(type, "copy_config")) {
return NetConfMessageType::NetConfMessageType_CopyConfig;
} else if (!strcmp(type, "delete_config")) {
return NetConfMessageType::NetConfMessageType_DeleteConfig;
} else if (!strcmp(type, "lock")){
return NetConfMessageType::NetConfMessageType_Lock;
} else if (!strcmp(type, "unlock")){
return NetConfMessageType::NetConfMessageType_Unlock;
} else if (!strcmp(type, "commit")){
return NetConfMessageType::NetConfMessageType_Commit;
}
return -1;
};
/**
* The time to execute the config
*/
SimTime executeAt;
/**
* The target store.
*/
std::string target;
/**
* The source store.
*/
std::string source;
/**
* Configuration data to transmit
*/
NetConfConfig* data;
/**
* Configuration filters to transmit
*/
NetConfFilter* filter;
/**
* Type
*/
NetConfMessageType_t type;
/**
* the state of this config
*/
ConfigurationState_t state;
friend std::ostream& operator<<(std::ostream& os, const Configuration_t& obj){
os << "{executeAt=" << obj.executeAt;
os << ", target=" << obj.target;
os << ", source=" << obj.source;
// os << ", data=" << obj.data;
// os << ", filter=" << obj.filter;
os << ", type=" << netconfMessageTypeToString(obj.type);
os << ", state=" << connectionStateToString(obj.state);
os << "}";
return os;
}
};
}
#endif /* SDN4CORE_NETCONF_APPLICATIONS_CONFIGPARSER_BASE_CONFIGURATION_T_H_ */
| 5,413
|
C++
|
.h
| 158
| 27.493671
| 82
| 0.647621
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,251
|
NetConfAppConfigParserCollection.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserCollection.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFAPPCONFIGPARSERBASECOLLECTION_H_
#define __SDN4CORE_NETCONFAPPCONFIGPARSERBASECOLLECTION_H_
//Omnet
#include <omnetpp.h>
//STD
#include <map>
#include <string>
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/base/Configuration_t.h>
#include <sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserBase.h>
#include <sdn4core/netconf/applications/base/NetConfApplicationBase.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Implements an XML parser for NetConf App configurations.
* Uses all known implementations for Configurations to parse XML input
* in the parsers vector @see(NetConfAppConfigParserIEEE8021Qbv)
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfAppConfigParserCollection {
public:
/**
* Create a list of NetConf app configurations from XML elements using the specific parsers.
* @param configuresXML The XML list to parse
* @return a list of configuration objects according to the XML for empty Configs and Filters a dummy object is used.
*/
static std::vector<Configuration_t*> parseXMLConfigList(
const cXMLElementList& configuresXML, bool executionTimeRequired = true);
/**
* Create a NetConf app configuration from an XML element using the specific parsers.
* @param configureXML The XML to parse
* @return a configuration object according to the XML for empty Config and Filter a dummy object is used.
*/
static Configuration_t* parseXMLConfig(cXMLElement* configureXML,
bool executionTimeRequired = true);
/**
* Create config data from XML.
*/
static NetConfConfig* getConfigDataFor(cXMLElement* element);
/**
* Create config filter from XML.
*/
static NetConfFilter* getConfigFilterFor(cXMLElement* element);
/**
* Create a list of NetConf app connections from XML elements.
* @param connectionsXML The XML to parse
* @return a list of connections objects according to the XML.
*/
static std::vector<NetConfApplicationBase::Connection_t> parseXMLConnectionList(
const cXMLElementList& connectionsXML, bool executionTimeRequired = true);
/**
* Create a NetConf app connection from an XML element.
* @param element The XML to parse
* @return a connections object according to the XML.
*/
static NetConfApplicationBase::Connection_t parseXMLConnection(
cXMLElement* element, bool executionTimeRequired = true);
private:
/**
* Available ConfigParsers
*/
static std::map<std::string, NetConfAppConfigParserBase*> parsers;
};
};// namespace SDN4CoRE
#endif //__SDN4CORE_NETCONFAPPCONFIGPARSERBASECOLLECTION_H_
| 3,472
|
C++
|
.h
| 82
| 38.439024
| 122
| 0.747038
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,252
|
NetConfAppConfigParserBase.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserBase.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFAPPCONFIGPARSERBASE_H_
#define __SDN4CORE_NETCONFAPPCONFIGPARSERBASE_H_
//Omnet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfConfig.h>
#include <sdn4core/netconf/datastructures/base/NetConfFilter.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Specifies the interface and base implementation of an XML parser
* for a NetConf Applicaition Configuration
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfAppConfigParserBase {
public:
/**
* Create config data from XML.
*/
virtual NetConfConfig* getConfigDataFor(cXMLElement* element) {
return nullptr;
}
/**
* Create config filter from XML.
*/
virtual NetConfFilter* getConfigFilterFor(cXMLElement* element) {
return nullptr;
}
};
} // namespace SDN4CoRE
#endif //__SDN4CORE_NETCONFAPPCONFIGPARSERBASE_H_
| 1,623
|
C++
|
.h
| 48
| 31.1875
| 78
| 0.756066
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,253
|
NetConfApplicationBase.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/base/NetConfApplicationBase.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFAPPLICATIONBASE_H_
#define __SDN4CORE_NETCONFAPPLICATIONBASE_H_
//OMNENT
#include <omnetpp.h>
//STD
#include <vector>
#include <string>
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/base/Configuration_t.h>
#include <sdn4core/netconf/datastructures/tcp/NetConfClientSessionInfoTCP.h>
#include "sdn4core/netconf/messages/NetConfCapability_m.h"
#include "sdn4core/netconf/messages/NetConfMessage_m.h"
#include "sdn4core/netconf/messages/NetConfCtrlInfo_m.h"
#include "sdn4core/netconf/messages/NetConfOperation_m.h"
using namespace omnetpp;
namespace SDN4CoRE {
#define SELFMESSAGE_SEND_HELLO "Send Hello"
/**
* Contains the common interface of a netconf application.
* This module needs to be connected to the NetConf client.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfApplicationBase: public cSimpleModule {
public:
/**
* Information on how and when to connect to server.
*/
typedef enum ConnectionState {
ConnectionStateWaiting = 0,
ConnectionStateScheduled = 1,
ConnectionStateRequested = 2,
ConnectionStateEstablished = 3
} ConnectionState_t;
static std::string connectionStateToString(ConnectionState_t state) {
switch(state) {
case ConnectionStateWaiting:
return "Waiting";
case ConnectionStateScheduled:
return "Scheduled";
case ConnectionStateRequested:
return "Requested";
case ConnectionStateEstablished:
return "Established";
default: break;
}
return "Unknown";
}
/**
* Information on how and when to connect to server.
*/
class Connection_t {
public:
/**
* the local port
*/
int localPort;
/**
* the server address to connect to
*/
std::string remoteAddress;
/**
* the netconf port at the server (usually 830)
*/
int remotePort;
/**
* the time at which the app connects to the server
*/
SimTime connectAt;
/**
* the state of this connection @see ~ConnectionState_t.
*/
ConnectionState_t state;
/**
* Configurations to make at a certain time.
*/
std::vector<Configuration_t*> configurations;
/**
* session_id
*/
int session_id = -1;
friend std::ostream& operator<<(std::ostream& os, const Connection_t& obj){
os << "{localPort=" << obj.localPort;
os << ", remoteAddress=" << obj.remoteAddress;
os << ", remotePort=" << obj.remotePort;
os << ", connectAt=" << obj.connectAt;
os << ", state=" << connectionStateToString(obj.state);
os << ", configurations=[";
int count = 0;
for (auto config : obj.configurations) {
if(count>0) {
os << ", ";
}
os << (*config);
count++;
}
os << "]";
os << ", session_id=" << obj.session_id;
os << "}";
return os;
}
};
virtual ~NetConfApplicationBase();
void setConnnections(std::vector<Connection_t>& connections);
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
/**
* Schedules a self messsage for the next connection creation;
*/
virtual bool scheduleNextConnection();
/**
* Schedules a self messsage for the next connection creation;
*/
virtual bool scheduleNextConfigurationFor(Connection_t* connection);
/**
* Creates a NetConfHello message for the connection.
* @param connection the connection data.
* @return the NetConfHello message
*/
virtual NetConfHello* createHelloFor(Connection_t* connection);
/**
* Create an editconfig configuration operation.
* @param config the configuration details
* @return the NetConfOperation_EditConfig message
*/
virtual NetConfOperation_EditConfig* createEditConfigOperation(
Configuration_t* config);
/**
* Create a getconfig configuration operation.
* @param config the configuration details
* @return the NetConfOperation_GetConfig message
*/
virtual NetConfOperation_GetConfig* createGetConfigOperation(
Configuration_t* config);
/**
* Create a copyconfig configuration operation.
* @param config the configuration details
* @return the NetConfOperation_CopyConfig message
*/
virtual NetConfOperation_CopyConfig* createCopyConfigOperation(
Configuration_t* config);
/**
* Create a copyconfig configuration operation.
* @param config the configuration details
* @return the NetConfOperation_DeleteConfig message
*/
virtual NetConfOperation_DeleteConfig* createDeleteConfigOperation(
Configuration_t* config);
/**
* Create a lock configuration operation.
* @param config the configuration details
* @return the NetConfOperation_Lock message
*/
virtual NetConfOperation_Lock* createLockOperation(
Configuration_t* config);
/**
* Create a unlock configuration operation.
* @param config the configuration details
* @return the NetConfOperation_Unlock message
*/
virtual NetConfOperation_Unlock* createUnlockOperation(
Configuration_t* config);
/**
* Create a commit configuration operation.
* @param config the configuration details
* @return the NetConfOperation_Commit message
*/
virtual NetConfOperation_Commit* createCommitOperation(
Configuration_t* config);
/**
* Creates a NetConfMessage_RPC message for a connection and the configuration at the given index
* @param connection the connection to use
* @param config configuration to be created
* @param message_id the identifier of the configuration message
* @return the NetConfMessage_RPC message
*/
virtual NetConfMessage_RPC* createNetConfRPCForConfiguration(
Connection_t* connection, Configuration_t* config,
std::string message_id);
/**
* map the sessioninfo to a connection.
* todo not use TCP specific info if not required.
*/
virtual Connection_t* mapSessionInfoToConnection(
NetConfClientSessionInfoTCP* sessionInfo);
/**
* Fills in the control info parameters
*/
virtual NetConfCtrlInfo* createControlInfo(int messageType, int sessionId,
const char* messageId);
/**
* The connections for this application
*/
std::vector<Connection_t> _connections;
};
} // namespace SDN4CoRE
#endif
| 7,620
|
C++
|
.h
| 214
| 28.747664
| 101
| 0.660342
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,254
|
NetConfClientTCP.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/client/tcp/NetConfClientTCP.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFCLIENTTCP_H_
#define __SDN4CORE_NETCONFCLIENTTCP_H_
#include <omnetpp.h>
#include "sdn4core/netconf/client/base/NetConfClientBase.h"
//INET
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Contains the TCP specific implementation of a NetConf client.
* This module has to be connected to the tcp module.
*
* All responses will be forwarded to the applicaitonOut gate with the
* same index as the arriving applicationIn gate
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfClientTCP : public NetConfClientBase
{
protected:
virtual void initialize() override;
virtual void handleMessage(cMessage* msg) override;
/**
* Forwards the message to the protocol specific transport layer.
* The NetConfCtrlInfo_Transport should be attached to the message.
* @param msg the message to forward
*/
virtual void sendToTransport(cMessage* msg) override;
/**
* Protocol specific implementation to open a new session for a NetConfHello message.
* Must insert the new session into the _openSessions list.
* @param hello the NetConfHello to create a session for NetConfHello
*/
virtual NetConfClientSessionInfo* openNewSession(NetConfHello* hello) override;
/**
* Closes the protocol specific session and removes the session from openSessions list.
* @param sessionId the session to close
* @return true if the session was closed
*/
virtual bool closeSession(int sessionId) override;
/**
* Finds the session info for an incoming message.
* @param msg the message of a session
* @return pointer to the session info stored in _openSessions, null if none found.
*/
virtual NetConfClientSessionInfo* findSessionInfoForMsg(cMessage *msg) override;
};
} // namespace SDN4CoRE
#endif
| 2,630
|
C++
|
.h
| 65
| 37.184615
| 92
| 0.748726
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,255
|
NetConfClientBase.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/client/base/NetConfClientBase.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFCLIENTBASE_H_
#define __SDN4CORE_NETCONFCLIENTBASE_H_
#include <omnetpp.h>
#include <sdn4core/netconf/datastructures/base/NetConfClientSessionInfo.h>
#include <vector>
#include "sdn4core/netconf/messages/NetConfMessage_m.h"
#include "sdn4core/netconf/messages/NetConfCtrlInfo_m.h"
#include "sdn4core/netconf/messages/NetConfOperation_m.h"
#include "sdn4core/netconf/messages/NetConfCapability_m.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Contains the basic implementation of a NetConf client.
* This module can be connected to any Transport protocol that should be of
* "Connection-Oriented Operation" and should provide "Authentication,
* Integrity, and Confidentiality" as specified in Network Configuration
* Protocol (NETCONF) RFC6241.
*
* All responses will be forwarded to the applicaitonOut gate with the
* same index as the arriving applicationIn gate
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfClientBase : public cSimpleModule
{
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
/**
* Forwards the message to the protocol specific transport layer.
* The NetConfCtrlInfo_Transport should be attached to the message.
* @param msg the message to forward
*/
virtual void sendToTransport(cMessage* msg) = 0;
/**
* Protocol specific implementation to open a new session.
* Checks if the session already exists, else opens a new one and adds the _nextSessionId
* Must insert the new session into the _openSessions list.
* @param msg the message to create a session for
*/
/**
* Protocol specific implementation to open a new session.
* Checks if the session already exists, else opens a new one.
* Must insert the new session into the _openSessions list.
* @param hello the NetConfHello to create a session for NetConfHello
* @return the session info for the new session.
*/
virtual NetConfClientSessionInfo* openNewSession(NetConfHello* hello) = 0;
/**
* Closes the protocol specific session and removes the session from openSessions list.
* @param sessionId the session to close
* @return true if the session was closed
*/
virtual bool closeSession(int sessionId) = 0;
/**
* Finds the session info for an incoming message.
* @param msg the message of a session
* @return pointer to the session info stored in _openSessions, null if none found.
*/
virtual NetConfClientSessionInfo* findSessionInfoForMsg(cMessage *msg) = 0;
/**
* Finds the session info for an existing session id.
* @param sessionId the id of the session to find
* @return pointer to the session info stored in _openSessions, null if none found.
*/
virtual NetConfClientSessionInfo* findSessionInfoForId(int sessionId);
/**
* Sends the Hello
* @param hello the incoming hello message
*/
virtual void sendHello(NetConfHello* hello);
/**
* Handles the hello message from the server.
* @param hello the incoming hello message
*/
virtual void handleHello(NetConfHello* hello);
/**
* Creates a NetConfCtrlInfo for the incoming message and sessionInfo.
* @param sessionInfo the session info for the message
* @param msg the incoming message
* @return a new NetConfCtrlInfo
*/
virtual NetConfCtrlInfo* createCtrlInfoFor(NetConfClientSessionInfo* sessionInfo, NetConfMessage* msg);
/**
* Network and Controller State
*/
std::vector<NetConfClientSessionInfo*> _openSessions;
/**
* Gate name for application outputs
*/
static const char APPLICATION_OUT_GATE_NAME []; // = "applicaitonOut";
/**
* Gate name for application inputs
*/
static const char APPLICATION_IN_GATE_NAME []; // = "applicationIn";
/**
* Gate name for transport inputs
*/
static const char TRANSPORT_IN_GATE_NAME []; //= "transportIn";
/**
* Gate name for transport outputs
*/
static const char TRANSPORT_OUT_GATE_NAME []; //= "transportOut";
};
} // namespace SDN4CoRE
#endif
| 4,949
|
C++
|
.h
| 122
| 36.352459
| 107
| 0.718802
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,256
|
TSN_OF_SwitchAgent.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/tsn/engine/TSN_OF_SwitchAgent.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Tobias Haugg, for HAW Hamburg
#ifndef SDN4CORE_SWITCH_TSN_ENGINE_TSN_OF_SWITCHAGENT_H_
#define SDN4CORE_SWITCH_TSN_ENGINE_TSN_OF_SWITCHAGENT_H_
#include <sdn4core/switch/base/engine/OF_SwitchAgent.h>
#include "core4inet/linklayer/ethernet/avb/SRPFrame_m.h"
namespace SDN4CoRE {
class TSN_OF_SwitchAgent: public OF_SwitchAgent {
protected:
virtual void handleMessage(cMessage *msg) override;
virtual void processControlPlanePacket(cMessage *msg) override;
/**
* Handels srp messages arriving from the controller and forward them to the local
* SRProtocol module.
* @param msg incoming srp message
*/
virtual void handleSRPFromController(cMessage* msg);
private:
/**
* Forward the response of the local SRProtocol module to the controller
* @param msg response of SRProtocol
*/
void sendSRPResponse(CoRE4INET::ListenerReady *msg);
};
}
#endif /* SDN4CORE_SWITCH_TSN_ENGINE_TSN_OF_SWITCHAGENT_H_ */
| 1,641
|
C++
|
.h
| 39
| 39.410256
| 86
| 0.760025
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,257
|
AVB_OF_RelayUnit.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/avb/engine/AVB_OF_RelayUnit.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __SDN4CORE_AVB_OF_RELAYUNIT_H_
#define __SDN4CORE_AVB_OF_RELAYUNIT_H_
//Omnet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/switch/base/engine/OF_RelayUnit.h>
//CoRE4INET
#include "core4inet/services/avb/SRP/SRPTable.h"
namespace SDN4CoRE{
/**
* The OF_RelayUnit is part of the switching engine of an OpenFlow switch.
* It handles the forwarding of incoming packets by matching them with the OpenFlowTable
* (@see~IOpenFlowFlowTable) entries. Additionally it may send packets to the OF_SwitchAgent
* for further handling.
* It adds the capability of handling the SRP protocol to the @see~OF_RelayUnit module.
*
* @author Timo Haeckel, Tobias Haugg, for HAW Hamburg
*/
class AVB_OF_RelayUnit : public OF_RelayUnit
{
public:
AVB_OF_RelayUnit();
~AVB_OF_RelayUnit();
virtual void finish() override;
/**
* Handles an SRP message coming from the srp protocol module and forwards it to the right modules.
* @param srp the message to handle
*/
virtual void handleSRPFromProtocol(omnetpp::cMessage* srp);
protected:
//omnetpp module funcitons
virtual void initialize(int stage) override;
virtual int numInitStages() const override { return inet::NUM_INIT_STAGES; }
/**
* Processes a data frame arriving on a dataPlane interface.
*/
virtual void processDataPlanePacket(omnetpp::cMessage* msg) override;
/**
* Checks whether the given message is an SRP message.
* @param msg the messag to check
* @return true if the message is an SRP message.
*/
virtual bool isSRPMessage(omnetpp::cMessage* msg);
/**
* Extracts the information from an incoming frame to be matched against the openflow table.
* @param frame the frame to create a match for
* @return the match for the frame
*/
virtual openflow::oxm_basic_match extractMatch(inet::EthernetIIFrame* frame) override;
protected:
/**
* Reference to the SRP Table module.
*/
CoRE4INET::SRPTable* _srpTable;
/**
* used initiate the forwarding of a srpFrame to the Controller using the AVB_OF_SwitchAgent
*/
simsignal_t forwardSRPtoConSig;
};
} /*end namespace SDN4CoRE*/
#endif /* __SDN4CORE_AVB_OF_RELAYUNIT_H_ */
| 2,946
|
C++
|
.h
| 77
| 34.909091
| 103
| 0.729692
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,258
|
AVB_OF_SwitchAgent.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/avb/engine/AVB_OF_SwitchAgent.h
|
#ifndef __SDN4CORE_AVB_OF_SWITCHAGENT_H_
#define __SDN4CORE_AVB_OF_SWITCHAGENT_H_
//Omneet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/switch/base/engine/OF_SwitchAgent.h>
#include <sdn4core/switch/avb/engine/AVB_OF_RelayUnit.h>
//CoRE4INET
#include "core4inet/services/avb/SRP/SRPTable.h"
namespace SDN4CoRE{
/**
* The AVB_OF_SwitchAgent is part of the switching engine of an OpenFlow switch.
* It is directly connected to the TCP module to communicate with the controller (@see~OF_Controller)
* using the open flow protocol. Additionally it communicates with the OF_RleayUnit and translates the
* commands from the controller into the necessary instructions to send to the RelayUnit.
* It adds the capability of handling the SRP protocol to the @see~OF_RelayUnit module.
*
* @author Timo Haeckel, Tobias Haugg for HAW Hamburg
*/
class AVB_OF_SwitchAgent : public OF_SwitchAgent
{
public:
AVB_OF_SwitchAgent();
~AVB_OF_SwitchAgent();
virtual void receiveSignal(cComponent *src, simsignal_t id, cObject *value, cObject *details) override;
protected:
//omnetpp module funcitons
virtual void initialize(int stage) override;
virtual int numInitStages() const override { return inet::NUM_INIT_STAGES; }
virtual void handleMessage(omnetpp::cMessage *msg) override;
/**
* Processes an OpenFlow packet arriving on controlPlane interface.
*/
virtual void processControlPlanePacket(omnetpp::cMessage* msg) override;
/**
* Handles an SRP message coming from the controller and forwards it to the right modules.
* @param srp the message to handle
*/
virtual void handleSRPFromController(omnetpp::cMessage* srp);
/**
* Forwards an SRP message to the OpenFlow controller.
* @param msg srp the message to forward
*/
virtual void forwardSRPtoController(omnetpp::cPacket* msg);
protected:
/**
* Reference to the SRP Table module.
*/
CoRE4INET::SRPTable* _srpTable;
/**
* used initiate the forwarding of a srpFrame to the Controller using the AVB_OF_SwitchAgent
*/
simsignal_t forwardSRPtoConSig;
};
} /*end namespace SDN4CoRE*/
#endif /* __SDN4CORE_AVB_OF_RELAYUNIT_H_ */
| 2,213
|
C++
|
.h
| 56
| 35.857143
| 107
| 0.745217
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,259
|
AVBEthernetInterfaceConnection.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/avb/port/AVBEthernetInterfaceConnection.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __OPENFLOW_AVBETHERNETINTERFACECONNECTIONGATEWAY_H_
#define __OPENFLOW_AVBETHERNETINTERFACECONNECTIONGATEWAY_H_
#include <omnetpp.h>
//CoRE4INET
#include "core4inet/applications/AS6802/CTApplicationBase.h"
namespace SDN4CoRE{
/**
* Gateway between Ports and Switching Application.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class AVBEthernetInterfaceConnection : public virtual CoRE4INET::CTApplicationBase
{
protected:
virtual void initialize();
virtual void handleMessage(omnetpp::cMessage *msg);
private:
/**
* Buffer for outgoing AVB traffic.
*/
omnetpp::cModule *_avbOutCTC = nullptr;
/**
* Buffer for outgoing BE traffic
*/
omnetpp::cModule *_beBuffer = nullptr;
/**
* The index of this port.
*/
int _portNo;
/**
* The number of ports on this switch
*/
int _portCount;
/**
* @brief Handles outgoing messages and forwards them to the correct output module.
* @param msg the message to forward.
*/
void handleOutMessage(omnetpp::cMessage* msg);
/**
* @brief Handles messages for the switching engine and forwards them to the upperLayer module.
* @param msg
*/
void handleSwitchMessage(omnetpp::cMessage* msg);
/**
* Checks if the incoming message is an SRP message.
* @param msg the message to check
* @return true if SRP message.
*/
bool isSRPMessage(omnetpp::cMessage* msg);
/**
* @brief handles SRP Messages and forwards them to the correct module.
* @param msg srp message to forward.
*/
void handleSRPMessage(omnetpp::cMessage* msg);
};
} /** end namespace SDN4CoRE **/
#endif /* __OPENFLOW_AVBETHERNETINTERFACECONNECTIONGATEWAY_H_ */
| 2,445
|
C++
|
.h
| 73
| 29.712329
| 99
| 0.714043
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,260
|
OF_AVBIncoming.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/avb/incoming/avb/OF_AVBIncoming.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef CORE4INET_OF_AVBIncoming_H_
#define CORE4INET_OF_AVBIncoming_H_
#include "omnetpp.h"
using namespace omnetpp;
//CoRE4INET
#include "core4inet/incoming/base/Incoming.h"
#include "core4inet/services/avb/SRP/SRPTable.h"
namespace SDN4CoRE {
//This disables the padding warning for this class! please recheck when adding new members!
#pragma GCC diagnostic ignored "-Wpadded"
/**
* @brief Class for the critical traffic conformance check of
* audio-video bridging traffic.
* Updated for usage in Openflow Switches.
*
* @sa Incoming
*
* @author Philipp Meyer, Timo Häckel
*/
class OF_AVBIncoming : public CoRE4INET::Incoming
{
private:
/**
* @brief Caches srpTable module
*/
CoRE4INET::SRPTable *srptable;
protected:
/**
* @brief Initialization of the module
*/
virtual void initialize() override;
/**
* @brief Forwards messages arriving on in-gate to out-gate.
*
* @param msg the incoming message.
*/
virtual void handleMessage(cMessage *msg) override;
public:
/**
* @brief Constructor.
*/
OF_AVBIncoming();
};
} /* namespace SDN4CoRE */
#endif /* CORE4INET_OF_AVBIncoming_H_ */
| 1,958
|
C++
|
.h
| 61
| 28.04918
| 91
| 0.699153
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,261
|
OF_RelayUnit.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/base/engine/OF_RelayUnit.h
|
#ifndef SDN4CORE_SWITCH_BASE_ENGINE_OF_RELAYUNIT_H_
#define SDN4CORE_SWITCH_BASE_ENGINE_OF_RELAYUNIT_H_
//Omnet
#include <omnetpp.h>
//STD
#include <vector>
//inet
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
#include "inet/common/InitStages.h"
//openflow
#include "openflow/openflow/switch/Buffer.h"
#include "openflow/messages/Open_Flow_Message_m.h"
#include "openflow/openflow/switch/flowtable/OF_FlowTable.h"
namespace SDN4CoRE{
/**
* The OF_RelayUnit is part of the switching engine of an OpenFlow switch.
* It handles the forwarding of incoming packets by matching them with the OpenFlowTable
* (@see~IOpenFlowFlowTable) entries. Additionally it may send packets to the OF_SwitchAgent
* for further handling.
*
* @author Timo Haeckel, Tobias Haugg, for HAW Hamburg
*/
class OF_RelayUnit: public cSimpleModule
{
public:
OF_RelayUnit();
~OF_RelayUnit();
virtual void finish() override;
void disablePorts(std::vector<int> ports);
protected:
/**
* Counters for data plane packet arrival events
*/
long dataPlanePacket;
/**
* Counters for flow table match events
*/
long flowTableHit;
/**
* Counters for flow table miss events
*/
long flowTableMiss;
/**
* used initiate the forwarding of a frame to the Controller using the OF_SwitchAgent
*/
simsignal_t forwardToConSign;
/**
* Signals the OF_SwitchAgent that no matching entry was found for an incoming frame
*/
simsignal_t tableMissSign;
//stats
simsignal_t dpPingPacketHash;
simsignal_t cpPingPacketHash;
/**
* The OpenFlow Flow Table containing match entries
*/
std::vector<openflow::OF_FlowTable*> _flowTables;
/**
* List of all connected ports
*/
std::vector<openflow::ofp_port> portVector;
protected:
virtual void initialize(int stage) override;
virtual int numInitStages() const override { return inet::NUM_INIT_STAGES; }
virtual void handleMessage(cMessage *msg) override;
/**
* Processes a data frame arriving on a dataPlane interface.
*/
virtual void processDataPlanePacket(omnetpp::cMessage* msg);
/**
* Processes an EthernetIIFrame by looking up a match in the table and forwarding it.
* @param frame the frame to process
*/
virtual void processFrame(inet::EthernetIIFrame *frame);
/**
* Extracts the information from an incoming frame to be matched against the openflow table.
* @param frame the frame to create a match for
* @return the match for the frame
*/
virtual openflow::oxm_basic_match extractMatch(inet::EthernetIIFrame* frame);
public:
/**
* Executes a PacketOut action(s) by sending the frame to the outports
* @param action the openflow output action
* @param frame the frame to forward
* @param inport the arrival port, to make sure to not flood it back to the in port.
*/
virtual void executePacketOutAction(openflow::ofp_action_output *action, inet::EthernetIIFrame *frame, uint32_t inport);
};
}
#endif /* SDN4CORE_SWITCH_BASE_ENGINEREWORK_OF_DATAPLANE_H_ */
| 3,166
|
C++
|
.h
| 91
| 30.637363
| 124
| 0.715965
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,262
|
OF_SwitchAgent.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/base/engine/OF_SwitchAgent.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef SDN4CORE_SWITCH_BASE_ENGINE_OF_SWITCHAGENT_H_
#define SDN4CORE_SWITCH_BASE_ENGINE_OF_SWITCHAGENT_H_
//Omnet
#include <omnetpp.h>
//STD
#include <vector>
//inet
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
#include "inet/common/InitStages.h"
//openflow
#include "openflow/openflow/switch/Buffer.h"
#include "openflow/messages/Open_Flow_Message_m.h"
#include "openflow/openflow/switch/flowtable/OF_FlowTable.h"
//relayUnit
#include <sdn4core/switch/base/engine/OF_RelayUnit.h>
namespace SDN4CoRE{
/**
* The OF_SwitchAgent is part of the switching engine of an OpenFlow switch.
* It is directly connected to the TCP module to communicate with the controller (@see~OF_Controller)
* using the open flow protocol. Additionally it communicates with the OF_RleayUnit and translates the
* commands from the controller into the necessary instructions to send to the RelayUnit.
*
* @author Timo Haeckel, Tobias Haugg, for HAW Hamburg
*/
class OF_SwitchAgent: public cSimpleModule, public cListener
{
public:
OF_SwitchAgent();
~OF_SwitchAgent();
virtual void finish() override;
virtual void receiveSignal(cComponent *src, simsignal_t id, cObject *value, cObject *details) override;
protected:
/**
* Indicates if the relay unit has a packet in the queue
*/
bool ofBusy;
/**
* Cached omnetpp parameter for timeout polling
*/
double flowTimeoutPollInterval;
/**
* Cached omnetpp parameter if the relay unit should forward the complete packet to the controller
*/
bool sendCompletePacket;
/**
* Cached omnetpp parameter if this switch has only a single openflow engine per switch.
* this will allow the switch to enter a busy status.
*/
bool parallelProcessing;
/**
* Cached omnetpp parameter for the relay units service time in seconds
*/
double ofServiceTime;
/**
* Counters for control plane packet arrival events
*/
long controlPlanePacket;
/**
* used initiate the forwarding of a frame to the Controller using the OF_SwitchAgent
*/
simsignal_t forwardToConSign;
/**
* Signals the OF_SwitchAgent that no matching entry was found for an incoming frame
*/
simsignal_t tableMissSign;
//stats
simsignal_t bufferSize;
simsignal_t waitingTime;
simsignal_t queueSize;
/**
* The OpenFlow Flow Table containing match entries
*/
std::vector<openflow::OF_FlowTable*> _flowTables;
/**
* Message List for incoming packets to be handled
*/
std::list<cMessage *> msgList;
/**
* Buffer for packets forwarded to the controller if sendCompletePacket==false
*/
openflow::Buffer buffer;
/**
* The TCP connection to the OpenFlow controller
*/
inet::TCPSocket socket;
/**
* Indicates if the hello handshake has been finished with the SDN Controller.
*/
bool hasController = false;
/**
* Reference to SwitchAgent and forward declaration to resolve circular dependencies
*/
OF_RelayUnit* relayUnit;
protected:
//omnetpp module funcitons
virtual void initialize(int stage) override;
virtual int numInitStages() const override { return inet::NUM_INIT_STAGES; }
virtual void handleMessage(cMessage *msg) override;
virtual void handleParameterChange(const char* parname) override;
/**
* Connects to the OpenFlow controller at the given address by sending the ofp hello message.
* @param connectToAddress the address of the controller
*/
virtual void connect(const char *connectToAddress);
/**
* Processes an OpenFlow packet arriving on controlPlane interface.
*/
virtual void processControlPlanePacket(omnetpp::cMessage* msg);
/**
* Handle the OpenFlow feature request message and creates a reply.
* @param of_msg the OpenFlow message
*/
virtual void handleFeaturesRequestMessage(openflow::Open_Flow_Message *of_msg);
/**
* Handle the OpenFlow flow mod message and initiate table modifications.
* @param of_msg the OpenFlow message
*/
virtual void handleFlowModMessage(openflow::Open_Flow_Message *of_msg);
/**
* Handle the OpenFlow packet out message by outputting the frame to the specified ports.
* @param of_msg the OpenFlow message
*/
virtual void handlePacketOutMessage(openflow::Open_Flow_Message *of_msg);
/**
* Similate the service time for a given message by scheduling a self message for the next processing.
* @param msg the message to schedule
*/
virtual void simulateServiceTime(omnetpp::cMessage* msg);
/**
* Checks if there are messages left in the msgList and schedules the next one.
*/
virtual void scheduleNextServiceTime();
/**
* Schedules a message as a servicetime message with ofServiceTime delay.
*/
virtual void scheduleForServiceTime(omnetpp::cMessage* msg);
/**
* returns true if a controller is connected
*/
virtual bool isConnectedToController(void);
public:
/**
* Handles a packet that has not matched any rule in the OpenFlow tables.
* @param frame the frame to process
*/
virtual void handleMissMatchedPacket(inet::EthernetIIFrame *frame);
/*
* Forwards a frame to the controller
* @param frame the frame that should be forwarded
*/
void forwardFrameToController(EthernetIIFrame* frame);
};
} /*end namespace SDN4CoRE*/
#endif /* __SDN4CORE_OF_RELAYUNIT_H_ */
| 6,246
|
C++
|
.h
| 170
| 32.435294
| 107
| 0.720884
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,263
|
IPTunnelingControllerApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/tunnel/IPTunnelingControllerApp.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_IPTUNNELINGCONTROLLERAPP_H_
#define __SDN4CORE_IPTUNNELINGCONTROLLERAPP_H_
#include <omnetpp.h>
#include "sdn4core/controllerApps/base/PacketProcessorBase.h"
#include "sdn4core/controllerState/devices/DeviceTable.h"
#include "sdn4core/controllerState/hosts/HostTable.h"
#include "sdn4core/controllerState/topology/TopologyManagement.h"
//STD
#include <vector>
//inet
#include "inet/networklayer/ipv4/IPv4.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Implements tunneling of the IPv4 protocol through an OpenFlow channel based
* on the inet::IPv4 implementation.
* Sadly, extension is not possible because of multiple cModule base inheritence.
*/
class IPTunnelingControllerApp: public PacketProcessorBase {
public:
protected:
virtual void initialize() override;
virtual void handleParameterChange(const char* parname) override;
virtual void refreshDisplay() const override;
void receiveSignal(cComponent *src, simsignal_t id, cObject *obj,
cObject *details) override;
virtual void handleMessage(cMessage *msg) override;
/**
* Interface function for the main processing engine of packet_in messages.
*
* This default implementation does nothing
*
* @param packet_in_msg The packet in message
*/
virtual void processPacketIn(openflow::OFP_Packet_In *packet_in_msg) override;
protected:
/**
* Check if a given address is in localIps.
* @param addr The address to compare
* @return True if it is on of localIps, else false
*/
virtual bool isLocalIp(const IPv4Address& addr);
virtual IPv4Address findBestFittingSrcIp(const IPv4Address& dest);
/**
* Processing of IPv4 datagrams. Called when a datagram reaches the front
* of the queue.
*/
virtual void endService(cPacket *packet);
/**
* Handle IPv4Datagram messages arriving from lower layer.
* Decrements TTL, then invokes routePacket().
*/
virtual void handleIncomingDatagram(IPv4Datagram *datagram);
void handleIncomingARPPacket(openflow::OFP_Packet_In* packet_in_msg);
/**
* Handle messages (typically packets to be send in IPv4) from transport or ICMP.
* Invokes encapsulate(), then routePacket().
*/
virtual void handlePacketFromHL(cPacket *packet);
/**
* Routes and sends datagram received from higher layers.
* Invokes datagramLocalOutHook(), then routePacket().
*/
virtual void datagramLocalOut(IPv4Datagram *datagram);
/**
* Performs unicast routing. Based on the routing decision, it sends the
* datagram through the outgoing interface.
*/
virtual void routeUnicastPacket(IPv4Datagram *datagram);
/**
* Performs multicast routing. Based on the routing decision, it sends the
* datagram through the outgoing interface(s).
*/
virtual void routeMulticastPacket(IPv4Datagram *datagram);
/**
* Broadcasts the datagram on the specified interface.
* When destIE is nullptr, the datagram is broadcasted on each interface.
*/
virtual void routeLocalBroadcastPacket(IPv4Datagram *datagram);
/**
* Perform reassembly of fragmented datagrams, then send them up to the
* higher layers using sendToHL().
*/
virtual void reassembleAndDeliver(IPv4Datagram *datagram);
/**
* Decapsulate and return encapsulated packet after attaching IPv4ControlInfo.
*/
virtual cPacket *decapsulate(IPv4Datagram *datagram);
/**
* Fragment packet if needed, then send it to the selected interface using
* sendDatagramToOutput().
*/
virtual void fragmentAndSend(IPv4Datagram *datagram, HostTable::HostEntry* host);
/**
* Send datagram on the given interface.
*/
virtual void sendDatagramToHost(IPv4Datagram *datagram, HostTable::HostEntry* host);
/**
* Encapsulate packet coming from higher layers into IPv4Datagram, using
* the given control info. Override if you subclassed controlInfo and/or
* want to add options etc to the datagram.
*/
virtual IPv4Datagram *encapsulate(cPacket *transportPacket, IPv4ControlInfo *controlInfo);
/**
* Creates a blank IPv4 datagram. Override when subclassing IPv4Datagram is needed
*/
virtual IPv4Datagram *createIPv4Datagram(const char *name);
private:
void dropPacketFromUpper(cMessage* packet, std::string reason = "");
void dropPacketFromLower(cMessage* packet, std::string reason = "");
inet::EthernetIIFrame* etherEncap(cPacket* packet, HostTable::HostEntry* host,
int etherType = ETHERTYPE_IPv4);
protected:
/**
* A management module handling all MAC operations.
*/
HostTable* hostTable;
/**
* A management module handling all MAC operations.
*/
DeviceTable* deviceTable;
/**
* A management module handling all MAC operations.
*/
TopologyManagement* topology;
// working vars
bool isUp = false; // TODO set is up if received controller booted signal!
long curFragmentId = -1; // counter, used to assign unique fragmentIds to datagrams
IPv4FragBuf fragbuf; // fragmentation reassembly buffer
simtime_t lastCheckTime; // when fragbuf was last checked for state fragments
ProtocolMapping mapping; // where to send packets after decapsulation
std::vector<std::string> localIps;
inet::MACAddress controllerSrcMac;
// config
int defaultTimeToLive = -1;
int defaultMCTimeToLive = -1;
simtime_t fragmentTimeoutTime;
bool forceBroadcast = false;
bool receiveMulticast = false;
bool receiveBroadcast = false;
bool sendBroadcast = false;
bool sendMulticast = false;
int mtu = 0; // mtu == 0 means infinite default Ethernet 1500
// statistics
int numMulticast = 0;
int numLocalDeliver = 0;
int numDropped = 0; // forwarding off, no outgoing interface, too large but "don't fragment" is set, TTL exceeded, etc
int numUnroutable = 0;
int numForwarded = 0;
};
} /*end namespace SDN4CoRE*/
#endif
| 6,773
|
C++
|
.h
| 166
| 36.108434
| 125
| 0.729528
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,264
|
SomeipSDControllerApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/someipSD/SomeipSDControllerApp.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, Jan Schmitt-Solbrig, for HAW Hamburg
//
#ifndef __SDN4CORE_SOMEIPSDCONTROLLERAPP_H_
#define __SDN4CORE_SOMEIPSDCONTROLLERAPP_H_
#define BROADCASTADDRESS "255.255.255.255"
#include <omnetpp.h>
#include "sdn4core/utility/layeredInformation/LayeredInformation.h"
#include "sdn4core/controllerApps/base/PacketProcessorBase.h"
#include "soa4core/messages/someip/SomeIpSDHeader.h"
#include "sdn4core/controllerState/devices/DeviceTable.h"
#include "sdn4core/controllerState/hosts/HostTable.h"
#include "sdn4core/controllerState/topology/TopologyManagement.h"
//AUTO-GENERATED MESSAGES
#include "soa4core/messages/someip/SomeIpSDEntry_m.h"
#include "soa4core/messages/someip/SomeIpSDOption_m.h"
//CoRE4INET
#include "core4inet/linklayer/ethernet/base/EtherFrameWithQTag_m.h"
//SOA4CoRE
#include "soa4core/serviceidentifier/ServiceIdentifier.h"
// STD
#include <map>
#include <list>
using namespace omnetpp;
namespace SDN4CoRE {
/**
// SomeipSDControllerApp is an SDN controller application that handles
// the service oriented architectures. The implementation controls the SOME/IP protocol
// which is implemented in the SOA4CoRE framework.
//
// @note This app is still in an early implementation stage and does not support
// the full SOME/IP feature set!
// Many features are missing and might not be implemented efficiently.
//
// @author Jan Schmitt-Solbrig, Timo Haeckel, for HAW Hamburg
*/
class SomeipSDControllerApp: public PacketProcessorBase
{
public:
/**
* struct to save a single offer-message with the corresponding options
*/
struct ServiceInstance {
SOA4CoRE::ServiceEntry* entry = nullptr;
LayeredInformation* layeredInformation = nullptr;
std::list<SOA4CoRE::SomeIpSDOption*> optionList;
void clear() {
if (entry) delete entry;
entry = nullptr;
if (layeredInformation) delete layeredInformation;
layeredInformation = nullptr;
for (auto elem: optionList) {
if (elem) delete elem;
elem = nullptr;
}
optionList.clear();
}
};
/**
* InstanceMap includes all available instances sorted by InstanceIDs as key
* used to insert the instances into the ServiceInstanceMap
*/
typedef std::map<int, ServiceInstance> InstanceMap;
/**
* Map includes all available services sorted by ServiceIDs as key
*/
typedef std::map<int, InstanceMap> ServiceInstanceMap;
struct FindRequest {
SOA4CoRE::SomeIpSDHeader* requestHeader;
LayeredInformation* layeredInformation;
SOA4CoRE::ServiceEntry* entry;
std::list<SOA4CoRE::SomeIpSDOption*> optionList;
void clear() {
if (requestHeader) delete requestHeader;
requestHeader = nullptr;
if (layeredInformation) delete layeredInformation;
layeredInformation = nullptr;
if (entry) delete entry;
entry= nullptr;
for (auto elem: optionList) {
if (elem) delete elem;
elem = nullptr;
}
optionList.clear();
}
};
/**
* RequestMap:Contains all Find-Messages that are not answered
*/
typedef std::map<int, std::list<FindRequest>> RequestMap;
struct Subscription {
SOA4CoRE::ServiceIdentifier service;
// from provider / publisher
LayeredInformation providerInformation;
SOA4CoRE::IPv4EndpointOption providerEndpoint;
// to consumer / subscriber
LayeredInformation consumerInformation;
SOA4CoRE::IPv4EndpointOption consumerEndpoint;
// control information
bool active = false;
bool waitingForAck = false;
bool isConsumer(LayeredInformation otherInformation, SOA4CoRE::IPv4EndpointOption otherEndpoint) {
return otherInformation.eth_src == consumerInformation.eth_src
&& otherInformation.ip_src == consumerInformation.ip_src
&& otherInformation.transport_src == consumerInformation.transport_src
&& otherEndpoint.getIpv4Address() == consumerEndpoint.getIpv4Address()
&& otherEndpoint.getPort() == consumerEndpoint.getPort();
}
bool isProvider(LayeredInformation otherInformation, SOA4CoRE::IPv4EndpointOption otherEndpoint) {
return otherInformation.eth_src == providerInformation.eth_src
&& otherInformation.ip_src == providerInformation.ip_src
&& otherInformation.transport_src == providerInformation.transport_src
&& otherEndpoint.getIpv4Address() == providerEndpoint.getIpv4Address()
&& otherEndpoint.getPort() == providerEndpoint.getPort();
}
bool isMcast() {
return consumerEndpoint.getType() == SOA4CoRE::SomeIpSDOptionType::IPV4MULTICAST;
}
IPv4Address getDstHostIp() {
if(isMcast()) {
return consumerInformation.ip_src.toIPv4();
}
return consumerEndpoint.getIpv4Address();
}
};
typedef std::list<Subscription> ServiceInstanceSubscriptionList;
typedef std::map<int, ServiceInstanceSubscriptionList> IntanceSubscriptionMap;
typedef std::map<int, IntanceSubscriptionMap> SubscriptionMap;
/**
* Cleans the serviceTable for finishing the simulation
*/
~SomeipSDControllerApp(){
for (auto idIter : serviceTable){
for (auto instanceIter : idIter.second) {
instanceIter.second.clear();
}
idIter.second.clear();
}
serviceTable.clear();
for (auto idIter : requestTable){
for (auto request : idIter.second) {
request.clear();
}
idIter.second.clear();
}
requestTable.clear();
};
protected:
ServiceInstanceMap serviceTable;
RequestMap requestTable;
SubscriptionMap subscriptionTable;
LayeredInformation myLayeredInformation;
uint16_t controllerRequestID;
virtual void initialize() override;
/**
* Interface function for the main processing engine of packet_in messages.
*
* This default implementation does nothing
*
* @param packet_in_msg The packet in message
*/
virtual void processPacketIn(openflow::OFP_Packet_In *packet_in_msg) override;
void processSomeIpSDHeader(SOA4CoRE::SomeIpSDHeader* someIpSDHeader);
void processFindEntry(SOA4CoRE::SomeIpSDEntry* findInquiry, SOA4CoRE::SomeIpSDHeader* someIpSDHeader);
void processOfferEntry(SOA4CoRE::SomeIpSDEntry* offerEntry, SOA4CoRE::SomeIpSDHeader* someIpSDHeader);
void processSubscribeEventGroupEntry(SOA4CoRE::SomeIpSDEntry* entry, SOA4CoRE::SomeIpSDHeader* someIpSDHeader);
void processSubscribeEventGroupAckEntry(SOA4CoRE::SomeIpSDEntry* entry, SOA4CoRE::SomeIpSDHeader* someIpSDHeader);
SOA4CoRE::SomeIpSDHeader* buildFind(SOA4CoRE::SomeIpSDHeader* findSource, SOA4CoRE::SomeIpSDEntry* findEntry);
SOA4CoRE::SomeIpSDHeader* buildOffer(SOA4CoRE::SomeIpSDHeader* findSource, SOA4CoRE::SomeIpSDEntry* findEntry, std::list<ServiceInstance>& foundInstances);
SOA4CoRE::SomeIpSDHeader* buildSubscribeEventGroup(SOA4CoRE::SomeIpSDHeader* source, SOA4CoRE::SomeIpSDEntry* entry);
SOA4CoRE::SomeIpSDHeader* buildSubscribeEventGroupAck(SOA4CoRE::SomeIpSDHeader* source, SOA4CoRE::SomeIpSDEntry* entry);
void sendFind(SOA4CoRE::SomeIpSDHeader*, SOA4CoRE::SomeIpSDHeader* findSource);
void sendOffer(SOA4CoRE::SomeIpSDHeader* offer, SOA4CoRE::SomeIpSDHeader* findSource, LayeredInformation* infoFind, LayeredInformation* infoOffer);
void installFlowForSubscription(Subscription& sub);
std::list<SOA4CoRE::SomeIpSDOption*> getEntryOptions(SOA4CoRE::SomeIpSDEntry* xEntry, SOA4CoRE::SomeIpSDHeader* header);
void updateServiceTable(ServiceInstance& newInfo);
/**
* looks for the service requested in the controllers list of known offers
* @param requestedServiceId the service id to look for
* @param requestedInstanceId the instance id to look for (can be 0xFFFF for any)
* @return List of requested instance entries
* containing zero elements if no service was found
* containing one element if a specific instance was requested
* containing all known instances if no specific instanceId was requested
*/
std::list<ServiceInstance> lookUpServiceInMap(uint16_t requestedServiceId, uint16_t requestedInstanceId);
private:
inet::EthernetIIFrame * encapSDHeader(SOA4CoRE::SomeIpSDHeader* header,
inet::MACAddress eth_src, inet::MACAddress eth_dst,
inet::L3Address ip_src, inet::L3Address ip_dst,
int udp_src, int udp_dst);
inet::EthernetIIFrame * encapSDHeader(SOA4CoRE::SomeIpSDHeader* header,
LayeredInformation* bedirectionInfo);
inet::EthernetIIFrame * encapSDHeader(SOA4CoRE::SomeIpSDHeader* header,
LayeredInformation* src, LayeredInformation* dst);
protected:
/**
* A management module handling all MAC operations.
*/
HostTable* hostTable;
/**
* A management module handling all MAC operations.
*/
DeviceTable* deviceTable;
/**
* A management module handling all MAC operations.
*/
TopologyManagement* topology;
bool forwardOfferMulticast;
IPv4Address someipMcastAddress;
};
std::ostream& operator<<(std::ostream& os, const SomeipSDControllerApp::ServiceInstance& instance)
{
os << "offer{";
if(instance.layeredInformation) {
os << " source=" << instance.layeredInformation->ip_src.str();
}
os << " endpoints{ ";
for (auto iter = instance.optionList.begin(); iter != instance.optionList.end(); ++iter) {
if(SOA4CoRE::IPv4EndpointOption* endpoint = dynamic_cast<SOA4CoRE::IPv4EndpointOption*>(*iter)) {
os << "{";
os << " IP=" << endpoint->getIpv4Address().str();
os << ", port=" << endpoint->getPort();
os << ", protocol=" << (uint32) endpoint->getL4Protocol();
os << " } ";
}
}
os << "} }";
return os;
}
std::ostream& operator<<(std::ostream& os, const SomeipSDControllerApp::FindRequest& request)
{
os << "find{";
os << " source=" << request.layeredInformation->ip_src.str();
os << " service=" << request.entry->getServiceID() << " instance=" << request.entry->getInstanceID();
os << " }";
return os;
}
std::ostream& operator<<(std::ostream& os, const SomeipSDControllerApp::Subscription& sub)
{
os << "provider {";
os << " IP=" << sub.providerEndpoint.getIpv4Address().str();
os << ", port=" << sub.providerEndpoint.getPort();
os << ", protocol=" << (uint32) sub.providerEndpoint.getL4Protocol();
os << "}";
os << ", consumer {";
os << " IP=" << sub.consumerEndpoint.getIpv4Address().str();
os << ", port=" << sub.consumerEndpoint.getPort();
os << ", protocol=" << (uint32) sub.consumerEndpoint.getL4Protocol();
os << "}";
os << ", active=" << sub.active;
os << ", waitingForAck=" << sub.waitingForAck;
return os;
}
} /*end namespace SDN4CoRE*/
#endif
| 12,320
|
C++
|
.h
| 269
| 37.810409
| 160
| 0.676655
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,265
|
StreamReservationControllerApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/srp/StreamReservationControllerApp.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, Tobias Haugg, for HAW Hamburg
//
#ifndef __SDN4CORE_StreamReservationControllerApp_H_
#define __SDN4CORE_StreamReservationControllerApp_H_
#include "sdn4core/controllerApps/base/LearningControllerApp.h"
#include "sdn4core/controllerState/srp/SRPTableManagement.h"
//STD
#include <vector>
using namespace omnetpp;
namespace SDN4CoRE{
/**
* StreamReservationControllerApp is an SDN controller application that handles
* stream reservation via the SRProtocol for AVB or TSN real time traffic.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class StreamReservationControllerApp : public PacketProcessorBase {
public:
protected:
virtual void initialize() override;
void receiveSignal(cComponent *src, simsignal_t id, cObject *obj, cObject *details) override;
/**
* Forward a talkerAdvertise to the network after a successful reservation
* @param packetIn SRPFrame with TalkerAdvertise
*/
void forwardTalkerAdvertise(openflow::OFP_Packet_In* packetIn);
/**
* Forward a listenerReady to the talker after a successful reservation
* @param packetIn SRPFrame with ListenerReady
*/
void forwardListenerReady(openflow::OFP_Packet_In* packetIn);
/**
* Main processing engine of packet_in messages.
*
* Checks whether packet in is an srp or avb frame and handles them,
* else the learning controller can handle it.
*
* @param packetIn The packet in message
*/
virtual void processPacketIn(openflow::OFP_Packet_In *packetIn) override;
/**
* Implements how to process SRP packets.
* @param packetIn Packet with the SRP message
*/
void handleSRPFromDataplane(openflow::OFP_Packet_In *packetIn);
/**
* Creates and sends an SRPFlowModification Message implementing a flow rule in the switch to forward AVB streams.
* @param mod_com The modification command of the FlowModMessage (e.g. create, delete, modify,...).
* @param match The match to be implemented in the switch.
* @param outports The output ports.
* @param socket The socket belonging to the switch connection.
* @param idleTimeOut The Idle TimeOut, default will be no timeout.
* @param hardTimeOut The Hard TimeOut, default will be no timeout.
*/
virtual void sendSRPFlowModMessage(openflow::ofp_flow_mod_command mod_com, const openflow::oxm_basic_match &match, std::vector<int> outports, inet::TCPSocket * socket, int idleTimeOut , int hardTimeOut);
/**
* Forwards an SRP Packet to the switch to be processed.
* @param packetIn the packet in from the switch
*/
virtual void updateSwitchSRPTable(openflow::OFP_Packet_In *packetIn);
/**
* Loads an offline Configuration for the controller app regarding a connected switch
* containing MAC and SRP Table.
* @param info The switch to load the offline config for.
* @return true if a config was loaded.
*/
virtual bool loadOfflineConfigFromXML(openflow::Switch_Info* info) override;
/**
* Interface function for processing new switch connections.
*
* calls loadOfflineConfigFromXML() for
* the switch and installs SRP rules on switch.
*
* @param info the new switch connected
*/
virtual void processSwitchConnection(openflow::Switch_Info* info) override;
/**
* installs the necessary rules for forwarding srp to the controller
*
* @param info the new switch connected
*/
virtual void installSRPRule(openflow::Switch_Info* info);
/**
* Exports the current state of the MAC and SRP table and creates an XML formatted string.
* @return The current state as an XML formatted string
*/
virtual std::string stateToXML () override;
/**
* A management module handling all SRP operations.
*/
SRPTableManagement* _srpManager;
private:
/**
* Path to the ned module of the SRPTableManagement.
*/
static const char SRPTABLEMANAGERMODULEPATH [];
};
} /*end namespace SDN4CoRE*/
#endif /* __SDN4CORE_StreamReservationControllerApp_H_ */
| 4,802
|
C++
|
.h
| 113
| 38.097345
| 207
| 0.72552
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,266
|
TSNLearningControllerApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/tsn/TSNLearningControllerApp.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Mohammad Fazel Soltani, for HAW Hamburg
//
#ifndef __SDN4CORE_TSNLEARNINGCONTROLLERAPP_H_
#define __SDN4CORE_TSNLEARNINGCONTROLLERAPP_H_
#include <omnetpp.h>
#include "sdn4core/controllerApps/avb/AVBLearningControllerApp.h"
namespace SDN4CoRE{
/**
* TSNLearningControllerApp is an SDN controller application that handles
* tsn real time traffic as well as best effort MAC switching.
*
* @author Mohammad Fazel Soltani, for HAW Hamburg
*/
class TSNLearningControllerApp : public virtual AVBLearningControllerApp
{
protected:
/**
* @brief Indicates a parameter has changed.
*
* @param parname Name of the changed parameter or nullptr if multiple parameter changed.
*/
virtual void handleParameterChange(const char* parname) override;
/**
* Creates a match from an packet in message, setting as many match fields as possible.
* @param packetIn The packet in message to create a match for.
* @return The match created.
*/
virtual openflow::oxm_basic_match createMatchFromPacketIn(openflow::OFP_Packet_In* packetIn) override;
/**
* Implements the main switching engine for best effort packets.
* @param packet_in_msg Packet in the be switched.
*/
virtual void processPacketIn(openflow::OFP_Packet_In *packet_in_msg) override;
/**
* priorities that should not be dynamically forwarded, e.g., if they are scheduled
*/
std::vector<int> _staticPriorities;
};
} /*end namespace SDN4CoRE*/
#endif
| 2,188
|
C++
|
.h
| 54
| 37.388889
| 106
| 0.746002
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,267
|
AVBSecurityControllerApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/avb/AVBSecurityControllerApp.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef OPENFLOW_CONTROLLERAPPS_AVB_AVBSECURITYCONTROLLERAPP_H_
#define OPENFLOW_CONTROLLERAPPS_AVB_AVBSECURITYCONTROLLERAPP_H_
#include <sdn4core/controllerApps/avb/AVBLearningControllerApp.h>
#include <sdn4core/utility/visual/ColorChangingNode.h>
//openflow
#include <openflow/openflow/protocol/OpenFlow.h>
namespace SDN4CoRE {
#define NADS_PORT_NONE -1 //needs to be -1 as it is compared >= for valid ports
/**
* Security state of the Network
*/
typedef enum SecurityState {
NONE,
OK,
WARNING,
DANGER,
}SecurityState_t;
/**
*The AVBSecurityControllerApp extends the RTEthernetControllerApp and adds security functionality.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class AVBSecurityControllerApp: public AVBLearningControllerApp {
public:
AVBSecurityControllerApp();
virtual ~AVBSecurityControllerApp();
SecurityState_t getState() const {
return _state;
}
void setState(SecurityState_t state = NONE) {
_state = state;
_stateUpdated = true;
}
virtual void finish() override;
protected:
//omnetpp interface methods.
virtual void handleMessage(cMessage* msg) override;
void receiveSignal(cComponent *src, simsignal_t id, cObject *obj, cObject *details) override;
virtual void initialize() override;
virtual void refreshDisplay() const override;
/**
* Creates a OpenFlow match using the data of the given OpenFlow packet in message.
* @param packetIn the OpenFlow packet in message to extract the data from
* @return the OpenFlow match
*/
virtual openflow::oxm_basic_match createMatchFromPacketIn(openflow::OFP_Packet_In* packetIn) override;
/**
*
* Sends a Flow Modification message with a single outport to the switch connected to the TCP socket using the parameter information.
* @param mod_com the OpenFlow flow modification command one of @see ofp_flow_mod_command
* @param match the OpenFlow match
* @param outport the output port
* @param socket the socket of the switch to send the message to
* @param idleTimeOut the idle timeout of the flow rule
* @param hardTimeOut the hard timeout of the flow rule
*/
virtual void sendFlowModMessage(openflow::ofp_flow_mod_command mod_com, const openflow::oxm_basic_match &match, uint32_t outport, inet::TCPSocket * socket, int idleTimeOut, int hardTimeOut) override;
/**
* Sends a Flow Modification message with multiple outports to the switch connected to the TCP socket using the parameter information.
* @param mod_com the OpenFlow flow modification command one of @see ofp_flow_mod_command
* @param match the OpenFlow match
* @param outports the output ports
* @param socket the socket of the switch to send the message to
* @param idleTimeOut the idle timeout of the flow rule
* @param hardTimeOut the hard timeout of the flow rule
*/
virtual void sendSRPFlowModMessage(openflow::ofp_flow_mod_command mod_com, const openflow::oxm_basic_match &match, std::vector<int> outports, inet::TCPSocket * socket, int idleTimeOut , int hardTimeOut) override;
/**
* Creates a OpenFlow packet out message using the data of the given OpenFlow packet in message.
* It will be send out of the given outport of the switch.
* @param packet_in_msg the OpenFlow packet in message to extract the data from
* @param outport the outport at the switch
* @return the OpenFlow Packet out message.
*/
virtual openflow::OFP_Packet_Out * createPacketOutFromPacketIn(openflow::OFP_Packet_In *packet_in_msg, uint32_t outport) override;
/**
* implements the mirroring rule in a new switch and allows to insert flows on connection.
* @param msg Incoming switch features reply
*/
virtual void handleNewSwitch(openflow::Open_Flow_Message* msg);
/**
* Handle the message from a Connected NADS. And apply security counter measures.
* @param msg
*/
virtual void handleNADSMessage(openflow::OFP_Packet_In* msg);
/**
* @brief Indicates a parameter has changed.
*
* @param parname Name of the changed parameter or nullptr if multiple parameter changed.
*/
virtual void handleParameterChange(const char* parname) override;
private:
/**
* Checks if the Vector contains the NADS port. If not the NADS port is added.
* @return true if the vector was altered.
*/
bool checkOrAddNADSPort(std::vector<int>* portlist);
/**
* Checks if the Frame encapsulated in the packetIn is white listed with a flow.
*/
bool isWhitelisted(openflow::OFP_Packet_In* packetIn);
void scheduleSelfMessage();
/**
* Security status of the Network
*/
SecurityState_t _state = NONE;
/**
* True if the state was updated, will result in display refresh.
*/
mutable bool _stateUpdated = false;
/**
* Caches controller MAC Address parameter
*/
inet::MACAddress _controllerMAC;
/**
* Caches the NADS port.
*/
int _NADSPort = NADS_PORT_NONE;
/**
* Holds a reference to the security traffic light, displaying the nework state.
*/
ColorChangingNode* _trafficLight;
/**
* Caches the allowNewFlows parameter
*/
bool _allowNewFlows = true;
/**
* Caches the allowNewFlows parameter
*/
bool _allowARP = true;
/**
* Caches the allowNewFlows parameter
*/
bool _allowSRP = true;
int _anomalyCount = 0;
simtime_t _lastAnomaly = 0;
double _anomalyTimeout = 0.1;
bool _anomalyScheduled = false;
};
} /* namespace SDN4CoRE */
#endif /* OPENFLOW_CONTROLLERAPPS_AVB_AVBSECURITYCONTROLLERAPP_H_ */
| 6,490
|
C++
|
.h
| 157
| 36.726115
| 216
| 0.712496
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,268
|
AVBLearningControllerApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/avb/AVBLearningControllerApp.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __OPENFLOW_AVB_AVBLEARNINGCONTROLLERAPP_H_
#define __OPENFLOW_AVB_AVBLEARNINGCONTROLLERAPP_H_
#include "sdn4core/controllerApps/base/LearningControllerApp.h"
#include "sdn4core/controllerState/srp/SRPTableManagement.h"
//STD
#include <vector>
using namespace omnetpp;
namespace SDN4CoRE{
/**
* AVBLearningControllerApp is an SDN controller application that handles
* avb real time traffic as well as best effort MAC switching.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class AVBLearningControllerApp : public LearningControllerApp
{
public:
protected:
virtual void initialize() override;
/**
* Main processing engine of packet_in messages.
*
* Checks whether packet in is an srp or avb frame and handles them,
* else the learning controller can handle it.
*
* @param packet_in_msg The packet in message
*/
virtual void processPacketIn(openflow::OFP_Packet_In *packet_in_msg) override;
/**
* Implements how to process SRP packets.
* @param packet_in_msg Packet with the SRP message
*/
void doSRP(openflow::OFP_Packet_In *packet_in_msg);
/**
* Creates and sends an SRPFlowModification Message implementing a flow rule in the switch to forward AVB streams.
* @param mod_com The modification command of the FlowModMessage (e.g. create, delete, modify,...).
* @param match The match to be implemented in the switch.
* @param outports The output ports.
* @param socket The socket belonging to the switch connection.
* @param idleTimeOut The Idle TimeOut, default will be no timeout.
* @param hardTimeOut The Hard TimeOut, default will be no timeout.
*/
virtual void sendSRPFlowModMessage(openflow::ofp_flow_mod_command mod_com, const openflow::oxm_basic_match &match, std::vector<int> outports, inet::TCPSocket * socket, int idleTimeOut , int hardTimeOut);
/**
* Forwards an SRP Packet to the switch to be processed.
* @param packet_in_msg the packet in from the switch
*/
virtual void forwardSRPPacket(openflow::OFP_Packet_In *packet_in_msg);
/**
* Loads an offline Configuration for the controller app regarding a connected switch
* containing MAC and SRP Table.
* @param info The switch to load the offline config for.
* @return true if a config was loaded.
*/
virtual bool loadOfflineConfigFromXML(openflow::Switch_Info* info) override;
/**
* Exports the current state of the MAC and SRP table and creates an XML formatted string.
* @return The current state as an XML formatted string
*/
virtual std::string stateToXML () override;
/**
* A management module handling all SRP operations.
*/
SRPTableManagement* _srpManager;
private:
/**
* Path to the ned module of the SRPTableManagement.
*/
static const char SRPTABLEMANAGERMODULEPATH [];
};
} /*end namespace SDN4CoRE*/
#endif /* __OPENFLOW_AVB_AVBLEARNINGCONTROLLERAPP_H_ */
| 3,727
|
C++
|
.h
| 88
| 38.386364
| 207
| 0.723557
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,269
|
PacketProcessorBase.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/base/PacketProcessorBase.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_PACKETPROCESSORBASE_H_
#define __SDN4CORE_PACKETPROCESSORBASE_H_
#include <omnetpp.h>
//STD
#include <map>
#include <string>
#include <vector>
//openflow
#include <openflow/openflow/protocol/OpenFlow.h>
#include "openflow/openflow/controller/Switch_Info.h"
#include "openflow/controllerApps/AbstractControllerApp.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Base application for a packet processor.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class PacketProcessorBase: public openflow::AbstractControllerApp {
public:
static simsignal_t packetFilteredSignal;
static simsignal_t packetProcessedSignal;
/**
* Packet Filter is a map of a string key and a string value list.
*/
class PacketFilter : public std::map<std::string, std::vector<std::string>> {
public:
/**
* Initializes the PacketFilter map from a parameter string value.
*
* Syntax: "<key1>=<value11>,<value12>; ...; <keyK>=<valueK1>,...,<valueKV>"
* A list of filters separated by semicolon ";". Each filter contains
* exactly one key followed by "=" and a list of values separated with a comma ",".
* accepted values keys are:
* key: "ethSrc" values: MAC address, e.g., AA-AA-AA-AA-AA-AA
* key: "ethDst" values: MAC address, e.g., AA-AA-AA-AA-AA-AA
* key: "etherType" values: etherType number, e.g., 0x0800 or 2048
* key: "vlanId" values: VLAN identifier, e.g., 42
* key: "vlanPcp" values: VLAN priority code points (0-7), e.g., 3
* key: "ipSrc" values: IP address with optional netmask, e.g., 192.168.178.42 or 192.168.178.1/24
* key: "ipDst" values: IP address with optional netmask, e.g., 192.168.178.42 or 192.168.178.1/24
* key: "ipProto" values: IP protocol, e.g. 0x11 or 17
* key: "udpSrc" values: UDP port, e.g., 1234
* key: "udpDst" values: UDP port, e.g., 1234
* key: "tcpSrc" values: TCP port, e.g., 1234
* key: "tcpDst" values: TCP port, e.g., 1234
*
* @param parameterValue The string from cPar::stdStringValue() to be parsed
*/
void initializeFromPar(const std::string& parameterValue);
bool addPacketFilter(std::string key, std::string value);
bool addPacketFilters(std::string key, std::vector<std::string> values);
bool matchesIntValue(std::string key, int value);
bool matchesStringValue(std::string key, std::string value);
bool matchesMACAddressValue(std::string key, inet::MACAddress value);
bool matchesL3AddressValue(std::string key, inet::L3Address value);
bool matchesPacketIn(openflow::OFP_Packet_In *packet_in_msg);
};
int getHardTimeout() const {
return _hardTimeout;
}
int getIdleTimeout() const {
return _idleTimeout;
}
protected:
void setHardTimeout(int hardTimeout) {
this->_hardTimeout = hardTimeout;
}
void setIdleTimeout(int idleTimeout) {
this->_idleTimeout = idleTimeout;
}
/**
* Trys to locate the managerModule in the controllerState module.
*
* @param managerModule the name of the module to locate
* @return the module of type T if found, else nullptr
*/
template<typename T>
T tryLocateStateManager(std::string managerModule) {
cModule* controllerState = this->getParentModule()->getSubmodule(
"controllerState");
if(controllerState) {
return dynamic_cast<T>(controllerState->getSubmodule(managerModule.c_str()));
}
return nullptr;
}
virtual void initialize() override;
virtual void handleParameterChange(const char* parname) override;
void receiveSignal(cComponent *src, simsignal_t id, cObject *obj,
cObject *details) override;
virtual void finish() override;
/**
* Checks whether the packetIn is filtered.
* This is the case, if the packet either does not match any of the entries in a
* non empty whitelist or it does match one entry in a non empty blacklist.
* @param packet_in_msg the packet information to check for filtering
* @return True if the packet is filtered, false indicates that it should be processed.
*/
virtual bool isFiltered(openflow::OFP_Packet_In *packet_in_msg);
// --------------------- INTERFACE FUNCTIONS ----------------------//
/**
* Interface function for the main processing engine of packet_in messages.
*
* This default implementation does nothing
*
* @param packet_in_msg The packet in message
*/
virtual void processPacketIn(openflow::OFP_Packet_In *packet_in_msg) { }
/**
* Interface function for processing new switch connections.
*
* This default implementation calls loadOfflineConfigFromXML() for
* the switch.
*
* @param info the new switch connected
*/
virtual void processSwitchConnection(openflow::Switch_Info* info) {
Enter_Method("processSwitchConnection()");
loadOfflineConfigFromXML(info);
}
/**
* Interface function to load an offline configuration for a newly connected switch.
*
* This default implementation does nothing and returns false.
*
* @param info The switch to load the offline config for.
* @return True if a config was loaded
*/
virtual bool loadOfflineConfigFromXML(openflow::Switch_Info* info) {
return false;
}
/**
* Interface function to exports the current state as an XML formatted string.
*
* This default implementation returns an empty string.
*
* @return The current state as an XML formatted string
*/
virtual std::string stateToXML() {
return "";
}
protected:
/**
* The cached flow rule IdleTimeOut parameter.
*/
int _idleTimeout;
/**
* The cached flow rule HardTimeOut parameter.
*/
int _hardTimeout;
/**
* A map with whitelisted packet filters cached from parameter.
*/
PacketFilter _whitelist;
/**
* A map with blacklisted packet filters cached from parameter.
*/
PacketFilter _blacklist;
};
} /*end namespace SDN4CoRE*/
#endif /* __SDN4CORE_PACKETPROCESSORBASE_H_ */
| 7,048
|
C++
|
.h
| 175
| 34.508571
| 111
| 0.669051
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,270
|
LearningControllerApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/base/LearningControllerApp.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __SDN4CORE_LEARNINGCONTROLLERAPP_H_
#define __SDN4CORE_LEARNINGCONTROLLERAPP_H_
#include "sdn4core/controllerApps/base/PacketProcessorBase.h"
#include "sdn4core/controllerState/devices/DeviceTable.h"
#include "sdn4core/controllerState/hosts/HostTable.h"
#include "sdn4core/controllerState/topology/TopologyManagement.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* LearningControllerApp is an SDN controller application that handles
* best effort MAC switching. It uses the @see~MACTableManagement for
* L2 Address learning.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class LearningControllerApp: public PacketProcessorBase {
protected:
virtual void initialize() override;
/**
* Implements the main switching engine for best effort packets.
* @param packet_in_msg Packet in the be switched.
*/
virtual void processPacketIn(openflow::OFP_Packet_In *packet_in_msg)
override;
/**
* Interface function for processing new switch connections.
*
* This default implementation calls loadOfflineConfigFromXML() for
* the switch.
*
* @param info the new switch connected
*/
virtual void processSwitchConnection(openflow::Switch_Info* info) override;
/**
* Creates a match from an packet in message.
* @param packetIn The packet in message to create a match for.
* @return The match created.
*/
virtual openflow::oxm_basic_match createMatchFromPacketIn(
openflow::OFP_Packet_In* packetIn);
/**
* Loads an offline Configuration for the controller app regarding a connected switch
* containing MAC and SRP Table.
* @param info The switch to load the offline config for.
* @return true if a config was loaded.
*/
virtual bool loadOfflineConfigFromXML(openflow::Switch_Info* info) override;
/**
* Exports the current state of the MAC and SRP table and creates an XML formatted string.
* @return The current state as an XML formatted string
*/
virtual std::string stateToXML() override;
protected:
/**
* A management module handling all MAC operations.
*/
HostTable* hostTable;
/**
* A management module handling all MAC operations.
*/
DeviceTable* deviceTable;
/**
* A management module handling all MAC operations.
*/
TopologyManagement* topology;
};
} /*end namespace SDN4CoRE*/
#endif /* __SDN4CORE_LEARNINGCONTROLLERAPP_H_ */
| 3,197
|
C++
|
.h
| 84
| 34.02381
| 94
| 0.726686
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,271
|
LLDPControllerApp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/lldp/LLDPControllerApp.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __SDN4CORE_LLDPCONTROLLERAPP_H_
#define __SDN4CORE_LLDPCONTROLLERAPP_H_
#include "sdn4core/controllerApps/base/LearningControllerApp.h"
//STD
#include <vector>
//inet
#include "inet/linklayer/ethernet/EtherFrame_m.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* LLDPControllerApp is an SDN controller application that handles link layer discovery.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class LLDPControllerApp: public PacketProcessorBase {
public:
protected:
virtual void initialize() override;
virtual void handleParameterChange(const char* parname) override;
virtual void handleMessage(cMessage *msg) override;
virtual void processPacketIn(openflow::OFP_Packet_In *packet_in_msg)
override;
virtual void processSwitchConnection(openflow::Switch_Info* swInfo)
override;
/**
* Schedule the next LLDP cycle.
*/
virtual void scheduleNextCycle();
/**
* Install a flow that forwards the LLDP messages to the controller on a switch.
* @param swInfo info about the switch
*/
virtual void installLLDPFLow(openflow::Switch_Info* swInfo);
/**
* Send LLDP packages to all connected network devices.
*/
virtual void sendLLDP();
/**
* Send LLDP packages to all ports of a specific network devices.
*/
virtual void sendLLDP(openflow::Switch_Info* swInfo);
/**
* Create an lldp frame for the given switch port.
* @param switchId The switch id
* @param port The port number
* @return An Ethernet frame containing the lldp message.
*/
virtual inet::EthernetIIFrame* createLLDPPacket(std::string switchId,
int port);
protected:
/**
* Cached parameter for the lldp execution cycle.
*/
simtime_t cycle;
/**
* Cached parameter indicating if lldp shall be triggered on new connection.
*/
bool lldpOnNewConnection;
/**
* Self message used to trigger the cyclic LLDP messages.
*/
cMessage* trigger;
/**
* Reference to the deviceTable module.
*/
DeviceTable* deviceTable;
};
} /*end namespace SDN4CoRE*/
#endif /* __SDN4CORE_LLDPCONTROLLERAPP_H_ */
| 2,897
|
C++
|
.h
| 85
| 29.988235
| 88
| 0.718683
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,272
|
XMLUtility.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/xml/XMLUtility.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_UTILITY_XML_XMLUTILITY_H_
#define SDN4CORE_UTILITY_XML_XMLUTILITY_H_
#include <string>
#include <omnetpp.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Helper method to get a string attribute from an XML config.
* @return the value from xml if present, the alternative value if the parameter is not required.
* @throw a runtime error if required is true and attribute cannot be found.
*/
std::string getStringAttributeFromXML(cXMLElement* configureXML,
const char* attribute, bool required = true, std::string alternativeValue = "");
/**
* Helper method to get a string attribute from an XML config.
* @return the value from xml if present, the alternative value if the parameter is not required.
* @throw a runtime error if required is true and attribute cannot be found.
*/
int getIntAttributeFromXML(cXMLElement* configureXML,
const char* attribute, bool required = true, int alternativeValue = 0);
/**
* Helper method to get a string attribute from an XML config.
* @return the value from xml if present, the alternative value if the parameter is not required.
* @throw a runtime error if required is true and attribute cannot be found.
*/
double getDoubleAttributeFromXML(cXMLElement* configureXML,
const char* attribute, bool required = true, double alternativeValue = 0);
}; // namespace SDN4CoRE
#endif /* SDN4CORE_UTILITY_XML_XMLUTILITY_H_ */
| 2,215
|
C++
|
.h
| 45
| 45.377778
| 101
| 0.73728
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,273
|
ProcessingTimeSimulation.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/processing/ProcessingTimeSimulation.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_PROCESSINGTIMESIMULATION_H_
#define __SDN4CORE_PROCESSINGTIMESIMULATION_H_
#include <omnetpp.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Schedules Processing for incoming messages two for a later time slot.
* Only allows the processing of one message at the time.
* Other incoming messages wait in a queue.
*/
class ProcessingTimeSimulation: public cSimpleModule {
public:
virtual ~ProcessingTimeSimulation();
double getProcessingTime();
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
virtual void handleParameterChange(const char *parname);
/**
* Schedules the message at a later time according to _processingTime parameter.
* After the processing time the message will be forwarded to processMessage().
* @param msg The msg to schedule.
*/
virtual void simulateProcessingTime(cMessage* msg);
/**
* Triggers the next processing time simulation. Resets the busy status if msgList
* is empty, otherwise schedules next message in processing time.
*/
virtual void triggerNextProcessingTime();
/**
* Processes the scheduled message. Needs to delete the message after handling it.
* @param msg the incoming message
*/
virtual void processScheduledMessage(cMessage *msg) = 0;
/**
* Cached parameter processing time.
*/
double _processingTime;
/**
* Caches the allowParallelProcessing parameter.
* allow parallel processing so new incoming
* messages will be scheduled in processing time.
*/
bool _allowParallelProcessing;
/**
* Incoming message list to simulate processing time.
*/
std::list<cMessage*> _msgList;
/**
* Indicates if a message is currently scheduled.
*/
bool _busy;
//stats
simsignal_t _queueSize;
simsignal_t _waitingTime;
};
} /*end namespace SDN4CoRE*/
#endif
| 2,661
|
C++
|
.h
| 74
| 32.081081
| 86
| 0.731128
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,274
|
ColorChangingNode.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/visual/ColorChangingNode.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __OPENFLOW_COLORCHANGINGNODE_H_
#define __OPENFLOW_COLORCHANGINGNODE_H_
#include <omnetpp.h>
#include <string>
namespace SDN4CoRE {
/**
* The Color changing Node provides functions to set the Color and Opacity during runtime.
* It either can be used as a simple Node to Display Colors in the Network or extended to
* inherit color changing functionality.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class ColorChangingNode: public omnetpp::cSimpleModule {
public:
const std::string& getColor() const {
return _color;
}
/**
* sets the color to the string value.
* The caller must ensure it is accepted by omnetpp display strings.
*/
virtual void setColor(const std::string& color);
const std::string& getOpacity() const {
return _opacity;
}
/**
* Sets the opacity to the string value.
* The caller must ensure it is accepted by omnetpp display strings.
*/
void setOpacity(const std::string& opacity);
protected:
/**
* initialize the module colors.
*/
virtual void initialize() override;
/**
* refresh the display string if it was updated.
*/
virtual void refreshDisplay() const override;
private:
/**
* The current color.
*/
std::string _color;
/**
* The current opacity.
*/
std::string _opacity;
/**
* True if the color was changed and needs to be updated by refresh display.
* Refresh display resets this status so it needs to be mutable.
*/
mutable bool _colorUpdated = false;
};
} // namespace SDN4CoRE
#endif
| 2,306
|
C++
|
.h
| 72
| 28.319444
| 90
| 0.704187
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,275
|
NodeDisplayEditor.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/visual/NodeDisplayEditor.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef OPENFLOW_UTILITY_NODEDISPLAYEDITOR_H_
#define OPENFLOW_UTILITY_NODEDISPLAYEDITOR_H_
#include <omnetpp.h>
namespace SDN4CoRE {
/**
* The Node Display Editor can be used to manipulate the a modules display string
* during runtime with abstracted methods.
*/
class NodeDisplayEditor {
public:
/**
* Constructor setting the Target Module.
* @param targetModule the manipulated module.
*/
NodeDisplayEditor(omnetpp::cModule* targetModule);
/**
* Default Constructor. Don't forget to set the target Module.
*/
NodeDisplayEditor();
virtual ~NodeDisplayEditor();
omnetpp::cModule* getTarget() {
return _target;
}
void setTarget(omnetpp::cModule* target) {
_target = target;
}
/**
* Set the color of the Node to the given String. The user has to ensure valid strings are used.
* @param color The color to set. Valid values are some common color names,
* such as white, black, red, etc. or rgb values in format #rgb or #rrggbb.
* @param opacity The opacity of the color. Valid values are 0-100.
*
*/
void setNodeColor(const char* color, const char* opacity = "50");
/**
* Set the color of the given module to the provided string values. The user has to ensure valid strings are used.
* @param target The target module to manipulate.
* @param color The color to set. Valid values are some common color names,
* such as white, black, red, etc. or rgb values in format #rgb or #rrggbb.
* @param opacity The opacity of the color. Valid values are 0-100.
*
*/
static void setNodeColor(omnetpp::cModule* target, const char* color, const char* opacity = "50");
private:
/**
* The targeted Module.
*/
omnetpp::cModule* _target;
};
} /* namespace SDN4CoRE */
#endif /* OPENFLOW_UTILITY_NODEDISPLAYEDITOR_H_ */
| 2,624
|
C++
|
.h
| 67
| 35.358209
| 118
| 0.69427
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,276
|
LayeredInformation.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/layeredInformation/LayeredInformation.h
|
/*
* LayeredInformation.h
*
* Created on: 13.09.2022
* Author: jsolb
*/
#ifndef SDN4CORE_UTILITY_LAYEREDINFORMATION_LAYEREDINFORMATION_H_
#define SDN4CORE_UTILITY_LAYEREDINFORMATION_LAYEREDINFORMATION_H_
#include <omnetpp/cobject.h>
#include "inet/linklayer/common/MACAddress.h"
#include "inet/networklayer/common/L3Address.h"
#include "openflow/openflow/controller/Switch_Info.h"
namespace SDN4CoRE {
class LayeredInformation: public omnetpp::cObject {
public:
inet::MACAddress eth_src;
inet::MACAddress eth_dst;
inet::L3Address ip_src;
inet::L3Address ip_dst;
int transport_src;
int transport_dst;
int in_port;
openflow::Switch_Info* sw_info;
LayeredInformation();
virtual ~LayeredInformation();
LayeredInformation(const LayeredInformation& other) : omnetpp::cObject(other) {
copy(other);
}
/**
* @brief Assignment operator
*/
LayeredInformation& operator=(const LayeredInformation& other)
{
if (this==&other) return *this;
cObject::operator=(other);
copy(other);
return *this;
}
virtual LayeredInformation *dup() const {return new LayeredInformation(*this);}
private:
void copy(const LayeredInformation& other);
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_UTILITY_LAYEREDINFORMATION_LAYEREDINFORMATION_H_ */
| 1,419
|
C++
|
.h
| 44
| 26.772727
| 84
| 0.700519
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,277
|
DynamicChannelParameterChanger.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/dynamicparameters/DynamicChannelParameterChanger.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_DYNAMICCHANNELPARAMETERCHANGER_H_
#define __SDN4CORE_DYNAMICCHANNELPARAMETERCHANGER_H_
#include <sdn4core/utility/dynamicparameters/DynamicParameterChanger.h>
namespace SDN4CoRE{
/**
* Module that changes a parameter of the channel to a new value
* at the specified time, and resets the value later if enabled
*/
class DynamicChannelParameterChanger : public DynamicParameterChanger
{
private:
protected:
virtual void fillComponentToChange(std::vector<std::string>& paths) override;
virtual cComponent* getChannelForGate(cGate* gate);
public:
};
} // namespace SDN4CoRE
#endif //__SDN4CORE_DYNAMICCHANNELPARAMETERCHANGER_H_
| 1,337
|
C++
|
.h
| 32
| 40.0625
| 81
| 0.791667
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,278
|
DynamicParameterChanger.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/dynamicparameters/DynamicParameterChanger.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_DYNAMICPARAMETERCHANGER_H_
#define __SDN4CORE_DYNAMICPARAMETERCHANGER_H_
#include <omnetpp.h>
#include <map>
#include <vector>
#include <string>
using namespace omnetpp;
namespace SDN4CoRE{
/**
* Module that changes a parameter in one or multiple components to a new value
* at the specified time, and resets the value later if enabled
*/
class DynamicParameterChanger : public cSimpleModule
{
protected:
/**
* Caches the components to be changed and the initial state of the parameters
*/
std::map<cComponent*, std::string> _componentsToChange;
/**
* Caches the parameter to be changed for the componentes
*/
std::string _parToChange;
/**
* Caches the value to be set for the parameter
*/
std::string _newValue;
protected:
virtual void initialize(int stage) override;
virtual int numInitStages() const override;
virtual void handleMessage(cMessage *msg) override;
virtual void fillComponentToChange(std::vector<std::string>& paths);
virtual void changePars();
virtual void resetPars();
};
} // namespace SDN4CoRE
#endif //__SDN4CORE_DYNAMICPARAMETERCHANGER_H_
| 1,847
|
C++
|
.h
| 51
| 33.333333
| 82
| 0.749439
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,279
|
DynamicModuleHandling.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/dynamicmodules/DynamicModuleHandling.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_UTILITY_DYNAMICMODULES_DYNAMICMODULEHANDLING_H_
#define SDN4CORE_UTILITY_DYNAMICMODULES_DYNAMICMODULEHANDLING_H_
#include <omnetpp.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Creates a module by calling createDynamicModule and finalizes it if the
* creation was successful by calling finalizeModuleAndSchedule.
*
* @param nedModulePath The path to the ned file.
* @param name The name of the submodule to create in the parent module.
* @param parentModule The instance of the parent module.
* @param isVector True if the dynamic module is a vector element.
* @param at The SimTime to schedule the module creation, default now.
* @return
*/
cModule* createFinalizeAndScheduleDynamicModule(const char* nedModulePath,
const char* name, cModule* parentModule, bool isVector, SimTime at = simTime());
/**
* Creates a new submodule which can be a vector with the given name in the parent
* module of module type specified in nedModulePath.
*
* @param nedModulePath The path to the ned file.
* @param name The name of the submodule to create in the parent module.
* @param parentModule The instance of the parent module.
* @param isVector True if the dynamic module is a vector element.
* @return
*/
cModule* createDynamicModule(const char* nedModulePath,
const char* name, cModule* parentModule, bool isVector);
/**
* Calls finalizeParameters();buildInside();callInitialize();scheduleStart(at);
*
* for the given module.
* @param module the module to finalize.
* @param at the SimTime to schedule default now.
*/
void finalizeModuleAndSchedule(cModule* module, SimTime at = simTime());
/**
* Counts the actual vector size of a module vector with the given name inside the parent module.
* @param name the name of the module vector.
* @param parentModule the parent cModule of the module vector.
* @return The size of the module vector, -1 if it is not a vector type.
*/
int getDynamicModuleVectorSize(const char* name, cModule* parentModule);
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_UTILITY_DYNAMICMODULES_DYNAMICMODULEHANDLING_H_ */
| 2,914
|
C++
|
.h
| 63
| 44.365079
| 97
| 0.749384
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,280
|
StreamingHandler.cpp
|
mule1972_NeoPixelBLVmgn/StreamingHandler.cpp
|
#include "Debugging.h"
#include "StreamingHandler.h"
#define EQ(x, y) (strcmp_P(x.c_str(), PSTR(y)) == 0)
#define D(x) DEBUG1F(x)
#define DLN(x) DEBUG1(x)
void StreamingHandler::handleValue(String value) {
if (EQ(current, "status") && EQ(stack[0], "state")) {
if (EQ(value, "idle")) {
Printer->resetPrinting();
Printer->Status = 'I';
} else if (EQ(value, "simulating")) {
Printer->Status = 'P';
} else if (EQ(value, "processing")) {
Printer->Status = 'P';
} else if (EQ(value, "resuming")) {
Printer->Status = 'B';
} else if (EQ(value, "busy")) {
Printer->Status = 'D';
} else if (EQ(value, "starting")) {
Printer->resetPrinting();
Printer->Status = 'F';
} else if (EQ(value, "updating")) {
Printer->resetPrinting();
Printer->Status = 'C';
} else if (EQ(value, "pausing")) {
Printer->Status = 'R';
} else if (EQ(value, "paused")) {
Printer->Status = 'A';
} else if (EQ(value, "halted")) {
Printer->resetPrinting();
Printer->Status = 'S';
} else if (EQ(value, "off")) {
Printer->resetPrinting();
Printer->Status = 'S';
}
D(F("Status: ")) DLN(Printer->Status);
Printer->UpdatePending = true;
} else if (EQ(current, "active") && EQ(stack[0], "heaters")) {
Printer->Heater_ActiveTemp[index] = value.toFloat();
D(F("Active Temp: ")) D(index) D(" ") DLN(value)
Printer->UpdatePending = true;
} else if (EQ(current, "standby") && EQ(stack[0], "heaters")) {
D(F("Standby Temp: ")) D(index) D(" ") DLN(value)
Printer->Heater_StandbyTemp[index] = value.toFloat();
Printer->UpdatePending = true;
} else if (EQ(current, "current") && EQ(stack[0], "heaters")) {
D(F("Current Temp: ")) D(index) D(" ") DLN(value)
Printer->Heater_ActTemp[index] = value.toFloat();
Printer->UpdatePending = true;
} else if (EQ(current, "state") && EQ(stack[0], "heaters")) {
if (EQ(value, "off") || EQ(value, "offline")) {
Printer->Heater_Status[index] = 0;
} else if (EQ(value, "active")) {
Printer->Heater_Status[index] = 2;
} else if (EQ(value, "standby")) {
Printer->Heater_Status[index] = 1;
} else if (EQ(value, "fault")) {
Printer->Heater_Status[index] = 3;
} else if (EQ(value, "tuning")) {
Printer->Heater_Status[index] = 4;
}
D(F("Heater State: ")) D(index) D(" ") DLN(value)
Printer->UpdatePending = true;
} else if (EQ(current, "slicer") && EQ(stack[0], "timesLeft")) {
D(F("Time Left: ")) DLN(value);
Printer->printRemaining = value.toInt();
Printer->UpdatePending = true;
} else if (EQ(current, "duration") && EQ(stack[0], "job") && Printer->printRemaining > 0) {
Printer->printDuration = value.toInt();
D(F("Duration: ")) DLN(value);
Printer->UpdatePending = true;
} else if (EQ(current, "warmUpDuration") && EQ(stack[0], "job") && Printer->printRemaining > 0) {
Printer->printWarmUpDuration = value.toInt();
D(F("WarmUpDuration: ")) DLN(value);
Printer->UpdatePending = true;
}
}
| 3,454
|
C++
|
.cpp
| 77
| 34.883117
| 102
| 0.525363
|
mule1972/NeoPixelBLVmgn
| 30
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,282
|
StreamingHandler.h
|
mule1972_NeoPixelBLVmgn/StreamingHandler.h
|
#pragma once
#include "src/json/JsonListener.h"
#define NumberHeaters 5
class StructPanelDueMessage {
friend class StreamingHandler;
public:
char Status;
uint8_t Heater_Status[NumberHeaters];
float Heater_ActTemp[NumberHeaters];
float Heater_ActiveTemp[NumberHeaters];
float Heater_StandbyTemp[NumberHeaters];
bool UpdatePending;
// prevent divby0
inline float FractionPrinted() { return (printDuration - printWarmUpDuration) / (float) max(1, ((printDuration - printWarmUpDuration) + printRemaining)); }
inline void reset() { UpdatePending = false; complete = false; }
bool complete = false;
private:
inline void resetPrinting() { printDuration = 0; printRemaining = 0; printWarmUpDuration = 0;}
uint16_t printDuration = 0;
uint16_t printRemaining = 0;
uint16_t printWarmUpDuration = 0;
};
const String EMPTY("");
class StreamingHandler: public JsonListener {
private:
StructPanelDueMessage* Printer = NULL;
String stack[3] = { EMPTY, EMPTY, EMPTY };
String current = EMPTY;
uint8_t index = -1;
bool shouldCount = true;
uint8_t aryDepth = 0;
bool inArray = false;
uint8_t values = 0;
public:
inline void startDocument() { }
inline void startArray() {
index = -1;
inArray = true;
aryDepth = 0;
push();
}
inline void startObject() {
if (aryDepth == 0 && inArray) index++;
push();
aryDepth++;
}
inline void endArray() {
pop();
current = EMPTY;
inArray = false;
}
inline void endObject() {
pop();
current = EMPTY;
aryDepth--;
}
inline void endDocument() { Printer->complete = true; }
inline void key(String k) {
current = String(k);
values = 0;
}
inline void value(String value) {
values++;
if (aryDepth == 0 && inArray) index++;
handleValue(value);
}
void handleValue(String value);
inline void whitespace(char c) { }
inline void setPrinter(StructPanelDueMessage* message) { Printer = message; }
void push() {
stack[2] = stack[1];
stack[1] = stack[0];
if (values == 0 && current != EMPTY) {
stack[0] = current;
}
}
void pop() {
stack[0] = stack[1];
stack[1] = stack[2];
}
};
| 2,459
|
C++
|
.h
| 81
| 23.345679
| 158
| 0.607725
|
mule1972/NeoPixelBLVmgn
| 30
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,283
|
Debugging.h
|
mule1972_NeoPixelBLVmgn/Debugging.h
|
#include <AltSoftSerial.h>
#pragma once
//#define DEBUGLEVEL1_ACTIVE
//#define DEBUGLEVEL2_ACTIVE
#if defined(DEBUGLEVEL1_ACTIVE) || defined(DEBUGLEVEL2_ACTIVE)
extern AltSoftSerial SoftSerialDebug;
#define SerialPortDebug SoftSerialDebug //Per default the serial port for debugging purposes is being auto configured depending on the chipset being used. If you whish to customize it by your own, you have to uncomment this line and define the serial port to be used (e.g. "Serial" or "Serial1" or SoftSerialDebug etc).
#endif
//Setup Serial Interface (Debug)
#if (defined SerialPortDebug)
#define SerialObjectDebug SerialPortDebug
#else
//Arduino-Mega & Co.
#if (defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__))
#define SerialObjectDebug Serial
#endif
//Arduino-Pro & Co.
#if (defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__))
#define SerialObjectDebug Serial
#endif
//Arduino-Leonardo & Co.
#if (defined(__AVR_ATmega32U4__))
#define SerialObjectDebug Serial1
#endif
//Arduino-Due & Co.
#if (defined(__SAM3X8E__))
#define SerialObjectDebug Serial1
#endif
#endif
#ifdef DEBUGLEVEL1_ACTIVE
#define DEBUG1(x) SerialObjectDebug.println(x);
#define DEBUG1F(x) SerialObjectDebug.print(x);
#else
#define DEBUG1(x) ;
#define DEBUG1F(x) ;
#endif
| 1,306
|
C++
|
.h
| 36
| 33.944444
| 320
| 0.760664
|
mule1972/NeoPixelBLVmgn
| 30
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,284
|
Config.h
|
mule1972_NeoPixelBLVmgn/Config.h
|
#pragma once
#include <Adafruit_Neopixel.h>
#include "Structures.h"
#define NeoPixelStartupAnimationActive true //Show Startup Animation for all Neopixels (true = activated / false = deactivated) !!Attention!! Animation will only be played if all NeoPixels have the same number of LEDs
#define COLOR(r, g, b) (((uint32_t)r << 16) | ((uint32_t)g << 8) | b)
#define DisplayPrinterObjectCycleFrequency 3 // Cycle frequency in seconds
/*
* Configure your Neopixels here
*
* Active - true/false: enable/disable this neopixel
* StartupAnimationColor - COLOR(red, green, blue), animates with color intensity 0-255
* DisplayPrinterObject - [0, 1, 2, 3, 4, 99]: heater, extruder1-4, 99 = printer status
* multiple may be selected, the last element must always be -1
* DisplayPrinterObjectChangeByFrequency - true/false: true: switch DisplayPrinter object based on the value of
* DisplayPrinterObjectCycleFrequency, false: pick the first of 99,
* or heater active, standby, off
* Type - neopixel library value, do not change from default unless they are not BOM neopixels
* LEDs - N: number of LEDs in the neopixel
* ArduinoPin - N: Arduino PIN number to attach this neopixel
* PixelOffset - N: LED position for starting point, positive is clockwise, negative is counterclockwise
* TempOffset - N.M: floating point minimum value at which the first LED lights up
* AnimationActive - true/false: Animate while heating
* AnimationReverse - true/false: Reverse the display direction
* Brightness - N: 0-255 brightness level
*
*/
StructNeoPixelConfig NeoPixelConfig[NumberNeoPixels] = {
{ // Neopixel 1
Active : true,
StartupAnimationColor : COLOR(0, 0, 255),
DisplayPrinterObject : { 1, 0, 99, -1 },
DisplayPrinterObjectChangeByFrequency : false,
Type : NEO_GRB + NEO_KHZ800,
LEDs : 16,
ArduinoPin : 7,
PixelOffset : 2,
TempOffset : 0,
AnimationActive : true,
AnimationReverse : false,
Brightness : 8,
},
{ // Neopixel 2
Active : true,
StartupAnimationColor : COLOR(255, 0, 0),
DisplayPrinterObject : { 0, -1 },
DisplayPrinterObjectChangeByFrequency : false,
Type : NEO_GRB + NEO_KHZ800,
LEDs : 16,
ArduinoPin : 6,
PixelOffset : 0,
TempOffset : 0,
AnimationActive : true,
AnimationReverse : false,
Brightness : 8,
},
{ // Neopixel 3
Active : true,
StartupAnimationColor : COLOR(0, 255, 0),
DisplayPrinterObject : { 1, -1 },
DisplayPrinterObjectChangeByFrequency : false,
Type : NEO_GRB + NEO_KHZ800,
LEDs : 16,
#if !defined(DEBUGLEVEL1_ACTIVE) && !defined(DEBUGLEVEL2_ACTIVE)
ArduinoPin : 8,
#else
ArduinoPin : 11, // move this neopixel to pin 11 if debugging is enabled
#endif
PixelOffset : 0,
TempOffset : 0,
AnimationActive : true,
AnimationReverse : false,
Brightness : 8,
},
{ // Neopixel 4
Active : false,
StartupAnimationColor : COLOR(255, 255, 0),
DisplayPrinterObject : { 2, -1 },
DisplayPrinterObjectChangeByFrequency : false,
Type : NEO_GRB + NEO_KHZ800,
LEDs : 16,
ArduinoPin : 5,
PixelOffset : 0,
TempOffset : 0,
AnimationActive : true,
AnimationReverse : false,
Brightness : 8,
},
{ // Neopixel 5
Active : false,
StartupAnimationColor : COLOR(0, 255, 255),
DisplayPrinterObject : { 3, -1 },
DisplayPrinterObjectChangeByFrequency : false,
Type : NEO_GRB + NEO_KHZ800,
LEDs : 16,
ArduinoPin : 4,
PixelOffset : 0,
TempOffset : 0,
AnimationActive : true,
AnimationReverse : false,
Brightness : 8,
},
{ // Neopixel 6
Active : false,
StartupAnimationColor : COLOR(255, 0, 255),
DisplayPrinterObject : { 4, -1 },
DisplayPrinterObjectChangeByFrequency : false,
Type : NEO_GRB + NEO_KHZ800,
LEDs : 16,
ArduinoPin : 3,
PixelOffset : 0,
TempOffset : 0,
AnimationActive : true,
AnimationReverse : false,
Brightness : 8,
},
};
/*
* Scale - N: Temperature / N = number of LEDs to color in
* ColorIdle, HeatUp, HeatUpDone, CoolDown, Animation: COLOR values for the specified state
*/
StructHeaterConfig HeaterConfig[NumberHeaters] = {
{ // heater0: bed
Scale : 6, // 0-96C range (over 96C = 16 LEDs), 6C steps
ColorIdle : COLOR(255, 255, 255),
ColorHeatUp : COLOR(255, 64, 64),
ColorHeatUpDone : COLOR(255, 0, 0),
ColorCoolDown : COLOR(0, 0, 255),
ColorAnimation : COLOR(0, 0, 0)
},
{ // heater1: extruder 1
Scale : 16, // 0-256C range (over 256C = 16 LEDs), 16C steps
ColorIdle : COLOR(255, 255, 255),
ColorHeatUp : COLOR(255, 64, 64),
ColorHeatUpDone : COLOR(255, 0, 0),
ColorCoolDown : COLOR(0, 0, 255),
ColorAnimation : COLOR(0, 0, 0)
},
{ // heater2: extruder 2
Scale : 20,
ColorIdle : COLOR(255, 255, 255),
ColorHeatUp : COLOR(255, 64, 64),
ColorHeatUpDone : COLOR(255, 0, 0),
ColorCoolDown : COLOR(0, 0, 255),
ColorAnimation : COLOR(0, 0, 0)
},
{ // heater3: extruder 3
Scale : 20,
ColorIdle : COLOR(255, 255, 255),
ColorHeatUp : COLOR(255, 64, 64),
ColorHeatUpDone : COLOR(255, 0, 0),
ColorCoolDown : COLOR(0, 0, 255),
ColorAnimation : COLOR(0, 0, 0)
},
{ // heater4: extruder 4
Scale : 20,
ColorIdle : COLOR(255, 255, 255),
ColorHeatUp : COLOR(255, 64, 64),
ColorHeatUpDone : COLOR(255, 0, 0),
ColorCoolDown : COLOR(0, 0, 255),
ColorAnimation : COLOR(0, 0, 0)
},
};
//PrinterObject#99 - PrinterStatus
#define PrinterStatus_ColorIdle 255,255,255 //RGB values for specified status
#define PrinterStatus_ColorPrinting 64,255,64 //RGB values for specified status
#define PrinterStatus_ColorPrintingDone 0,255,0 //RGB values for specified status
#define PrinterStatus_ColorStopped 0,0,255 //RGB values for specified status
#define PrinterStatus_ColorConfiguring 255,255,0 //RGB values for specified status
#define PrinterStatus_ColorPaused 160,32,240 //RGB values for specified status
#define PrinterStatus_ColorBusy 255,255,0 //RGB values for specified status
#define PrinterStatus_ColorPausing 160,32,240 //RGB values for specified status
#define PrinterStatus_ColorResuming 255,255,0 //RGB values for specified status
#define PrinterStatus_ColorFlashing 255,255,0 //RGB values for specified status
#define PrinterStatus_ColorDefault 255,255,255 //RGB values for specified status
#define PrinterStatus_ColorAnimation 0,0,0 //RGB values for specified status
| 8,371
|
C++
|
.h
| 175
| 44.074286
| 218
| 0.536565
|
mule1972/NeoPixelBLVmgn
| 30
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,285
|
Structures.h
|
mule1972_NeoPixelBLVmgn/Structures.h
|
#pragma once
#define NumberHeaters 5
#define NumberNeoPixels 6
struct StructNeoPixelConfig {
bool Active;
uint32_t StartupAnimationColor;
int8_t DisplayPrinterObject[(NumberHeaters + 1)];
bool DisplayPrinterObjectChangeByFrequency;
neoPixelType Type;
uint16_t LEDs;
uint16_t ArduinoPin;
int8_t PixelOffset;
float TempOffset;
bool AnimationActive;
bool AnimationReverse;
uint8_t Brightness;
uint8_t DisplayPrinterObjectPosition;
bool AnimationMemoryActive;
bool AnimationMemoryRunning;
uint8_t AnimationMemoryPosition;
uint8_t AnimationMemoryPosition_Memory;
uint8_t AnimationMemoryRangeBegin;
uint8_t AnimationMemoryRangeEnd;
int8_t AnimationMemoryDisplayPrinterObject;
uint8_t AnimationMemoryAnimationColor;
};
struct StructHeaterConfig {
uint8_t Scale;
uint32_t ColorIdle;
uint32_t ColorHeatUp;
uint32_t ColorHeatUpDone;
uint32_t ColorCoolDown;
uint32_t ColorAnimation;
};
| 934
|
C++
|
.h
| 34
| 24.735294
| 51
| 0.827202
|
mule1972/NeoPixelBLVmgn
| 30
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,287
|
main.cpp
|
retifrav_glfw-imgui-example/main.cpp
|
// C++
#include <string>
#include <iostream>
#include <filesystem>
// GLFW
#include <glad/glad.h>
#include <GLFW/glfw3.h>
// Dear ImGui
#include <dearimgui/imgui.h>
#include <dearimgui/imgui_stdlib.h>
#include <dearimgui/imgui_impl_glfw.h>
#include <dearimgui/imgui_impl_opengl3.h>
#include "functions.h"
#include "imgui-style.h"
std::string programName = "GLFW and Dear ImGui";
int windowWidth = 1200,
windowHeight = 800;
float highDPIscaleFactor = 1.0;
float backgroundR = 0.1f,
backgroundG = 0.3f,
backgroundB = 0.2f;
std::filesystem::path currentPath = ".";
std::filesystem::path basePath = ".";
std::string fontName = "JetBrainsMono-ExtraLight.ttf";
GLFWwindow *glfWindow = NULL;
bool show_demo_window = false;
bool show_another_window = false;
int counter = 0;
unsigned int shaderProgram, VBO, VAO;
const char *vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char *fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
static void glfw_error_callback(int error, const char *description)
{
std::cerr << "[ERROR] GLFW error: " << error << ", " << description << std::endl;
}
static void framebuffer_size_callback(GLFWwindow *window, int width, int height)
{
glViewport(0, 0, width, height);
}
void teardown()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
// optional: de-allocate all resources once they've outlived their purpose
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteProgram(shaderProgram);
if (glfWindow != NULL) { glfwDestroyWindow(glfWindow); }
glfwTerminate();
}
bool initializeGLFW()
{
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit())
{
std::cerr << "[ERROR] Couldn't initialize GLFW" << std::endl;
return false;
}
else
{
std::cout << "[INFO] GLFW initialized" << std::endl;
}
glfwWindowHint(GLFW_DOUBLEBUFFER , 1);
glfwWindowHint(GLFW_DEPTH_BITS, 24);
glfwWindowHint(GLFW_STENCIL_BITS, 8);
// adjust these values depending on the OpenGL supported by your GPU driver
std::string glsl_version = "";
#ifdef __APPLE__
// GLSL 150 + GL 4.1
glsl_version = "#version 150";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
// required on Mac OS
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#elif __linux__
// GLSL 150 + GL 4.3
glsl_version = "#version 150";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#elif _WIN32
// GLSL 130 + GL 4.6
glsl_version = "#version 130";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
#endif
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef _WIN32
// if it's a HighDPI monitor, try to scale everything
GLFWmonitor *monitor = glfwGetPrimaryMonitor();
float xscale, yscale;
glfwGetMonitorContentScale(monitor, &xscale, &yscale);
std::cout << "[INFO] Monitor scale: " << xscale << "x" << yscale << std::endl;
if (xscale > 1 || yscale > 1)
{
highDPIscaleFactor = xscale;
glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE);
}
#elif __APPLE__
// to prevent 1200x800 from becoming 2400x1600
// and some other weird resizings
glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE);
#endif
//const GLFWvidmode *mode = glfwGetVideoMode(monitor);
//glfwWindowHint(GLFW_MAXIMIZED, GLFW_TRUE);
glfWindow = glfwCreateWindow(
windowWidth,//mode->width,
windowHeight,//mode->height,
programName.c_str(),
NULL,//monitor
NULL
);
if (!glfWindow)
{
std::cerr << "[ERROR] Couldn't create a GLFW window" << std::endl;
return false;
}
glfwSetWindowPos(glfWindow, 100, 100);
glfwSetWindowSizeLimits(
glfWindow,
static_cast<int>(900 * highDPIscaleFactor),
static_cast<int>(500 * highDPIscaleFactor),
GLFW_DONT_CARE,
GLFW_DONT_CARE
);
// watch window resizing
glfwSetFramebufferSizeCallback(glfWindow, framebuffer_size_callback);
glfwMakeContextCurrent(glfWindow);
// VSync
glfwSwapInterval(1);
std::cout << "[INFO] OpenGL from GLFW "
<< glfwGetWindowAttrib(glfWindow, GLFW_CONTEXT_VERSION_MAJOR)
<< "."
<< glfwGetWindowAttrib(glfWindow, GLFW_CONTEXT_VERSION_MINOR)
<< std::endl;
return true;
}
bool initializeGLAD()
{
// load all OpenGL function pointers with glad
// without it not all the OpenGL functions will be available,
// such as glGetString(GL_RENDERER), and application might just segfault
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cerr << "[ERROR] Couldn't initialize GLAD" << std::endl;
return false;
}
else
{
std::cout << "[INFO] GLAD initialized" << std::endl;
}
std::cout << "[INFO] OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "[INFO] OpenGL from glad "
<< GLVersion.major << "." << GLVersion.minor
<< std::endl;
return true;
}
bool initializeDearImGui()
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.Fonts->AddFontFromFileTTF(
fontName.c_str(),
24.0f * highDPIscaleFactor,
NULL,
NULL
);
setImGuiStyle(highDPIscaleFactor);
// setup platform/renderer bindings
if (!ImGui_ImplGlfw_InitForOpenGL(glfWindow, true)) { return false; }
if (!ImGui_ImplOpenGL3_Init()) { return false; }
return true;
}
// build and compile our shader program
void buildShaderProgram()
{
// vertex shader
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// check for shader compile errors
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// fragment shader
unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// check for shader compile errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// link shaders
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// set up vertex data (and buffer(s)) and configure vertex attributes
float vertices[] =
{
-0.5f, -0.5f, 0.0f, // left
0.5f, -0.5f, 0.0f, // right
0.0f, 0.5f, 0.0f // top
};
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s),
// and then configure vertex attributes(s)
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// note that this is allowed, the call to glVertexAttribPointer registered VBO
// as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
// you can unbind the VAO afterwards so other VAO calls won't accidentally
// modify this VAO, but this rarely happens. Modifying other VAOs requires a call
// to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs)
// when it's not directly necessary
glBindVertexArray(0);
// uncomment this call to draw in wireframe polygons
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
void composeDearImGuiFrame()
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// standard demo window
if (show_demo_window) { ImGui::ShowDemoWindow(&show_demo_window); }
// a window is defined by Begin/End pair
{
int glfw_width = 0, glfw_height = 0, controls_width = 0;
// get the window size as a base for calculating widgets geometry
glfwGetFramebufferSize(glfWindow, &glfw_width, &glfw_height);
controls_width = glfw_width;
// make controls widget width to be 1/3 of the main window width
if ((controls_width /= 3) < 300) { controls_width = 300; }
// position the controls widget in the top-right corner with some margin
ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_Always);
// here we set the calculated width and also make the height to be
// be the height of the main window also with some margin
ImGui::SetNextWindowSize(
ImVec2(static_cast<float>(controls_width), static_cast<float>(glfw_height - 20)),
ImGuiCond_Always
);
ImGui::SetNextWindowBgAlpha(0.7f);
// create a window and append into it
ImGui::Begin("Controls", NULL, ImGuiWindowFlags_NoResize);
ImGui::Dummy(ImVec2(0.0f, 1.0f));
ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Time");
ImGui::Text("%s", currentTime(std::chrono::system_clock::now()).c_str());
ImGui::Dummy(ImVec2(0.0f, 3.0f));
ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Application");
ImGui::Text("Main window width: %d", glfw_width);
ImGui::Text("Main window height: %d", glfw_height);
ImGui::Dummy(ImVec2(0.0f, 3.0f));
ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "GLFW");
ImGui::Text("%s", glfwGetVersionString());
ImGui::Dummy(ImVec2(0.0f, 3.0f));
ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Dear ImGui");
ImGui::Text("%s", IMGUI_VERSION);
ImGui::Dummy(ImVec2(0.0f, 10.0f));
ImGui::Separator();
ImGui::Dummy(ImVec2(0.0f, 10.0f));
// buttons and most other widgets return true when clicked/edited/activated
if (ImGui::Button("Counter button"))
{
std::cout << "counter button clicked" << std::endl;
counter++;
if (counter == 9) { ImGui::OpenPopup("Easter egg"); }
}
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
if (ImGui::BeginPopupModal("Easter egg", NULL))
{
ImGui::Text("Ho-ho, you found me!");
if (ImGui::Button("Buy Ultimate Orb")) { ImGui::CloseCurrentPopup(); }
ImGui::EndPopup();
}
ImGui::Dummy(ImVec2(0.0f, 15.0f));
if (!show_demo_window)
{
if (ImGui::Button("Open standard demo"))
{
show_demo_window = true;
}
}
ImGui::Checkbox("show a custom window", &show_another_window);
if (show_another_window)
{
ImGui::SetNextWindowSize(
ImVec2(250.0f, 150.0f),
ImGuiCond_FirstUseEver // after first launch it will use values from imgui.ini
);
// the window will have a closing button that will clear the bool variable
ImGui::Begin("A custom window", &show_another_window);
ImGui::Dummy(ImVec2(0.0f, 1.0f));
ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Some label");
ImGui::TextColored(ImVec4(128 / 255.0f, 128 / 255.0f, 128 / 255.0f, 1.0f), "%s", "another label");
ImGui::Dummy(ImVec2(0.0f, 0.5f));
ImGui::Dummy(ImVec2(0.0f, 1.0f));
if (ImGui::Button("Close"))
{
std::cout << "close button clicked" << std::endl;
show_another_window = false;
}
ImGui::End();
}
ImGui::End();
}
}
int main(int argc, char *argv[])
{
std::cout << "["
<< currentTime(std::chrono::system_clock::now())
<< "] "
<< "Start\n- - -\n\n";
// setting paths to resources
currentPath = std::filesystem::current_path();
//std::cout << "[DEBUG] Current working directory: " << currentPath << std::endl;
//basePath = std::filesystem::path(argv[0]).parent_path();
basePath = std::filesystem::path(argv[0]).remove_filename();
#ifndef _WIN32 // on Windows argv[0] is absolute path
basePath = currentPath / basePath;
#endif
//std::cout << "[DEBUG] Executable name/path: " << argv[0] << std::endl
// << "parent path: " << basePath << std::endl << std::endl;
fontName = (basePath / fontName).string();
if (!initializeGLFW())
{
std::cerr << "[ERROR] GLFW initialization failed" << std::endl;
return EXIT_FAILURE;
}
if (!initializeGLAD())
{
std::cerr << "[ERROR] glad initialization failed" << std::endl;
return EXIT_FAILURE;
}
if (!initializeDearImGui())
{
std::cerr << "[ERROR] Dear ImGui initialization failed" << std::endl;
return EXIT_FAILURE;
}
// build and compile our shader program
buildShaderProgram();
// rendering loop
while (!glfwWindowShouldClose(glfWindow))
{
// the frame starts with a clean scene
glClearColor(backgroundR, backgroundG, backgroundB, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// draw our triangle
glUseProgram(shaderProgram);
// seeing as we only have a single VAO there's no need to bind it every time,
// but we'll do so to keep things a bit more organized
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
//glBindVertexArray(0); // no need to unbind it every time
// Dear ImGui frame
composeDearImGuiFrame();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(glfWindow);
// continuous rendering, even if window is not visible or minimized
glfwPollEvents();
// or you can sleep the thread until there are some events
// in case of running animations (glTF, for example), also call glfwPostEmptyEvent() in render()
//glfwWaitEvents();
}
teardown();
std::cout << "\n- - -\n"
<< "["
<< currentTime(std::chrono::system_clock::now())
<< "] "
<< "Quit\n";
return 0;
}
| 15,537
|
C++
|
.cpp
| 407
| 31.589681
| 110
| 0.636949
|
retifrav/glfw-imgui-example
| 30
| 3
| 0
|
GPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,291
|
string.cpp
|
xavieran_BaKGL/com/string.cpp
|
#include "com/string.hpp"
#include <cctype>
#include <iterator>
#include <algorithm>
std::string ToUpper(std::string_view str)
{
std::string uppered{};
std::transform(
str.begin(),
str.end(),
std::back_inserter(uppered),
[](auto c){ return std::toupper(c); });
return uppered;
}
std::vector<std::string> SplitString(
std::string delim,
std::string input)
{
std::vector<std::string> words{};
size_t pos = 0;
while ((pos = input.find(delim)) != std::string::npos)
{
words.push_back(input.substr(0, pos));
input.erase(0, pos + delim.length());
}
if (!input.empty())
words.emplace_back(input);
return words;
}
| 719
|
C++
|
.cpp
| 29
| 19.896552
| 59
| 0.608504
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,292
|
demangle.cpp
|
xavieran_BaKGL/com/demangle.cpp
|
#include "com/demangle.hpp"
namespace com {
std::string demangle(const char* mangled)
{
#ifndef _MSC_VER
int status = 0;
std::unique_ptr<char[], void (*)(void*)> result(
abi::__cxa_demangle(mangled, 0, 0, &status), std::free);
return result.get() ? std::string(result.get()) : "error occurred";
#else
return mangled;
#endif
}
}
| 361
|
C++
|
.cpp
| 14
| 22.428571
| 73
| 0.645349
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,293
|
logger.cpp
|
xavieran_BaKGL/com/logger.cpp
|
#include "com/logger.hpp"
#include <iostream>
namespace Logging {
std::string_view LevelToString(LogLevel level)
{
switch (level)
{
case LogLevel::Spam: return "SPAM";
case LogLevel::Debug: return "DEBUG";
case LogLevel::Info: return "INFO";
case LogLevel::Warn: return "WARN";
case LogLevel::Error: return "ERROR";
case LogLevel::Fatal: return "FATAL";
case LogLevel::Always: return "ALWAYS";
default: return "UNDEF";
}
}
std::string_view LevelToColor(LogLevel level)
{
switch (level)
{
case LogLevel::Spam: [[fallthrough]];
case LogLevel::Debug: return "\033[0;37m";
case LogLevel::Info: return "\033[1;34m";
case LogLevel::Warn: return "\033[1;33m";
case LogLevel::Error: return "\033[1;31m";
case LogLevel::Fatal: [[fallthrough]];
case LogLevel::Always: return "\033[1;4;31m";
default: return "UNDEF";
}
}
LogLevel LogState::sGlobalLogLevel{LogLevel::Info};
std::string LogState::sTimeFormat{"%H:%M:%S.%m"};
bool LogState::sLogTime{true};
bool LogState::sLogColor{false};
std::vector<std::string> LogState::sEnabledLoggers{};
std::vector<std::string> LogState::sDisabledLoggers{};
std::vector<std::unique_ptr<Logger>> LogState::sLoggers{};
OStreamMux LogState::sMux{};
std::ostream LogState::sOutput{&LogState::sMux};
std::ostream LogState::nullStream{nullptr};
std::ostream& LogFatal(const std::string& loggerName)
{
return LogState::Log(Logging::LogLevel::Fatal, loggerName);
}
std::ostream& LogError(const std::string& loggerName)
{
return LogState::Log(Logging::LogLevel::Error, loggerName);
}
std::ostream& LogWarn(const std::string& loggerName)
{
return LogState::Log(Logging::LogLevel::Warn, loggerName);
}
std::ostream& LogInfo(const std::string& loggerName)
{
return LogState::Log(Logging::LogLevel::Info, loggerName);
}
std::ostream& LogDebug(const std::string& loggerName)
{
return LogState::Log(Logging::LogLevel::Debug, loggerName);
}
std::ostream& LogSpam(const std::string& loggerName)
{
return LogState::Log(Logging::LogLevel::Spam, loggerName);
}
}
| 2,114
|
C++
|
.cpp
| 66
| 29.106061
| 63
| 0.715339
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,294
|
random.cpp
|
xavieran_BaKGL/com/random.cpp
|
#include "com/random.hpp"
#include <random>
unsigned GetRandomNumber(unsigned min, unsigned max)
{
static std::random_device random_device;
static std::mt19937 engine{random_device()};
std::uniform_int_distribution<> dist(min, max);
return dist(engine);
}
| 274
|
C++
|
.cpp
| 9
| 27.444444
| 52
| 0.741445
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,295
|
path.cpp
|
xavieran_BaKGL/com/path.cpp
|
#include "com/path.hpp"
std::string GetHomeDirectory()
{
#ifdef _MSC_VER
constexpr auto homeVar = "APPDATA";
#else
constexpr auto homeVar = "HOME";
#endif
auto* home = getenv(homeVar);
if (home == nullptr)
{
throw std::runtime_error("No " + std::string{homeVar} + " environment variable set.");
}
return std::string{home};
}
std::filesystem::path GetBakDirectoryPath()
{
return std::filesystem::path{GetHomeDirectory()} / "bak";
}
std::string GetBakDirectory()
{
return GetBakDirectoryPath().string();
}
| 554
|
C++
|
.cpp
| 23
| 20.913043
| 94
| 0.68251
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,296
|
ostreamMux.cpp
|
xavieran_BaKGL/com/ostreamMux.cpp
|
#include "com/ostreamMux.hpp"
#include <algorithm>
#include <string>
OStreamMux::OStreamMux()
:
mOutputs{&std::cout}
{}
std::streamsize OStreamMux::xsputn(const char_type* s, std::streamsize n)
{
const auto str = std::string{
s,
static_cast<unsigned>(n)};
for (auto* stream : mOutputs)
(*stream) << str;
return n;
}
OStreamMux::int_type OStreamMux::overflow(int_type c)
{
for (auto* stream : mOutputs)
(*stream) << static_cast<char>(c);
return c;
}
void OStreamMux::AddStream(std::ostream* stream)
{
mOutputs.emplace_back(stream);
}
void OStreamMux::RemoveStream(std::ostream* stream)
{
auto it = std::find(mOutputs.begin(), mOutputs.end(), stream);
if (it != mOutputs.end())
mOutputs.erase(it);
}
| 784
|
C++
|
.cpp
| 32
| 20.8125
| 73
| 0.66442
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,298
|
sprites.cpp
|
xavieran_BaKGL/graphics/sprites.cpp
|
#include "graphics/sprites.hpp"
#include "com/assert.hpp"
#include "com/logger.hpp"
#include <GL/glew.h>
#include <memory>
#include <optional>
#include <vector>
namespace Graphics {
Sprites::Sprites() noexcept
:
mNonSpriteObjects{1},
mVertexArray{},
mBuffers{},
mTextureBuffer{GL_TEXTURE_2D_ARRAY},
mObjects{},
mSpriteDimensions{}
{
}
Sprites::Sprites(Sprites&& other) noexcept
:
mTextureBuffer{GL_TEXTURE_2D_ARRAY}
{
(*this) = std::move(other);
}
Sprites& Sprites::operator=(Sprites&& other) noexcept
{
if (this == &other) return *this;
this->mNonSpriteObjects = std::move(other.mNonSpriteObjects);
this->mVertexArray = std::move(other.mVertexArray);
this->mBuffers = std::move(other.mBuffers);
this->mTextureBuffer = std::move(other.mTextureBuffer);
this->mObjects = other.mObjects;
this->mSpriteDimensions = other.mSpriteDimensions;
return *this;
}
void Sprites::BindGL() const
{
mVertexArray.BindGL();
// FIXME!!! blergh...
glActiveTexture(GL_TEXTURE0);
mTextureBuffer.BindGL();
}
void Sprites::UnbindGL() const
{
mVertexArray.UnbindGL();
mTextureBuffer.UnbindGL();
}
void Sprites::LoadTexturesGL(const TextureStore& textures)
{
mTextureBuffer.LoadTexturesGL(
textures.GetTextures(),
textures.GetMaxDim());
// Normal quad for use as arbitrary rectangle
mObjects.AddObject(Quad{1.0, 1.0, 1.0, 0});
// This is why mNonSpriteObjects = 1;
for (unsigned i = 0; i < textures.GetTextures().size(); i++)
{
const auto& tex = textures.GetTexture(i);
mObjects.AddObject(
Quad{
static_cast<double>(tex.GetWidth()),
static_cast<double>(tex.GetHeight()),
static_cast<double>(textures.GetMaxDim()),
i});
mSpriteDimensions.emplace_back(
tex.GetWidth(),
tex.GetHeight());
}
mVertexArray.BindGL();
mBuffers.AddStaticArrayBuffer<glm::vec3>("vertex", GLLocation{0});
mBuffers.AddStaticArrayBuffer<glm::vec3>("textureCoord", GLLocation{1});
mBuffers.AddElementBuffer("elements");
mBuffers.LoadBufferDataGL("vertex", mObjects.mVertices);
mBuffers.LoadBufferDataGL("textureCoord", mObjects.mTextureCoords);
mBuffers.LoadBufferDataGL("elements", mObjects.mIndices);
mBuffers.BindArraysGL();
UnbindGL();
}
std::size_t Sprites::size()
{
return mSpriteDimensions.size();
}
glm::vec2 Sprites::GetDimensions(unsigned i) const
{
ASSERT(i < mSpriteDimensions.size());
return mSpriteDimensions[i];
}
void DestroySpriteSheet::operator()(TemporarySpriteHandle* handle)
{
assert(handle->mManager);
handle->mManager->RemoveSpriteSheet(handle->mSpriteSheet);
delete handle;
}
SpriteManager::SpriteManager()
:
mSprites(),
mNextSpriteSheet{0},
mActiveSpriteSheet{}
{
}
SpriteSheetIndex SpriteManager::AddSpriteSheet()
{
const auto& logger = Logging::LogState::GetLogger("SpriteManager");
const auto spriteSheetIndex = NextSpriteSheet();
logger.Debug() << "Adding sprite sheet index: " << spriteSheetIndex << "\n";
mSprites.emplace(spriteSheetIndex, Sprites{});
return spriteSheetIndex;
}
SpriteManager::TemporarySpriteSheet SpriteManager::AddTemporarySpriteSheet()
{
return TemporarySpriteSheet(new TemporarySpriteHandle{this, AddSpriteSheet()});
}
void SpriteManager::RemoveSpriteSheet(SpriteSheetIndex index)
{
const auto& logger = Logging::LogState::GetLogger("SpriteManager");
logger.Debug() << "Removing sprite sheet index: " << index << std::endl;
DeactivateSpriteSheet();
mSprites.erase(index);
}
void SpriteManager::DeactivateSpriteSheet()
{
if (mActiveSpriteSheet)
{
GetSpriteSheet(*mActiveSpriteSheet).UnbindGL();
mActiveSpriteSheet = std::optional<SpriteSheetIndex>{};
}
}
void SpriteManager::ActivateSpriteSheet(SpriteSheetIndex spriteSheet)
{
if (!mActiveSpriteSheet || spriteSheet != *mActiveSpriteSheet)
{
GetSpriteSheet(spriteSheet).BindGL();
mActiveSpriteSheet = spriteSheet;
}
}
Sprites& SpriteManager::GetSpriteSheet(SpriteSheetIndex spriteSheet)
{
ASSERT(mSprites.contains(spriteSheet));
return mSprites.find(spriteSheet)->second;
}
SpriteSheetIndex SpriteManager::NextSpriteSheet()
{
return Graphics::SpriteSheetIndex{mNextSpriteSheet++};
}
}
| 4,398
|
C++
|
.cpp
| 145
| 26.096552
| 83
| 0.718009
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,299
|
guiTypes.cpp
|
xavieran_BaKGL/graphics/guiTypes.cpp
|
#include "graphics/guiTypes.hpp"
#include "graphics/glm.hpp"
namespace Graphics {
std::ostream& operator<<(std::ostream& os, const ColorMode& dm)
{
switch (dm)
{
case ColorMode::Texture: return os << "Texture";
case ColorMode::SolidColor: return os << "SolidColor";
case ColorMode::TintColor: return os << "TintColor";
case ColorMode::ReplaceColor: return os << "ReplaceColor";
default: return os << "Unknown";
}
}
std::ostream& operator<<(std::ostream& os, const DrawMode& dm)
{
switch (dm)
{
case DrawMode::Rect: return os << "Rect";
case DrawMode::Sprite: return os << "Sprite";
case DrawMode::ClipRegion: return os << "ClipRegion";
default: return os << "Unknown";
}
}
std::ostream& operator<<(std::ostream& os, const DrawInfo& di)
{
os << "DrawInfo={ dm: " << di.mDrawMode << ", ss: " << di.mSpriteSheet
<< " , tex: " << di.mTexture << ", cm: " << di.mColorMode << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const PositionInfo& pi)
{
os << "PositionInfo={ pos: " << pi.mPosition
<< ", scale: " << pi.mDimensions
<< ", rotation: " << glm::degrees(pi.mRotation)
<< " , childRel: " << pi.mChildrenRelative
<< "}";
return os;
}
}
| 1,292
|
C++
|
.cpp
| 40
| 28.2
| 75
| 0.605305
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,300
|
meshObject.cpp
|
xavieran_BaKGL/graphics/meshObject.cpp
|
#include "graphics/meshObject.hpp"
#include "graphics/sphere.hpp"
namespace Graphics {
MeshObject SphereToMeshObject(const Sphere& sphere, glm::vec4 color)
{
std::vector<glm::vec3> vertices{};
std::vector<glm::vec3> normals{};
std::vector<glm::vec4> colors{};
std::vector<glm::vec3> textureCoords{};
std::vector<float> textureBlends{};
std::vector<unsigned> indices{};
auto sVertices = sphere.getVertices();
auto sNormals = sphere.getNormals();
auto sIndices = sphere.getIndices();
for (unsigned i = 0; i < sphere.getIndexCount(); i++)
{
indices.emplace_back(i);
vertices.emplace_back(
sVertices[sIndices[i] * 3],
sVertices[sIndices[i] * 3 + 1],
sVertices[sIndices[i] * 3 + 2]);
normals.emplace_back(
sNormals[sIndices[i] * 3],
sNormals[sIndices[i] * 3 + 1],
sNormals[sIndices[i] * 3 + 2]);
colors.emplace_back(color);
textureCoords.emplace_back(0,0,0);
textureBlends.emplace_back(0);
}
return MeshObject{
vertices,
normals,
colors,
textureCoords,
textureBlends,
indices};
}
}
| 1,210
|
C++
|
.cpp
| 38
| 24.736842
| 68
| 0.609966
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,301
|
IGuiElement.cpp
|
xavieran_BaKGL/graphics/IGuiElement.cpp
|
#include "graphics/IGuiElement.hpp"
#include "com/assert.hpp"
#include <algorithm>
namespace Graphics {
IGuiElement::IGuiElement()
:
mChildren{}
{}
const std::vector<IGuiElement*>&
IGuiElement::GetChildren() const
{
return mChildren;
}
IGuiElement::~IGuiElement()
{
}
void IGuiElement::AddChildFront(Graphics::IGuiElement* elem)
{
mChildren.insert(mChildren.begin(), elem);
}
void IGuiElement::AddChildBack(Graphics::IGuiElement* elem)
{
mChildren.emplace_back(elem);
}
void IGuiElement::RemoveChild(Graphics::IGuiElement* elem)
{
const auto it = std::find(mChildren.begin(), mChildren.end(), elem);
ASSERT(it != mChildren.end());
mChildren.erase(it);
}
void IGuiElement::ClearChildren()
{
mChildren.clear();
}
std::ostream& operator<<(std::ostream& os, const IGuiElement& element)
{
os << "Element: { " << element.GetDrawInfo() << ", "
<< element.GetPositionInfo() << "}";
return os;
}
}
| 940
|
C++
|
.cpp
| 41
| 20.707317
| 72
| 0.726862
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,302
|
opengl.cpp
|
xavieran_BaKGL/graphics/opengl.cpp
|
#include "graphics/opengl.hpp"
#include "graphics/texture.hpp"
#include "com/assert.hpp"
#include "com/logger.hpp"
#include <GL/glew.h>
#include <cmath>
namespace Graphics {
GLenum ToGlEnum(GLBindPoint p)
{
switch (p)
{
case GLBindPoint::ArrayBuffer: return GL_ARRAY_BUFFER;
case GLBindPoint::ElementArrayBuffer: return GL_ELEMENT_ARRAY_BUFFER;
case GLBindPoint::TextureBuffer: return GL_TEXTURE_BUFFER;
default: ASSERT(false); return GL_ARRAY_BUFFER;
}
}
GLenum ToGlEnum(GLUpdateType p)
{
switch (p)
{
case GLUpdateType::StaticDraw: return GL_STATIC_DRAW;
case GLUpdateType::DynamicDraw: return GL_DYNAMIC_DRAW;
default: ASSERT(false); return GL_STATIC_DRAW;
}
}
VertexArrayObject::VertexArrayObject()
:
mVertexArrayId{GenVertexArrayGL()},
mActive{true}
{}
VertexArrayObject::VertexArrayObject(VertexArrayObject&& other) noexcept
{
(*this) = std::move(other);
}
VertexArrayObject& VertexArrayObject::operator=(VertexArrayObject&& other) noexcept
{
if (this == &other) return *this;
other.mVertexArrayId = mVertexArrayId;
other.mActive = false;
return *this;
}
VertexArrayObject::~VertexArrayObject()
{
if (mActive)
{
Logging::LogDebug("GLBuffers") << "Deleting GL vertex array id: " << mVertexArrayId << "\n";
glDeleteVertexArrays(1, &mVertexArrayId);
}
}
void VertexArrayObject::BindGL() const
{
glBindVertexArray(mVertexArrayId);
}
void VertexArrayObject::UnbindGL() const
{
glBindVertexArray(0);
}
GLuint VertexArrayObject::GenVertexArrayGL()
{
GLuint vertexArrayId;
glGenVertexArrays(1, &vertexArrayId);
return vertexArrayId;
}
GLBuffers::GLBuffers()
:
mBuffers{},
mElementBuffer{GenBufferGL().mValue},
mActive{true}
{
}
GLBuffers::GLBuffers(GLBuffers&& other) noexcept
{
(*this) = std::move(other);
}
GLBuffers& GLBuffers::operator=(GLBuffers&& other) noexcept
{
if (this == &other) return *this;
for (const auto& [name, buffer] : mBuffers)
mBuffers.emplace(name, buffer);
other.mActive = false;
return *this;
}
GLBuffers::~GLBuffers()
{
if (mActive)
{
Logging::LogDebug("GLBuffers") << "Deleting GL buffers" << std::endl;
for (const auto& [name, buffer] : mBuffers)
{
Logging::LogDebug("GLBuffers") << " Deleting buffer: "
<< name << std::endl;
glDeleteBuffers(1, &buffer.mBuffer.mValue);
}
}
}
void GLBuffers::AddBuffer(
const std::string& name,
GLLocation location,
GLElems elems,
GLDataType dataType,
GLBindPoint bindPoint,
GLUpdateType updateType)
{
mBuffers.emplace(
name,
GLBuffer{
location,
elems,
bindPoint,
dataType,
updateType,
GenBufferGL()});
BindAttribArrayGL(GetGLBuffer(name));
}
void GLBuffers::AddElementBuffer(
const std::string& name)
{
AddBuffer(name, GLNullLocation, GLElems{1}, GLDataType{GL_UNSIGNED_INT}, GLBindPoint::ElementArrayBuffer, GLUpdateType::StaticDraw);
}
void GLBuffers::AddTextureBuffer(
const std::string& name)
{
AddBuffer(name, GLNullLocation, GLElems{4}, GLDataType{GL_FLOAT}, GLBindPoint::TextureBuffer, GLUpdateType::DynamicDraw);
}
GLBufferId GLBuffers::GenBufferGL()
{
GLuint buffer;
glGenBuffers(1, &buffer);
return GLBufferId{buffer};
}
void GLBuffers::BindAttribArrayGL(const GLBuffer& buffer)
{
if (buffer.mLocation != GLNullLocation)
{
glEnableVertexAttribArray(buffer.mLocation.mValue);
glBindBuffer(ToGlEnum(buffer.mGLBindPoint), buffer.mBuffer.mValue);
glVertexAttribPointer(
buffer.mLocation.mValue,
buffer.mElems.mValue,
buffer.mDataType.mValue,
GL_FALSE, // normalized?
0, // stride
(void*) 0 // array buffer offset
);
}
else
{
glBindBuffer(ToGlEnum(buffer.mGLBindPoint), buffer.mBuffer.mValue);
}
}
void GLBuffers::BindArraysGL()
{
for (const auto& [name, buffer] : mBuffers)
{
BindAttribArrayGL(buffer);
}
}
TextureBuffer::TextureBuffer(
GLuint textureType)
:
mTextureBuffer{
std::invoke([](){
unsigned texture;
glGenTextures(1, &texture);
return texture;
})
},
mTextureType{textureType},
mActive{true}
{}
TextureBuffer::TextureBuffer(TextureBuffer&& other) noexcept
{
(*this) = std::move(other);
}
TextureBuffer& TextureBuffer::operator=(TextureBuffer&& other) noexcept
{
other.mTextureBuffer = mTextureBuffer;
other.mTextureType = mTextureType;
other.mActive = false;
return *this;
}
TextureBuffer::~TextureBuffer()
{
if (mActive)
{
Logging::LogDebug("GLBuffers") << "Deleting GL texture buffer id: " << mTextureBuffer<< "\n";
glDeleteTextures(1, &mTextureBuffer);
}
}
GLuint TextureBuffer::GetId() const
{
return mTextureBuffer;
}
void TextureBuffer::BindGL() const
{
glBindTexture(mTextureType, mTextureBuffer);
}
void TextureBuffer::UnbindGL() const
{
glBindTexture(mTextureType, 0);
}
void TextureBuffer::MakeDepthBuffer(unsigned width, unsigned height)
{
ASSERT(mTextureType == GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
BindGL();
glTexImage2D(mTextureType, 0, GL_DEPTH_COMPONENT,
width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
glTexParameteri(mTextureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(mTextureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(mTextureType, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(mTextureType, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
void TextureBuffer::MakePickBuffer(unsigned width, unsigned height)
{
ASSERT(mTextureType == GL_TEXTURE_2D);
BindGL();
glTexImage2D(
mTextureType, 0,
GL_RGBA32F,
width, height, 0,
GL_RGBA, GL_FLOAT, nullptr);
glTexParameteri(mTextureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(mTextureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
//void TextureBuffer::MakeTexture2DArray()
//{
// BindGL();
//
// glTexStorage3D(
// mTextureType,
// 1, // levels
// GL_RGBA8, // Internal format
// maxDim, maxDim, // width,height
// sMaxTextures // Number of layers
// );
//}
void TextureBuffer::LoadTexturesGL(
const std::vector<Texture>& textures,
unsigned maxDim)
{
if (textures.size() > sMaxTextures)
throw std::runtime_error("Too many textures");
BindGL();
glTexStorage3D(
mTextureType,
1, // levels
GL_RGBA8, // Internal format
maxDim, maxDim, // width,height
sMaxTextures // Number of layers
);
unsigned index = 0;
for (const auto& tex : textures)
{
std::vector<glm::vec4> paddedTex(
maxDim * maxDim,
glm::vec4{0});
// Chuck the image in the padded sized texture
// GetPixel() will wrap and fill the texture
for (unsigned x = 0; x < maxDim; x++)
for (unsigned y = 0; y < maxDim; y++)
paddedTex[x + y * maxDim] = tex.GetPixel(x, y);
glTexSubImage3D(
mTextureType,
0, // Mipmap number
0, 0, index, // xoffset, yoffset, zoffset
maxDim, maxDim, 1, // width, height, depth
GL_RGBA, // format
GL_FLOAT, // type
paddedTex.data()); // pointer to data
index++;
}
// Doesn't actually look very good with mipmaps...
//glGenerateMipmap(mTextureType);
constexpr auto interpolation = GL_NEAREST;
//constexpr auto interpolation = GL_LINEAR;
constexpr auto extend = GL_REPEAT;
//constexpr auto extend = GL_CLAMP_TO_BORDER;
glTexParameteri(mTextureType, GL_TEXTURE_WRAP_S, extend);
glTexParameteri(mTextureType, GL_TEXTURE_WRAP_T, extend);
glTexParameteri(mTextureType, GL_TEXTURE_MIN_FILTER, interpolation);
glTexParameteri(mTextureType, GL_TEXTURE_MAG_FILTER, interpolation);
UnbindGL();
}
}
| 8,250
|
C++
|
.cpp
| 286
| 23.79021
| 136
| 0.662955
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,303
|
shaderProgram.cpp
|
xavieran_BaKGL/graphics/shaderProgram.cpp
|
#include "graphics/shaderProgram.hpp"
#include "shaders/shaders.hpp"
#include "com/path.hpp"
#include <glm/gtc/type_ptr.hpp>
#include <filesystem>
#include <fstream>
#include <iostream>
namespace {
static const std::vector<std::filesystem::path> sSearchPaths{
".shaders",
"shaders",
std::filesystem::path{"bak"} / "shaders",
"C:/Users/xavieran/source/repos/xavieran/BaKGL/shaders"
};
auto MakeSearchPath(std::filesystem::path aPath)
{
const auto home = GetHomeDirectory();
auto fullPath = std::filesystem::path{home} / aPath;
return fullPath;
}
}
std::string ShaderTypeToString(GLenum shaderType)
{
switch (shaderType)
{
case GL_VERTEX_SHADER: return "VertexShader";
case GL_GEOMETRY_SHADER: return "GeometryShader";
case GL_FRAGMENT_SHADER: return "FragmentShader";
default: return "UnknownShader";
}
}
ShaderProgramHandle::ShaderProgramHandle(GLuint handle)
:
mHandle{handle}
{}
ShaderProgramHandle& ShaderProgramHandle::operator=(ShaderProgramHandle&& other) noexcept
{
mHandle = other.mHandle;
other.mHandle = 0;
return *this;
}
ShaderProgramHandle::ShaderProgramHandle(ShaderProgramHandle&& other) noexcept
{
mHandle = other.mHandle;
other.mHandle = 0;
}
void ShaderProgramHandle::UseProgramGL() const
{
glUseProgram(GetHandle());
}
void ShaderProgramHandle::SetUniform(GLuint id, const glm::mat4& value)
{
glUniformMatrix4fv(id, 1, GL_FALSE, glm::value_ptr(value));
}
void ShaderProgramHandle::SetUniform(GLuint id, int value)
{
glUniform1i(id, value);
}
void ShaderProgramHandle::SetUniform(GLuint id, unsigned value)
{
glUniform1ui(id, value);
}
void ShaderProgramHandle::SetUniform(GLuint id, Float value)
{
glUniform1f(id, value.mValue);
}
void ShaderProgramHandle::SetUniform(GLuint id, const glm::vec3& value)
{
glUniform3f(id, value.x, value.y, value.z);
}
void ShaderProgramHandle::SetUniform(GLuint id, const glm::vec4& value)
{
glUniform4f(id, value.r, value.g, value.b, value.a);
}
ShaderProgramHandle::~ShaderProgramHandle()
{
glDeleteProgram(mHandle);
mHandle = 0;
}
GLuint ShaderProgramHandle::GetUniformLocation(const std::string& name) const
{
return glGetUniformLocation(
mHandle,
name.c_str());
}
GLuint ShaderProgramHandle::GetHandle() const
{
return mHandle;
}
ShaderProgram::ShaderProgram(
const std::string& vertexShader,
const std::string& fragmentShader)
:
ShaderProgram(
vertexShader,
std::optional<std::string>{},
fragmentShader)
{}
ShaderProgram::ShaderProgram(
const std::string& vertexShader,
const std::optional<std::string>& geometryShader,
const std::string& fragmentShader)
:
mVertexShader{vertexShader},
mGeometryShader{geometryShader},
mFragmentShader{fragmentShader},
mProgramId{0},
mLogger{Logging::LogState::GetLogger("ShaderProgram")}
{}
ShaderProgramHandle ShaderProgram::Compile()
{
std::vector<GLuint> shaders{};
shaders.emplace_back(CompileShader(mVertexShader, GL_VERTEX_SHADER));
if (mGeometryShader)
shaders.emplace_back(CompileShader(*mGeometryShader, GL_GEOMETRY_SHADER));
shaders.emplace_back(CompileShader(mFragmentShader, GL_FRAGMENT_SHADER));
GLuint programId = glCreateProgram();
mLogger.Debug() << "Linking shader program: " << mVertexShader
<< " with Id: " << programId << "\n";
for (auto shaderId : shaders)
glAttachShader(programId, shaderId);
glLinkProgram(programId);
GLint result = GL_FALSE;
int infoLogLength = 0;
glGetProgramiv(programId, GL_LINK_STATUS, &result);
glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 0 || result == GL_FALSE)
{
std::vector<char> programErrorMessage(infoLogLength + 1);
glGetProgramInfoLog(programId, infoLogLength, NULL, &programErrorMessage[0]);
mLogger.Error() << "ProgramErrorMessage: " << &programErrorMessage[0] << std::endl;
throw std::runtime_error("Could not link shader program");
}
for (auto shaderId : shaders)
{
glDetachShader(programId, shaderId);
glDeleteShader(shaderId);
}
mProgramId = programId;
return ShaderProgramHandle{programId};
}
GLuint ShaderProgram::GetProgramId() const
{
return mProgramId;
}
GLuint ShaderProgram::CompileShader(const std::string& shader, GLenum shaderType)
{
auto shaderId = glCreateShader(shaderType);
GLint result = GL_FALSE;
int infoLogLength = 0;
auto shaderFile = LoadFileContents(shader);
char const* shaderSrc = shaderFile.c_str();
glShaderSource(shaderId, 1, &shaderSrc, nullptr);
glCompileShader(shaderId);
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &result);
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 0 || result == GL_FALSE)
{
std::vector<char> shaderErrorMessage(infoLogLength + 1);
glGetShaderInfoLog(shaderId, infoLogLength, NULL, &shaderErrorMessage[0]);
mLogger.Error() << ShaderTypeToString(shaderType) << "Error: "
<< &shaderErrorMessage[0] << std::endl;
throw std::runtime_error("Could not compile shader");
}
return shaderId;
}
std::optional<std::string> ShaderProgram::FindFile(const std::string& shaderPath)
{
for (const auto& searchPath : sSearchPaths)
{
const auto fullPath = MakeSearchPath(searchPath) / shaderPath;
if (std::filesystem::exists(fullPath))
return fullPath.string();
}
return std::nullopt;
}
std::string ShaderProgram::LoadFileContents(const std::string& path)
{
auto fullPath = FindFile(path);
if (!fullPath)
{
auto contents = Shaders::GetFile(path);
if (contents)
{
Logging::LogInfo(__FUNCTION__) << "Loaded precompiled shader contents for file: " << path << "\n";
return *contents;
}
std::stringstream err{};
err << "Could not find shader file ["
<< path << "] in shader search directories [";
std::string c = "";
for (const auto& path : sSearchPaths)
{
err << c << MakeSearchPath(path).string();
c = ", ";
}
err << "]\n";
err << "Please place or link the files in BaKGL/shaders in the search path.";
throw std::runtime_error{err.str()};
}
std::ifstream in{};
in.open(*fullPath, std::ios::in);
if (!in.good())
{
std::stringstream err{};
err << "Could not open file: " << *fullPath << std::endl;
throw std::runtime_error{err.str()};
}
std::string contents{
(std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>()};
in.close();
return contents;
}
| 6,835
|
C++
|
.cpp
| 214
| 27.121495
| 110
| 0.690832
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,304
|
glfw.cpp
|
xavieran_BaKGL/graphics/glfw.cpp
|
#include "graphics/glfw.hpp"
#include "com/logger.hpp"
#include <stdexcept>
namespace Graphics {
void GLAPIENTRY OpenGlMessageCallback(
GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam)
{
const auto GetLogLevel = [](GLenum level)
{
if (level == GL_DEBUG_SEVERITY_NOTIFICATION)
return Logging::LogLevel::Spam;
else if (level == GL_DEBUG_SEVERITY_LOW)
return Logging::LogLevel::Debug;
else if (level == GL_DEBUG_SEVERITY_MEDIUM)
return Logging::LogLevel::Info;
else
return Logging::LogLevel::Fatal;
};
const auto logLevel = GetLogLevel(severity);
static const auto& logger = Logging::LogState::GetLogger("OpenGL");
logger.Log(logLevel) << " type = 0x" << std::hex
<< type << " severity = 0x" << severity << std::dec
<< " message = " << message << std::endl;
//if (type == GL_DEBUG_TYPE_ERROR)
// throw std::runtime_error("OpenGL Error");
}
std::unique_ptr<GLFWwindow, DestroyGlfwWindow> MakeGlfwWindow(
unsigned height,
unsigned width,
std::string_view title)
{
const auto logger = Logging::LogState::GetLogger("GLFW");
glfwSetErrorCallback([](int error, const char* desc){ puts(desc); });
if( !glfwInit() )
{
logger.Error() << "Failed to initialize GLFW" << std::endl;
throw std::runtime_error("Failed to initialize GLFW");
}
GLFWwindow* window{nullptr};
constexpr auto antiAliasingSamples = 4;
glfwWindowHint(GLFW_SAMPLES, antiAliasingSamples);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(width, height, title.data(), nullptr, nullptr);
if( window == nullptr)
{
logger.Log(Logging::LogLevel::Error) << "Failed to open GLFW window" << std::endl;
glfwTerminate();
throw std::runtime_error("Failed to open GLFW window");
}
glfwMakeContextCurrent(window);
glewExperimental = true;
if (glewInit() != GLEW_OK)
{
logger.Log(Logging::LogLevel::Error) << "Failed to initialize GLEW" << std::endl;
glfwTerminate();
throw std::runtime_error("Failed to initialize GLEW");
}
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(OpenGlMessageCallback, 0);
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, GLFW_TRUE);
return std::unique_ptr<GLFWwindow, DestroyGlfwWindow>{window};
}
}
| 2,682
|
C++
|
.cpp
| 72
| 31.402778
| 90
| 0.667823
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,305
|
inputHandler.cpp
|
xavieran_BaKGL/graphics/inputHandler.cpp
|
#include "graphics/inputHandler.hpp"
#include "com/assert.hpp"
#include <functional>
namespace Graphics {
InputHandler::InputHandler() noexcept
:
mHandleInput{true},
mKeyBindings{},
mCharacterCallback{},
mMouseBindings{},
mMouseMovedBinding{},
mMouseScrolledBinding{}
{}
void InputHandler::BindMouseToWindow(GLFWwindow* window, InputHandler& handler)
{
sHandler = &handler;
glfwSetMouseButtonCallback(window, InputHandler::MouseAction);
glfwSetCursorPosCallback(window, InputHandler::MouseMotionAction);
glfwSetScrollCallback(window, InputHandler::MouseScrollAction);
}
void InputHandler::BindKeyboardToWindow(GLFWwindow* window, InputHandler& handler)
{
sHandler = &handler;
glfwSetCharCallback(window, InputHandler::CharacterAction);
//glfwSetKeyCallback(window, InputHandler::KeyboardAction);
}
void InputHandler::Bind(int key, KeyCallback&& callback)
{
mKeyBindings.emplace(key, std::move(callback));
}
void InputHandler::BindCharacter(CharacterCallback&& callback)
{
mCharacterCallback = std::move(callback);
}
void InputHandler::BindMouse(int button, MouseCallback&& pressed, MouseCallback&& released)
{
mMouseBindings.emplace(button,
std::make_pair(
std::move(pressed),
std::move(released)));
}
void InputHandler::BindMouseMotion(MouseCallback&& moved)
{
mMouseMovedBinding = std::move(moved);
}
void InputHandler::BindMouseScroll(MouseCallback&& scrolled)
{
mMouseScrolledBinding = std::move(scrolled);
}
void InputHandler::HandleInput(GLFWwindow* window)
{
if (mHandleInput)
{
for (const auto& keyVal : mKeyBindings)
{
if (glfwGetKey(window, keyVal.first) == GLFW_PRESS)
{
std::invoke(keyVal.second);
}
}
}
}
void InputHandler::HandleMouseCallback(GLFWwindow* window, int button, int action, int mods)
{
if (mHandleInput)
{
const auto it = mMouseBindings.find(button);
if (it != mMouseBindings.end())
{
if (action == GLFW_PRESS)
{
double pointerX, pointerY;
glfwGetCursorPos(window, &pointerX, &pointerY);
std::invoke(it->second.first, glm::vec2{pointerX, pointerY});
}
else if (action == GLFW_RELEASE)
{
double pointerX, pointerY;
glfwGetCursorPos(window, &pointerX, &pointerY);
std::invoke(it->second.second, glm::vec2{pointerX, pointerY});
}
}
}
}
void InputHandler::HandleMouseMotionCallback(GLFWwindow* window, double xpos, double ypos)
{
if (mMouseMovedBinding)
std::invoke(mMouseMovedBinding, glm::vec2{xpos, ypos});
}
void InputHandler::HandleMouseScrollCallback(GLFWwindow* window, double xpos, double ypos)
{
if (mMouseScrolledBinding)
std::invoke(mMouseScrolledBinding, glm::vec2{xpos, ypos});
}
void InputHandler::HandleKeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (mHandleInput)
{
const auto it = mKeyBindings.find(key);
if (it != mKeyBindings.end())
{
if (action == GLFW_PRESS)
{
std::invoke(it->second);
}
}
}
}
void InputHandler::HandleCharacterCallback(GLFWwindow* window, unsigned character)
{
if (mHandleInput)
{
if (mCharacterCallback)
{
mCharacterCallback(character & 0xff);
}
}
}
void InputHandler::HandleMouseInput(GLFWwindow* window)
{
if (mHandleInput)
{
double pointerX, pointerY;
glfwGetCursorPos(window, &pointerX, &pointerY);
for (const auto& keyVal : mMouseBindings)
{
if (glfwGetMouseButton(window, keyVal.first) == GLFW_PRESS)
std::invoke(keyVal.second.first, glm::vec2{pointerX, pointerY});
if (glfwGetMouseButton(window, keyVal.first) == GLFW_RELEASE)
std::invoke(keyVal.second.second, glm::vec2{pointerX, pointerY});
}
}
}
void InputHandler::MouseAction(GLFWwindow* window, int button, int action, int mods)
{
ASSERT(sHandler);
sHandler->HandleMouseCallback(window, button, action, mods);
}
void InputHandler::MouseMotionAction(GLFWwindow* window, double xpos, double ypos)
{
ASSERT(sHandler);
sHandler->HandleMouseMotionCallback(window, xpos, ypos);
}
void InputHandler::MouseScrollAction(GLFWwindow* window, double xpos, double ypos)
{
ASSERT(sHandler);
sHandler->HandleMouseScrollCallback(window, xpos, ypos);
}
void InputHandler::KeyboardAction(GLFWwindow* window, int key, int scancode, int action, int mods)
{
ASSERT(sHandler);
sHandler->HandleKeyboardCallback(window, key, scancode, action, mods);
}
void InputHandler::CharacterAction(GLFWwindow* window, unsigned character)
{
ASSERT(sHandler);
sHandler->HandleCharacterCallback(window, character);
}
InputHandler* InputHandler::sHandler = nullptr;
}
| 5,046
|
C++
|
.cpp
| 160
| 25.8375
| 106
| 0.686444
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,306
|
guiRenderer.cpp
|
xavieran_BaKGL/graphics/guiRenderer.cpp
|
#include "graphics/guiRenderer.hpp"
#include "com/assert.hpp"
#include <GL/glew.h>
#include <cmath>
namespace Graphics {
// Tightly coupled with the GUI shader
GuiCamera::GuiCamera(
float width,
float height,
float scale,
const ShaderProgramHandle& shader)
:
mWidth{width},
mHeight{height},
mScale{scale},
mScaleMatrix{
glm::scale(glm::mat4{1}, glm::vec3{scale, scale, 0})},
mViewMatrix{
glm::ortho(
0.0f,
width,
height,
0.0f,
-1.0f,
1.0f)},
mModelMatrix{glm::mat4{1.0f}},
mMVP{glm::mat4{1.0f}},
mMvpMatrixId{shader.GetUniformLocation("MVP")},
mModelMatrixId{shader.GetUniformLocation("M")},
mViewMatrixId{shader.GetUniformLocation("V")}
{
}
void GuiCamera::CalculateMatrices()
{
mScaleMatrix = glm::scale(
glm::mat4{1},
glm::vec3{mScale, mScale, 0});
mViewMatrix = glm::ortho(
0.0f,
mWidth,
mHeight,
0.0f,
-100.0f,
100.0f);
}
void GuiCamera::UpdateModelViewMatrix(const glm::mat4& modelMatrix)
{
mModelMatrix = modelMatrix;
mMVP = mViewMatrix * mScaleMatrix * mModelMatrix;
ShaderProgramHandle::SetUniform(mMvpMatrixId , mMVP);
ShaderProgramHandle::SetUniform(mModelMatrixId, mModelMatrix);
ShaderProgramHandle::SetUniform(mViewMatrixId , mViewMatrix);
}
void GuiCamera::ScissorRegion(glm::vec2 topLeft, glm::vec2 dimensions)
{
// Bottom in terms of glScissor is going to be:
// screenHeight - scaledBottom
// Because we need to account for the bottom starting
// at the height of the screen
glScissor(
topLeft.x * mScale,
mHeight - (topLeft.y + dimensions.y)*mScale,
dimensions.x * mScale,
dimensions.y * mScale);
glEnable(GL_SCISSOR_TEST);
}
void GuiCamera::DisableScissor()
{
glDisable(GL_SCISSOR_TEST);
}
GuiRenderer::GuiRenderer(
float width,
float height,
float scale,
SpriteManager& spriteManager)
:
mShader{ShaderProgram{vertexShader, fragmentShader}.Compile()},
mSpriteManager{spriteManager},
mDimensions{width, height, scale},
mCamera{
width,
height,
scale,
mShader
},
mBlockColorId{mShader.GetUniformLocation("blockColor")},
mColorModeId{mShader.GetUniformLocation("colorMode")},
mRenderCalls{0},
mLogger{Logging::LogState::GetLogger("GuiRenderer")}
{}
void GuiRenderer::RenderGui(
Graphics::IGuiElement* element)
{
glDisable(GL_DEPTH_TEST);
mShader.UseProgramGL();
mRenderCalls = 0;
mLogger.Spam() << "Beginning Render\n";
RenderGuiImpl(
glm::vec3{0},
element);
mLogger.Spam() << "Rendered Gui, Calls: " << mRenderCalls << "\n";
mSpriteManager.DeactivateSpriteSheet();
glEnable(GL_DEPTH_TEST);
}
void GuiRenderer::RenderGuiImpl(
glm::vec2 translate,
Graphics::IGuiElement* element)
{
mRenderCalls++;
ASSERT(element);
mLogger.Spam() << "Rendering GUI Element: [0x" << std::hex
<< element << std::dec << "] " << *element << "\n";
const auto& di = element->GetDrawInfo();
const auto& pi = element->GetPositionInfo();
auto finalPos = translate + pi.mPosition;
if (di.mDrawMode == DrawMode::ClipRegion)
{
mCamera.ScissorRegion(
finalPos,
pi.mDimensions);
}
else
{
mSpriteManager.ActivateSpriteSheet(di.mSpriteSheet);
const auto rotation = glm::mat4{
cosf(pi.mRotation), -sinf(pi.mRotation), 0, 0,
sinf(pi.mRotation), cos(pi.mRotation), 0, 0,
0,0,1,0,
0,0,0,1};
// FIXME: why are these different..?
//const auto rotation = glm::rotate(glm::mat4{1}, glm::degrees(pi.mRotation), glm::vec3{0,0,1});
const auto sprScale = glm::scale(glm::mat4{1}, glm::vec3{pi.mDimensions, 0});
const auto sprTrans = glm::translate(glm::mat4{1}, glm::vec3{finalPos, 0});
const auto modelMatrix = sprTrans * (rotation * sprScale);
const auto& sprites = mSpriteManager.GetSpriteSheet(di.mSpriteSheet);
const auto object = di.mDrawMode == DrawMode::Sprite
? sprites.Get(di.mTexture.mValue)
: sprites.GetRect();
Draw(
modelMatrix,
di.mColorMode,
di.mColor,
di.mTexture,
object);
}
for (auto* elem : element->GetChildren())
RenderGuiImpl(
pi.mChildrenRelative
? finalPos
: translate,
elem);
if (di.mDrawMode == DrawMode::ClipRegion)
mCamera.DisableScissor();
}
void GuiRenderer::Draw(
const glm::mat4& modelMatrix,
ColorMode colorMode,
const glm::vec4& blockColor,
TextureIndex texture,
std::tuple<unsigned, unsigned> object)
{
mCamera.UpdateModelViewMatrix(modelMatrix);
mShader.SetUniform(mColorModeId, static_cast<int>(colorMode));
mShader.SetUniform(mBlockColorId, blockColor);
const auto [offset, length] = object;
glDrawElementsBaseVertex(
GL_TRIANGLES,
length,
GL_UNSIGNED_INT,
(void*) (offset * sizeof(GLuint)),
offset
);
}
}
| 5,266
|
C++
|
.cpp
| 174
| 23.804598
| 104
| 0.639461
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,307
|
framebuffer.cpp
|
xavieran_BaKGL/graphics/framebuffer.cpp
|
#include "graphics/framebuffer.hpp"
#include "com/logger.hpp"
namespace Graphics {
FrameBuffer::FrameBuffer()
:
mFrameBufferId{GenFrameBufferGL()},
mActive{true}
{
}
FrameBuffer::FrameBuffer(FrameBuffer&& other) noexcept
{
(*this) = std::move(other);
}
FrameBuffer& FrameBuffer::operator=(FrameBuffer&& other) noexcept
{
other.mFrameBufferId = mFrameBufferId;
other.mActive = false;
return *this;
}
FrameBuffer::~FrameBuffer()
{
if (mActive)
{
Logging::LogDebug("GLBuffers") << "Deleting GL frame buffer id: " << mFrameBufferId << "\n";
glDeleteFramebuffers(1, &mFrameBufferId);
}
}
void FrameBuffer::BindGL() const
{
glBindFramebuffer(GL_FRAMEBUFFER, mFrameBufferId);
}
void FrameBuffer::UnbindGL() const
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void FrameBuffer::AttachDepthTexture(const Graphics::TextureBuffer& buffer, bool clearDrawBuffer) const
{
BindGL();
glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D,
buffer.GetId(),
0);
if (clearDrawBuffer)
{
glDrawBuffer(GL_NONE);
}
glReadBuffer(GL_NONE);
UnbindGL();
}
void FrameBuffer::AttachTexture(const Graphics::TextureBuffer& buffer) const
{
BindGL();
glFramebufferTexture(
GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
buffer.GetId(),
0);
GLenum drawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, drawBuffers);
UnbindGL();
}
GLuint FrameBuffer::GenFrameBufferGL()
{
GLuint framebufferId;
glGenFramebuffers(1, &framebufferId);
return framebufferId;
}
}
| 1,647
|
C++
|
.cpp
| 70
| 19.485714
| 103
| 0.701407
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,308
|
cutscenes.cpp
|
xavieran_BaKGL/bak/cutscenes.cpp
|
#include "bak/cutscenes.hpp"
#include <sstream>
namespace BAK {
std::vector<CutsceneAction> CutsceneList::GetStartScene(Chapter chapter)
{
std::vector<CutsceneAction> actions{};
std::stringstream ss{};
ss << "CHAPTER" << chapter.mValue;
actions.emplace_back(TTMScene{ss.str() + ".ADS", ss.str() + ".TTM"});
ss = {};
ss << "C" << chapter.mValue << "1";
actions.emplace_back(BookChapter{ss.str() + ".BOK"});
ss = {};
ss << "C" << chapter.mValue << "1";
actions.emplace_back(TTMScene{ss.str() + ".ADS", ss.str() + ".TTM"});
return actions;
}
std::vector<CutsceneAction> CutsceneList::GetFinishScene(Chapter chapter)
{
std::vector<CutsceneAction> actions{};
if (chapter == Chapter{10})
{
return actions;
}
std::stringstream ss{};
if (chapter == Chapter{2}
|| chapter == Chapter{4}
|| chapter == Chapter{6}
|| chapter == Chapter{7}
|| chapter == Chapter{8})
{
}
else
{
ss << "C" << chapter.mValue << "2";
actions.emplace_back(BookChapter{ss.str() + ".BOK"});
}
ss = {};
ss << "C" << chapter.mValue << "2";
actions.emplace_back(TTMScene{ss.str() + ".ADS", ss.str() + ".TTM"});
// Actually this is after the final battle
if (chapter == Chapter{9})
{
ss = {};
ss << "C" << chapter.mValue << "3";
actions.emplace_back(TTMScene{ss.str() + ".ADS", ss.str() + ".TTM"});
}
return actions;
}
}
| 1,494
|
C++
|
.cpp
| 50
| 24.6
| 77
| 0.567832
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,309
|
font.cpp
|
xavieran_BaKGL/bak/font.cpp
|
#include "bak/dataTags.hpp"
#include "bak/font.hpp"
#include "com/logger.hpp"
#include "graphics/texture.hpp"
namespace BAK {
Graphics::Texture GlyphToTexture(const Glyph& glyph)
{
auto data = Graphics::Texture::TextureType{};
for (int r = glyph.mHeight - 1; r >= 0; r--)
{
for (unsigned c = 0; c < glyph.mWidth; c++)
{
const auto pixel = (glyph.mPoints[r] & (0x8000 >> c))
? glm::vec4{0.0f, 0.0f, 0.0f, 1.0f}
: glm::vec4{0.0f, 0.0f, 0.0f, 0.0f};
data.push_back(pixel);
}
}
return Graphics::Texture{data, glyph.mWidth, glyph.mHeight};
}
Font LoadFont(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
auto fntBuf = fb.Find(DataTag::FNT);
const auto version = fntBuf.GetUint8();
const auto maxWidth = fntBuf.GetUint8();
const auto height = fntBuf.GetUint8();
const auto baseline = fntBuf.GetUint8();
const auto firstChar = fntBuf.GetUint8();
const auto numChars = fntBuf.GetUint8();
const auto dataLength = fntBuf.GetUint16LE();
if (fntBuf.GetUint8() != 0x01)
throw std::runtime_error("Expected font to be RLE compressed");
const auto decompSize = fntBuf.GetUint32LE();
auto glyphBuf = FileBuffer(decompSize);
fntBuf.DecompressRLE(&glyphBuf);
auto glyphOffsets = std::vector<unsigned>{};
for (auto i = 0; i < numChars; i++)
glyphOffsets.emplace_back(glyphBuf.GetUint16LE());
const auto glyphDataStart = glyphBuf.GetBytesDone();
auto glyphs = std::vector<Glyph>{};
auto textures = Graphics::TextureStore{};
for (auto i = 0; i < numChars; i++)
{
glyphBuf.Seek(glyphDataStart + i);
const auto width = glyphBuf.GetUint8();
glyphBuf.Seek(glyphDataStart + numChars + glyphOffsets[i]);
if (version == 0xff)
{
std::array<std::uint16_t, 16> points{};
for (auto j = 0; j < height; j++)
{
points[j] = static_cast<std::uint16_t>(glyphBuf.GetUint8()) << 8;
if (width > 8)
points[j] |= static_cast<std::uint16_t>(glyphBuf.GetUint8());
}
textures.AddTexture(GlyphToTexture(Glyph(width, height, points)));
}
// SPELL.FNT
else if (version == 0xfd)
{
auto data = Graphics::Texture::TextureType{};
for (unsigned r = 0; r < height; r++)
{
for (unsigned c = 0; c < width; c++)
{
auto index = glyphBuf.GetUint8();
// FIXME: probably do this elsewhere...
float shade = static_cast<float>(index) / 128.0f;
auto color = glm::vec4{shade, 0, 0, index != 0 ? 1.0f : 0.0f};
data.push_back(color);
}
}
auto texture = Graphics::Texture{data, width, height};
texture.Invert();
textures.AddTexture(texture);
}
else
{
throw std::runtime_error("Unexpected font version: ");
}
}
// OpenGL requires min texture dims of 16
auto empty = Glyph{16, 16, std::array<std::uint16_t, 16>{}};
textures.AddTexture(GlyphToTexture(empty));
return Font{
firstChar,
height,
textures};
}
}
| 3,410
|
C++
|
.cpp
| 91
| 28.32967
| 82
| 0.568466
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,310
|
inventoryItem.cpp
|
xavieran_BaKGL/bak/inventoryItem.cpp
|
#include "bak/inventoryItem.hpp"
#include "com/assert.hpp"
#include "com/ostream.hpp"
#include <iostream>
namespace BAK {
bool CheckItemStatus(std::uint8_t status, ItemStatus flag)
{
return CheckBitSet(status, flag);
}
std::uint8_t SetItemStatus(std::uint8_t status, ItemStatus flag, bool state)
{
return SetBit(status, flag, state);
}
InventoryItem::InventoryItem(
GameObject const* object,
ItemIndex itemIndex,
unsigned condition,
std::uint8_t status,
std::uint8_t modifiers)
:
mObject{object},
mItemIndex{itemIndex},
mCondition{condition},
mStatus{status},
mModifiers{modifiers}
{}
std::ostream& operator<<(std::ostream& os, const InventoryItem& i)
{
os << i.GetObject().mName << " #" << i.GetItemIndex() << " pct/qty: " <<
+i.GetCondition() << " status: " << +i.GetStatus() << " mods: [" << i.GetModifiers()
<< "] IsEquipped: " << i.IsEquipped() << "\n";
return os;
}
}
| 956
|
C++
|
.cpp
| 34
| 24.705882
| 93
| 0.670678
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,311
|
monster.cpp
|
xavieran_BaKGL/bak/monster.cpp
|
#include "bak/monster.hpp"
#include "com/logger.hpp"
#include "com/assert.hpp"
#include "com/ostream.hpp"
#include "bak/fileBufferFactory.hpp"
#include <iostream>
namespace BAK {
MonsterNames::MonsterNames()
:
mMonsterNames{},
mMonsterPrefixes{}
{
const auto& logger = Logging::LogState::GetLogger("MonsterNames");
{
auto fb = FileBufferFactory::Get().CreateDataBuffer("MNAMES.DAT");
const auto monsters = fb.GetUint32LE();
logger.Spam() << "Loading monsters: " << "\n";
logger.Spam() << "Monsters: " << monsters << "\n";
std::vector<unsigned> offsets{};
for (unsigned i = 0; i < monsters; i++)
{
const auto& offset = offsets.emplace_back(fb.GetUint16LE());
logger.Spam() << "I: " << i << " "
<< std::hex << offset << std::dec << std::endl;
}
std::vector<std::string> strings{};
auto start = fb.Tell();
unsigned p = 0;
for (auto offset : offsets)
{
if (start + offset > fb.GetSize())
{
logger.Spam() << "Seeking past end of file!\n";
strings.emplace_back("INVALID MONSTER");
mMonsterNames.emplace_back("INVALID MONSTER");
continue;
}
fb.Seek(start + offset);
const auto& keyword = strings.emplace_back(fb.GetString());
logger.Spam() << p++ << " " << keyword << std::endl;
mMonsterNames.emplace_back(keyword);
}
for (unsigned i = 0; i < strings.size(); i ++)
{
logger.Spam() << "K: " << i << " : " << strings[i] << "\n";
}
}
{
auto fb = FileBufferFactory::Get().CreateDataBuffer("BNAMES.DAT");
auto monsters = fb.GetUint32LE();
logger.Spam() << "Loading keywords" << "\n";
logger.Spam() << "Length: " << monsters << "\n";
std::vector<unsigned> offsets{};
for (unsigned i = 0; i < monsters; i++)
{
const auto& offset = offsets.emplace_back(fb.GetUint16LE());
logger.Spam() << "I: " << i << " "
<< std::hex << offset << std::dec << std::endl;
}
std::vector<std::string> strings{};
auto start = fb.Tell();
unsigned p = 0;
for (auto offset : offsets)
{
if (start + offset > fb.GetSize()) continue;
fb.Seek(start + offset);
const auto prefix = fb.GetString();
const auto unk0 = fb.GetUint8();
const auto unk1 = fb.GetUint8();
const auto unk2 = fb.GetUint8();
const auto unk3 = fb.GetUint8();
logger.Spam() << p++ << " " << prefix << " "
<< +unk0 << " "
<< +unk1 << " "
<< +unk2 << " "
<< +unk3 << " " << std::endl;
mMonsterPrefixes.emplace_back(prefix, unk0, unk1, unk2, unk3);
}
}
}
}
| 2,986
|
C++
|
.cpp
| 81
| 27.148148
| 74
| 0.50121
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,312
|
book.cpp
|
xavieran_BaKGL/bak/book.cpp
|
#include "bak/book.hpp"
#include "com/logger.hpp"
#include <string_view>
namespace BAK {
std::string_view ToString(TextAlignment t)
{
using enum TextAlignment;
switch (t)
{
case Left: return "Left";
case Right: return "Right";
case Justify: return "Justify";
case Center: return "Center";
}
return "UnknownTextAlignment";
}
std::string_view ToString(FontStyle f)
{
using enum FontStyle;
switch (f)
{
case Normal: return "Normal";
case Bold: return "Bold";
case Italic: return "Italic";
case Underlined: return "Underlined";
case Ghosted: return "Ghosted";
}
return "UnknownFontStyle";
}
std::string ToString(Mirroring m)
{
using enum Mirroring;
switch (m)
{
case None: return "None";
case Horizontal: return "Horizontal";
case Vertical: return "Vertical";
case HorizontalAndVertical: return "HorizontalAndVertical";
}
return "UnknownMirroring" + std::to_string(static_cast<std::uint16_t>(m));
}
std::ostream& operator<<(std::ostream& os, const ReservedArea& r)
{
os << " Reserved { pos: " << r.mPos << " dims: " << r.mDims << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const BookImage& i)
{
os << " BookImage { pos: " << i.mPos << " img: " << i.mImage << " "
<< ToString(i.mMirroring) << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const TextSegment& p)
{
os << " TextSegment { font: " << p.mFont << " yoff: " << p.mYOff
<< " fs: " << ToString(p.mFontStyle) << " color: " << p.mColor << "\n";
os << " " << p.mText << "\n";
return os;
}
std::ostream& operator<<(std::ostream& os, const Paragraph& p)
{
os << " Paragraph { off: " << p.mOffset << " width: " << p.mWidth
<< " lineSpc: " << p.mLineSpacing << " wordSpc: " << p.mWordSpacing
<< " indent: " << p.mStartIndent << " align: " << ToString(p.mAlignment)
<< " text:\n";
for (const auto& ts : p.mText)
{
os << ts;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const Page& page)
{
os << "Page\n" " details: " << page.mDisplayNumber << " off: " << page.mOffset
<< " dims: " << page.mDims << " pg: " << page.mPageNumber
<< " prevPg: " << page.mPreviousPageNumber << " nextPg: "
<< page.mNextPageNumber << " showPg: " << page.mShowPageNumber
<< "\n";
os << " Reserved areas: \n";
for (const auto& reserved : page.mReservedAreas)
{
os << reserved << "\n";
}
os << " Images: \n";
for (const auto& image : page.mImages)
{
os << image << "\n";
}
os << " Paragraphs: \n";
for (const auto& paragraph : page.mParagraphs)
{
os << paragraph << "\n";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const Book& book)
{
os << "Book:";
for (const auto& page : book.mPages)
{
os << page;
}
return os;
}
Page LoadPage(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
Page page;
logger.Debug() << "Location: " << fb.Tell() << "\n";
unsigned posX = fb.GetSint16LE();
unsigned posY = fb.GetSint16LE();
page.mOffset = glm::ivec2{posX, posY};
unsigned dimX = fb.GetSint16LE();
unsigned dimY = fb.GetSint16LE();
page.mDims = glm::ivec2{dimX, dimY};
page.mDisplayNumber = fb.GetUint16LE();
page.mPageNumber = fb.GetUint16LE();
page.mPreviousPageNumber = fb.GetUint16LE();
page.mNextPageNumber = fb.GetUint16LE();
unsigned pagePointer = fb.GetUint16LE();
fb.Skip(2);
unsigned images = fb.GetUint16LE();
unsigned reserveds = fb.GetUint16LE();
page.mShowPageNumber = fb.GetUint16LE();
fb.DumpAndSkip(4);
fb.DumpAndSkip(16);
fb.DumpAndSkip(10);
for (unsigned i = 0 ; i < reserveds; i++)
{
auto x = fb.GetSint16LE();
auto y = fb.GetSint16LE();
auto width = fb.GetSint16LE();
auto height = fb.GetSint16LE();
page.mReservedAreas.emplace_back(ReservedArea{{x, y}, {width, height}});
}
for (unsigned i = 0 ; i < images; i++)
{
auto x = fb.GetSint16LE();
auto y = fb.GetSint16LE();
unsigned image = fb.GetUint16LE();
Mirroring mirror = static_cast<Mirroring>(fb.GetUint16LE());
page.mImages.emplace_back(BookImage{{x, y}, image, mirror});
}
static constexpr std::uint8_t EndPage = 0xf0;
static constexpr std::uint8_t StartParagraph = 0xf1;
static constexpr std::uint8_t StartText = 0xf4;
static constexpr std::uint8_t UpperCharacterLimit = 0xb1;
bool pageDone = false;
auto paragraph = std::optional<Paragraph>();
while (!pageDone)
{
const auto delimiter = fb.GetUint8();
if (delimiter == EndPage)
{
pageDone = true;
if (paragraph)
{
page.mParagraphs.emplace_back(*paragraph);
}
}
else if (delimiter == StartParagraph)
{
if (paragraph)
{
page.mParagraphs.emplace_back(*paragraph);
}
paragraph = Paragraph{};
const auto xoff = fb.GetSint16LE();
paragraph->mWidth = fb.GetSint16LE();
paragraph->mLineSpacing = fb.GetUint16LE();
paragraph->mWordSpacing = fb.GetUint16LE();
paragraph->mStartIndent = fb.GetUint16LE();
fb.Skip(2);
const auto yoff = fb.GetSint16LE();
paragraph->mOffset = glm::ivec2{xoff, yoff};
paragraph->mAlignment = static_cast<TextAlignment>(fb.GetUint16LE());
}
else if (delimiter == StartText)
{
auto text = TextSegment{};
text.mFont = fb.GetUint16LE();
text.mYOff = fb.GetSint16LE();
text.mColor = fb.GetUint16LE();
fb.Skip(2);
text.mFontStyle = static_cast<FontStyle>(fb.GetUint16LE());
std::stringstream ss{};
while (fb.Peek() < UpperCharacterLimit)
{
ss << fb.GetUint8();
}
text.mText = ss.str();
assert(paragraph);
paragraph->mText.emplace_back(text);
}
else
{
}
}
return page;
}
Book LoadBook(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
unsigned size = fb.GetUint32LE();
unsigned pageCount = fb.GetUint16LE();
std::vector<unsigned> pageOffsets;
for (unsigned i = 0; i < pageCount; i++)
{
pageOffsets.emplace_back(fb.GetUint32LE() + 4);
}
Book book{};
for (unsigned i = 0; i < pageCount; i++)
{
fb.Seek(pageOffsets[i]);
auto page = LoadPage(fb);
book.mPages.emplace_back(page);
}
return book;
}
}
| 6,944
|
C++
|
.cpp
| 220
| 24.863636
| 83
| 0.574589
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,313
|
trap.cpp
|
xavieran_BaKGL/bak/trap.cpp
|
#include "bak/trap.hpp"
#include "bak/fileBufferFactory.hpp"
#include "com/logger.hpp"
#include "com/ostream.hpp"
#include "graphics/glm.hpp"
namespace BAK {
std::string_view ToString(TrapElementType e)
{
using enum TrapElementType;
switch (e)
{
case RedCrystal: return "RedCrystal";
case GreenCrystal: return "GreenCrystal";
case SolidDiamond: return "SolidDiamond";
case TransparentDiamond: return "TransparentDiamond";
case Unknown_C3: return "Unknown_C3";
case Unknown_FFEE: return "Unknown_FFEE";
case Character0: return "Character0";
case Character1: return "Character1";
case Character2: return "Character2";
case BlasterDown: return "BlasterDown";
case BlasterUp: return "BlasterUp";
case BlasterRight: return "BlasterRight";
case BlasterLeft: return "BlasterLeft";
case Exit: return "Exit";
default: return "UnknownElement";
}
}
std::ostream& operator<<(std::ostream& os, const Trap& trap)
{
os << "Trap #" << trap.mIndex << "\n";
for (const auto& elem : trap.mElements)
{
os << " " << ToString(elem.mElement) << " - " << elem.mPosition << "\n";
}
return os;
}
std::vector<Trap> LoadTraps()
{
std::vector<Trap> traps{};
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
auto fb = FileBufferFactory::Get().CreateDataBuffer("TRAPS.DAT");
// Zun Trap starts at 0x3a2 -- Trap #15
unsigned i = 0;
while (fb.GetBytesLeft() != 0)
{
auto trap = Trap{};
trap.mIndex = i++;
auto numElements = fb.GetUint16LE();
logger.Debug() << "@" << std::hex << fb.Tell() << std::dec << "\n";
for (unsigned j = 0; j < numElements; j++)
{
auto elementType = fb.GetUint16LE();
auto pos = fb.LoadVector<std::uint8_t, 2>();
trap.mElements.emplace_back(TrapElement{static_cast<TrapElementType>(elementType), pos});
}
for (unsigned j = 0; j < (15u - numElements); j++)
{
fb.Skip(4);
}
logger.Debug() << trap << "\n";
traps.emplace_back(trap);
}
return traps;
}
}
| 2,153
|
C++
|
.cpp
| 66
| 27.151515
| 101
| 0.625723
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,314
|
party.cpp
|
xavieran_BaKGL/bak/party.cpp
|
#include "bak/party.hpp"
namespace BAK {
std::ostream& operator<<(std::ostream& os, const Party& party)
{
os << "Party {\n\tGold: " << party.mGold << " royals\n";
os << "\tKeys: " << party.mKeys << "\n";
os << "\tCharacters: \n";
for (const auto& c : party.mCharacters)
os << c;
os << "\tActive: ";
for (const auto i : party.mActiveCharacters)
os << " " << party.mCharacters[i.mValue].mName << " ";
os << "\n}";
return os;
}
}
| 479
|
C++
|
.cpp
| 16
| 25.6875
| 62
| 0.553377
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,315
|
zoneReference.cpp
|
xavieran_BaKGL/bak/zoneReference.cpp
|
#include "com/logger.hpp"
#include "graphics/glm.hpp"
#include "bak/fileBufferFactory.hpp"
namespace BAK {
std::vector<glm::uvec2> LoadZoneRef(const std::string& path)
{
auto fb = FileBufferFactory::Get().CreateDataBuffer(path);
const auto logger = Logging::LogState::GetLogger("LoadZoneRef");
const auto numberTiles = fb.GetUint8();
logger.Spam() << "Number of tiles: " << numberTiles << "\n";
std::vector<glm::uvec2> tiles{};
tiles.reserve(numberTiles);
for (unsigned i = 0; i < numberTiles; i++)
{
const auto& tile = tiles.emplace_back(
fb.LoadVector<std::uint8_t, 2>());
logger.Spam() << std::hex << tile << " " << i << std::dec << "\n";
}
return tiles;
}
}
| 739
|
C++
|
.cpp
| 21
| 30.52381
| 74
| 0.634697
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,316
|
fileBufferFactory.cpp
|
xavieran_BaKGL/bak/fileBufferFactory.cpp
|
#include "bak/fileBufferFactory.hpp"
#include "bak/file/util.hpp"
#include "com/logger.hpp"
#include "com/path.hpp"
#include <filesystem>
namespace BAK {
FileBufferFactory::FileBufferFactory()
:
mDataPath{(std::filesystem::path{GetBakDirectory()} / "data").string()},
mDataFileProvider{{(std::filesystem::path{GetBakDirectory()} / "data").string()}}
{}
FileBufferFactory& FileBufferFactory::Get()
{
static FileBufferFactory factory{};
return factory;
}
void FileBufferFactory::SetDataPath(const std::string& dataPath)
{
mDataPath = dataPath;
}
FileBuffer FileBufferFactory::CreateDataBuffer(const std::string& fileName)
{
auto* dataBuffer = mDataFileProvider.GetDataBuffer(fileName);
if (dataBuffer != nullptr)
{
return dataBuffer->MakeSubBuffer(0, dataBuffer->GetSize());
}
else
{
std::stringstream ss{};
ss << "File not found: " << fileName << std::endl;
Logging::LogFatal("FileBufferFactory") << ss.str();
throw new std::runtime_error(ss.str());
}
}
bool FileBufferFactory::DataBufferExists(const std::string& fileName)
{
return mDataFileProvider.GetDataBuffer(fileName) != nullptr;
}
FileBuffer FileBufferFactory::CreateSaveBuffer(const std::string& fileName)
{
if (std::filesystem::exists(fileName))
{
return File::CreateFileBuffer(fileName);
}
else
{
return CreateDataBuffer(fileName);
}
}
}
| 1,441
|
C++
|
.cpp
| 51
| 24.45098
| 85
| 0.711385
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,317
|
palette.cpp
|
xavieran_BaKGL/bak/palette.cpp
|
#include "bak/dataTags.hpp"
#include "bak/palette.hpp"
#include "com/assert.hpp"
#include "bak/fileBufferFactory.hpp"
namespace BAK {
Palette::Palette(const std::string& filename)
:
mColors{}
{
auto fb = FileBufferFactory::Get().CreateDataBuffer(filename);
auto palbuf = fb.Find(DataTag::VGA);
const auto size = palbuf.GetSize() / 3;
mColors.reserve(size);
const auto F = [](auto x){
return static_cast<float>(x) / 255.; };
for (unsigned i = 0; i < size; i++)
{
const auto r = F(palbuf.GetUint8() << 2);
const auto g = F(palbuf.GetUint8() << 2);
const auto b = F(palbuf.GetUint8() << 2);
const auto a = i == 0 ? 0.0 : 1.0;
mColors.emplace_back(r, g, b , a);
}
}
const glm::vec4& Palette::GetColor(unsigned i) const
{
ASSERT(i < mColors.size());
return mColors[i];
}
ColorSwap::ColorSwap(const std::string& filename)
:
mIndices{}
{
mIndices.reserve(sSize);
auto fb = FileBufferFactory::Get().CreateDataBuffer(filename);
for (unsigned i = 0; i < sSize; i++)
{
mIndices.emplace_back(fb.GetUint8());
}
}
const glm::vec4& ColorSwap::GetColor(unsigned i, const Palette& pal) const
{
ASSERT(i < sSize);
return pal.GetColor(mIndices[i]);
}
}
| 1,277
|
C++
|
.cpp
| 46
| 23.652174
| 74
| 0.636885
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,318
|
inventory.cpp
|
xavieran_BaKGL/bak/inventory.cpp
|
#include "bak/inventory.hpp"
#include "com/assert.hpp"
#include "com/logger.hpp"
#include <algorithm>
#include <numeric>
namespace BAK {
std::size_t Inventory::GetSpaceUsed() const
{
return std::accumulate(
mItems.begin(), mItems.end(),
0,
[](const auto sum, const auto& elem) -> unsigned {
if (!elem.IsEquipped())
return sum + elem.GetObject().mImageSize;
return sum;
});
}
bool Inventory::HasIncompleteStack(const InventoryItem& item) const
{
const auto it = std::find_if(
mItems.begin(), mItems.end(),
[&item](const auto& elem){
const auto stackSize = elem.GetObject().mStackSize;
return (elem.GetItemIndex() == item.GetItemIndex())
&& (elem.GetQuantity() != elem.GetObject().mStackSize);
});
return it != mItems.end();
}
std::size_t Inventory::CanAddCharacter(const InventoryItem& item) const
{
// This is an annoying hack because the game gives characters inventory
// size of 24, rather than 20 + 8 (items + equipped)
const auto currentQuantity = GetSpaceUsed() + 4;
const auto fits = (currentQuantity + item.GetObject().mImageSize) <= mCapacity;
return CanAdd(fits, item);
}
std::size_t Inventory::CanAddContainer(const InventoryItem& item) const
{
const auto fits = GetNumberItems() < mCapacity;
return CanAdd(fits, item);
}
std::size_t Inventory::CanAdd(bool fits, const InventoryItem& item) const
{
if (fits)
{
if (item.IsStackable())
return item.GetQuantity();
else
return 1;
}
else if (item.IsStackable() && HasIncompleteStack(item))
{
ASSERT(item.GetQuantity() > 0);
ASSERT(item.GetQuantity() <= item.GetObject().mStackSize);
auto stack = FindStack(item);
return std::min(
item.GetObject().mStackSize - stack->GetQuantity(),
item.GetQuantity());
}
return 0;
}
bool Inventory::HaveItem(const InventoryItem& item) const
{
const auto it = std::find_if(
mItems.begin(), mItems.end(),
[item](const auto& elem){
return item.GetItemIndex() == elem.GetItemIndex();
});
if (it != mItems.end() && item.IsStackable())
{
return it->GetCondition() >= item.GetCondition();
}
return it != mItems.end();
}
void Inventory::AddItem(const InventoryItem& item)
{
if (item.IsStackable() && HasIncompleteStack(item))
{
ASSERT(item.GetQuantity() > 0);
ASSERT(item.GetQuantity() <= item.GetObject().mStackSize);
auto it = FindStack(item);
ASSERT(it != mItems.end());
const auto amountToStack = item.GetObject().mStackSize - it->GetQuantity();
const auto additionalQuantity = std::min(item.GetQuantity(), amountToStack);
it->SetQuantity(it->GetQuantity() + additionalQuantity);
if (item.GetQuantity() > amountToStack)
{
auto newItem = item;
newItem.SetCondition(item.GetQuantity() - amountToStack);
mItems.emplace_back(newItem);
}
}
else
{
mItems.emplace_back(item);
}
CheckPostConditions();
}
bool Inventory::RemoveItem(BAK::InventoryIndex item)
{
ASSERT(item.mValue < mItems.size());
if (item.mValue < mItems.size())
{
mItems.erase(mItems.begin() + item.mValue);
return true;
}
return false;
}
bool Inventory::RemoveItem(BAK::InventoryIndex index, unsigned quantity)
{
ASSERT(index.mValue < mItems.size());
if (index.mValue < mItems.size())
{
auto& item = mItems[index.mValue];
ASSERT(quantity <= item.GetQuantity());
item.SetQuantity(item.GetQuantity() - quantity);
if (item.GetQuantity() == 0)
{
mItems.erase(mItems.begin() + index.mValue);
}
return true;
}
return false;
}
bool Inventory::RemoveItem(const InventoryItem& item)
{
if ((item.IsStackable() || item.IsChargeBased())
&& HaveItem(item))
{
unsigned remainingToRemove = item.GetQuantity();
auto it = FindStack(item);
do
{
ASSERT(it != mItems.end());
const auto amountToRemove = std::min(
remainingToRemove,
it->GetQuantity());
it->SetQuantity(it->GetQuantity() - amountToRemove);
remainingToRemove -= amountToRemove;
if (it->GetQuantity() == 0)
mItems.erase(it);
} while (remainingToRemove > 0
&& (it = FindStack(item)) != mItems.end());
CheckPostConditions();
return true;
}
else
{
auto it = FindItem(item);
if (it != mItems.end())
{
mItems.erase(it);
return true;
}
}
return false;
}
bool Inventory::ReplaceItem(BAK::InventoryIndex index, BAK::InventoryItem item)
{
ASSERT(index.mValue < mItems.size());
if (index.mValue < mItems.size())
{
mItems[index.mValue] = item;
return true;
}
return false;
}
void Inventory::CheckPostConditions()
{
for (const auto& item : mItems)
{
// We should never end up with a stack bigger than allowed
if (item.IsStackable())
{
// The game actually does not enforce this at all...
ASSERT(item.GetQuantity() <= item.GetObject().mStackSize);
ASSERT(item.GetQuantity() > 0);
}
}
}
std::ostream& operator<<(std::ostream& os, const Inventory& inventory)
{
os << "Inventory {\n";
for (unsigned i = 0; i < inventory.GetNumberItems(); i++)
{
os << "#" << i << " -> " << inventory.GetAtIndex(InventoryIndex{i}) << "\n";
}
os << "}";
return os;
}
Inventory LoadInventory(FileBuffer& fb, unsigned itemCount, unsigned capacity)
{
auto items = std::vector<InventoryItem>{};
unsigned i;
for (i = 0; i < itemCount; i++)
{
const auto item = ItemIndex{fb.GetUint8()};
const auto& object = ObjectIndex::Get().GetObject(item);
const auto condition = fb.GetUint8();
const auto status = fb.GetUint8();
const auto modifiers = fb.GetUint8();
items.emplace_back(
InventoryItemFactory::MakeItem(
item,
condition,
status,
modifiers));
}
for (; i < capacity; i++)
fb.Skip(4);
return Inventory{capacity, std::move(items)};
}
}
| 6,535
|
C++
|
.cpp
| 213
| 23.802817
| 84
| 0.599873
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,319
|
camp.cpp
|
xavieran_BaKGL/bak/camp.cpp
|
#include "bak/camp.hpp"
#include "bak/condition.hpp"
#include "bak/skills.hpp"
#include "graphics/glm.hpp"
#include "com/logger.hpp"
namespace BAK {
CampData::CampData()
:
mClockTicks{},
mDaytimeShadow{}
{
const auto& logger = Logging::LogState::GetLogger("CampData");
auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer("ENCAMP.DAT");
mHighlightSize = {fb.GetSint16LE(), fb.GetSint16LE()};
auto mUnknown = fb.GetSint16LE();
auto mUnknown2 = fb.GetSint16LE();
auto tickCount = fb.GetSint16LE();
for (unsigned i = 0; i < 24; i++)
{
auto x = fb.GetSint16LE();
auto y = fb.GetSint16LE();
logger.Debug() << "clk: " << +x << " " << +y << "\n";
mClockTicks.emplace_back(x, y);
}
mClockTwelve = {fb.GetSint16LE(), fb.GetSint16LE()};
mClockCenter = {fb.GetSint16LE(), fb.GetSint16LE()};
for (unsigned i = 0; i < 24; i++)
{
auto x = fb.GetSint16LE();
auto y = fb.GetSint16LE();
logger.Debug() << +x << " " << +y << "\n";
mDaytimeShadow.emplace_back(x, y);
}
}
const std::vector<glm::vec2>& CampData::GetClockTicks() const
{
return mClockTicks;
}
const std::vector<glm::vec2>& CampData::GetDaytimeShadow() const
{
return mDaytimeShadow;
}
}
| 1,279
|
C++
|
.cpp
| 43
| 25.418605
| 75
| 0.624085
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,320
|
textureFactory.cpp
|
xavieran_BaKGL/bak/textureFactory.cpp
|
#include "bak/textureFactory.hpp"
#include "bak/imageStore.hpp"
#include "bak/screen.hpp"
#include <algorithm>
#include <random>
namespace BAK {
Graphics::Texture ImageToTexture(const Image& image, const Palette& palette)
{
auto texture = Graphics::Texture::TextureType{};
const auto imageSize = image.GetWidth() * image.GetHeight();
texture.reserve(imageSize);
auto* pixels = image.GetPixels();
for (unsigned i = 0; i < imageSize; i++)
{
texture.push_back(palette.GetColor(pixels[i]));
}
auto tex = Graphics::Texture{
texture,
static_cast<unsigned>(image.GetWidth()),
static_cast<unsigned>(image.GetHeight()) };
// For OpenGL
tex.Invert();
return tex;
}
Graphics::TextureStore TextureFactory::MakeTextureStore(
std::string_view bmx,
std::string_view pal)
{
auto store = Graphics::TextureStore{};
AddToTextureStore(store, bmx, pal);
return store;
}
void TextureFactory::AddToTextureStore(
Graphics::TextureStore& store,
std::string_view bmx,
std::string_view pal)
{
const auto palette = Palette{std::string{pal}};
auto fb = FileBufferFactory::Get()
.CreateDataBuffer(std::string{bmx});
const auto images = LoadImages(fb);
AddToTextureStore(store, images, palette);
}
void TextureFactory::AddScreenToTextureStore(
Graphics::TextureStore& store,
std::string_view scx,
std::string_view pal)
{
const auto palette = Palette{std::string{pal}};
auto fb = FileBufferFactory::Get()
.CreateDataBuffer(std::string{scx});
AddToTextureStore(store, LoadScreenResource(fb), palette);
}
void TextureFactory::AddTerrainToTextureStore(
Graphics::TextureStore& store,
const Image& terrain,
const Palette& palette)
{
auto* pixels = terrain.GetPixels();
auto width = terrain.GetWidth();
auto startOff = 0;
// FIXME: Can I find these in the data files somewhere?
for (auto offset : {70, 20, 20, 32, 20, 27, 6, 5})
{
auto image = Graphics::Texture::TextureType{};
const auto imageStart = startOff * width;
const auto imageEnd = (startOff + offset) * width;
image.reserve(imageEnd - imageStart);
for (unsigned i = imageStart; i < imageEnd; i++)
{
const auto& color = palette.GetColor(pixels[i]);
image.push_back(color);
}
if (offset == 70)
{
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(image.begin(), image.end(), g);
}
startOff += offset;
store.AddTexture(
Graphics::Texture{
image,
static_cast<unsigned>(width),
static_cast<unsigned>(offset)});
}
}
void TextureFactory::AddToTextureStore(
Graphics::TextureStore& store,
const Image& image,
const Palette& palette)
{
store.AddTexture(ImageToTexture(image, palette));
}
void TextureFactory::AddToTextureStore(
Graphics::TextureStore& store,
const std::vector<Image>& images,
const Palette& palette)
{
for (const auto& image : images)
AddToTextureStore(store, image, palette);
}
} // namespace BAK {
| 3,228
|
C++
|
.cpp
| 103
| 25.592233
| 76
| 0.657946
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,321
|
lock.cpp
|
xavieran_BaKGL/bak/lock.cpp
|
#include "bak/lock.hpp"
#include "bak/random.hpp"
#include "com/ostream.hpp"
#include "com/string.hpp"
namespace BAK {
std::ostream& operator<<(std::ostream& os, const LockStats& lock)
{
os << "Lock { flag: " << lock.mLockFlag << " rating: " << lock.mRating
<< " fairy: " << lock.mFairyChestIndex << " damage: " << lock.mTrapDamage << "}";
return os;
}
LockStats LoadLock(FileBuffer& fb)
{
const auto lockFlag = fb.GetUint8();
const auto picklock = fb.GetUint8();
const auto fairyChestIndex = fb.GetUint8();
const auto damage = fb.GetUint8();
return LockStats{lockFlag, picklock, fairyChestIndex, damage};
}
std::ostream& operator<<(std::ostream& os, const Door& door)
{
os << "Door { index: " << door.mDoorIndex << "}";
return os;
}
LockType ClassifyLock(unsigned lockRating)
{
if (lockRating < 0x33)
return LockType::Easy;
else if (lockRating < 0x51)
return LockType::Medium;
else if (lockRating < 0x65)
return LockType::Hard;
else
return LockType::Unpickable;
}
LockType ClassifyDoor(unsigned lockRating)
{
if (lockRating < 50)
return LockType::Easy;
else if (lockRating < 80)
return LockType::Medium;
else if (lockRating < 100)
return LockType::Hard;
else
return LockType::Unpickable;
}
std::string_view ToString(LockType lock)
{
switch (lock)
{
case BAK::LockType::Easy: return "Easy";
case BAK::LockType::Medium: return "Medium";
case BAK::LockType::Hard: return "Hard";
case BAK::LockType::Unpickable: return "Unpickable";
default: return "UnknownLockType";
}
}
static constexpr auto sKeyItemIndexOffset = 60; // keys start at 60;
static constexpr auto sLockIndices = std::array<std::uint8_t, 12>{
0x0, 0x32, 0x5a, 0x65, 0x66, 0x67, 0x68, 0x46, 0x3C, 0x50, 0x69, 0x6A};
std::optional<unsigned> GetLockIndex(unsigned lockRating)
{
const auto it = std::find(sLockIndices.begin(), sLockIndices.end(), lockRating);
if (it == sLockIndices.end())
return std::optional<unsigned>{};
else
return std::distance(sLockIndices.begin(), it);
}
unsigned GetKeyRating(const BAK::ItemIndex& key)
{
ASSERT(key.mValue > 60);
const auto keyIndex = key.mValue - sKeyItemIndexOffset;
ASSERT(keyIndex <= sLockIndices.size());
return sLockIndices[keyIndex];
}
ItemIndex GetCorrespondingKey(unsigned lockIndex)
{
return ItemIndex{lockIndex + sKeyItemIndexOffset};
}
bool TryOpenLockWithKey(const BAK::InventoryItem& item, unsigned lockRating)
{
const auto lockIndex = GetLockIndex(lockRating);
return lockIndex
&& (GetCorrespondingKey(*lockIndex) == item.GetItemIndex());
}
bool WouldKeyBreak(const InventoryItem& item, unsigned lockRating)
{
// Special keys should never break
return !TryOpenLockWithKey(item, lockRating) && GetKeyRating(item.GetItemIndex()) <= 100;
}
unsigned DescribeLock(unsigned picklockSkill, unsigned lockRating)
{
if (lockRating > 106)
return 3; // lock is broken
else if (lockRating > 100 && lockRating < 107)
return 2; // lock takes special key
else if (picklockSkill > lockRating)
return 0; // lock is easy
else if (picklockSkill <= lockRating)
return 1; // lock too complicated
else
ASSERT(false);
return 0;
}
unsigned GetRandomMod100()
{
return (GetRandom() & 0xfff) % 100;
}
bool KeyBroken(const InventoryItem& item, unsigned skill, unsigned lockRating)
{
// Returns e.g. 0x32 for peasants key...
const auto keyRating = GetKeyRating(item.GetItemIndex());
// from the disassembly... looks reasonable
const auto diff = 100 - keyRating;
const auto skillDiv3 = skill / 3;
const auto diffSubSkill = (diff - skillDiv3) << 1;
const auto diffSubSkillDiv3 = diffSubSkill / 3;
const auto randomNumber = GetRandomMod100();
return randomNumber < diffSubSkillDiv3;
}
bool PicklockBroken(unsigned skill, unsigned lockRating)
{
const auto randomNumber = GetRandomMod100();
// Returns e.g. 0x32 for peasants key...
const auto diff = ((lockRating - skill) << 1) / 3;
return randomNumber < diff;
}
bool PicklockSkillImproved()
{
return GetRandomMod100() < 0x28;
}
bool CanPickLock(unsigned skill, unsigned lockRating)
{
return (lockRating <= 100) && (skill > lockRating);
}
FairyChest GenerateFairyChest(const std::string& data)
{
const auto texts = SplitString("\n#", data);
ASSERT(texts.size() == 3);
const auto& answer = texts[0];
auto options = SplitString("\n", texts[1]);
options.erase(options.begin()); // remove leading empty string
const auto& hint = texts[2];
for (unsigned i = 0; i < options.size(); i++)
ASSERT(options[i].size() == answer.size());
return FairyChest{answer, options, hint};
}
}
| 4,857
|
C++
|
.cpp
| 148
| 28.763514
| 93
| 0.690746
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,322
|
temple.cpp
|
xavieran_BaKGL/bak/temple.cpp
|
#include "bak/temple.hpp"
#include "bak/inventoryItem.hpp"
#include "bak/skills.hpp"
namespace BAK::Temple {
bool CanBlessItem(const BAK::InventoryItem& item)
{
const auto& object = item.GetObject();
return object.mType == ItemType::Armor
|| object.mType == ItemType::Sword;
}
bool IsBlessed(const BAK::InventoryItem& item)
{
return item.HasModifier(Modifier::Blessing1)
|| item.HasModifier(Modifier::Blessing2)
|| item.HasModifier(Modifier::Blessing3);
}
Royals CalculateBlessPrice(const BAK::InventoryItem& item, const ShopStats& shop)
{
const auto& object = item.GetObject();
const auto cost = (shop.GetTempleBlessFixedCost() * 10) + ((object.mValue * shop.GetTempleBlessPercent()) / 100);
assert(cost > 0);
return Royals{static_cast<unsigned>(cost)};
}
void BlessItem(BAK::InventoryItem& item, const ShopStats& shop)
{
item.SetModifier(shop.GetTempleBlessType());
}
void RemoveBlessing(BAK::InventoryItem& item)
{
for (const auto blessType : {Modifier::Blessing1, Modifier::Blessing2, Modifier::Blessing3})
{
item.UnsetModifier(blessType);
}
}
Royals CalculateTeleportCost(
unsigned srcTemple,
unsigned dstTemple,
glm::vec2 srcPos,
glm::vec2 dstPos,
unsigned teleportMultiplier,
unsigned teleportConstant)
{
ASSERT(srcTemple > 0 && dstTemple > 0);
ASSERT(srcTemple <= 13 && dstTemple <= 13);
auto xDiff = static_cast<unsigned>(std::abs(srcPos.x - dstPos.x));
auto yDiff = static_cast<unsigned>(std::abs(srcPos.y - dstPos.y));
auto cost = std::max(xDiff, yDiff) + (std::min(xDiff, yDiff) * 3) / 8;
cost = ((cost * teleportMultiplier) + teleportConstant) * 10;
cost = (cost + 5) / 10;
return Royals{cost};
}
Royals CalculateCureCost(
unsigned cureFactor,
bool isTempleOfSung,
Skills& skills,
const Conditions& conditions,
const std::vector<SkillAffector>& skillAffectors)
{
static constexpr unsigned conditionCost[7] = {
4, 10, 10, 3, 0, 2, 30
};
unsigned totalCost = 0;
for (unsigned i = 0; i < Conditions::sNumConditions; i++)
{
const auto cond = conditions.GetCondition(static_cast<Condition>(i));
if (i != static_cast<unsigned>(Condition::Healing) && cond.Get() > 0)
totalCost += (cond.Get() * conditionCost[i]) + 10;
}
totalCost = (totalCost * cureFactor) / 100;
if (isTempleOfSung)
{
totalCost += CalculateEffectiveSkillValue(
SkillType::TotalHealth,
skills,
conditions,
skillAffectors,
SkillRead::MaxSkill);
totalCost -= CalculateEffectiveSkillValue(
SkillType::TotalHealth,
skills,
conditions,
skillAffectors,
SkillRead::Current);
}
return Royals{totalCost};
}
void CureCharacter(Skills& skills, Conditions& conditions, bool isTempleOfSung)
{
for (unsigned i = 0; i < Conditions::sNumConditions; i++)
{
const auto cond = static_cast<Condition>(i);
const auto amount = cond == Condition::Healing ? 20 : -100;
conditions.AdjustCondition(skills, cond, amount);
}
if (isTempleOfSung)
{
DoAdjustHealth(skills, conditions, 100, 0x7fff);
conditions.AdjustCondition(skills, Condition::Healing, 100);
}
}
}
| 3,360
|
C++
|
.cpp
| 101
| 27.792079
| 117
| 0.667799
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,323
|
dialog.cpp
|
xavieran_BaKGL/bak/dialog.cpp
|
#include "bak/dialog.hpp"
#include "bak/constants.hpp"
#include "bak/dialogReplacements.hpp"
#include "com/assert.hpp"
namespace BAK {
Keywords::Keywords()
:
mPartyMembers{
"Locklear",
"Gorath",
"Owyn",
"Pug",
"James",
"Patrus"},
mKeywords{}
{
const auto& logger = Logging::LogState::GetLogger("Keywords");
auto fb = FileBufferFactory::Get().CreateDataBuffer("KEYWORD.DAT");
auto length = fb.GetUint16LE();
logger.Spam() << "Loading keywords" << "\n";
logger.Spam() << "Length: " << length << "\n";
std::vector<unsigned> offsets{};
unsigned i = 0;
while (fb.Tell() != 0x2b8)
{
const auto& offset = offsets.emplace_back(fb.GetUint16LE());
logger.Spam() << "I: " << i << " "
<< std::hex << offset << std::dec << "\n";
i++;
}
std::vector<std::string> strings{};
for (auto offset : offsets)
{
fb.Seek(offset);
const auto& keyword = strings.emplace_back(fb.GetString());
mKeywords.emplace_back(keyword);
}
for (unsigned i = 0; i < strings.size(); i ++)
{
logger.Spam() << "K: " << i << " : " << strings[i] << "\n";
}
}
std::string_view Keywords::GetDialogChoice(unsigned i) const
{
ASSERT(i < mKeywords.size());
return mKeywords[i];
}
std::string_view Keywords::GetQueryChoice(unsigned i) const
{
ASSERT(i < mKeywords.size());
return mKeywords[i];
}
std::string_view Keywords::GetNPCName(unsigned i) const
{
ASSERT(i + mCharacterNameOffset < mKeywords.size());
if (i < mPartyMembers.size())
{
ASSERT(i != 0);
return mPartyMembers[i - 1];
}
return mKeywords[i + mCharacterNameOffset];
}
DialogSnippet::DialogSnippet(FileBuffer& fb, std::uint8_t dialogFile)
{
const auto fileOffset = fb.Tell();
mDisplayStyle = fb.GetUint8();
mActor = fb.GetUint16LE();
mDisplayStyle2 = fb.GetUint8();
mDisplayStyle3 = fb.GetUint8();
std::uint8_t choices = fb.GetUint8();
std::uint8_t actions = fb.GetUint8();
auto length = fb.GetUint16LE();
std::uint8_t i;
const auto GetTarget = [dialogFile](auto rawTarget) -> Target
{
constexpr std::uint32_t targetBit = 0xf0000000;
if (targetBit & rawTarget)
return KeyTarget{rawTarget & ~targetBit};
else
return OffsetTarget{dialogFile, rawTarget};
};
for (i = 0; i < choices; i++)
{
const auto state = fb.GetUint16LE();
const auto choice0 = fb.GetUint16LE();
const auto choice1 = fb.GetUint16LE();
const auto offset = fb.GetUint32LE();
const auto target = offset != 0 ? GetTarget(offset) : KeyTarget{0};
mChoices.emplace_back(state, choice0, choice1, target);
}
for (i = 0; i < actions; i++)
{
const auto type = fb.GetUint16LE();
const auto dr = static_cast<DialogResult>(type);
switch (dr)
{
case DialogResult::SetTextVariable:
{
const auto which = fb.GetUint16LE();
const auto what = fb.GetUint16LE();
const auto rest = fb.GetArray<4>();
mActions.emplace_back(
SetTextVariable{
which,
what,
rest});
} break;
case DialogResult::GiveItem:
{
const auto item = fb.GetUint8();
const auto character = fb.GetUint8();
const auto quantity = fb.GetUint16LE();
const auto rest = fb.GetArray<4>();
mActions.emplace_back(
GiveItem{
item,
character,
quantity,
rest});
} break;
case DialogResult::LoseItem:
{
const auto item = fb.GetUint16LE();
auto quantity = fb.GetUint16LE();
if (quantity == 0)
quantity = 1;
const auto rest = fb.GetArray<4>();
mActions.emplace_back(
LoseItem{
item,
quantity,
rest});
} break;
case DialogResult::SetFlag:
{
const auto eventPtr = fb.GetUint16LE();
const auto mask = fb.GetUint8();
const auto data = fb.GetUint8();
const auto zero = fb.GetUint16LE();
const auto value = fb.GetUint16LE();
mActions.emplace_back(
SetFlag{
eventPtr,
mask,
data,
zero,
value});
} break;
case DialogResult::LoadActor:
{
const auto a1= fb.GetUint16LE();
const auto a2 = fb.GetUint16LE();
const auto a3 = fb.GetUint16LE();
const auto un = fb.GetUint16LE();
mActions.emplace_back(
LoadActor{a1, a2, a3, un});
} break;
case DialogResult::SetPopupDimensions:
{
const auto posX = fb.GetUint16LE();
const auto posY = fb.GetUint16LE();
const auto dimsX = fb.GetUint16LE();
const auto dimsY = fb.GetUint16LE();
mActions.emplace_back(
SetPopupDimensions{
glm::vec2{posX, posY},
glm::vec2{dimsX, dimsY}});
} break;
case DialogResult::SpecialAction:
{
const auto type = static_cast<SpecialActionType>(fb.GetUint16LE());
const auto var1 = fb.GetUint16LE();
const auto var2 = fb.GetUint16LE();
const auto var3 = fb.GetUint16LE();
mActions.emplace_back(SpecialAction{type, var1, var2, var3});
} break;
case DialogResult::GainCondition:
{
const auto who = fb.GetUint16LE();
const auto condition = static_cast<Condition>(fb.GetUint16LE());
const auto min = fb.GetSint16LE();
const auto max = fb.GetSint16LE();
assert(min <= max);
mActions.emplace_back(
GainCondition{
who,
condition,
min,
max});
} break;
case DialogResult::GainSkill:
{
const auto flag = fb.GetUint16LE();
const auto skill = static_cast<SkillType>(fb.GetUint16LE());
const auto min = fb.GetSint16LE();
const auto max = fb.GetSint16LE();
assert(min <= max);
mActions.emplace_back(
GainSkill{flag, skill, min, max});
} break;
case DialogResult::LoadSkillValue:
{
const auto target = fb.GetUint16LE();
const auto skill = static_cast<SkillType>(fb.GetUint16LE());
fb.Skip(4);
mActions.emplace_back(
LoadSkillValue{target, skill});
} break;
case DialogResult::PlaySound:
{
const auto soundIndex = fb.GetUint16LE();
const auto flag = fb.GetUint16LE();
const auto rest = fb.GetUint32LE();
mActions.emplace_back(
PlaySound{
soundIndex,
flag,
rest});
} break;
case DialogResult::ElapseTime:
{
const auto time = Time{fb.GetUint32LE()};
const auto rest = fb.GetArray<4>();
mActions.emplace_back(
ElapseTime{
time,
rest});
} break;
case DialogResult::SetAddResetState:
{
const auto state = fb.GetUint16LE();
const auto unk0 = fb.GetUint16LE();
const auto time = Time{fb.GetUint32LE()};
mActions.emplace_back(
SetAddResetState{state, unk0, time});
} break;
case DialogResult::PushNextDialog:
{
const auto offset = fb.GetUint32LE();
const auto rest = fb.GetArray<4>();
mActions.emplace_back(
PushNextDialog{
GetTarget(offset),
rest});
} break;
case DialogResult::UpdateCharacters:
{
const auto number = fb.GetUint16LE();
std::vector<CharIndex> characters{};
unsigned i = 0;
for (; i < number; i++)
{
characters.emplace_back(fb.GetUint16LE());
}
for (; i < 3; i++)
{
fb.GetUint16LE();
}
mActions.emplace_back(
UpdateCharacters{characters});
} break;
case DialogResult::HealCharacters:
{
const auto who = fb.GetUint16LE();
const auto howMuch = fb.GetUint16LE();
fb.GetUint16LE();
fb.GetUint16LE();
mActions.emplace_back(HealCharacters{who, howMuch});
} break;
case DialogResult::LearnSpell:
{
const auto who = fb.GetUint16LE();
const auto whichSpell = fb.GetUint16LE();
const auto rest = fb.GetArray<4>();
mActions.emplace_back(
LearnSpell{
who,
whichSpell});
} break;
case DialogResult::Teleport:
{
const auto teleportIndex = fb.GetUint16LE();
fb.Skip(6);
mActions.emplace_back(
Teleport{TeleportIndex{teleportIndex}});
} break;
case DialogResult::SetEndOfDialogState:
{
const auto state = fb.GetSint16LE();
const auto rest = fb.GetArray<6>();
mActions.emplace_back(
SetEndOfDialogState{
state,
rest});
} break;
case DialogResult::SetTimeExpiringState:
{
const auto type = ExpiringStateType{fb.GetUint8()};
const auto flag = fb.GetUint8();
const auto state = fb.GetUint16LE();
const auto time = Time{fb.GetUint32LE()};
mActions.emplace_back(
SetTimeExpiringState{type, flag, state, time});
} break;
case DialogResult::LoseNOfItem:
{
const auto item = fb.GetUint16LE();
auto quantity = fb.GetUint16LE();
if (quantity == 0)
quantity = 1;
const auto rest = fb.GetArray<4>();
mActions.emplace_back(
LoseNOfItem{
item,
quantity,
rest});
} break;
default:
{
const auto& rest = fb.GetArray<8>();
bool nonZero{};
for (unsigned i = 0; i < 8; i++)
{
if (rest[i] != 0) nonZero = true;
}
if (nonZero)
{
mActions.emplace_back(BuggedAction{rest});
}
else
{
mActions.emplace_back(
UnknownAction{
type,
rest});
}
} break;
}
}
Replacements::ReplaceActions(OffsetTarget{dialogFile, fileOffset}, mActions);
if (length > 0)
mText = fb.GetString(length);
else
mText = "";
}
std::ostream& operator<<(std::ostream& os, const DialogSnippet& d)
{
os << "[ ds: " << std::hex << +d.mDisplayStyle << " act: " << +d.mActor
<< " ds2: " << +d.mDisplayStyle2 << " ds3: " << +d.mDisplayStyle3
<< " ]" << std::dec << "\n";
for (const auto& action : d.mActions)
os << "++ " << action << "\n";
for (const auto& choice : d.mChoices)
os << ">> " << choice << "\n";
os << "Text [ " << d.mText << " ]" << "\n";
os << "Next [ ";
if (d.mChoices.size() > 0)
os << d.mChoices.back().mTarget;
else
os << "None";
os << " ]" << "\n";
os << std::dec;
return os;
}
const DialogStore& DialogStore::Get()
{
static DialogStore dialogStore{};
return dialogStore;
}
DialogStore::DialogStore()
:
mDialogMap{},
mSnippetMap{},
mLogger{Logging::LogState::GetLogger("DialogStore")}
{
Load();
}
void DialogStore::Load()
{
for (std::uint8_t dialogFile = 0; dialogFile < 32; dialogFile++)
{
auto fname = GetDialogFile(dialogFile);
auto fb = FileBufferFactory::Get().CreateDataBuffer(fname);
unsigned dialogs = fb.GetUint16LE();
mLogger.Debug() << "Dialog " << fname << " has: " << dialogs << " dialogs" << "\n";
for (unsigned i = 0; i < dialogs; i++)
{
auto key = KeyTarget{fb.GetUint32LE()};
const auto val = OffsetTarget{dialogFile, fb.GetUint32LE()};
const auto [it, emplaced] = mDialogMap.emplace(
key,
val);
//ASSERT(emplaced);
auto [checkF, checkV] = it->second;
mLogger.Spam() << std::hex << "0x" << it->first
<< " -> 0x" << checkV << std::dec << "\n";
}
while (fb.GetBytesLeft() > 0)
{
const auto offset = OffsetTarget{dialogFile, fb.Tell()};
auto snippet = DialogSnippet{fb, dialogFile};
mLogger.Spam() << offset << " @ " << snippet << "\n";
const auto& [it, emplaced] = mSnippetMap.emplace(offset, snippet);
}
}
}
void DialogStore::ShowAllDialogs()
{
for (const auto& dialogKey : mDialogMap)
{
try
{
ShowDialog(dialogKey.first);
}
catch (const std::runtime_error&)
{
mLogger.Error() << "Failed to walk dialog tree: " << dialogKey.first << "\n";
}
}
}
void DialogStore::ShowDialog(Target dialogKey)
{
auto snippet = std::visit(*this, dialogKey);
bool noText = true;
mLogger.Info() << "Dialog for key: " << std::hex << dialogKey << std::dec << "\n";
mLogger.Debug() << "Text: " << GetFirstText(snippet) << "\n";
}
const DialogSnippet& DialogStore::GetSnippet(Target target) const
{
return std::visit(*this, target);
}
bool DialogStore::HasSnippet(Target target) const
{
try
{
std::visit(*this, target);
return true;
}
catch (std::runtime_error& e)
{
mLogger.Error() << __FUNCTION__ << " " << e.what() << std::endl;
return false;
}
}
OffsetTarget DialogStore::GetTarget(KeyTarget dialogKey) const
{
auto it = mDialogMap.find(dialogKey);
if (it == mDialogMap.end())
{
std::stringstream err{};
err << "Key not found: " << std::hex << dialogKey << std::dec;
throw std::runtime_error(err.str());
}
return it->second;
}
std::string_view DialogStore::GetFirstText(const DialogSnippet& snippet) const
{
if (snippet.GetText().length() != 0)
return snippet.GetText();
else
{
if (snippet.GetChoices().size() > 0)
return GetFirstText(
GetSnippet(snippet.GetChoices().front().mTarget));
else
return "* no text *";
}
}
const DialogSnippet& DialogStore::operator()(KeyTarget dialogKey) const
{
auto it = mDialogMap.find(dialogKey);
if (it == mDialogMap.end())
{
std::stringstream err{};
err << "Key not found: " << std::hex << dialogKey << std::dec;
throw std::runtime_error(err.str());
}
return (*this)(it->second);
}
const DialogSnippet& DialogStore::operator()(OffsetTarget snippetKey) const
{
auto snip = mSnippetMap.find(snippetKey);
if (snip == mSnippetMap.end())
{
std::stringstream err{};
err << "Offset not found: " << std::hex << snippetKey << std::dec;
throw std::runtime_error(err.str());
}
return snip->second;
}
std::string DialogStore::GetDialogFile(std::uint8_t i)
{
std::stringstream ss{};
ss << "DIAL_Z" << std::setw(2) << std::setfill('0') << +i << ".DDX";
return ss.str();
}
}
| 16,155
|
C++
|
.cpp
| 497
| 22.792757
| 91
| 0.524566
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,324
|
sceneData.cpp
|
xavieran_BaKGL/bak/sceneData.cpp
|
#include "bak/sceneData.hpp"
#include "com/visit.hpp"
#include "graphics/glm.hpp"
#include <sstream>
namespace BAK {
std::string_view ToString(AdsActions a)
{
switch (a)
{
case AdsActions::INDEX: return "Index";
case AdsActions::IF_NOT_PLAYED: return "IfNotPlayed";
case AdsActions::IF_PLAYED: return "IfPlayed";
case AdsActions::IF_CHAP_LTE: return "IfChapterLTE";
case AdsActions::ELSE: return "Else";
case AdsActions::IF_CHAP_GTE: return "IfChapterGTE";
case AdsActions::AND: return "And";
case AdsActions::OR: return "Or";
case AdsActions::ADD_SCENE2: return "AddScene2";
case AdsActions::ADD_SCENE: return "AddScene";
case AdsActions::STOP_SCENE: return "StopScene";
case AdsActions::PLAY_SCENE: return "PlayScene";
case AdsActions::PLAY_ALL_SCENES: return "PlayAllScenes";
case AdsActions::FADE_OUT: return "FadeOut";
case AdsActions::END_IF: return "EndIf";
case AdsActions::END: return "End";
default:
std::stringstream ss{};
ss << "Invalid ads action: 0x" << std::hex
<< static_cast<int>(a) << "\n";
throw std::runtime_error(ss.str());
}
}
std::ostream& operator<<(std::ostream& os, AdsActions a)
{
os << ToString(a);
return os;
}
std::string_view ToString(Actions a)
{
switch (a)
{
case Actions::SAVE_BACKGROUND: return "SaveBackground";
case Actions::DRAW_BACKGROUND: return "DrawBackground";
case Actions::DRAW_BACKGROUND_B: return "DRAW_BACKGROUND_B";
case Actions::PURGE: return "Purge";
case Actions::UPDATE: return "Update";
case Actions::DO_SOMETHING_A: return "DOSOMETHINGA";
case Actions::DISABLE_CLEAR: return "DisableClear";
case Actions::ENABLE_CLEAR: return "EnableClear";
case Actions::DELAY: return "Delay";
case Actions::SLOT_IMAGE: return "SlotImage";
case Actions::SLOT_PALETTE: return "SlotPalette";
case Actions::SLOT_FONT: return "SlotFont";
case Actions::SET_SCENE: return "SetScene";
case Actions::SET_SCENEA: return "SETSCENEA";
case Actions::SET_SAVE_LAYER: return "SetSaveLayer";
case Actions::GOTO_TAG: return "GotoTag";
case Actions::SET_COLOR: return "SetColors";
case Actions::SHOW_DIALOG: return "ShowDialog";
case Actions::FADE_OUT: return "FadeOut";
case Actions::FADE_IN: return "FadeIn";
case Actions::SAVE_IMAGE0: return "SaveImage0";
case Actions::SAVE_REGION_TO_LAYER: return "SaveRegionToLayer";
case Actions::SET_UNKNOWN: return "SETUNKNOWN";
case Actions::SET_WINDOWA: return "SETWINDOWA";
case Actions::SET_WINDOWB: return "SETWINDOWB";
case Actions::SET_WINDOWC: return "SETWINDOWC";
case Actions::DRAW_RECT: return "DrawRect";
case Actions::DRAW_SPRITE0: return "DrawSprite";
case Actions::DRAW_SPRITE1: return "DrawSprite1";
case Actions::DRAW_SPRITE_FLIP_Y: return "DrawSpriteFlipY";
case Actions::DRAW_SPRITE_FLIP_XY: return "DrawSpriteFlipXY";
case Actions::DRAW_SPRITE_ROTATE: return "DrawSpriteRotate";
case Actions::DRAW_SAVED_REGION: return "DrawSavedRegion";
case Actions::DRAW_SCREEN: return "DrawScreen";
case Actions::LOAD_SOUND_RESOURCE: return "LoadSoundResource";
case Actions::SELECT_SOUND: return "SelectSound";
case Actions::DESELECT_SOUND: return "DeselectSound";
case Actions::PLAY_SOUND: return "PlaySound";
case Actions::STOP_SOUND: return "StopSound";
case Actions::LOAD_SCREEN: return "LoadScreen";
case Actions::LOAD_IMAGE: return "LoadImage";
case Actions::LOAD_PALETTE: return "LoadPalette";
case Actions::LOAD_FONT: return "LoadFont";
case Actions::SET_CLIP_REGION: return "SetClipRegion";
case Actions::UNKNOWN_A: return "UNKNOWN_A";
case Actions::UNKNOWN3: return "UNKNOWN3";
case Actions::UNKNOWN4: return "UNKNOWN4";
case Actions::DRAW_FRAME: return "DrawFrame";
case Actions::DRAW_TEXT: return "DrawText";
case Actions::UNKNOWN6: return "UNKNOWN6";
case Actions::UNKNOWN7: return "UNKNOWN7";
default:
std::stringstream ss{};
ss << "Invalid action: 0x" << std::hex
<< static_cast<int>(a) << "\n";
throw std::runtime_error(ss.str());
}
}
std::ostream& operator<<(std::ostream& os, Actions a)
{
os << ToString(a);
return os;
}
std::ostream& operator<<(std::ostream& os, const SetScene& ss)
{
os << "SetScene {" << ss.mSceneNumber << " " << ss.mName << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const LoadScreen& ls)
{
os << "LoadScreen {" << ls.mScreenName << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const ClearScreen& ls)
{
os << "ClearScreen {}";
return os;
}
std::ostream& operator<<(std::ostream& os, const DrawRect& a)
{
os << "DrawRect { PaletteColor: (" << std::get<0>(a.mPaletteColor)
<< ", " << std::get<1>(a.mPaletteColor)
<< "), Pos: " << a.mPos << ", Dims: "
<< a.mDims << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const DrawScreen& a)
{
os << "DrawScreen{ " << a.mPosition << " - " << a.mDimensions << " ("
<< a.mArg1 << ", " << a.mArg2 << ")}";
return os;
}
std::ostream& operator<<(std::ostream& os, const DrawSprite& a)
{
os << "DrawSprite{ flipped: " << a.mFlippedInY << " Pos { " << a.mX << ", " << a.mY
<< "} Sprite: " << a.mSpriteIndex << " imgSlot: " << a.mImageSlot
<< " Dims { " << a.mTargetWidth << ", " << a.mTargetHeight << " } }";
return os;
}
std::ostream& operator<<(std::ostream& os, const ClipRegion& a)
{
os << "ClipRegion{ TL: " << a.mTopLeft << " BR: " << a.mBottomRight << " } }";
return os;
}
std::ostream& operator<<(std::ostream& os, const DisableClipRegion& a)
{
return os << "DisableClipRegion";
}
std::ostream& operator<<(std::ostream& os, const Delay& a)
{
return os << "Delay { time: " << a.mDelayMs << "}";
}
std::ostream& operator<<(std::ostream& os, const Update& a)
{
return os << "Update{}";
}
std::ostream& operator<<(std::ostream& os, const SaveBackground& a)
{
return os << "SaveBackground{}";
}
std::ostream& operator<<(std::ostream& os, const DrawBackground& a)
{
return os << "DrawBackground{}";
}
std::ostream& operator<<(std::ostream& os, const FadeIn& a)
{
return os << "FadeIn{}";
}
std::ostream& operator<<(std::ostream& os, const FadeOut& a)
{
return os << "FadeOut{}";
}
std::ostream& operator<<(std::ostream& os, const Purge& a)
{
return os << "Purge{}";
}
std::ostream& operator<<(std::ostream& os, const SaveImage& a)
{
return os << "SaveImage{ pos: " << a.pos << " dims: " << a.dims << "}";
}
std::ostream& operator<<(std::ostream& os, const SaveRegionToLayer& a)
{
return os << "SaveRegionToLayer{ pos: " << a.pos << " dims: " << a.dims << "}";
}
std::ostream& operator<<(std::ostream& os, const LoadPalette& a)
{
return os << "LoadPalette{ " << a.mPalette << "}";
}
std::ostream& operator<<(std::ostream& os, const LoadImage& a)
{
return os << "LoadImage{ " << a.mImage << "}";
}
std::ostream& operator<<(std::ostream& os, const SlotImage& a)
{
return os << "SlotImage{ " << a.mSlot << "}";
}
std::ostream& operator<<(std::ostream& os, const SetSaveLayer& a)
{
return os << "SetSaveLayer{ " << a.mLayer << "}";
}
std::ostream& operator<<(std::ostream& os, const DrawSavedRegion& a)
{
return os << "DrawSavedRegion{ " << a.mLayer << "}";
}
std::ostream& operator<<(std::ostream& os, const SetColors& a)
{
return os << "SetColors{ fg: " << a.mForegroundColor << " bg: "
<< a.mBackgroundColor << "}";
}
std::ostream& operator<<(std::ostream& os, const SlotPalette& a)
{
return os << "SlotPalette{ " << a.mSlot << "}";
}
std::ostream& operator<<(std::ostream& os, const ShowDialog& a)
{
return os << "ShowDialog{ " << std::hex << a.mDialogKey << std::dec
<< " type: " << a.mDialogType << "}";
}
std::ostream& operator<<(std::ostream& os, const PlaySoundS& a)
{
return os << "PlaySound { " << a.mSoundIndex << "}";
}
std::ostream& operator<<(std::ostream& os, const GotoTag& a)
{
return os << "GotoTag{ " << a.mTag << "}";
}
std::ostream& operator<<(std::ostream& os, const SceneAction& sa)
{
std::visit(overloaded{
[&](const auto& x){ os << x; }},
sa);
return os;
}
}
| 8,325
|
C++
|
.cpp
| 235
| 31.655319
| 87
| 0.646095
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,325
|
soundStore.cpp
|
xavieran_BaKGL/bak/soundStore.cpp
|
#include "bak/dataTags.hpp"
#include "bak/soundStore.hpp"
#include "bak/tags.hpp"
#include "com/path.hpp"
namespace BAK {
SoundStore& SoundStore::Get()
{
static SoundStore soundStore{};
return soundStore;
}
SoundData& SoundStore::GetSoundData(unsigned id)
{
return mSoundMap.at(id);
}
SoundStore::SoundStore()
{
auto fb = FileBufferFactory::Get().CreateDataBuffer(sSoundFile);
auto infbuf = fb.Find(DataTag::INF);
auto tagbuf = fb.Find(DataTag::TAG);
infbuf.Skip(2);
unsigned n = infbuf.GetUint16LE();
infbuf.Skip(1);
Tags tags{};
tags.Load(tagbuf);
for (unsigned i = 0; i < n; i++)
{
unsigned id = infbuf.GetUint16LE();
std::streamoff offset = infbuf.GetUint32LE();
if (const auto name = tags.GetTag(Tag{id}))
{
fb.Seek(offset + 8);
if (id != fb.GetUint16LE())
{
throw std::runtime_error("Data corruption in sound file");
}
unsigned soundType = fb.GetUint8();
fb.Skip(2);
const auto size = fb.GetUint32LE();
auto sndbuf = FileBuffer{size - 2};
fb.Skip(2);
sndbuf.Fill(&fb);
fb.Skip(-sndbuf.GetSize());
std::vector<Sound> sounds{};
int code = fb.GetUint8();
while (code != 0xff)
{
Sound& sound = sounds.emplace_back(code);
std::vector<unsigned int> offsetVec;
std::vector<unsigned int> sizeVec;
code = fb.GetUint8();
while (code != 0xff)
{
fb.Skip(1);
offsetVec.push_back(fb.GetUint16LE());
sizeVec.push_back(fb.GetUint16LE());
code = fb.GetUint8();
}
for (unsigned int j = 0; j < offsetVec.size(); j++)
{
sndbuf.Seek(offsetVec[j]);
auto samplebuf = FileBuffer{sizeVec[j]};
samplebuf.Fill(&sndbuf);
sound.AddVoice(samplebuf);
}
sound.GenerateBuffer();
code = fb.GetUint8();
}
mSoundMap.try_emplace(id, *name, soundType, std::move(sounds));
}
else
{
throw std::runtime_error("Data corruption in sound file");
}
}
}
}
| 2,434
|
C++
|
.cpp
| 76
| 21.578947
| 75
| 0.516212
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,326
|
money.cpp
|
xavieran_BaKGL/bak/money.cpp
|
#include "bak/money.hpp"
#include <sstream>
namespace BAK {
Sovereigns GetSovereigns(Royals royals)
{
return Sovereigns{royals.mValue / 10};
}
Royals GetRoyals(Sovereigns sovereigns)
{
return Royals{sovereigns.mValue * 10};
}
Royals GetRemainingRoyals(Royals royals)
{
return Royals{royals.mValue % 10};
}
std::string ToString(Royals money)
{
const auto sovereigns = BAK::GetSovereigns(money);
const auto royals = BAK::GetRemainingRoyals(money);
std::stringstream ss{};
ss << "#" << sovereigns << "s " << royals << "r";
return ss.str();
}
std::string ToShopString(Royals money)
{
if (money == sUnpurchaseablePrice)
{
return "Unavailable";
}
const auto sovereigns = BAK::GetSovereigns(money);
const auto royals = BAK::GetRemainingRoyals(money);
std::stringstream ss{};
ss << "" ;
if (sovereigns.mValue != 0) ss << sovereigns << " gold";
if (royals.mValue != 0) ss << " " << royals << " silver";
return ss.str();
}
std::string ToShopDialogString(Royals money)
{
const auto sovereigns = BAK::GetSovereigns(money);
const auto royals = BAK::GetRemainingRoyals(money);
std::stringstream ss{};
if (sovereigns.mValue != 0) ss << '\xf0' << sovereigns << " \xf0" << "sovereign";
if (sovereigns.mValue > 1) ss << "s";
if (royals.mValue != 0 && sovereigns.mValue != 0) ss << " \xf0" << "and ";
if (royals.mValue != 0) ss << '\xf0' << royals << " \xf0" << "royal";
if (royals.mValue > 1) ss << "s";
return ss.str();
}
}
| 1,534
|
C++
|
.cpp
| 50
| 27.14
| 85
| 0.645621
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,327
|
backgroundSounds.cpp
|
xavieran_BaKGL/bak/backgroundSounds.cpp
|
#include "bak/backgroundSounds.hpp"
#include "audio/audio.hpp"
#include "bak/gameState.hpp"
#include "bak/types.hpp"
#include "com/random.hpp"
namespace BAK {
void PlayUndergroundSound() {
if (GetRandomNumber(0, 0xfff) % 384 == 0)
{
AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{3});
//unsigned duration = (GetRandomNumber(0, 0xfff) % 50) + 10;
}
}
void PlayNightTimeSound()
{
unsigned soundIndex;
if (GetRandomNumber(0, 0xfff) % 100 <= 5)
{
soundIndex = 0x5A;
}
else
{
soundIndex = 0x33;
}
AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{soundIndex});
//unsigned duration = (GetRandomNumber(0, 0xfff) % 54) + 10;
}
void PlayZoneTwoSound()
{
unsigned soundIndex;
if (GetRandomNumber(0, 0xfff) % 100 <= 50)
{
soundIndex = 0x85; // gulls
}
else
{
soundIndex = (GetRandomNumber(0, 0xfff) % 2) + 0x35;
}
AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{soundIndex});
//unsigned duration = (GetRandomNumber(0, 0xfff) % 54) + 10;
}
void PlayRegularSound()
{
unsigned soundIndex = (GetRandomNumber(0, 0xfff) % 3) + 0x34;
AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{soundIndex});
}
void PlayBackgroundSounds(GameState& gs)
{
// Is underground...
if (gs.GetZone().mValue > 9)
{
PlayUndergroundSound();
}
else if (gs.GetChapter() != Chapter{8} && gs.GetZone() != ZoneNumber{6})
{
if (GetRandomNumber(0, 0xfff) % 110 == 0)
{
if (!gs.ReadEventBool(0x753a))
{
PlayNightTimeSound();
}
else
{
if (gs.GetZone() == ZoneNumber{2})
{
PlayZoneTwoSound();
}
else
{
PlayRegularSound();
}
}
}
}
}
}
| 1,950
|
C++
|
.cpp
| 76
| 18.960526
| 76
| 0.567828
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,328
|
condition.cpp
|
xavieran_BaKGL/bak/condition.cpp
|
#include "bak/condition.hpp"
#include "bak/skills.hpp"
#include "com/logger.hpp"
namespace BAK {
std::string_view ToString(Condition s)
{
using enum Condition;
switch (s)
{
case Sick: return "Sick";
case Plagued: return "Plagued";
case Poisoned: return "Poisoned";
case Drunk: return "Drunk";
case Healing: return "Healing";
case Starving: return "Starving";
case NearDeath: return "NearDeath";
default: return "UnknownCondition";
}
}
std::ostream& operator<<(std::ostream& os, const Conditions& s)
{
os << "Conditions: { ";
char sep = ' ';
for (unsigned i = 0; i < Conditions::sNumConditions; i++)
{
os << sep << ToString(static_cast<Condition>(i))
<< ": " << s.mConditions[i] << "%";
sep = ',';
}
os << "}";
return os;
}
bool Conditions::NoConditions() const
{
for (const auto cond : mConditions)
if (cond != 0) return false;
return true;
}
const ConditionValue& Conditions::GetCondition(BAK::Condition cond) const
{
const auto i = static_cast<unsigned>(cond);
ASSERT(i < sNumConditions);
return mConditions[i];
}
void Conditions::IncreaseCondition(BAK::Condition cond, signed value)
{
const auto i = static_cast<unsigned>(cond);
ASSERT(i < sNumConditions);
mConditions[i] += value;
}
void Conditions::SetCondition(BAK::Condition cond, std::uint8_t amount)
{
mConditions[static_cast<std::uint8_t>(cond)] = ConditionValue{amount};
}
void Conditions::AdjustCondition(Skills& skills, BAK::Condition cond, signed amount)
{
Logging::LogDebug(__FUNCTION__) << " called with : cond: " << ToString(cond) << " amt: " << amount << "\n";
const auto currentValue = GetCondition(cond).Get();
int newValue = currentValue + amount;
if (newValue > 100)
{
newValue = 100;
}
else if (newValue < 0)
{
newValue = 0;
}
SetCondition(cond, newValue);
const bool inCombat = false;
if (cond != Condition::Healing
&& cond != Condition::Drunk
&& (cond != Condition::NearDeath || !inCombat))
{
if (currentValue != 0 && newValue == 0)
{
//mGameState.SetEventFlag(activeCharIndex * 7 + static_cast<unsigned>(cond) + sConditionBasedFlag, 0);
}
else if (currentValue == 0 && newValue != 0)
{
//mGameState.SetEventFlag(activeCharIndex * 7 + static_cast<unsigned>(cond) + sConditionBasedFlag, 1);
}
}
if (cond == Condition::NearDeath)
{
// Check all character NearDeath
//bool allDead = true;
//for (auto character : mActiveCharacter)
//{
// if (character.GetCondition(BAK::Condition::NearDeath).Get() == 0)
// {
// allDead = false;
// }
//}
if (amount > 0)
{
Logging::LogDebug(__FUNCTION__) << " Near death...\n";
for (unsigned i = 0; i < Conditions::sNumConditions - 1; i++)
{
SetCondition(static_cast<Condition>(i), 0);
}
SetCondition(BAK::Condition::NearDeath, 100);
skills.GetSkill(SkillType::Health).mTrueSkill = 0;
skills.GetSkill(SkillType::Stamina).mTrueSkill = 0;
// Near death condition will inhibit this health "increase"...
skills.ImproveSkill(*this, SkillType::TotalHealth, SkillChange::HealMultiplier_100, 0x7fff);
}
}
}
}
| 3,483
|
C++
|
.cpp
| 109
| 25.807339
| 114
| 0.604949
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,329
|
haggle.cpp
|
xavieran_BaKGL/bak/haggle.cpp
|
#include "bak/haggle.hpp"
#include "bak/money.hpp"
namespace BAK::Haggle {
int HaggleRollRandomNumber(int skillValue)
{
int maxRoll = 0;
for (unsigned i = 0; i < 3; i++)
{
const auto roll = static_cast<int>(GetRandomNumber(0, 0xfff) % skillValue);
if (roll > maxRoll)
{
maxRoll = roll;
}
}
return maxRoll;
}
std::optional<unsigned> DoFailHaggle(Party& party, const ShopStats& shop, int randomSkillFactor)
{
const int skillImprovedTest = GetRandomNumber(0, 0xfff) % 100;
// the higher the skill, the less likely we train it
const auto skillTrainThreshold = (100 - randomSkillFactor) / 5;
if (skillImprovedTest < skillTrainThreshold)
{
party.ImproveSkillForAll(SkillType::Haggling, SkillChange::ExercisedSkill, 1);
}
const auto shopAnnoyedTest = GetRandomNumber(0, 0xfff) % 100;
if (shopAnnoyedTest < shop.mHaggleAnnoyanceFactor)
{
return std::make_optional(sUnpurchaseablePrice.mValue);
}
return std::nullopt;
}
std::pair<unsigned, unsigned> GetHaggleWinMargin(unsigned characterSkillValue, unsigned shopHaggleDifficulty)
{
const auto randomSkillFactor = HaggleRollRandomNumber(characterSkillValue);
const auto randomShopHaggleFactor = HaggleRollRandomNumber(shopHaggleDifficulty);
return std::make_pair(
randomSkillFactor,
std::clamp(randomSkillFactor - randomShopHaggleFactor, 0, randomSkillFactor));
}
std::optional<unsigned> TryHaggle(
Party& party,
ActiveCharIndex character,
ShopStats& shop,
ItemIndex item,
int shopCurrentDiscount)
{
const auto itemValue = ObjectIndex::Get().GetObject(item).mValue;
const auto scaledShopValue = (shop.mSellFactor + 100) * itemValue;
const int shopBasicValue = scaledShopValue / 100;
const auto shopBasicValueRemainder = scaledShopValue % 100;
if (shop.mMaxDiscount == 0)
{
return std::nullopt;
}
// Have already haggled successfully if this is the case
if (shopCurrentDiscount != 0)
{
return DoFailHaggle(party, shop, 0x1);
}
const auto characterSkillValue = party.GetCharacter(character).GetSkill(SkillType::Haggling);
const auto [randomSkillFactor, haggleWinMargin] = GetHaggleWinMargin(characterSkillValue, shop.mHaggleDifficulty);
if (haggleWinMargin > 0)
{
const int discount = ((shop.mMaxDiscount - shopBasicValueRemainder) >> 1)
+ haggleWinMargin;
const auto randomDiscount = std::clamp(
HaggleRollRandomNumber(discount),
0, static_cast<int>(shop.mMaxDiscount));
const int discountAmount = (shopBasicValue * randomDiscount) / 100;
party.ImproveSkillForAll(SkillType::Haggling, SkillChange::ExercisedSkill, 1);
party.GetCharacter(character).ImproveSkill(SkillType::Haggling, SkillChange::ExercisedSkill, 1);
return std::make_optional(discountAmount);
}
else
{
return DoFailHaggle(party, shop, randomSkillFactor);
}
}
}
| 3,038
|
C++
|
.cpp
| 80
| 32.3125
| 118
| 0.713363
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,330
|
scene.cpp
|
xavieran_BaKGL/bak/scene.cpp
|
#include "bak/dataTags.hpp"
#include "bak/scene.hpp"
#include "bak/tags.hpp"
#include "bak/dialogSources.hpp"
#include "com/logger.hpp"
#include "com/ostream.hpp"
#include "com/string.hpp"
#include <unordered_map>
namespace BAK {
std::ostream& operator<<(std::ostream& os, const ADSIndex& ai)
{
os << "ADSIndex{ if (" << ai.mLessThan << " <= [chapter] <= "
<< ai.mGreaterThan << ") then " << ai.mIf << " else " << ai.mElse;
return os;
}
std::ostream& operator<<(std::ostream& os, const SceneIndex& si)
{
os << "SceneIndex{ tag: " << si.mSceneTag << " index: " << si.mSceneIndex << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const Scene& scene)
{
os << "Scene :: " << scene.mSceneTag << " [\n";
for (const auto& a : scene.mActions)
{
os << '\t' << a << "\n";
}
os << " ]\n";
os << "Scene Images: \n";
for (const auto& [key, imagePal] : scene.mImages)
{
const auto& [image, palKey] = imagePal;
os << "K: " << key << " " << image << " pal: " << palKey << "\n";
}
os << "Scene Palettes: \n";
for (const auto& [key, pal] : scene.mPalettes)
{
os << "K: " << key << " " << pal << "\n";
}
return os;
}
std::unordered_map<unsigned, SceneIndex> LoadSceneIndices(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
auto resbuf = fb.Find(DataTag::RES);
auto scrbuf = fb.Find(DataTag::SCR);
auto tagbuf = fb.Find(DataTag::TAG);
if (scrbuf.GetUint8() != 0x02)
{
throw std::runtime_error("Script buffer not compressed");
}
auto decompressedSize = scrbuf.GetUint32LE();
auto script = FileBuffer(decompressedSize);
scrbuf.DecompressLZW(&script);
Tags tags{};
tags.Load(tagbuf);
std::optional<unsigned> currentIndex{};
std::optional<unsigned> ttmIndex{};
auto adsIndex = ADSIndex{};
bool inElseClause = false;
std::unordered_map<unsigned, SceneIndex> sceneIndices;
while (!script.AtEnd())
{
if (!currentIndex)
{
currentIndex = script.GetUint16LE();
logger.Debug() << "Index: " << currentIndex << "\n";
}
auto code = script.GetUint16LE();
auto action = static_cast<AdsActions>(code);
std::stringstream ss{};
ss << std::hex << code << std::dec << " adsAct: " << action << " ";
switch (action)
{
case AdsActions::INDEX:
{
const auto a = script.GetUint16LE();
const auto b = script.GetUint16LE();
ss << a << " " << b;
}
break;
case AdsActions::IF_NOT_PLAYED: [[fallthrough]];
case AdsActions::IF_PLAYED:
{
const auto a = script.GetUint16LE();
const auto b = script.GetUint16LE();
ss << a << " " << b;
}
break;
case AdsActions::ADD_SCENE2: [[fallthrough]];
case AdsActions::ADD_SCENE:
{
const auto a = script.GetUint16LE();
const auto b = script.GetUint16LE();
const auto c = script.GetUint16LE();
const auto d = script.GetUint16LE();
ss << a << " " << b << " " << c << " " << d;
ttmIndex = std::max(
std::max(a, b),
std::max(c, d));
if (!inElseClause)
adsIndex.mIf = *ttmIndex;
else
adsIndex.mElse = *ttmIndex;
}
break;
case AdsActions::END:
{
ASSERT(currentIndex);
ASSERT(ttmIndex);
const auto sceneName = tags.GetTag(Tag{*currentIndex});
if (!sceneName)
throw std::runtime_error("Tag not found");
sceneIndices[*currentIndex] = SceneIndex{
*sceneName,
adsIndex};
// Reset the state for next scene index
currentIndex.reset();
ttmIndex.reset();
adsIndex = ADSIndex{};
inElseClause = false;
}
break;
case AdsActions::STOP_SCENE:
{
const auto a = script.GetUint16LE();
const auto b = script.GetUint16LE();
const auto c = script.GetUint16LE();
ss << a << " " << b << " " << c;
}
break;
case AdsActions::IF_CHAP_GTE:
{
const auto a = script.GetUint16LE();
ss << a;
adsIndex.mGreaterThan = a;
}
break;
case AdsActions::IF_CHAP_LTE:
{
const auto a = script.GetUint16LE();
ss << a;
adsIndex.mLessThan = a;
}
break;
case AdsActions::ELSE:
inElseClause = true;
break;
// Currently only chapter conditions are implemented
// so and and or are not implemented...
case AdsActions::AND: [[fallthrough]];
case AdsActions::OR: [[fallthrough]];
case AdsActions::FADE_OUT: [[fallthrough]];
case AdsActions::END_IF: [[fallthrough]];
case AdsActions::PLAY_SCENE: [[fallthrough]];
case AdsActions::PLAY_ALL_SCENES:
break;
}
logger.Debug() << ss.str() << "\n";
}
return sceneIndices;
}
std::unordered_map<unsigned, std::vector<SceneSequence>> LoadSceneSequences(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
auto resbuf = fb.Find(DataTag::RES);
auto scrbuf = fb.Find(DataTag::SCR);
auto tagbuf = fb.Find(DataTag::TAG);
if (scrbuf.GetUint8() != 0x02)
{
throw std::runtime_error("Script buffer not compressed");
}
auto decompressedSize = scrbuf.GetUint32LE();
auto script = FileBuffer(decompressedSize);
scrbuf.DecompressLZW(&script);
Tags tags{};
tags.Load(tagbuf);
tags.DumpTags();
std::optional<unsigned> currentIndex{};
std::unordered_map<unsigned, std::vector<SceneSequence>> sceneIndices;
SceneSequence currentSequence{};
while (!script.AtEnd())
{
if (!currentIndex)
{
currentIndex = script.GetUint16LE();
sceneIndices.emplace(*currentIndex, std::vector<SceneSequence>({}));
logger.Debug() << "Index: " << currentIndex << "\n";
}
auto code = script.GetUint16LE();
auto action = static_cast<AdsActions>(code);
std::stringstream ss{};
ss << std::hex << code << std::dec << " adsAct: " << action << " ";
switch (action)
{
case AdsActions::INDEX:
{
const auto a = script.GetUint16LE();
const auto b = script.GetUint16LE();
ss << a << " " << b;
}
break;
case AdsActions::IF_NOT_PLAYED: [[fallthrough]];
case AdsActions::IF_PLAYED:
{
const auto a = script.GetUint16LE();
const auto b = script.GetUint16LE();
ss << a << " " << b;
}
break;
case AdsActions::ADD_SCENE2: [[fallthrough]];
case AdsActions::ADD_SCENE:
{
const auto a = script.GetUint16LE();
const auto b = script.GetUint16LE();
const auto c = script.GetUint16LE();
const auto d = script.GetUint16LE();
ss << a << " " << b << " " << c << " " << d;
ASSERT(currentIndex);
currentSequence.mScenes.emplace_back(SceneADS(a, b, false));
}
break;
case AdsActions::PLAY_SCENE:
{
ASSERT(currentIndex);
const auto sceneName = tags.GetTag(Tag{*currentIndex});
if (!sceneName)
throw std::runtime_error("Tag not found");
// Reset the state for next scene index
currentSequence.mName = *sceneName;
sceneIndices.at(*currentIndex).emplace_back(currentSequence);
currentSequence = {};
} break;
case AdsActions::PLAY_ALL_SCENES:
{
ASSERT(currentIndex);
const auto sceneName = tags.GetTag(Tag{*currentIndex});
if (!sceneName)
throw std::runtime_error("Tag not found");
currentSequence.mName = *sceneName;
sceneIndices.at(*currentIndex).emplace_back(currentSequence);
currentSequence = {};
} break;
case AdsActions::END:
{
currentIndex.reset();
} break;
case AdsActions::STOP_SCENE:
{
const auto a = script.GetUint16LE();
const auto b = script.GetUint16LE();
const auto c = script.GetUint16LE();
ss << a << " " << b << " " << c;
} break;
case AdsActions::IF_CHAP_GTE:
{
assert(false);
} break;
case AdsActions::IF_CHAP_LTE:
{
assert(false);
}
break;
case AdsActions::ELSE:
assert(false);
break;
// Currently only chapter conditions are implemented
// so and and or are not implemented...
case AdsActions::AND: [[fallthrough]];
case AdsActions::OR: [[fallthrough]];
case AdsActions::FADE_OUT: [[fallthrough]];
case AdsActions::END_IF:
break;
}
logger.Debug() << ss.str() << "\n";
}
return sceneIndices;
}
std::unordered_map<unsigned, Scene> LoadScenes(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
std::vector<SceneChunk> chunks;
auto pageBuffer = fb.Find(DataTag::PAG);
auto versionBuffer = fb.Find(DataTag::VER);
auto tt3Buffer = fb.Find(DataTag::TT3);
auto tagBuffer = fb.Find(DataTag::TAG);
const auto pages = pageBuffer.GetUint16LE();
logger.Debug() << "Pages:" << pages << " size: " << pageBuffer.GetSize() << "\n";
logger.Debug() << "Version size: " << versionBuffer.GetSize() << "\n";
auto compression = tt3Buffer.GetUint8();
auto decompressedSize = tt3Buffer.GetUint32LE();
FileBuffer decompBuffer = FileBuffer(decompressedSize);
logger.Debug() << "TT3 size: " << decompressedSize << "\n";
if (compression == 1)
{
logger.Debug() << "RLE Compressed\n";
tt3Buffer.DecompressRLE(&decompBuffer);
}
else
{
logger.Debug() << "No compression\n";
tt3Buffer.CopyTo(&decompBuffer, decompressedSize);
}
Tags tags{};
tags.Load(tagBuffer);
tags.DumpTags();
auto offset = 8 * 3 + pageBuffer.GetSize() + versionBuffer.GetSize() + 5;
while (!decompBuffer.AtEnd())
{
unsigned location = decompBuffer.Tell() + offset;
unsigned int code = decompBuffer.GetUint16LE();
unsigned int size = code & 0x000f;
code &= 0xfff0;
auto action = static_cast<Actions>(code);
std::stringstream ss{};
ss << "off: " << std::hex << location << " |Code: " << std::hex << code << " "
<< action << std::dec;
if ((code == 0x1110) && (size == 1))
{
unsigned int id = decompBuffer.GetUint16LE();
auto name = tags.GetTag(Tag{id});
if (!name)
{
std::stringstream ids{};
ids << "Unknown[" << id << "]";
name = ids.str();
}
ss << " Name: " << *name << " id [" << id <<"]";
chunks.emplace_back(action, name, std::vector<std::int16_t>{static_cast<int16_t>(id)});
}
else if (size == 0xf)
{
std::string name = ToUpper(decompBuffer.GetString());
ss << " Name: " << name << " noId";
if (decompBuffer.GetBytesLeft() & 1) decompBuffer.Skip(1);
chunks.emplace_back(action, name, std::vector<std::int16_t>{-1});
}
else
{
std::vector<std::int16_t> args{};
for (unsigned int i = 0; i < size; i++)
args.emplace_back(decompBuffer.GetSint16LE());
ss << " args [ ";
auto sep = ' ';
for (const auto& a : args)
{
ss << sep << a;
sep = ',';
}
ss << " ]";
chunks.emplace_back(
action,
std::optional<std::string>{},
args);
}
logger.Debug() << ss.str() << "\n";
}
std::unordered_map<unsigned, Scene> scenes{};
Scene currentScene;
bool loadingScene = false;
bool flipped = false;
std::optional<unsigned> imageSlot = 0;
std::optional<PaletteSlot> paletteSlot{};
std::optional<std::pair<unsigned, unsigned>> activeColor{};
std::unordered_map<unsigned, std::string> palettes{};
std::unordered_map<
unsigned,
std::pair<std::string, unsigned>> images{};
// FIXME: Probably a nicer way of doing image slots.
std::unordered_map<
unsigned,
ImageSlot> imageSlots;
std::unordered_map<
unsigned,
std::pair<std::string, unsigned>> screens{};
const auto PushScene = [&]{
currentScene.mPalettes = palettes;
currentScene.mImages.clear();
for (auto [key, val] : images)
{
if (!currentScene.mPalettes.contains(val.second))
{
val = std::make_pair(val.first, 0);
}
currentScene.mImages[key] = val;
}
currentScene.mScreens = screens;
currentScene.mActions.emplace_back(DisableClipRegion{});
const auto tag = tags.FindTag(currentScene.mSceneTag);
if (tag)
{
scenes[tag->mValue] = currentScene;
}
else
{
throw std::runtime_error("Tag not found");
}
};
for (const auto& chunk : chunks)
{
switch (chunk.mAction)
{
case Actions::SLOT_IMAGE:
imageSlot = chunk.mArguments[0];
break;
case Actions::SLOT_PALETTE:
paletteSlot = chunk.mArguments[0];
break;
case Actions::SET_SCENE:
if (loadingScene)
PushScene();
ASSERT(chunk.mResourceName);
currentScene.mSceneTag = *chunk.mResourceName;
currentScene.mActions.clear();
currentScene.mImages.clear();
currentScene.mScreens.clear();
currentScene.mPalettes.clear();
images.clear();
imageSlots.clear();
palettes.clear();
imageSlot.reset();
activeColor.reset();
screens.clear();
loadingScene = true;
break;
case Actions::SET_CLIP_REGION:
// Transform this to opengl coords...
currentScene.mActions.emplace_back(
ClipRegion{
glm::vec2{chunk.mArguments[0], chunk.mArguments[1]},
glm::vec2{chunk.mArguments[2], chunk.mArguments[3]}});
break;
case Actions::LOAD_PALETTE:
{
//ASSERT(loadingScene);
ASSERT(chunk.mResourceName);
ASSERT(paletteSlot);
const auto paletteName = *chunk.mResourceName;
palettes[*paletteSlot] = paletteName;
if (!imageSlots.contains(*paletteSlot))
{
imageSlots[*paletteSlot] = ImageSlot{};
}
imageSlots[*paletteSlot].mPalette = *paletteSlot;
} break;
case Actions::SET_COLOR:
//ASSERT(paletteSlot);
activeColor = std::make_pair(
paletteSlot ? *paletteSlot : 0,
chunk.mArguments[0]);
break;
case Actions::LOAD_IMAGE:
{
//ASSERT(loadingScene);
ASSERT(chunk.mResourceName);
ASSERT(imageSlot);
auto name = *chunk.mResourceName;
(*(name.end() - 1)) = 'X';
images[*imageSlot] = std::make_pair(name, paletteSlot ? *paletteSlot: *imageSlot);
if (!imageSlots.contains(*imageSlot))
{
imageSlots[*imageSlot] = ImageSlot{};
}
} break;
case Actions::LOAD_SCREEN:
{
ASSERT(chunk.mResourceName);
if (!paletteSlot) break;
auto name = *chunk.mResourceName;
(*(name.end() - 1)) = 'X';
screens[*paletteSlot] = std::make_pair(name, *paletteSlot);
} break;
case Actions::DRAW_SCREEN:
{
currentScene.mActions.emplace_back(
DrawScreen{
glm::vec2{chunk.mArguments[0], chunk.mArguments[1]},
glm::vec2{chunk.mArguments[2], chunk.mArguments[3]},
static_cast<unsigned>(chunk.mArguments[4]),
static_cast<unsigned>(chunk.mArguments[5])
});
} break;
case Actions::DRAW_RECT:
case Actions::DRAW_FRAME:
// There must be a default colour?
//ASSERT(activeColor);
currentScene.mActions.emplace_back(
DrawRect{
*activeColor,
glm::vec2{chunk.mArguments[0], chunk.mArguments[1]},
glm::vec2{chunk.mArguments[2], chunk.mArguments[3]}});
break;
// FIXME: Implement the rotation
case Actions::DRAW_SPRITE_ROTATE: [[fallthrough]];
// FIXME: Implement flip in x and y
case Actions::DRAW_SPRITE_FLIP_XY: [[fallthrough]];
case Actions::DRAW_SPRITE1: [[fallthrough]];
case Actions::DRAW_SPRITE_FLIP_Y:
flipped = true;
[[fallthrough]];
case Actions::DRAW_SPRITE0:
{
const auto scaled = chunk.mArguments.size() >= 5;
currentScene.mActions.emplace_back(
DrawSprite{
flipped,
chunk.mArguments[0],
chunk.mArguments[1],
chunk.mArguments[2],
chunk.mArguments[3],
static_cast<std::int16_t>(scaled ? chunk.mArguments[4] : 0),
static_cast<std::int16_t>(scaled ? chunk.mArguments[5] : 0)});
flipped = false;
} break;
case Actions::UPDATE:
{
currentScene.mActions.emplace_back(Update{});
} break;
case Actions::PURGE:
{
currentScene.mActions.emplace_back(Purge{});
} break;
case Actions::DELAY:
{
currentScene.mActions.emplace_back(
Delay{static_cast<unsigned>(chunk.mArguments[0])});
} break;
default:
//logger.Debug() << "Unhandled action: " << chunk.mAction << "\n";
break;
}
}
// Push final scene
PushScene();
return scenes;
}
std::vector<SceneAction> LoadDynamicScenes(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
std::vector<SceneChunk> chunks;
auto pageBuffer = fb.Find(DataTag::PAG);
auto versionBuffer = fb.Find(DataTag::VER);
auto tt3Buffer = fb.Find(DataTag::TT3);
auto tagBuffer = fb.Find(DataTag::TAG);
const auto pages = pageBuffer.GetUint16LE();
logger.Debug() << "Pages:" << pages << " size: " << pageBuffer.GetSize() << "\n";
logger.Debug() << "Version size: " << versionBuffer.GetSize() << "\n";
auto compression = tt3Buffer.GetUint8();
auto decompressedSize = tt3Buffer.GetUint32LE();
FileBuffer decompBuffer = FileBuffer(decompressedSize);
if (compression == 1)
{
logger.Debug() << "RLE Compressed\n";
tt3Buffer.DecompressRLE(&decompBuffer);
}
else
{
logger.Debug() << "No compression\n";
tt3Buffer.CopyTo(&decompBuffer, decompressedSize);
}
Tags tags{};
tags.Load(tagBuffer);
tags.DumpTags();
while (!decompBuffer.AtEnd())
{
unsigned int code = decompBuffer.GetUint16LE();
unsigned int size = code & 0x000f;
code &= 0xfff0;
auto action = static_cast<Actions>(code);
std::stringstream ss{};
ss << "Code: " << std::hex << code << " "
<< action << std::dec;
if ((code == 0x1110) && (size == 1))
{
unsigned int id = decompBuffer.GetUint16LE();
auto name = tags.GetTag(Tag{id});
if (!name)
{
std::stringstream ids{};
ids << id;
name = ids.str();
}
ss << " Name: " << *name << " id [" << id <<"]";
chunks.emplace_back(action, name, std::vector<std::int16_t>{});
}
else if (size == 0xf)
{
std::string name = ToUpper(decompBuffer.GetString());
ss << " Name: " << name;
if (decompBuffer.GetBytesLeft() & 1) decompBuffer.Skip(1);
chunks.emplace_back(action, name, std::vector<std::int16_t>{});
}
else
{
std::vector<std::int16_t> args{};
for (unsigned int i = 0; i < size; i++)
args.emplace_back(decompBuffer.GetSint16LE());
ss << " args [ ";
auto sep = ' ';
for (const auto& a : args)
{
ss << sep << a;
sep = ',';
}
ss << " ]";
chunks.emplace_back(
action,
std::optional<std::string>{},
args);
}
logger.Debug() << ss.str() << "\n";
}
std::vector<SceneAction> actions{};
bool flipped = false;
for (const auto& chunk : chunks)
{
switch (chunk.mAction)
{
case Actions::SLOT_IMAGE:
actions.emplace_back(SlotImage{static_cast<unsigned>(chunk.mArguments[0])});
break;
case Actions::SLOT_PALETTE:
actions.emplace_back(SlotPalette{static_cast<unsigned>(chunk.mArguments[0])});
break;
case Actions::SET_SCENEA: [[fallthrough]];
case Actions::SET_SCENE:
{
//actions.emplace_back(DisableClipRegion{});
auto action = SetScene{};
std::string sceneTag{};
unsigned tagId{};
if (chunk.mResourceName)
{
sceneTag = *chunk.mResourceName;
const auto tag = tags.FindTag(sceneTag);
if (tag)
{
tagId = tag->mValue;
}
else
{
tagId = -1;
}
}
else
{
const auto tag = tags.GetTag(Tag{static_cast<unsigned>(chunk.mArguments[0])});
tagId = chunk.mArguments[0];
if (!tag)
{
std::stringstream ss{};
ss << chunk.mArguments[0];
sceneTag = ss.str();
}
else
{
sceneTag = *tag;
}
}
action.mName = sceneTag;
action.mSceneNumber = tagId;
actions.emplace_back(action);
} break;
case Actions::SET_CLIP_REGION:
// Transform this to opengl coords...
actions.emplace_back(
ClipRegion{
glm::vec2{chunk.mArguments[0], chunk.mArguments[1]},
glm::vec2{chunk.mArguments[2], chunk.mArguments[3]}});
break;
case Actions::LOAD_PALETTE:
{
const auto paletteName = *chunk.mResourceName;
actions.emplace_back(LoadPalette{paletteName});
} break;
case Actions::SAVE_IMAGE0:
{
actions.emplace_back(
SaveImage{
glm::vec2{chunk.mArguments[0], chunk.mArguments[1]},
glm::vec2{chunk.mArguments[2], chunk.mArguments[3]}});
} break;
case Actions::PLAY_SOUND:
{
actions.emplace_back(
PlaySoundS{static_cast<unsigned>(chunk.mArguments[0])});
} break;
case Actions::SAVE_BACKGROUND:
{
actions.emplace_back(
SaveBackground{});
} break;
case Actions::SET_COLOR:
actions.emplace_back(
SetColors{
static_cast<unsigned>(chunk.mArguments[0]),
static_cast<unsigned>(chunk.mArguments[1])});
break;
case Actions::LOAD_IMAGE:
{
auto imageName = *chunk.mResourceName;
(*(imageName.end() - 1)) = 'X';
actions.emplace_back(LoadImage{imageName});
} break;
case Actions::LOAD_SCREEN:
{
ASSERT(chunk.mResourceName);
auto name = *chunk.mResourceName;
(*(name.end() - 1)) = 'X';
actions.emplace_back(LoadScreen{name});
} break;
case Actions::DRAW_SCREEN:
{
actions.emplace_back(
DrawScreen{
glm::vec2{chunk.mArguments[0], chunk.mArguments[1]},
glm::vec2{chunk.mArguments[2], chunk.mArguments[3]},
static_cast<unsigned>(chunk.mArguments[4]),
static_cast<unsigned>(chunk.mArguments[5])
});
} break;
case Actions::FADE_IN:
{
actions.emplace_back(FadeIn{});
} break;
case Actions::FADE_OUT:
{
actions.emplace_back(FadeOut{});
} break;
case Actions::GOTO_TAG:
{
actions.emplace_back(GotoTag{static_cast<unsigned>(chunk.mArguments[0])});
} break;
case Actions::SHOW_DIALOG:
{
actions.emplace_back(
ShowDialog{
static_cast<unsigned>(chunk.mArguments[0]),
static_cast<unsigned>(chunk.mArguments[1])});
} break;
case Actions::DRAW_RECT:
case Actions::DRAW_FRAME:
actions.emplace_back(
DrawRect{
std::make_pair(0,0), // active color
glm::vec2{chunk.mArguments[0], chunk.mArguments[1]},
glm::vec2{chunk.mArguments[2], chunk.mArguments[3]}});
break;
// FIXME: Implement the rotation
case Actions::DRAW_SPRITE_ROTATE: [[fallthrough]];
// FIXME: Implement flip in x and y
case Actions::DRAW_SPRITE_FLIP_XY: [[fallthrough]];
case Actions::DRAW_SPRITE1: [[fallthrough]];
case Actions::DRAW_SPRITE_FLIP_Y:
flipped = true;
[[fallthrough]];
case Actions::DRAW_SPRITE0:
{
const auto scaled = chunk.mArguments.size() >= 5;
actions.emplace_back(
DrawSprite{
flipped,
chunk.mArguments[0],
chunk.mArguments[1],
chunk.mArguments[2],
chunk.mArguments[3],
static_cast<std::int16_t>(scaled ? chunk.mArguments[4] : 0),
static_cast<std::int16_t>(scaled ? chunk.mArguments[5] : 0)});
flipped = false;
} break;
case Actions::SET_SAVE_LAYER:
{
actions.emplace_back(SetSaveLayer{
static_cast<unsigned>(chunk.mArguments[0])});
} break;
case Actions::DRAW_SAVED_REGION:
{
actions.emplace_back(DrawSavedRegion{
static_cast<unsigned>(chunk.mArguments[0])});
} break;
case Actions::SAVE_REGION_TO_LAYER:
{
actions.emplace_back(
SaveRegionToLayer{
glm::vec2{chunk.mArguments[0], chunk.mArguments[1]},
glm::vec2{chunk.mArguments[2], chunk.mArguments[3]}});
} break;
case Actions::UPDATE:
{
actions.emplace_back(Update{});
} break;
case Actions::PURGE:
{
actions.emplace_back(Purge{});
} break;
case Actions::DELAY:
{
actions.emplace_back(
Delay{static_cast<unsigned>(chunk.mArguments[0])});
} break;
default:
logger.Debug() << "Unhandled action: " << chunk.mAction << "\n";
break;
}
}
return actions;
}
FileBuffer DecompressTTM(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
auto pageBuffer = fb.Find(DataTag::PAG);
auto versionBuffer = fb.Find(DataTag::VER);
auto tt3Buffer = fb.Find(DataTag::TT3);
auto tagBuffer = fb.Find(DataTag::TAG);
const auto pages = pageBuffer.GetUint16LE();
logger.Debug() << "Pages:" << pages << " size: " << pageBuffer.GetSize() << "\n";
logger.Debug() << "Version: " << versionBuffer.GetString() << "\n";
auto compression = tt3Buffer.GetUint8();
logger.Debug() << "Compression: " << +compression << "\n";
auto size = tt3Buffer.GetUint32LE();
logger.Debug() << "Decompressed size: " << size << "\n";
FileBuffer decompBuffer = FileBuffer(size);
auto decomped = tt3Buffer.DecompressRLE(&decompBuffer);
logger.Debug() << "Decompressed bytes: " << decomped << "\n";
Tags tags{};
tags.Load(tagBuffer);
tags.DumpTags();
auto decompressedTTM = FileBuffer(
pageBuffer.GetSize() + 8
+ versionBuffer.GetSize() + 8
+ tagBuffer.GetSize() + 8
+ 1 + 4 + decomped + 8);
decompressedTTM.PutUint32LE(static_cast<std::uint32_t>(DataTag::VER));
decompressedTTM.PutUint32LE(versionBuffer.GetSize());
versionBuffer.Rewind();
versionBuffer.CopyTo(&decompressedTTM, versionBuffer.GetSize());
decompressedTTM.PutUint32LE(static_cast<std::uint32_t>(DataTag::PAG));
decompressedTTM.PutUint32LE(pageBuffer.GetSize());
pageBuffer.Rewind();
pageBuffer.CopyTo(&decompressedTTM, pageBuffer.GetSize());
decompressedTTM.PutUint32LE(static_cast<std::uint32_t>(DataTag::TT3));
decompressedTTM.PutUint32LE(1 + 4 + decomped);
decompressedTTM.PutUint8(0);
decompressedTTM.PutUint32LE(decomped);
decompBuffer.Rewind();
decompBuffer.CopyTo(&decompressedTTM, decompBuffer.GetSize());
decompressedTTM.PutUint32LE(static_cast<std::uint32_t>(DataTag::TAG));
decompressedTTM.PutUint32LE(tagBuffer.GetSize());
tagBuffer.Rewind();
tagBuffer.CopyTo(&decompressedTTM, tagBuffer.GetSize());
return decompressedTTM;
}
}
| 31,398
|
C++
|
.cpp
| 853
| 25.515826
| 99
| 0.522636
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,331
|
character.cpp
|
xavieran_BaKGL/bak/character.cpp
|
#include "bak/character.hpp"
#include "bak/itemNumbers.hpp"
#include "com/ostream.hpp"
#include <algorithm>
#include <ios>
namespace BAK {
Character::Character(
unsigned index,
const std::string& name,
const Skills& skills,
Spells spells,
const std::array<std::uint8_t, 2>& unknown,
const std::array<std::uint8_t, 7>& unknown2,
const Conditions& conditions,
Inventory&& inventory)
:
mCharacterIndex{index},
mName{name},
mSkills{skills},
mSpells{spells},
mUnknown{unknown},
mUnknown2{unknown2},
mConditions{conditions},
mInventory{std::move(inventory)},
mSkillAffectors{},
mLogger{Logging::LogState::GetLogger("BAK::Character")}
{}
/* IContainer */
Inventory& Character::GetInventory() { return mInventory; }
const Inventory& Character::GetInventory() const { return mInventory; }
bool Character::CanSwapItem(const InventoryItem& ref) const
{
return (ref.IsItemType(BAK::ItemType::Sword) && IsSwordsman())
|| (ref.IsItemType(BAK::ItemType::Staff) && IsSpellcaster());
}
bool Character::CanAddItem(const InventoryItem& ref) const
{
auto item = ref;
const auto itemIndex = ref.GetItemIndex();
// Day's rations are equivalent to 1 of normal rations
if (itemIndex == BAK::sDayRations)
{
item = InventoryItemFactory::MakeItem(BAK::sRations, 1);
}
if (mInventory.CanAddCharacter(item) > 0)
return true;
else if (item.IsItemType(ItemType::Staff)
&& HasEmptyStaffSlot())
return true;
else if (item.IsItemType(ItemType::Sword)
&& HasEmptySwordSlot())
return true;
else if (item.IsItemType(ItemType::Crossbow)
&& HasEmptyCrossbowSlot())
return true;
else if (item.IsItemType(ItemType::Armor)
&& HasEmptyArmorSlot())
return true;
else
return false;
}
bool Character::GiveItem(const InventoryItem& ref)
{
auto item = ref;
const auto itemIndex = ref.GetItemIndex();
bool equipped = false;
if (CanReplaceEquippableItem(item.GetObject().mType)
&& mInventory.FindEquipped(item.GetObject().mType)
== mInventory.GetItems().end())
{
item.SetEquipped(true);
equipped = true;
}
else
{
item.SetEquipped(false);
}
// Day's rations are equivalent to 1 of normal rations
if (itemIndex == BAK::sDayRations)
{
item = InventoryItemFactory::MakeItem(BAK::sRations, 1);
}
// Quegian brandy
else if (itemIndex == BAK::sBrandy
|| itemIndex == BAK::sAle
|| itemIndex == BAK::sKeshianAle)
{
mConditions.IncreaseCondition(
static_cast<Condition>(ref.GetObject().mEffectMask),
ref.GetObject().mEffect);
return true;
}
if (item.GetItemIndex() == sRations
&& GetConditions().GetCondition(Condition::Starving).Get() > 0)
{
AdjustCondition(Condition::Starving, -100);
item.SetQuantity(item.GetQuantity() - 1);
if (item.GetQuantity() == 0)
{
return true;
}
}
const auto stackSize = item.GetObject().mStackSize;
// Split into stacks if necessary
std::vector<InventoryItem> items{};
if (item.IsStackable()
&& item.GetQuantity() > stackSize)
{
const auto nStacks = item.GetQuantity() / stackSize;
for (unsigned i = 0; i < nStacks; i++)
{
items.emplace_back(
InventoryItemFactory::MakeItem(
ItemIndex{itemIndex},
stackSize));
}
const auto remainder = item.GetQuantity() % stackSize;
if (remainder != 0)
items.emplace_back(
InventoryItemFactory::MakeItem(
ItemIndex{itemIndex},
remainder));
}
else
{
items.emplace_back(item);
}
bool added = false;
for (const auto& item : items)
{
if (mInventory.CanAddCharacter(item) || equipped)
{
mInventory.AddItem(item);
added = true;
}
}
return added;
}
bool Character::RemoveItem(const InventoryItem& item)
{
if (mInventory.HaveItem(item))
{
mInventory.RemoveItem(item);
return true;
}
return false;
}
ContainerType Character::GetContainerType() const
{
return ContainerType::Inv;
}
ShopStats& Character::GetShop() { ASSERT(false); return *reinterpret_cast<ShopStats*>(this);}
const ShopStats& Character::GetShop() const { ASSERT(false); return *reinterpret_cast<const ShopStats*>(this);}
LockStats& Character::GetLock() { ASSERT(false); return *reinterpret_cast<LockStats*>(this); }
/* Character Getters */
CharIndex Character::GetIndex() const { return mCharacterIndex; }
bool Character::IsSpellcaster() const { return mSkills.GetSkill(BAK::SkillType::Casting).mMax != 0; }
bool Character::IsSwordsman() const { return !IsSpellcaster(); }
bool Character::HasEmptyStaffSlot() const
{
return IsSpellcaster()
&& mInventory.FindEquipped(ItemType::Staff)
== mInventory.GetItems().end();
}
bool Character::HasEmptySwordSlot() const
{
return IsSwordsman()
&& mInventory.FindEquipped(ItemType::Sword)
== mInventory.GetItems().end();
}
bool Character::HasEmptyCrossbowSlot() const
{
return IsSwordsman()
&& mInventory.FindEquipped(ItemType::Crossbow)
== mInventory.GetItems().end();
}
bool Character::HasEmptyArmorSlot() const
{
return mInventory.FindEquipped(ItemType::Armor)
== mInventory.GetItems().end();
}
InventoryIndex Character::GetItemAtSlot(ItemType slot) const
{
auto it = mInventory.FindEquipped(slot) ;
const auto index = mInventory.GetIndexFromIt(it);
assert(index);
return *index;
}
ItemType Character::GetWeaponType() const
{
if (IsSpellcaster())
return ItemType::Staff;
else
return ItemType::Sword;
}
bool Character::CanReplaceEquippableItem(ItemType type) const
{
if (IsSpellcaster() && type == ItemType::Staff)
return true;
else if (IsSwordsman() && (type == ItemType::Sword
|| type == ItemType::Crossbow))
return true;
else if (type == ItemType::Armor)
return true;
return false;
}
void Character::ApplyItemToSlot(InventoryIndex index, ItemType slot)
{
auto& item = mInventory.GetAtIndex(index);
auto equipped = mInventory.FindEquipped(slot);
if (equipped == mInventory.GetItems().end())
{
item.SetEquipped(true);
return;
}
const auto slotIndex = *mInventory.GetIndexFromIt(equipped);
// We are trying to move this item onto itself
if (slotIndex == index)
{
return;
}
if (item.IsItemType(slot))
{
item.SetEquipped(true);
if (equipped != mInventory.GetItems().end())
equipped->SetEquipped(false);
}
else
{
// Try use item at index on slot item
//UseItem(index, slotIndex);
}
Logging::LogDebug("CharacterAFMove") << __FUNCTION__ << " " << item << " " << BAK::ToString(slot) << "\n";
if (equipped != mInventory.GetItems().end())
Logging::LogDebug("CharacterAFEquip") << __FUNCTION__ << " " << *equipped << " " << equipped->IsEquipped() << " " << BAK::ToString(slot) << "\n";
}
void Character::CheckPostConditions()
{
if (IsSpellcaster())
{
ASSERT(GetInventory().FindEquipped(ItemType::Sword)
== GetInventory().GetItems().end());
ASSERT(GetInventory().FindEquipped(ItemType::Crossbow)
== GetInventory().GetItems().end());
unsigned staffCount = 0;
for (const auto& item : GetInventory().GetItems())
{
if (item.IsItemType(ItemType::Staff) && item.IsEquipped())
{
staffCount++;
}
}
ASSERT(staffCount <= 1);
}
else
{
ASSERT(GetInventory().FindEquipped(ItemType::Staff)
== GetInventory().GetItems().end());
unsigned swordCount = 0;
for (const auto& item : GetInventory().GetItems())
{
if (item.IsItemType(ItemType::Sword) && item.IsEquipped())
{
swordCount++;
}
}
ASSERT(swordCount <= 1);
unsigned crossbowCount = 0;
for (const auto& item : GetInventory().GetItems())
{
if (item.IsItemType(ItemType::Crossbow) && item.IsEquipped())
{
crossbowCount++;
}
}
ASSERT(crossbowCount <= 1);
}
}
unsigned Character::GetTotalItem(const std::vector<BAK::ItemIndex>& itemIndex)
{
unsigned total = 0;
for (const auto& item : GetInventory().GetItems())
{
if (std::find_if(itemIndex.begin(), itemIndex.end(), [&item](auto& elem){ return item.GetItemIndex() == elem;}) != itemIndex.end())
{
if (item.IsConditionBased() || item.IsChargeBased())
{
total += 1;
}
else
{
total += item.GetQuantity();
}
}
}
return total;
}
const std::string& Character::GetName() const
{
return mName;
}
bool Character::CanHeal(bool isInn)
{
const auto multiplier = isInn ? 1.0 : .80;
const auto health = GetSkill(BAK::SkillType::TotalHealth);
const auto maxHealth = GetMaxSkill(BAK::SkillType::TotalHealth);
return health < (maxHealth * multiplier);
}
bool Character::HaveNegativeCondition()
{
for (unsigned i = 0; i < Conditions::sNumConditions; i++)
{
auto cond = static_cast<BAK::Condition>(i);
if (cond == BAK::Condition::Healing) continue;
if (mConditions.GetCondition(cond).Get() > 0) return true;
}
return false;
}
const Skills& Character::GetSkills() const
{
return mSkills;
}
Skills& Character::GetSkills()
{
return mSkills;
}
void Character::ImproveSkill(SkillType skill, SkillChange skillChangeType, int multiplier)
{
mSkills.ImproveSkill(mConditions, skill, skillChangeType, multiplier);
UpdateSkills();
}
unsigned Character::GetSkill(SkillType skill) const
{
if (skill != SkillType::TotalHealth)
{
mSkills.GetSkill(skill).mModifier = mInventory.CalculateModifiers(skill);
}
return CalculateEffectiveSkillValue(
skill,
mSkills,
mConditions,
mSkillAffectors,
SkillRead::Current);
}
unsigned Character::GetMaxSkill(SkillType skill) const
{
if (skill != SkillType::TotalHealth)
{
mSkills.GetSkill(skill).mModifier = mInventory.CalculateModifiers(skill);
}
return CalculateEffectiveSkillValue(
skill,
mSkills,
mConditions,
mSkillAffectors,
SkillRead::MaxSkill);
}
void Character::AdjustCondition(BAK::Condition cond, signed amount)
{
mConditions.AdjustCondition(mSkills, cond, amount);
}
const Conditions& Character::GetConditions() const { return mConditions; }
Conditions& Character::GetConditions() { return mConditions; }
void Character::UpdateSkills()
{
for (unsigned i = 0; i < BAK::Skills::sSkills; i++)
GetSkill(static_cast<SkillType>(i));
}
Spells& Character::GetSpells()
{
return mSpells;
}
const Spells& Character::GetSpells() const
{
return mSpells;
}
void Character::AddSkillAffector(const SkillAffector& affector)
{
mSkillAffectors.emplace_back(affector);
}
std::vector<SkillAffector>& Character::GetSkillAffectors()
{
return mSkillAffectors;
}
const std::vector<SkillAffector>& Character::GetSkillAffectors() const
{
return mSkillAffectors;
}
std::ostream& operator<<(std::ostream& os, const Character& c)
{
os << "Character [" << c.mName << " Skills: \n" << c.mSkills;
os << "Spells: " << std::hex << c.mSpells << std::dec << "\n";
os << "Unknown: " << std::hex << c.mUnknown << std::dec << "\n";
os << "Unknown2: " << std::hex << c.mUnknown2 << std::dec << "\n";
os << c.mConditions << "\n";
os << "SkillAffectors: " << c.mSkillAffectors << "\n";
os << "Inventory: " << c.mInventory << "\n";
return os;
}
}
| 12,142
|
C++
|
.cpp
| 400
| 24.48
| 153
| 0.63722
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,332
|
random.cpp
|
xavieran_BaKGL/bak/random.cpp
|
#include "bak/random.hpp"
#include "com/random.hpp"
namespace BAK {
unsigned GetRandom()
{
return GetRandomNumber(0, 0xffff);
}
}
| 138
|
C++
|
.cpp
| 8
| 15.25
| 38
| 0.753968
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,333
|
keyContainer.cpp
|
xavieran_BaKGL/bak/keyContainer.cpp
|
#include "bak/keyContainer.hpp"
namespace BAK {
KeyContainer::KeyContainer(
Inventory&& inventory)
:
mInventory{std::move(inventory)}
{}
std::ostream& operator<<(std::ostream& os, const KeyContainer& i)
{
os << "KeyContainer {" << i.mInventory << "}";
return os;
}
}
| 287
|
C++
|
.cpp
| 13
| 19.538462
| 65
| 0.688889
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,334
|
screen.cpp
|
xavieran_BaKGL/bak/screen.cpp
|
#include "bak/screen.hpp"
namespace BAK {
constexpr unsigned SCREEN_WIDTH = 320;
constexpr unsigned SCREEN_HEIGHT = 200;
constexpr unsigned BOOK_SCREEN_WIDTH = 640;
constexpr unsigned BOOK_SCREEN_HEIGHT = 350;
Image LoadScreenResource(FileBuffer& fb)
{
bool isBookScreen = false;
if (fb.GetUint16LE() != 0x27b6)
{
fb.Rewind();
isBookScreen = true;
}
if (fb.GetUint8() != 0x02)
{
throw std::runtime_error("Could not load screen resource");
}
FileBuffer *decompressed = new FileBuffer(fb.GetUint32LE());
fb.DecompressLZW(decompressed);
auto image = isBookScreen
? Image(BOOK_SCREEN_WIDTH, BOOK_SCREEN_HEIGHT, 0, true)
: Image(SCREEN_WIDTH, SCREEN_HEIGHT, 0, false);
image.Load(decompressed);
delete decompressed;
return image;
}
}
| 840
|
C++
|
.cpp
| 28
| 25.464286
| 67
| 0.681988
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,335
|
image.cpp
|
xavieran_BaKGL/bak/image.cpp
|
#include "bak/image.hpp"
#include "com/assert.hpp"
#include <cstring>
namespace BAK {
const unsigned int FLAG_XYSWAPPED = 0x20;
const unsigned int FLAG_UNKNOWN = 0x40;
const unsigned int FLAG_COMPRESSED = 0x80;
Image::Image(unsigned width, unsigned height, unsigned flags, bool isHighResLowCol)
:
mWidth(width),
mHeight(height),
mFlags(flags),
mIsHighResLowCol(isHighResLowCol),
mPixels()
{
mPixels.resize(width * height);
}
unsigned Image::GetWidth() const
{
return mWidth;
}
unsigned Image::GetHeight() const
{
return mHeight;
}
unsigned Image::GetSize() const
{
return mWidth * mHeight;
}
bool Image::IsHighResLowCol() const
{
return mIsHighResLowCol;
}
uint8_t* Image::GetPixels() const
{
// FIXME!
return const_cast<uint8_t *>(mPixels.data());
}
uint8_t Image::GetPixel(unsigned x, unsigned y) const
{
return mPixels[x + mWidth * y];
}
void Image::SetPixel(unsigned x, unsigned y, std::uint8_t color)
{
if ((x < mWidth) && (y < mHeight))
{
mPixels[x + mWidth * y] = color;
}
}
void Image::Load(FileBuffer *buffer)
{
ASSERT(mPixels.size() == mWidth * mHeight);
FileBuffer *imgbuf;
if (mFlags & FLAG_COMPRESSED)
{
imgbuf = new FileBuffer(mWidth * mHeight);
buffer->DecompressRLE(imgbuf);
}
else
{
imgbuf = buffer;
}
if (mFlags & FLAG_XYSWAPPED)
{
for (unsigned x = 0; x < mWidth; x++)
{
for (unsigned y = 0; y < mHeight; y++)
{
SetPixel(x, y, imgbuf->GetUint8());
}
}
}
else
{
if (IsHighResLowCol())
{
for (unsigned y = 0; y < mHeight; y++)
{
for (unsigned x = 0; x < mWidth; x++)
{
std::uint8_t c = imgbuf->GetUint8();
SetPixel(x, y, (c & 0xf0) >> 4);
x++;
SetPixel(x, y, c & 0x0f);
}
}
}
else
{
for (unsigned i = 0; i < GetSize(); i++)
{
mPixels[i] = imgbuf->GetUint8();
}
}
}
if (mFlags & FLAG_COMPRESSED)
{
delete imgbuf;
}
}
}
| 2,267
|
C++
|
.cpp
| 101
| 16.217822
| 83
| 0.544905
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,336
|
coordinates.cpp
|
xavieran_BaKGL/bak/coordinates.cpp
|
#include "bak/coordinates.hpp"
#include "bak/constants.hpp"
#include "com/assert.hpp"
namespace BAK {
std::ostream& operator<<(std::ostream& os, const GamePositionAndHeading& pah)
{
os << "{ pos: " << pah.mPosition << ", angle: " << pah.mHeading << "}";
return os;
}
glm::uvec2 GetTile(
glm::uvec2 pos)
{
return glm::floor(glm::cast<float>(pos)
/ glm::vec2{BAK::gTileSize});
}
GamePosition MakeGamePositionFromTileAndCell(
glm::uvec2 tile,
glm::vec<2, std::uint8_t> cell)
{
const auto Convert = [](auto t, auto c)
{
return t * BAK::gTileSize + gCellSize * c + (gCellSize >> 1);
};
return GamePosition{
Convert(tile.x, cell.x),
Convert(tile.y, cell.y)};
}
// Convert a 16 bit BAK angle to radians
glm::vec3 ToGlAngle(const glm::ivec3& angle)
{
return ToGlCoord<float>(angle)
/ static_cast<float>(0xffff)
* 2.0f * glm::pi<float>();
}
BAK::GameHeading ToBakAngle(double angle)
{
const auto multiplier = static_cast<double>(0xff);
const auto angleGreaterThanZero = angle + glm::pi<double>();
const auto bakAngle = multiplier * (angleGreaterThanZero / (2 * glm::pi<double>()));
ASSERT(bakAngle > 0);
return static_cast<BAK::GameHeading>(bakAngle);
}
double NormaliseRadians(double angle)
{
if (angle > glm::pi<double>())
return angle - (glm::pi<double>() * 2);
else if (angle < -glm::pi<double>())
return angle + (glm::pi<double>() * 2);
return angle;
}
// Convert an 8 bit BAK angle to radians
glm::vec2 ToGlAngle(GameHeading heading)
{
constexpr auto divider = static_cast<float>(0xff);
const auto ratio = static_cast<float>(heading) / divider;
const auto angle = ratio * 2.0f * glm::pi<float>();
return glm::vec2{NormaliseRadians(angle + glm::pi<float>()), 0};
}
std::ostream& operator<<(std::ostream& os, const MapLocation& l)
{
os << "MapLocation{ pos: " << l.mPosition
<< " Heading: " << l.mHeading << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const Location& l)
{
os << "Location{ zone: " << l.mZone << " tile: " << l.mTile
<< " Pos: " << l.mLocation << "}";
return os;
}
std::uint16_t HeadingToFullMapAngle(std::uint16_t heading)
{
constexpr auto unit = 0xff / 8;
return 4 * ((heading / unit) % 8);
}
}
| 2,339
|
C++
|
.cpp
| 76
| 26.960526
| 88
| 0.637578
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,337
|
shop.cpp
|
xavieran_BaKGL/bak/shop.cpp
|
#include "bak/shop.hpp"
#include "bak/IContainer.hpp"
#include "bak/fileBufferFactory.hpp"
#include "bak/inventoryItem.hpp"
#include "bak/itemNumbers.hpp"
#include "bak/money.hpp"
#include "bak/objectInfo.hpp"
#include "com/logger.hpp"
#include "com/ostream.hpp"
#include <algorithm>
#include <cmath>
namespace BAK {
std::ostream& operator<<(std::ostream& os, const ShopStats& shop)
{
os << std::dec << "ShopStats { templeNumber: " << +shop.mTempleNumber
<< " sellFactor/fixedBlsCost: " << +shop.mSellFactor
<< " maxDiscount/blessPcnt: " << +shop.mMaxDiscount
<< " buyFactor/blessType: " << +shop.mBuyFactor
<< " haggleDifficulty: " << std::hex << +shop.mHaggleDifficulty << std::dec
<< " haggleAnnoyanceFactor: " << std::hex << +shop.mHaggleAnnoyanceFactor << std::dec
<< " bardingSkill: " << +shop.mBardingSkill
<< " bardingReward: " << +shop.mBardingReward
<< " bardingMaxReward: " << +shop.mBardingMaxReward
<< " unknown: " << std::hex << shop.mUnknown << std::dec
<< " innSleepTilHour: " << +shop.mInnSleepTilHour
<< " innCost: " << +shop.mInnCost
<< " repairTypes: " << +shop.mRepairTypes
<< " repairFactor: " << +shop.mRepairFactor
<< " categories: " << std::hex << shop.mCategories << std::dec
<< " [" << GetCategories(shop.mCategories) << "]}";
return os;
}
std::uint8_t ShopStats::GetRepairFactor() const
{
return mRepairFactor;
}
std::uint8_t ShopStats::GetTempleBlessFixedCost() const
{
return mSellFactor;
}
std::uint8_t ShopStats::GetTempleBlessPercent() const
{
return mMaxDiscount;
}
Modifier ShopStats::GetTempleBlessType() const
{
return static_cast<Modifier>(4 + mBuyFactor);
}
std::uint8_t ShopStats::GetTempleHealFactor() const
{
return mHaggleDifficulty;
}
ShopStats LoadShop(FileBuffer& fb)
{
const auto templeNumber = fb.GetUint8();
const auto sellFactor = fb.GetUint8();
const auto maxDiscount = fb.GetUint8();
const auto buyFactor = fb.GetUint8();
const auto haggle1 = fb.GetUint8();
const auto haggle2 = fb.GetUint8();
const auto bardingSkill = fb.GetUint8();
const auto bardingReward = fb.GetUint8();
const auto bardingMaxReward = fb.GetUint8();
const auto unknown = fb.GetUint8();
const auto innSleepTilHour = fb.GetUint8();
const auto innCost = fb.GetUint8();
const auto repairTypes = fb.GetUint8();
const auto repairFactor = fb.GetUint8();
const auto categories = fb.GetUint16LE();
return ShopStats{
templeNumber,
sellFactor,
maxDiscount,
buyFactor,
haggle1,
haggle2,
bardingSkill,
bardingReward,
bardingMaxReward,
unknown,
innSleepTilHour,
innCost,
repairTypes,
repairFactor,
categories
};
}
}
namespace BAK::Shop {
Royals GetSellPrice(const BAK::InventoryItem& item, const ShopStats& stats, Royals discount, bool isRomneyGuildWars)
{
const auto sellFactor = static_cast<double>(100 + stats.mSellFactor) / 100.0;
if (item.GetObject().mType == ItemType::Scroll)
{
return ObjectIndex::Get().GetScrollValue(item.GetSpell());
}
auto baseValue = static_cast<double>(item.GetObject().mValue);
for (auto mod : item.GetModifiers())
{
switch (mod)
{
case Modifier::Blessing1:
baseValue = (baseValue * 150) / 100;
break;
case Modifier::Blessing2:
baseValue = (baseValue * 175) / 100;
break;
case Modifier::Blessing3:
baseValue = (baseValue * 200) / 100;
break;
default:
break;
}
}
if (baseValue <= 0) baseValue = 1;
auto shopBasicValue = std::clamp(
sellFactor * baseValue - discount.mValue,
1.0, sellFactor * baseValue);
if (isRomneyGuildWars)
{
shopBasicValue = (shopBasicValue * 600) / 100;
}
const auto value = shopBasicValue * GetItemQuantityMultiple(item);
const auto money = Royals{static_cast<unsigned>(std::round(value))};
return money;
}
Royals GetBuyPrice (const BAK::InventoryItem& item, const ShopStats& stats, bool isRomneyGuildWars)
{
const auto buyFactor = static_cast<double>(stats.mBuyFactor) / 100.0;
const auto sellPrice = static_cast<double>(GetSellPrice(item, stats, Royals{0}, isRomneyGuildWars).mValue);
auto buyPrice = static_cast<unsigned>(std::round(buyFactor * sellPrice));
if (item.IsItemType(BAK::ItemType::Armor))
{
buyPrice >>= 1;
}
return Royals{buyPrice};
}
bool CanRepair(const InventoryItem& item, const ShopStats& stats)
{
if (item.IsItemType(ItemType::Crossbow))
{
return stats.mRepairTypes & 0x4;
}
else if (item.IsItemType(ItemType::Sword))
{
return stats.mRepairTypes & 0x1;
}
else if (item.IsItemType(ItemType::Armor))
{
return stats.mRepairTypes & 0x2;
}
else
{
return false;
}
}
Royals CalculateRepairCost(const InventoryItem& item, const ShopStats& stats)
{
if (item.IsItemType(ItemType::Crossbow))
{
if (item.GetItemIndex() == BAK::sBessyMauler)
return Royals{800};
else
return Royals{400};
}
else
{
const auto value = item.GetObject().mValue;
return Royals{(value * stats.GetRepairFactor() * (100 - item.GetCondition())) / 10000};
}
}
void RepairItem(InventoryItem& item)
{
item.SetCondition(100);
item.SetRepairable(false);
item.SetBroken(false);
}
double GetItemQuantityMultiple(const BAK::InventoryItem& item)
{
if (item.IsStackable() || item.IsChargeBased())
{
return static_cast<double>(item.GetQuantity())
/ static_cast<double>(item.GetObject().mDefaultStackSize);
}
else if (item.IsConditionBased())
{
return static_cast<double>(item.GetCondition()) / 100.0;
}
else
{
return 1.0;
}
}
bool CanBuyItem(const BAK::InventoryItem& item, const BAK::IContainer& shop)
{
return shop.GetInventory().HaveItem(item) ||
(item.GetObject().mCategories & shop.GetShop().mCategories) != 0x0000;
}
}
| 6,378
|
C++
|
.cpp
| 199
| 26.336683
| 116
| 0.639187
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,338
|
dialogTarget.cpp
|
xavieran_BaKGL/bak/dialogTarget.cpp
|
#include "bak/dialogTarget.hpp"
#include <iomanip>
#include <type_traits>
namespace BAK {
std::ostream& operator<<(std::ostream& os, const Target& t)
{
std::visit([&os](auto&& arg){
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, KeyTarget>)
os << "Key [ " << std::hex << arg.mValue << " ]";
else
os << "Offset { " << std::dec << +arg.dialogFile << " @ 0x" << std::hex << arg.value << " }";
}, t);
return os;
}
}
| 500
|
C++
|
.cpp
| 16
| 26.25
| 105
| 0.541667
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,339
|
model.cpp
|
xavieran_BaKGL/bak/model.cpp
|
#include "bak/dataTags.hpp"
#include "bak/model.hpp"
#include "com/ostream.hpp"
#include "graphics/glm.hpp"
namespace BAK {
inline std::ostream& operator<<(std::ostream& os, const FaceOption& m)
{
os << " FaceOption[FT: " << m.mFaceType << " EC: " << m.mEdgeCount << " FCs: " << m.mFaceColors.size() << " PALs: "
<< m.mPalettes.size() << " Faces " << m.mFaces.size() << " -- ";
for (const auto& f: m.mFaces)
{
os << " " << f.size() << ",";
}
os << "]";
return os;
}
inline std::ostream& operator<<(std::ostream& os, const Mesh& m)
{
os << " FaceOptions: " << m.mFaceOptions.size() << "\n";
for (const auto& f: m.mFaceOptions)
{
os << " " << f << "\n";
}
return os;
}
inline std::ostream& operator<<(std::ostream& os, const Component& m)
{
os << " Meshes: " << m.mMeshes.size() << "\n";
for (unsigned i = 0; i < m.mMeshes.size(); i++)
{
os << " Mesh #" << i << "\n";
os << m.mMeshes[i] << "";
}
return os;
}
inline std::ostream& operator<<(std::ostream& os, const Model& m)
{
os << m.mName << " EF: " << m.mEntityFlags << " ET: " << m.mEntityType
<< " TT: " << m.mTerrainType << " Scale: " << m.mScale << " Sprite: " << m.mSprite
<< "\n";
os << " NumVertices: " << m.mVertices.size() << "\n";
os << " Components: " << m.mComponents.size() << "\n";
for (unsigned i = 0; i < m.mComponents.size(); i++)
{
os << " Component: " << i << "\n" << m.mComponents[i] << "\n";
}
return os;
}
inline std::ostream& operator<<(std::ostream& os, const ClipPoint& p)
{
os << "[" << p.mUV << "] (" << p.mXY << ")";
return os;
}
inline std::ostream& operator<<(std::ostream& os, const ClipElement& c)
{
os << " UnknownFlags: " << std::hex << c.mUnknown << std::dec << "\n";
for (const auto& pt : c.mPoints)
{
os << " " << pt << "\n";
}
if (c.mExtraPoint)
{
os << " ExtraPoint: " << *c.mExtraPoint << "\n";
}
return os;
}
inline std::ostream& operator<<(std::ostream& os, const ModelClipX& m)
{
os << "ModelClip{ " << m.mName << " radius: " << m.mRadius
<< " hasVert: " << m.hasVertical << " Elements:\n";
for (unsigned i = 0; i < m.mElements.size(); i++)
{
os << " ClipElement #" << i << "\n";
os << m.mElements[i] << "\n";
}
return os;
}
std::vector<std::string> LoadModelNames(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
fb.Skip(2);
const auto numItems = fb.GetUint16LE();
std::vector<unsigned> offsets{};
std::vector<std::string> mapItems{};
offsets.reserve(numItems);
mapItems.reserve(numItems);
for (unsigned i = 0; i < numItems; i++)
{
offsets.emplace_back(fb.GetUint16LE());
}
fb.Skip(2);
const auto dataStart = fb.GetBytesDone();
for (auto offset : offsets)
{
fb.Seek(dataStart + offset);
mapItems.emplace_back(fb.GetString());
}
return mapItems;
}
unsigned CalculateOffset(unsigned upper, unsigned lower)
{
return (upper << 4) + (lower & 0xf);
}
ModelClipX LoadGidItem(BAK::FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
struct ElementOffsets
{
unsigned mOffset;
unsigned mLength;
std::optional<unsigned> mExtraOffset;
std::array<std::uint8_t, 3> mUnknown;
};
std::vector<ElementOffsets> offsets{};
auto start = fb.Tell();
auto x = fb.GetUint16LE();
auto y = fb.GetUint16LE();
auto hasVertical = fb.GetUint8();
auto elems = fb.GetUint8();
auto offsetAdjust = fb.GetUint16LE() - 8;
assert(offsetAdjust >= 0);
assert(hasVertical == 0 || hasVertical == 2);
ModelClipX modelClip{};
modelClip.mRadius = glm::ivec2{x, y};
modelClip.hasVertical = hasVertical == 2;
for (unsigned i = 0; i < elems; i++)
{
auto off = fb.GetUint16LE();
auto entries = fb.GetUint8();
auto unknown = fb.GetArray<3>();
std::optional<unsigned> extra = std::nullopt;
if (hasVertical == 2)
{
off = fb.GetUint16LE();
extra = off;
auto unknown2 = fb.GetArray<2>();
}
offsets.emplace_back(ElementOffsets{off, entries, extra, unknown});
}
for (unsigned i = 0; i < elems; i++)
{
fb.Seek(start + offsets[i].mOffset - offsetAdjust);
ClipElement element{};
element.mUnknown = offsets[i].mUnknown;
for (unsigned j = 0; j < offsets[i].mLength; j++)
{
auto u = fb.GetSint8();
auto v = fb.GetSint8();
auto x = fb.GetSint16LE();
auto y = fb.GetSint16LE();
element.mPoints.emplace_back(ClipPoint{glm::ivec2{u, v}, glm::ivec2{x, y}});
}
if (offsets[i].mExtraOffset)
{
fb.Seek(start + *offsets[i].mExtraOffset - offsetAdjust);
auto u = fb.GetSint8();
auto v = fb.GetSint8();
auto x = fb.GetSint16LE();
auto y = fb.GetSint16LE();
element.mExtraPoint = ClipPoint{glm::ivec2{u, v}, glm::ivec2{x, y}};
}
modelClip.mElements.emplace_back(element);
}
return modelClip;
}
std::vector<ModelClipX> LoadModelClip(FileBuffer& fb, std::vector<std::string> names)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
auto numItems = names.size();
std::vector<unsigned> offsets{};
offsets.reserve(numItems);
std::vector<ModelClipX> modelClips{};
modelClips.reserve(numItems);
for (unsigned i = 0; i < numItems; i++)
{
const auto lower = fb.GetUint16LE();
const auto upper = fb.GetUint16LE();
offsets.emplace_back(CalculateOffset(upper, lower));
}
for (unsigned int i = 0; i < numItems; i++)
{
fb.Seek(offsets[i]);
modelClips.emplace_back(LoadGidItem(fb));
modelClips.back().mName = names[i];
}
return modelClips;
}
struct FaceData
{
unsigned mFaceType;
unsigned mEdgeCount;
unsigned mEdgeOffset;
};
struct MeshOffsetData
{
unsigned mVertexCount;
unsigned mVertexOffset;
unsigned mVertexIndexTransform;
unsigned mFaceCount;
unsigned mFaceOffset;
};
struct ComponentData
{
unsigned mMeshCount;
unsigned mMeshOffset;
std::vector<MeshOffsetData> mMeshOffsetDatas;
};
std::vector<Model> LoadModels(FileBuffer& fb, std::vector<std::string> itemNames)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
const unsigned numItems = itemNames.size();
std::vector<unsigned> offsets{};
offsets.reserve(numItems);
std::vector<Model> newModels{};
newModels.reserve(numItems);
for (unsigned i = 0; i < numItems; i++)
{
const auto lower = fb.GetUint16LE();
const auto upper = fb.GetUint16LE();
offsets.emplace_back(CalculateOffset(upper, lower));
}
for (unsigned i = 0; i < numItems; i++)
{
Model newModel{};
fb.Seek(offsets[i]);
auto offset = offsets[i];
newModel.mName = itemNames[i];
newModel.mEntityFlags = fb.GetUint8();
newModel.mEntityType = fb.GetUint8();
newModel.mTerrainType = fb.GetUint8();
newModel.mScale = fb.GetUint8();
// uncertain what these are for...
// animCount seems to be related to the number of face
// options, e.g. the catapult
auto animCount = fb.GetUint16LE();
auto animOffset = fb.GetUint16LE();
if (newModel.mName == "boom")
{
// to keep the indices aligned - not sure what to do with this
newModels.emplace_back(newModels.back());
continue;
}
auto componentCount = fb.GetUint16LE();
auto baseOffset = fb.GetUint16LE();
fb.Skip(2);
bool bounded = !(newModel.mEntityFlags & EF_UNBOUNDED);
if (bounded)
{
newModel.mMin = fb.LoadVector<std::int16_t, 3>();
newModel.mMax = fb.LoadVector<std::int16_t, 3>();
}
std::vector<ComponentData> componentOffsetDatas;
for (auto componentI = 0; componentI < componentCount; componentI++)
{
fb.Skip(2);
unsigned meshCount = fb.GetUint16LE();
unsigned meshOffset = fb.GetUint16LE();
componentOffsetDatas.emplace_back(ComponentData{meshCount, meshOffset, {}});
}
offset += 14 + (bounded ? 12 : 0);
std::vector<std::pair<unsigned, unsigned>> vertexSets{};
std::vector<unsigned> vertexSums{};
for (auto componentI = 0; componentI < componentCount; componentI++)
{
auto& component = componentOffsetDatas[componentI];
fb.Seek(offset + component.mMeshOffset - baseOffset);
for (unsigned meshI = 0; meshI < component.mMeshCount; meshI++)
{
fb.Skip(3);
unsigned vertices = fb.GetUint8();
unsigned vertexOffset = fb.GetUint16LE();
unsigned faceCount = fb.GetUint16LE();
unsigned faceOffset = fb.GetUint16LE();
if (vertexSets.empty())
{
vertexSets.emplace_back(vertices, vertexOffset);
vertexSums.emplace_back(0);
}
else
{
if (std::make_pair(vertices, vertexOffset) != vertexSets.back())
{
vertexSums.emplace_back(vertexSums.back() + vertexSets.back().first);
vertexSets.emplace_back(vertices, vertexOffset);
}
}
component.mMeshOffsetDatas.emplace_back(MeshOffsetData{vertices, vertexOffset, vertexSums.back(), faceCount, faceOffset});
fb.Skip(4);
}
}
std::vector<glm::i32vec3> vertices{};
unsigned vs = 0;
for (auto [vertexCount, vertexOffset] : vertexSets)
{
fb.Seek(offset - baseOffset + vertexOffset);
for (unsigned vv = 0; vv < vertexCount; vv++)
{
vertices.emplace_back(fb.LoadVector<std::int16_t, 3>());
}
}
newModel.mVertices = vertices;
for (unsigned componentI = 0; componentI < componentCount; componentI++)
{
auto& component = newModel.mComponents.emplace_back(Component{{}});
auto& componentOffsetData = componentOffsetDatas[componentI];
for (unsigned meshI = 0; meshI < componentOffsetData.mMeshCount; meshI++)
{
auto& meshOffsetData = componentOffsetData.mMeshOffsetDatas[meshI];
auto fo = offset - baseOffset + meshOffsetData.mFaceOffset;
fb.Seek(fo);
auto& newMesh = component.mMeshes.emplace_back(Mesh{{}});
newMesh.mFaceOptions.reserve(meshOffsetData.mFaceCount);
std::vector<FaceData> faceOffsetDatas;
for (unsigned faceI = 0; faceI < meshOffsetData.mFaceCount; faceI++)
{
auto& faceOption = newMesh.mFaceOptions.emplace_back(FaceOption{});
auto faceType = fb.GetUint16LE();
auto edgeCount = fb.GetUint16LE();
faceOption.mFaceType = faceType;
faceOption.mEdgeCount = edgeCount;
auto edgeOffset = fb.GetUint16LE();
fb.Skip(2);
faceOffsetDatas.emplace_back(FaceData{faceType, edgeCount, edgeOffset});
if (faceType == 2)
{
newModel.mSprite = edgeCount;
continue;
}
}
assert(newMesh.mFaceOptions.size() == meshOffsetData.mFaceCount);
for (unsigned faceI = 0; faceI < meshOffsetData.mFaceCount; faceI++)
{
auto& faceOption = newMesh.mFaceOptions[faceI];
auto& faceOffsetData = faceOffsetDatas[faceI];
if (faceOffsetData.mFaceType == 2) continue;
fb.Seek(offset - baseOffset + faceOffsetData.mEdgeOffset);
unsigned edgeSeekOffset = offset - baseOffset + faceOffsetData.mEdgeOffset;
for (unsigned edgeI = 0; edgeI < faceOffsetData.mEdgeCount; edgeI++)
{
fb.Seek(edgeSeekOffset);
auto palette = fb.GetUint8();
auto color = fb.LoadVector<std::uint8_t, 4>();
auto group = fb.GetUint8();
auto vertexOffset = fb.GetUint16LE();
edgeSeekOffset = fb.Tell();
fb.Seek(offset - baseOffset + vertexOffset);
std::uint8_t vertexIndex;
std::vector<std::uint16_t> vertexIndices{};
while ((vertexIndex = fb.GetUint8()) != 0xff)
{
vertexIndices.emplace_back(static_cast<std::uint16_t>(vertexIndex) + meshOffsetData.mVertexIndexTransform);
}
faceOption.mFaceColors.emplace_back(color);
faceOption.mPalettes.emplace_back(palette);
faceOption.mFaces.emplace_back(vertexIndices);
}
}
}
}
newModels.emplace_back(std::move(newModel));
}
for (auto& model : newModels)
{
logger.Spam() << "Model: " << model << "\n";
}
return newModels;
}
std::vector<Model> LoadTBL(FileBuffer& fb)
{
const auto& logger = Logging::LogState::GetLogger(__FUNCTION__);
auto mapbuf = fb.Find(DataTag::MAP);
auto appbuf = fb.Find(DataTag::APP);
auto gidbuf = fb.Find(DataTag::GID);
auto datbuf = fb.Find(DataTag::DAT);
const auto names = LoadModelNames(mapbuf);
std::stringstream ss{};
for (const auto& name : names)
{
ss << " " << name << ",";
}
logger.Info() << "Loading models: " << ss.str() << "\n";
auto clips = LoadModelClip(gidbuf, names);
for (auto& c : clips)
logger.Spam() << c << "\n";
return LoadModels(datbuf, names);
}
}
| 14,490
|
C++
|
.cpp
| 387
| 28.180879
| 138
| 0.559946
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,340
|
worldClock.cpp
|
xavieran_BaKGL/bak/worldClock.cpp
|
#include "bak/worldClock.hpp"
#include <sstream>
namespace BAK {
std::string ToString(Time t)
{
std::stringstream ss{};
ss << t.GetDays() << " days " << std::setw(2) << std::setfill('0')
<< t.GetHour() << ":" << std::setw(2) << std::setfill('0') << t.GetMinute()
<< " (" << std::hex << t.mTime << std::dec << ")";
return ss.str();
}
std::ostream& operator<<(std::ostream& os, const Time& t)
{
os << "Time {" << ToString(t) << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const WorldClock& c)
{
os << "Time: " << c.GetTime() << " LastSlept: " << c.GetTimeLastSlept();
return os;
}
}
| 652
|
C++
|
.cpp
| 22
| 26.181818
| 83
| 0.552167
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.