repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
zzqcn/udpi
src/dpi_app_match.h
/* *------------------------------------------------------------------ * Copyright (c) 2019 Intel, Travelping and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------ */ /* #************************************************************* # Copyright (c) 2003-2017, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following # disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the # following disclaimer in the documentation and/or other materials provided with the distribution. # * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # #************************************************************* */ #ifndef dpi_app_match_h #define dpi_app_match_h typedef enum { DPI_APP_CISCO = 1, DPI_APP_GOOGLE = 2, DPI_APP_BING = 3, DPI_APP_MSN = 4, DPI_APP_YAHOO = 5, DPI_APP_YAHOOMAIL = 6, DPI_APP_INTEL = 7, DPI_APP_AMAZON = 8, DPI_APP_AMD = 9, DPI_APP_BAIDU = 10, DPI_APP_APPLE = 11, DPI_APP_FACEBOOK = 12, DPI_APP_EBAY = 13, DPI_APP_GITHUB = 14, DPI_APP_GMAIL = 15, DPI_APP_QQ = 16, DPI_APP_WECHAT = 17, DPI_APP_PINTEREST = 18, DPI_APP_LENOVO = 19, DPI_APP_LINKEDIN = 20, DPI_APP_SKYPE = 21, DPI_APP_MICROSOFT = 22, DPI_APP_NETFLIX = 23, DPI_APP_NOKIA = 24, DPI_APP_NVIDIA = 25, DPI_APP_OFFICE = 26, DPI_APP_ORACLE = 27, DPI_APP_OUTLOOK = 28, DPI_APP_PANDORA = 29, DPI_APP_PAYPAL = 30, DPI_APP_SINA = 31, DPI_APP_SOGOU = 32, DPI_APP_SYMANTEC = 33, DPI_APP_TAOBAO = 34, DPI_APP_TWITTER = 35, DPI_APP_UPS = 36, DPI_APP_VISA = 37, DPI_APP_MCAFEE = 38, DPI_APP_VMWARE = 39, DPI_APP_WORDPRESS = 40, DPI_APP_ADOBE = 41, DPI_APP_AKAMAI = 42, DPI_APP_ALIENVAULT = 43, DPI_APP_BITCOMET = 44, DPI_APP_CHECKPOINT = 45, DPI_APP_BLOOMBERG = 46, DPI_APP_DELL = 47, DPI_APP_F5 = 48, DPI_APP_FIREEYE = 49, DPI_APP_DROPBOX = 50, /* last app ID */ DPI_N_APPLICATIONS = 51, } dpi_application_id_t; typedef struct dpi_app_match_rule_ { char *host; char *pattern; char *app_name; u32 app_id; } dpi_app_match_rule; #define DPI_MAX_APP_NUM DPI_N_APPLICATIONS extern dpi_app_match_rule app_match_rules[]; #endif /* dpi_app_match_h */ /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
zzqcn/udpi
src/protocols/dpi_ssl.c
/* * Copyright (c) 2019 Intel and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdint.h> #include <string.h> #include <net/if.h> #include <sys/ioctl.h> #include <inttypes.h> #include <vlib/vlib.h> #include <vlib/unix/unix.h> #include "../dpi.h" typedef enum { State_Initial = 0, State_Client_Hello = 1, State_Server_Hello = 2, State_Certificate = 3, } ssl_state; enum { MAJOR_TLS = 0x3, }; enum { MINOR_SSL30 = 0, MINOR_TLS10 = 0x1, MINOR_TLS11 = 0x2, MINOR_TLS12 = 0x3, }; typedef enum { change_cipher_spec = 20, alert = 21, handshake = 22, application_data = 23, } ContentType; typedef struct { u8 major; u8 minor; } ProtocolVersion; typedef struct { u8 type; ProtocolVersion version; u16 length; } __attribute__ ((packed)) ssl_header; typedef enum { hello_request = 0, client_hello = 1, server_hello = 2, certificate = 11, server_key_exchange = 12, certificate_request = 13, server_hello_done = 14, certificate_verify = 15, client_key_exchange = 16, finished = 20, } HandshakeType; typedef struct { u8 msg_type; /* handshake type */ u8 length[3]; /* bytes in message */ } Handshake_header; int dpi_ssl_detect_protocol_from_cert (u8 * payload, u32 payload_len, dpi_flow_info_t * flow); #define dpi_isprint(ch) ((ch) >= 0x20 && (ch) <= 0x7e) #define dpi_isalpha(ch) (((ch) >= 'a' && (ch) <= 'z') || ((ch) >= 'A' && (ch) <= 'Z')) #define dpi_isdigit(ch) ((ch) >= '0' && (ch) <= '9') #define dpi_isspace(ch) (((ch) >= '\t' && (ch) <= '\r') || ((ch) == ' ')) #define dpi_min(a,b) ((a < b) ? a : b) static void dpi_set_detected_protocol (dpi_flow_info_t * flow, u32 upper_protocol, u32 lower_protocol) { if ((upper_protocol == DPI_PROTOCOL_UNKNOWN) && (lower_protocol != DPI_PROTOCOL_UNKNOWN)) upper_protocol = lower_protocol; if (upper_protocol == lower_protocol) lower_protocol = DPI_PROTOCOL_UNKNOWN; if ((upper_protocol != DPI_PROTOCOL_UNKNOWN) && (lower_protocol == DPI_PROTOCOL_UNKNOWN)) { if ((flow->guessed_host_protocol_id != DPI_PROTOCOL_UNKNOWN) && (upper_protocol != flow->guessed_host_protocol_id)) { lower_protocol = upper_protocol; upper_protocol = flow->guessed_host_protocol_id; } } flow->detected_protocol[0] = upper_protocol; flow->detected_protocol[1] = lower_protocol; } static u32 dpi_ssl_refine_master_protocol (dpi_flow_info_t * flow, u32 protocol) { if (flow->l4.tcp.ssl_got_server_cert == 1) protocol = DPI_PROTOCOL_SSL; else protocol = DPI_PROTOCOL_SSL_NO_CERT; return protocol; } int dpi_ssl_detect_protocol_from_cert (u8 * payload, u32 payload_len, dpi_flow_info_t * flow) { u32 host_protocol = DPI_PROTOCOL_UNKNOWN; int rv = 0; /* Only check SSL handshake packets. * Check first segment and subsequent segments. */ if (((payload_len > (sizeof (ssl_header) + sizeof (Handshake_header))) && (payload[0] == handshake)) || (flow->detect_begin)) { if ((flow->detected_protocol[0] == DPI_PROTOCOL_UNKNOWN) || (flow->detected_protocol[0] == DPI_PROTOCOL_SSL)) { rv = dpi_search_host_protocol (flow, (char *) payload, payload_len, DPI_PROTOCOL_SSL, &host_protocol); if (host_protocol != DPI_PROTOCOL_UNKNOWN) { dpi_set_detected_protocol (flow, host_protocol, dpi_ssl_refine_master_protocol (flow, DPI_PROTOCOL_SSL)); return rv; } } } return 0; } void dpi_search_tcp_ssl (u8 * payload, u32 payload_len, dpi_flow_info_t * flow) { u32 cur_len = payload_len; u32 cur_len2; u8 handshake_type; /* Check first segment of SSL Certificate message */ if ((payload_len > (sizeof (ssl_header) + sizeof (Handshake_header))) && (payload[0] == handshake)) { handshake_type = payload[5]; if (handshake_type == client_hello) { flow->l4.tcp.ssl_stage = State_Client_Hello; return; } else if (handshake_type == server_hello) { cur_len = ntohs (get_u16_t (payload, 3)) + sizeof (ssl_header); /* This packet only contains Server Hello message */ if (cur_len == payload_len) { flow->l4.tcp.ssl_stage = State_Server_Hello; return; } /* This packet contains Server Hello, Certificate and more messages */ if (payload_len >= cur_len + sizeof (ssl_header) && payload[cur_len] == handshake && payload[cur_len + 1] == MAJOR_TLS) { cur_len2 = ntohs (get_u16_t (payload, cur_len + 3)) + sizeof (ssl_header); if (payload[cur_len + 5] == certificate) { flow->l4.tcp.ssl_stage = State_Certificate; flow->detect_begin = 1; /* Scan segments of certificate message */ if (dpi_ssl_detect_protocol_from_cert (&payload[cur_len], cur_len2, flow) > 0) return; } } } else if (handshake_type == certificate) { cur_len = ntohs (get_u16_t (payload, 3)) + sizeof (ssl_header); /* This packet contains first segment of certificate message */ if (cur_len == payload_len) { flow->l4.tcp.ssl_stage = State_Certificate; flow->detect_begin = 1; /* Scan segments of certificate message */ if (dpi_ssl_detect_protocol_from_cert (payload, cur_len, flow) > 0) return; } } else if (flow->detect_begin) { /* Check subsequent segments of SSL Certificate message */ if (dpi_ssl_detect_protocol_from_cert (payload, cur_len, flow) > 0) return; } } return; } /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
zzqcn/udpi
src/dpi_node.c
/* * Copyright (c) 2019 Intel and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vlib/vlib.h> #include <vnet/pg/pg.h> #include <vnet/vnet.h> #include <vnet/ip/ip.h> #include <vppinfra/bihash_48_8.h> #include <vppinfra/dlist.h> #include <vppinfra/pool.h> #include <vppinfra/vec.h> #include <vnet/plugin/plugin.h> //#include <vpp/app/version.h> #include <vnet/flow/flow.h> #include <vnet/tcp/tcp_packet.h> #include "dpi.h" vlib_node_registration_t dpi4_input_node; vlib_node_registration_t dpi6_input_node; vlib_node_registration_t dpi4_flow_input_node; vlib_node_registration_t dpi6_flow_input_node; typedef struct { u32 next_index; u32 flow_id; u32 app_id; u32 error; } dpi_rx_trace_t; /* *INDENT-OFF* */ VNET_FEATURE_INIT (dpi4_input, static) = { .arc_name = "ip4-unicast", .node_name = "dpi4-input", .runs_before = VNET_FEATURES ("ip4-lookup"), }; VNET_FEATURE_INIT (dpi6_input, static) = { .arc_name = "ip6-unicast", .node_name = "dpi6-input", .runs_before = VNET_FEATURES ("ip6-lookup"), }; /* *INDENT-on* */ /* *INDENT-OFF* */ VNET_FEATURE_INIT (dpi4_flow_input, static) = { .arc_name = "ip4-unicast", .node_name = "dpi4-flow-input", .runs_before = VNET_FEATURES ("ip4-lookup"), }; VNET_FEATURE_INIT (dpi6_flow_input, static) = { .arc_name = "ip6-unicast", .node_name = "dpi6-flow-input", .runs_before = VNET_FEATURES ("ip6-lookup"), }; /* *INDENT-on* */ static u8 * format_dpi_rx_trace (u8 * s, va_list * args) { CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *); CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *); dpi_rx_trace_t *t = va_arg (*args, dpi_rx_trace_t *); if (t->flow_id == ~0) return format (s, "DPI error - flow %d does not exist", t->flow_id); return format (s, "DPI from flow %d app_id %d next %d error %d", t->flow_id, t->app_id, t->next_index, t->error); } static inline int parse_ip4_packet_and_lookup (ip4_header_t * ip4, u32 fib_index, dpi4_flow_key_t * key4, int * not_found, u64 * flow_id) { dpi_main_t *dm = &dpi_main; u8 protocol = ip4_is_fragment (ip4) ? 0xfe : ip4->protocol; u16 src_port = 0; u16 dst_port = 0; dpi_flow_entry_t *flow; key4->key[0] = ip4->src_address.as_u32 | (((u64) ip4->dst_address.as_u32) << 32); if (protocol == IP_PROTOCOL_UDP || protocol == IP_PROTOCOL_TCP) { /* tcp and udp ports have the same offset */ udp_header_t * udp = ip4_next_header (ip4); src_port = udp->src_port; dst_port = udp->dst_port; } key4->key[1] = (((u64) protocol) << 32) | ((u32) src_port << 16) | dst_port; key4->key[2] = (u64) fib_index; key4->value = ~0; *not_found = clib_bihash_search_inline_24_8 (&dm->dpi4_flow_by_key, key4); *flow_id = key4->value; /* not found, then create new SW flow dynamically */ if (*not_found) { int add_failed; pool_get_aligned(dm->dpi_flows, flow, CLIB_CACHE_LINE_BYTES); clib_memset(flow, 0, sizeof(*flow)); *flow_id = flow - dm->dpi_flows; flow->next_index = DPI_INPUT_NEXT_IP4_LOOKUP; flow->flow_index = ~0; pool_get_aligned(dm->dpi_infos, flow->info, CLIB_CACHE_LINE_BYTES); clib_memset(flow->info, 0, sizeof(*flow->info)); flow->info->app_id = ~0; /* Add forwarding flow entry */ key4->value = *flow_id; add_failed = clib_bihash_add_del_24_8 (&dm->dpi4_flow_by_key, key4, 1 /*add */); if (add_failed) { pool_put(dm->dpi_infos, flow->info); pool_put(dm->dpi_flows, flow); return -1; } /* Add reverse flow entry*/ key4->key[0] = ip4->dst_address.as_u32 | (((u64) ip4->src_address.as_u32) << 32); key4->key[1] = (((u64) protocol) << 32) | ((u32) dst_port << 16) | src_port; key4->key[2] = (u64) fib_index; key4->value = (u64) flow_id | ((u64) 1 << 63); add_failed = clib_bihash_add_del_24_8 (&dm->dpi4_flow_by_key, key4, 1 /*add */); if (add_failed) { pool_put(dm->dpi_infos, flow->info); pool_put(dm->dpi_flows, flow); return -1; } /* Open a Hyperscan stream for each flow */ hs_error_t err = hs_open_stream (dm->default_db.database, 0, &(flow->info->stream)); if (err != HS_SUCCESS) { pool_put(dm->dpi_infos, flow->info); pool_put(dm->dpi_flows, flow); return -1; } } return 0; } static inline int parse_ip6_packet_and_lookup (ip6_header_t * ip6, u32 fib_index, dpi6_flow_key_t * key6, int * not_found, u64 * flow_id) { dpi_main_t *dm = &dpi_main; u8 protocol = ip6->protocol; u16 src_port = 0; u16 dst_port = 0; dpi_flow_entry_t *flow; key6->key[0] = ip6->src_address.as_u64[0]; key6->key[1] = ip6->src_address.as_u64[1]; key6->key[2] = ip6->dst_address.as_u64[0]; key6->key[3] = ip6->dst_address.as_u64[1]; if (protocol == IP_PROTOCOL_UDP || protocol == IP_PROTOCOL_TCP) { /* tcp and udp ports have the same offset */ udp_header_t * udp = ip6_next_header(ip6); src_port = udp->src_port; dst_port = udp->dst_port; } key6->key[4] = (((u64) protocol) << 32) | ((u32) src_port << 16) | dst_port; key6->key[5] = (u64) fib_index; key6->value = ~0; *not_found = clib_bihash_search_inline_48_8 (&dm->dpi6_flow_by_key, key6); *flow_id = key6->value; /* not found, then create new SW flow dynamically */ if (*not_found) { int add_failed; pool_get_aligned(dm->dpi_flows, flow, CLIB_CACHE_LINE_BYTES); clib_memset(flow, 0, sizeof(*flow)); *flow_id = flow - dm->dpi_flows; flow->next_index = DPI_INPUT_NEXT_IP4_LOOKUP; flow->flow_index = ~0; pool_get_aligned(dm->dpi_infos, flow->info, CLIB_CACHE_LINE_BYTES); clib_memset(flow->info, 0, sizeof(*flow->info)); flow->info->app_id = ~0; /* Add forwarding flow entry */ key6->value = (u64) flow_id; add_failed = clib_bihash_add_del_48_8 (&dm->dpi6_flow_by_key, key6, 1 /*add */ ); if (add_failed) { pool_put(dm->dpi_infos, flow->info); pool_put(dm->dpi_flows, flow); return -1; } /* Add reverse flow entry*/ key6->key[0] = ip6->dst_address.as_u64[0]; key6->key[1] = ip6->dst_address.as_u64[1]; key6->key[2] = ip6->src_address.as_u64[0]; key6->key[3] = ip6->src_address.as_u64[1]; key6->key[4] = (((u64) protocol) << 32) | ((u32) dst_port << 16) | src_port; key6->key[5] = (u64) fib_index; key6->value = (u64) flow_id | ((u64) 1 << 63); add_failed = clib_bihash_add_del_48_8 (&dm->dpi6_flow_by_key, key6, 1 /*add */ ); if (add_failed) { pool_put(dm->dpi_infos, flow->info); pool_put(dm->dpi_flows, flow); return -1; } /* Open a Hyperscan stream for each flow */ hs_error_t err = hs_open_stream (dm->default_db.database, 0, &(flow->info->stream)); if (err != HS_SUCCESS) { pool_put(dm->dpi_infos, flow->info); pool_put(dm->dpi_flows, flow); return -1; } } return 0; } static inline void dpi_trim_overlap(u32 left_sn, segment *seg) { int overlap_len; overlap_len = left_sn - seg->send_sn; /* trim leading overlap bytes */ seg->data += overlap_len; seg->len -= overlap_len; seg->send_sn += overlap_len; /* trim the right overlap bytes */ if( seg->next && (seg->send_sn+seg->len) > (seg->next->send_sn) ) { overlap_len = (seg->send_sn+seg->len) - (seg->next->send_sn); if(seg->len > overlap_len) { seg->len -= overlap_len; } } } /* * re-order out-of-order segments, and handle overlap segments. * */ static inline void dpi_handle_tcp_segments (dpi_flow_entry_t *flow, tcp_stream_t *stream, u32 bi, u8 *pkt, u32 payload_len) { dpi_main_t *dm = &dpi_main; u32 send_sn; u32 ack_sn; u32 next_sn; u32 left_sn; segment *first_seg = 0; segment *seg = 0; segment *new_seg = 0; tcp_header_t *tcp = (tcp_header_t *)pkt; u8 *payload = pkt + tcp_doff(tcp) * 4; if((tcp->flags & TCP_FLAG_ACK) == TCP_FLAG_ACK) { ack_sn = clib_net_to_host_u32(tcp->ack_number); if(ack_sn != stream->ack_sn) { stream->ack_sn = ack_sn; } } send_sn = clib_net_to_host_u32(tcp->seq_number); next_sn = send_sn + payload_len; /* Handle fully overlapping segments */ if(SN_GT(stream->send_sn, next_sn)) { flow->consumed = 1; return; } if(SN_LT(stream->send_sn, send_sn)) { /* Store out-of-order segments to segment queue */ for(seg=stream->seg_queue; seg; seg=seg->next) { if (send_sn < seg->send_sn ) break; } pool_get_aligned (dm->seg_pool, new_seg, CLIB_CACHE_LINE_BYTES); new_seg->bi = bi; new_seg->send_sn = send_sn; new_seg->data = payload; new_seg->len = payload_len; /* Insert new segment to right position of segment queue */ if(seg == stream->seg_queue) { new_seg->next = stream->seg_queue; stream->seg_queue = new_seg; stream->send_sn = seg->send_sn; left_sn = stream->send_sn; } else { new_seg->next = seg->next; seg->next = new_seg; left_sn = seg->send_sn; } /* trim overlapped packet */ dpi_trim_overlap(left_sn, new_seg); flow->consumed = 1; } else { pool_get_aligned(dm->seg_pool, first_seg, CLIB_CACHE_LINE_BYTES); first_seg->bi = bi; first_seg->send_sn = send_sn; first_seg->data = payload; first_seg->len = payload_len; first_seg->next = stream->seg_queue; /* trim overlapped packet */ dpi_trim_overlap (stream->send_sn, first_seg); /* reassemble continuous segments and move forward to scan */ for (seg = first_seg; seg->next; seg = seg->next) { if (seg->send_sn + seg->len != seg->next->send_sn) break; } /* left non-continuous segments */ stream->seg_queue = seg->next; stream->send_sn = seg->send_sn + seg->len; flow->first_seg = first_seg; seg->next = 0; /* scan ordered segments */ for (seg = first_seg; seg; seg = seg->next) { /* detect layer 7 application for single segment */ dpi_detect_application (seg->data, seg->len, flow->info); if(flow->info->detect_done) break; } } } static inline int dpi_handle_tcp_stream (dpi_flow_entry_t *flow, u32 bi, u8 *pkt, u32 payload_len, u8 is_reverse) { tcp_header_t *tcp; tcp_stream_t *stream; tcp = (tcp_header_t *)pkt; if((tcp->flags & (TCP_FLAG_SYN|TCP_FLAG_ACK)) == TCP_FLAG_SYN) { flow->c2s.send_sn = clib_net_to_host_u32(tcp->seq_number) + 1; flow->pkt_dir = DIR_C2S; flow->forward_is_c2s = !is_reverse; flow->tcp_state = TCP_STATE_SYN; } else { /* forward_is_c2s | is_reverse 0 1 0 s2c(1) c2s(0) 1 c2s(0) s2c(1) */ flow->pkt_dir = (flow->forward_is_c2s == is_reverse); } switch(flow->tcp_state) { case TCP_STATE_SYN: { if(flow->pkt_dir != DIR_S2C) break; if((tcp->flags & (TCP_FLAG_SYN|TCP_FLAG_ACK)) != (TCP_FLAG_SYN|TCP_FLAG_ACK)) break; flow->s2c.send_sn = clib_net_to_host_u32(tcp->seq_number) + 1; flow->s2c.ack_sn = clib_net_to_host_u32(tcp->ack_number) + 1; flow->tcp_state = TCP_STATE_SYN_ACK; break; } case TCP_STATE_SYN_ACK: { if(flow->pkt_dir != DIR_C2S) break; flow->c2s.ack_sn = clib_net_to_host_u32(tcp->ack_number) + 1; flow->tcp_state = TCP_STATE_ESTABLISH; break; } case TCP_STATE_ACK: case TCP_STATE_ESTABLISH: case TCP_STATE_FIN1: { stream = (flow->pkt_dir == DIR_C2S)? &(flow->c2s) : &(flow->s2c); if( (flow->reass_dir == REASS_BOTH) || ((flow->pkt_dir==DIR_C2S) && (flow->reass_dir==REASS_C2S)) || ((flow->pkt_dir==DIR_S2C) && (flow->reass_dir==REASS_S2C)) ) { dpi_handle_tcp_segments(flow, stream, bi, pkt, payload_len); } break; } case TCP_STATE_CLOSE: { /* Free all segments in the queue */ break; } } return 0; } void dpi_detect_application (u8 *payload, u32 payload_len, dpi_flow_info_t *flow) { /* detect if payload is SSL's payload for default port */ dpi_search_tcp_ssl(payload, payload_len, flow); /* TBD: add detect if is SSL's payload with non default port*/ } always_inline uword dpi_input_inline (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame, u32 is_ip4) { dpi_main_t *dm = &dpi_main; u32 *from, *to_next, n_left_from, n_left_to_next, next_index; from = vlib_frame_vector_args (frame); n_left_from = frame->n_vectors; next_index = node->cached_next_index; while (n_left_from > 0) { vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next); while (n_left_from > 0 && n_left_to_next > 0) { u32 bi0, next0 = 0; vlib_buffer_t *b0; ip4_header_t *ip40; ip6_header_t *ip60; tcp_header_t *tcp0; udp_header_t *udp0; dpi4_flow_key_t key40; dpi6_flow_key_t key60; u32 fib_index0 = ~0; u64 flow_id0 = ~0; u32 flow_index0 = ~0; int not_found0 = 0; u8 is_reverse0 = 0; dpi_flow_entry_t *flow0 = 0; u32 ip_len0, l4_len0, payload_len0; u8 protocol0; u8 *l4_pkt0, *payload0; u16 dst_port = 0; segment *seg = 0; segment *prev_seg = 0; bi0 = to_next[0] = from[0]; b0 = vlib_get_buffer (vm, bi0); ip_len0 = vlib_buffer_length_in_chain (vm, b0); if (is_ip4) { ip40 = vlib_buffer_get_current (b0); ip4_main_t *im4 = &ip4_main; fib_index0 = vec_elt (im4->fib_index_by_sw_if_index, vnet_buffer(b0)->sw_if_index[VLIB_RX]); parse_ip4_packet_and_lookup(ip40, fib_index0, &key40, &not_found0, &flow_id0); } else { ip60 = vlib_buffer_get_current (b0); ip6_main_t *im6 = &ip6_main; fib_index0 = vec_elt (im6->fib_index_by_sw_if_index, vnet_buffer(b0)->sw_if_index[VLIB_RX]); parse_ip6_packet_and_lookup(ip60, fib_index0, &key60, &not_found0, &flow_id0); } is_reverse0 = (u8)((flow_id0 >> 63) & 0x1); flow_index0 = (u32)(flow_id0 & (u32)(~0)); flow0 = pool_elt_at_index (dm->dpi_flows, flow_index0); /* have detected successfully, directly return */ if(flow0->info->detect_done) goto enqueue0; /* check layer4 */ if (is_ip4) { l4_pkt0 = (u8 *)(ip40 + 1); l4_len0 = ip_len0 - sizeof(ip4_header_t); protocol0 = ip40->protocol; } else { l4_pkt0 = (u8 *)(ip60 + 1); l4_len0 = ip_len0 - sizeof(ip6_header_t); protocol0 = ip60->protocol; } if((protocol0 == IP_PROTOCOL_TCP) && (l4_len0 >= 20)) { tcp0 = (tcp_header_t *)l4_pkt0; payload_len0 = l4_len0 - tcp_doff(tcp0) * 4; payload0 = l4_pkt0 + tcp_doff(tcp0) * 4; dst_port = tcp0->dst_port; } else if ((protocol0 == IP_PROTOCOL_UDP) && (l4_len0 >= 8)) { udp0 = (udp_header_t *)l4_pkt0; payload_len0 = l4_len0 - sizeof(udp_header_t); payload0 = l4_pkt0 + sizeof(udp_header_t); dst_port = udp0->dst_port; } else { payload_len0 = l4_len0; payload0 = l4_pkt0; } flow0->info->l4_protocol = protocol0; flow0->info->dst_port = dst_port; /* TCP stream reassembly and detect a protocol pdu */ if((protocol0 == IP_PROTOCOL_TCP) && (flow0->reass_en)) { dpi_handle_tcp_stream(flow0, bi0, l4_pkt0, payload_len0, is_reverse0); /* This packet has been consumed, retrieve next packet */ if(flow0->consumed) goto trace0; /* send out continuous scanned segments */ seg=flow0->first_seg; dpi_enqueue_tcp_segments(seg,vm,node,next_index,to_next,n_left_to_next,bi0,next0); flow0->first_seg = 0; /* Here detected successfully, send out remaining segments in seg_queue */ if(flow0->info->detect_done) { seg=flow0->c2s.seg_queue; dpi_enqueue_tcp_segments(seg,vm,node,next_index,to_next,n_left_to_next,bi0,next0); flow0->c2s.seg_queue = 0; seg=flow0->s2c.seg_queue; dpi_enqueue_tcp_segments(seg,vm,node,next_index,to_next,n_left_to_next,bi0,next0); flow0->s2c.seg_queue = 0; } goto trace0; } else { /* detect layer 7 application for single packet */ dpi_detect_application (payload0, payload_len0, flow0->info); } enqueue0: to_next[0] = bi0; to_next++; n_left_to_next--; next0 = flow0->next_index; vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next, n_left_to_next, bi0, next0); trace0: if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED)) { dpi_rx_trace_t *tr = vlib_add_trace (vm, node, b0, sizeof (*tr)); tr->app_id = flow0->info->app_id; tr->next_index = next0; tr->error = b0->error; tr->flow_id = flow_index0; } from += 1; n_left_from -= 1; } vlib_put_next_frame (vm, node, next_index, n_left_to_next); } return frame->n_vectors; } VLIB_NODE_FN (dpi4_input_node) (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { return dpi_input_inline (vm, node, frame, /* is_ip4 */ 1); } /* *INDENT-OFF* */ VLIB_REGISTER_NODE (dpi4_input_node) = { .name = "dpi4-input", .vector_size = sizeof (u32), .n_errors = DPI_INPUT_N_ERROR, .error_strings = dpi_input_error_strings, .n_next_nodes = DPI_INPUT_N_NEXT, .next_nodes = { #define _(s,n) [DPI_INPUT_NEXT_##s] = n, foreach_dpi_input_next #undef _ }, .format_trace = format_dpi_rx_trace, }; /* *INDENT-ON* */ /* Dummy init function to get us linked in. */ static clib_error_t * dpi4_input_init (vlib_main_t * vm) { return 0; } VLIB_INIT_FUNCTION (dpi4_input_init); VLIB_NODE_FN (dpi6_input_node) (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { return dpi_input_inline (vm, node, frame, /* is_ip4 */ 0); } /* *INDENT-OFF* */ VLIB_REGISTER_NODE (dpi6_input_node) = { .name = "dpi6-input", .vector_size = sizeof (u32), .n_errors = DPI_INPUT_N_ERROR, .error_strings = dpi_input_error_strings, .n_next_nodes = DPI_INPUT_N_NEXT, .next_nodes = { #define _(s,n) [DPI_INPUT_NEXT_##s] = n, foreach_dpi_input_next #undef _ }, .format_trace = format_dpi_rx_trace, }; /* *INDENT-ON* */ /* Dummy init function to get us linked in. */ static clib_error_t * dpi6_input_init (vlib_main_t * vm) { return 0; } VLIB_INIT_FUNCTION (dpi6_input_init); static_always_inline u8 dpi_check_ip4 (ip4_header_t * ip4, u16 payload_len) { u16 ip_len = clib_net_to_host_u16 (ip4->length); return ip_len > payload_len || ip4->ttl == 0 || ip4->ip_version_and_header_length != 0x45; } static_always_inline u8 dpi_check_ip6 (ip6_header_t * ip6, u16 payload_len) { u16 ip_len = clib_net_to_host_u16 (ip6->payload_length); return ip_len > (payload_len - sizeof (ip6_header_t)) || ip6->hop_limit == 0 || (ip6->ip_version_traffic_class_and_flow_label >> 28) != 0x6; } always_inline uword dpi_flow_input_inline (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame, u32 is_ip4) { dpi_main_t *dm = &dpi_main; u32 *from, *to_next, n_left_from, n_left_to_next, next_index; from = vlib_frame_vector_args (frame); n_left_from = frame->n_vectors; next_index = node->cached_next_index; while (n_left_from > 0) { vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next); while (n_left_from > 0 && n_left_to_next > 0) { u32 bi0, next0 = 0; vlib_buffer_t *b0; ip4_header_t *ip40; ip6_header_t *ip60; tcp_header_t *tcp0; udp_header_t *udp0; u32 flow_id0 = ~0; u32 flow_index0 = ~0; u32 is_reverse0 = 0; dpi_flow_entry_t *flow0; u32 ip_len0, l4_len0, payload_len0; u8 protocol0; u8 *l4_pkt0, *payload0; u16 dst_port = 0; segment *seg = 0; segment *prev_seg = 0; bi0 = to_next[0] = from[0]; b0 = vlib_get_buffer (vm, bi0); vlib_buffer_advance (b0, +(sizeof (ethernet_header_t))); ip_len0 = vlib_buffer_length_in_chain (vm, b0); if (is_ip4) { ip40 = vlib_buffer_get_current (b0); dpi_check_ip4 (ip40, ip_len0); } else { ip60 = vlib_buffer_get_current (b0); dpi_check_ip6 (ip60, ip_len0); } flow_id0 = b0->flow_id - dm->flow_id_start; is_reverse0 = (u32) ((flow_id0 >> 31) & 0x1); flow_index0 = (u32) (flow_id0 & (u32) (~(1 << 31))); flow0 = pool_elt_at_index (dm->dpi_flows, flow_index0); /* have detected successfully, directly return */ if (flow0->info->detect_done) goto enqueue0; /* check layer4 */ if (is_ip4) { l4_pkt0 = (u8 *) (ip40 + 1); l4_len0 = ip_len0 - sizeof (ip4_header_t); protocol0 = ip40->protocol; } else { l4_pkt0 = (u8 *) (ip60 + 1); l4_len0 = ip_len0 - sizeof (ip6_header_t); protocol0 = ip60->protocol; } if ((protocol0 == IP_PROTOCOL_TCP) && (l4_len0 >= 20)) { tcp0 = (tcp_header_t *) l4_pkt0; payload_len0 = l4_len0 - tcp_doff (tcp0) * 4; payload0 = l4_pkt0 + tcp_doff (tcp0) * 4; dst_port = tcp0->dst_port; } else if ((protocol0 == IP_PROTOCOL_UDP) && (l4_len0 >= 8)) { udp0 = (udp_header_t *) l4_pkt0; payload_len0 = l4_len0 - sizeof (udp_header_t); payload0 = l4_pkt0 + sizeof (udp_header_t); dst_port = udp0->dst_port; } else { payload_len0 = l4_len0; payload0 = l4_pkt0; } flow0->info->l4_protocol = protocol0; flow0->info->dst_port = dst_port; /* TCP stream reassembly and detect a protocol pdu */ if ((protocol0 == IP_PROTOCOL_TCP) && (flow0->reass_en)) { dpi_handle_tcp_stream (flow0, bi0, l4_pkt0, payload_len0, is_reverse0); /* This packet has been consumed, retrieve next packet */ if (flow0->consumed) goto trace0; /* send out continuous scanned segments */ seg = flow0->first_seg; dpi_enqueue_tcp_segments (seg, vm, node, next_index, to_next, n_left_to_next, bi0, next0); flow0->first_seg = 0; /* Here detected successfully, send out remaining segments in seg_queue */ if (flow0->info->detect_done) { seg = flow0->c2s.seg_queue; dpi_enqueue_tcp_segments (seg, vm, node, next_index, to_next, n_left_to_next, bi0, next0); flow0->c2s.seg_queue = 0; seg = flow0->s2c.seg_queue; dpi_enqueue_tcp_segments (seg, vm, node, next_index, to_next, n_left_to_next, bi0, next0); flow0->s2c.seg_queue = 0; } goto trace0; } else { /* detect layer 7 application for single packet */ dpi_detect_application (payload0, payload_len0, flow0->info); } enqueue0: to_next[0] = bi0; to_next++; n_left_to_next--; next0 = flow0->next_index; vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next, n_left_to_next, bi0, next0); trace0: if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED)) { dpi_rx_trace_t *tr = vlib_add_trace (vm, node, b0, sizeof (*tr)); tr->app_id = flow0->info->app_id; tr->next_index = next0; tr->error = b0->error; tr->flow_id = flow_index0; } from += 1; n_left_from -= 1; } vlib_put_next_frame (vm, node, next_index, n_left_to_next); } return frame->n_vectors; } VLIB_NODE_FN (dpi4_flow_input_node) (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { return dpi_flow_input_inline (vm, node, frame, /* is_ip4 */ 1); } /* *INDENT-OFF* */ VLIB_REGISTER_NODE (dpi4_flow_input_node) = { .name = "dpi4-flow-input", .type = VLIB_NODE_TYPE_INTERNAL, .vector_size = sizeof (u32), .format_trace = format_dpi_rx_trace, .n_errors = DPI_FLOW_N_ERROR, .error_strings = dpi_flow_error_strings, .n_next_nodes = DPI_FLOW_N_NEXT, .next_nodes = { #define _(s,n) [DPI_FLOW_NEXT_##s] = n, foreach_dpi_flow_input_next #undef _ }, }; /* *INDENT-ON* */ /* Dummy init function to get us linked in. */ static clib_error_t * dpi4_flow_input_init (vlib_main_t * vm) { return 0; } VLIB_INIT_FUNCTION (dpi4_flow_input_init); VLIB_NODE_FN (dpi6_flow_input_node) (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { return dpi_flow_input_inline (vm, node, frame, /* is_ip4 */ 0); } /* *INDENT-OFF* */ VLIB_REGISTER_NODE (dpi6_flow_input_node) = { .name = "dpi6-flow-input", .type = VLIB_NODE_TYPE_INTERNAL, .vector_size = sizeof (u32), .format_trace = format_dpi_rx_trace, .n_errors = DPI_FLOW_N_ERROR, .error_strings = dpi_flow_error_strings, .n_next_nodes = DPI_FLOW_N_NEXT, .next_nodes = { #define _(s,n) [DPI_FLOW_NEXT_##s] = n, foreach_dpi_flow_input_next #undef _ }, }; /* *INDENT-ON* */ /* Dummy init function to get us linked in. */ static clib_error_t * dpi6_flow_input_init (vlib_main_t * vm) { return 0; } VLIB_INIT_FUNCTION (dpi6_flow_input_init); /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
zzqcn/udpi
src/dpi.h
/* *------------------------------------------------------------------ * Copyright (c) 2018 Intel, Travelping and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------ */ #ifndef included_vnet_dpi_h #define included_vnet_dpi_h #include <vppinfra/lock.h> #include <vppinfra/error.h> #include <vppinfra/hash.h> #include <vnet/vnet.h> #include <vnet/ip/ip.h> #include <vnet/ethernet/ethernet.h> #include <vnet/ip/ip4_packet.h> #include <vnet/ip/ip6_packet.h> #include <vnet/udp/udp.h> #include <vnet/dpo/dpo.h> #include <vppinfra/bihash_8_8.h> #include <vppinfra/bihash_24_8.h> #include <vppinfra/bihash_48_8.h> #include <hs/hs.h> #include <hs/hs_common.h> #include <hs/hs_compile.h> #include <hs/hs_runtime.h> #include "dpi_app_match.h" extern vlib_node_registration_t dpi4_flow_input_node; extern vlib_node_registration_t dpi6_flow_input_node; typedef u8 *regex_t; typedef struct { u8 *name; regex_t *expressions; u32 *flags; u32 *ids; hs_database_t *database; hs_scratch_t *scratch; u32 ref_cnt; } dpi_entry_t; typedef struct { int res; u32 id; } dpi_cb_args_t; typedef struct { union { struct { ip46_address_t src_ip; ip46_address_t dst_ip; u16 src_port; u16 dst_port; u8 protocol; u32 fib_index; }; u64 key[6]; }; } dpi_flow_key_t; typedef clib_bihash_kv_24_8_t dpi4_flow_key_t; typedef clib_bihash_kv_48_8_t dpi6_flow_key_t; typedef struct { /* SSL */ u8 ssl_stage; u8 ssl_got_server_cert; } dpi_flow_tcp_t; typedef struct { /* TBD */ } dpi_flow_udp_t; typedef struct segment_ { u32 send_sn; u8 *data; u32 len; u32 bi; /* vlib buffer index */ struct segment_ *next; } segment; typedef struct tcp_stream_ { u32 send_sn; /* expected segment sn */ u32 ack_sn; /* acked segment sn */ segment *seg_queue; /* store out-of-order segments */ } tcp_stream_t; typedef struct dpi_flow_info { /* Required for pool_get_aligned */ CLIB_CACHE_LINE_ALIGN_MARK (cacheline0); u16 detected_protocol[2]; u16 protocol_stack_info; u16 pkt_num; u16 pkt_direct_counter[2]; hs_stream_t *stream; u8 detect_begin; u8 detect_done; u32 app_id; /* L7 APP ID */ u16 guessed_protocol_id; u16 guessed_host_protocol_id; u8 max_more_pkts_to_check; int (*more_pkts_func) (u8 * payload, u32 payload_len, struct dpi_flow_info * flow); u16 dst_port; u8 l4_protocol; union { dpi_flow_tcp_t tcp; dpi_flow_udp_t udp; } l4; u8 ssl_cert_detected:4; u8 ssl_cert_num_checks:4; union { struct { char server_cert[64]; } ssl; /* TBD: Add more protocols */ } protos; } dpi_flow_info_t; typedef enum { TCP_STATE_SYN = 1, TCP_STATE_SYN_ACK = 2, TCP_STATE_ACK = 3, TCP_STATE_ESTABLISH = 4, TCP_STATE_FIN1 = 5, TCP_STATE_CLOSE = 6, } tcp_state_t; /* tcp packet direction */ #define DIR_C2S 0 #define DIR_S2C 1 /* tcp reassembly side */ #define REASS_C2S 0 #define REASS_S2C 1 #define REASS_BOTH 2 /* Macros to handle sequence numbers */ #define SN_LT(a,b) ((int)((a) - (b)) < 0) #define SN_GT(a,b) ((int)((a) - (b)) > 0) #define SN_EQ(a,b) ((int)((a) - (b)) == 0) typedef struct { /* Required for pool_get_aligned */ CLIB_CACHE_LINE_ALIGN_MARK (cacheline0); u32 flow_index; /* infra flow index */ u32 next_index; u8 check_more_pkts:1; u8 pkt_dir:1; u8 forward_is_c2s:1; u8 consumed:1; u8 reass_en:1; u8 reass_dir:2; dpi_flow_key_t key; dpi_flow_info_t *info; /* TCP stream reassembly */ tcp_state_t tcp_state; tcp_stream_t c2s; tcp_stream_t s2c; segment *first_seg; } dpi_flow_entry_t; typedef struct { u32 flow_id; u8 reass_en; u8 reass_dir; } tcp_reass_args_t; typedef struct { u8 is_add; u8 is_ipv6; ip46_address_t src_ip; ip46_address_t dst_ip; u16 src_port; u16 dst_port; u8 protocol; u32 fib_index; } dpi_add_del_flow_args_t; typedef struct { u32 app_id; u32 db_id; } dpi_adr_t; typedef struct { /* lookup tunnel by key */ clib_bihash_24_8_t dpi4_flow_by_key; clib_bihash_48_8_t dpi6_flow_by_key; /* vector of dpi flow instances */ dpi_flow_entry_t *dpi_flows; u32 flow_id_start; dpi_flow_info_t *dpi_infos; segment *seg_pool; /* Default hyperscan database */ dpi_entry_t default_db; /* graph node state */ uword *bm_ip4_bypass_enabled_by_sw_if; uword *bm_ip6_bypass_enabled_by_sw_if; /* API message ID base */ u16 msg_id_base; /* convenience */ vlib_main_t *vlib_main; vnet_main_t *vnet_main; } dpi_main_t; extern dpi_main_t dpi_main; #define foreach_copy_field \ _(src_ip) \ _(dst_ip) \ _(src_port) \ _(dst_port) \ _(protocol) \ _(fib_index) #define dpi_enqueue_tcp_segments(seg,vm,node,next_index,to_next,n_left_to_next,bi0,next0) \ while(seg) \ { \ bi0 = seg->bi; \ to_next[0] = bi0; \ to_next++; \ n_left_to_next--; \ next0 = flow0->next_index; \ vlib_validate_buffer_enqueue_x1 (vm, node, next_index, \ to_next, n_left_to_next, \ bi0, next0); \ prev_seg = seg; \ seg=seg->next; \ pool_put(dm->seg_pool, prev_seg); \ } #define get_u16_t(X,O) (*(u16 *)(((u8 *)X) + O)) #define DPI_MAX_SSL_REQUEST_SIZE 10000 int dpi_flow_add_del (dpi_add_del_flow_args_t * a, u32 * flow_idp); int dpi_reverse_flow_add_del (dpi_add_del_flow_args_t * a, u32 flow_id); int dpi_add_del_rx_flow (u32 hw_if_index, u32 flow_id, int is_add, u32 is_ipv6); int dpi_tcp_reass (tcp_reass_args_t * a); void dpi_flow_bypass_mode (u32 sw_if_index, u8 is_ip6, u8 is_enable); void dpi_flow_offload_mode (u32 sw_if_index, u8 is_ip6, u8 is_enable); int dpi_search_host_protocol (dpi_flow_info_t * flow, char *str_to_match, u32 str_to_match_len, u16 master_protocol_id, u32 * host_protocol_id); void dpi_search_tcp_ssl (u8 * payload, u32 payload_len, dpi_flow_info_t * flow); void dpi_detect_application (u8 * payload, u32 payload_len, dpi_flow_info_t * flow); typedef enum { DPI_PROTOCOL_UNKNOWN = 0, DPI_PROTOCOL_SSL = 1, DPI_PROTOCOL_SSL_NO_CERT = 2, DPI_N_PROTOCOL } dpi_protocol_id_t; #define foreach_dpi_input_next \ _(DROP, "error-drop") \ _(IP4_LOOKUP, "ip4-lookup") \ _(IP6_LOOKUP, "ip6-lookup") typedef enum { #define _(s,n) DPI_INPUT_NEXT_##s, foreach_dpi_input_next #undef _ DPI_INPUT_N_NEXT, } dpi_input_next_t; #endif #define foreach_dpi_input_error \ _(NONE, "no error") \ _(NO_SUCH_FLOW, "flow not existed") typedef enum { #define _(sym,str) DPI_INPUT_ERROR_##sym, foreach_dpi_input_error #undef _ DPI_INPUT_N_ERROR, } dpi_input_error_t; static char *dpi_input_error_strings[] = { #define _(sym,string) string, foreach_dpi_input_error #undef _ }; #define foreach_dpi_flow_input_next \ _(DROP, "error-drop") \ _(IP4_LOOKUP, "ip4-lookup") \ _(IP6_LOOKUP, "ip6-lookup") typedef enum { #define _(s,n) DPI_FLOW_NEXT_##s, foreach_dpi_flow_input_next #undef _ DPI_FLOW_N_NEXT, } dpi_flow_input_next_t; #define foreach_dpi_flow_error \ _(NONE, "no error") \ _(IP_CHECKSUM_ERROR, "Rx ip checksum errors") \ _(IP_HEADER_ERROR, "Rx ip header errors") \ _(UDP_CHECKSUM_ERROR, "Rx udp checksum errors") \ _(UDP_LENGTH_ERROR, "Rx udp length errors") typedef enum { #define _(f,s) DPI_FLOW_ERROR_##f, foreach_dpi_flow_error #undef _ DPI_FLOW_N_ERROR, } dpi_flow_error_t; static char *dpi_flow_error_strings[] = { #define _(n,s) s, foreach_dpi_flow_error #undef _ }; /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/component/terrain_destroy.c
<filename>engine/src/component/terrain_destroy.c /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** terrain_destroy */ #include "../../include/internal.h" #include "../../include/component.h" char *terrain__destroy_reference(color_ref_t **reference, int index) { char *r = reference[index]->name; for (int i = 0; reference[i] != NULL; i++) { free (reference[i]->name); free (reference[i]); } if (reference) free (reference); return (r); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/core/thread_update.c
<reponame>Fosowl/S.T.A.R.S.E.T-Game-Engine /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** core_update */ #include "../../include/internal.h" #include "../../include/component.h" void internal__dynamic_engine(void *ptr) { thread_pass_t *pass = (thread_pass_t *)ptr; entities_t *player = NULL; for (entities_t *entitie = pass->entities; entitie != NULL ; entitie = entitie->next) { if (pass->image != NULL) { free (entitie->terrain); entitie->terrain = component__terrain_scanner(entitie , pass->image); } search_e("player", entitie->name) != -1 ? player = entitie : 0; internal__dynamic_sound(entitie, player); if (entitie) starset_entities_render_single(entitie, pass->window); } } void internal__collider_call(void *ptr) { thread_pass_t *pass = (thread_pass_t *)ptr; internal__collider_update(pass->entities, pass->window); } static void internal__update_random(void) { static sfClock *delay = NULL; sfTime t; (!delay) ? delay = sfClock_create() : 0; t = sfClock_getElapsedTime(delay); srand(sfTime_asMilliseconds(t)); } int starset_update_engine(entities_t *entities, sfRenderWindow *window , sfImage *image) { thread_pass_t pass; internal__update_random(); pass.entities = entities; pass.window = window; pass.image = image; internal__collider_call(&pass); internal__dynamic_engine(&pass); return (0); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/tiny_lib/buffer.c
<filename>engine/src/tiny_lib/buffer.c<gh_stars>1-10 /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** $ */ #include <stdlib.h> #include <stdio.h> #include "../../include/dependancies.h" int my_strcpy_e(char *dest, char *src) { for (int i = 0; src[i] != '\0'; i++) dest[i] = src[i]; return (0); } char *clean_alloc_e(int size) { char *str = NULL; str = malloc(size * sizeof(char)); if (str == NULL) { return (NULL); } for (int i = 0; i < size; i++) str[i] = '\0'; return (str); } char *fill_e(char *with) { int i = 0; char *this = NULL; this = clean_alloc_e(sizeof(char) * my_strlen_e(with) + 2); if (this == NULL) return (NULL); for (i = 0; with[i] != '\0'; i++) { this[i] = with[i]; } this[i] = '\0'; return (this); } char **clean_double_alloc_e(int y, int x) { char **double_buffer = NULL; double_buffer = malloc(sizeof(char *) * (y + 1)); if (double_buffer == NULL) { put_err("allocation error_e !\n"); return (NULL); } for (int i = 0; i < y; i++) { double_buffer[i] = NULL; double_buffer[i] = clean_alloc_e(x); if (double_buffer[i] == NULL) { put_err("allocation error_e !\n"); return (NULL); } } double_buffer[y] = NULL; return (double_buffer); } char **divide_array_e(char *str, char separation) { int o = 0; int result_x = 0; char **result = clean_double_alloc_e(count_word_e(str) + 2 , longest_word_e(str) + 1); for (int str_x = 0; str[str_x] != '\0'; str_x++) { if (str[str_x] == separation || str[str_x] == '\t') { for (; str[str_x] == separation || str[str_x] == '\t'; str_x++); str_x -= 1; result[o][result_x] = '\0'; o += 1; result_x = -1; } else { result[o][result_x] = str[str_x]; } result_x += 1; } result[o + 1] = NULL; return (result); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/creator/obstacle.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** obstacle creator */ #include "../../include/starset_engine.h" static entities_t *internal__create_obstacle(sfVector2f spot , sfVector2f size) { entities_t *new = malloc(sizeof(entities_t)); if (new == NULL) return (NULL); new->size.x = size.x; new->size.y = size.y; new->spot.x = spot.x; new->spot.y = spot.y; new->visible = false; new->id = -1; new->is_trigger = false; new->fixed = true; new->life = 1000; new->next = NULL; new->audio = NULL; new->aspect = NULL; new->component = NULL; return (new); } entities_t *starset_add_obstacle_entities(entities_t *entities_list , sfVector2f spot, sfVector2f size) { entities_t *new_entities = NULL; entities_t *copy = NULL; if (entities_list == NULL) { new_entities = internal__create_obstacle(spot, size); return (new_entities); } else { for (copy = entities_list; copy->next != NULL; copy = copy->next); copy->next = internal__create_obstacle(spot, size); new_entities = entities_list; } return (new_entities); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/physics/physics_collide.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** realistic collsion physics */ #include "../../include/internal.h" sfVector2i internal__invert_vector(sfVector2i vector) { sfVector2i new; new.x = vector.x * -1; new.y = vector.y * -1; return (new); } static void internal__apply_impulse_law(sfVector2i collision_vector , entities_t *entitie_1, entities_t *entitie_2, float impulse) { float mass_sum = entitie_1->mass + entitie_2->mass; float velocity_1 = entitie_1->speed - (entitie_1->mass / mass_sum) *impulse; float velocity_2 = entitie_2->speed + (entitie_2->mass / mass_sum) *impulse; if (entitie_1->fixed == false) { entitie_1->spot.x += velocity_1 * collision_vector.x * -1; entitie_1->spot.y += velocity_1 * collision_vector.y * -1; } if (entitie_2->fixed == false) { entitie_2->spot.x += velocity_2 * collision_vector.x; entitie_2->spot.y += velocity_2 * collision_vector.y; } } void internal__collision_physics(entities_t *entitie_1 , entities_t *entitie_2, sfVector2i collision_vector) { float normal = internal__dot_product(entitie_1->spot , entitie_2->spot); float e = (entitie_1->restitution < entitie_2->restitution ?entitie_1->restitution : entitie_2->restitution); float impulse = -(1 + e) * normal * 0.17f; impulse /= 1 / entitie_1->mass + 1 / entitie_2->mass; entitie_2->collision_vector.x = collision_vector.x; entitie_2->collision_vector.y = collision_vector.y; if (collision_vector.x != 0 && collision_vector.y != 0) { internal__apply_impulse_law(collision_vector, entitie_1 , entitie_2, impulse); if (normal > 0) return; } }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/tiny_lib/gather.c
<gh_stars>1-10 /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** gather */ #include "../../include/dependancies.h" int char_in_e(char c, char *str) { for (int i = 0; str[i] != '\0'; i++) { if (str[i] == c) return (i); } return (-1); } int compare_e(char *str, char *try) { int i = 0; int o = 0; while (str[i] != '\0') { if (str[i] == try[i]) o += 1; i += 1; } if (i == o) return (1); else return (0); } int my_strlen_e(char *str) { int i = 0; while (str[i] != '\0') { i += 1; } return (i); } int search_e(char *this, char *in) { int i = 0; int o = 0; int size = my_strlen_e(this); while (in[i] != '\0') { if (this[o] == in[i]) o += 1; else o = 0; if (o == size) return (i - my_strlen_e(this) + 1); i += 1; } return (-1); } int count_word_e(char *buffer) { int count = 0; for (int i = 0; buffer[i] != '\0'; i++) { for (; buffer[i + 1] == ' ' || buffer[i + 1] == '\t'; i++); if (buffer[i] == ' ' || buffer[i] == '\t') count++; } return (count); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/core/sound_set.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** sound_set */ #include "../../include/macro.h" #include "../../include/internal.h" static audio_t *internal__get_audio(audio_t *audio, char *name) { sfBool ok = false; char **get = internal__get_class(name); audio_t *tmp = NULL; for (audio_t *copy = audio; copy != NULL; copy = copy->next) { if (search_e(get[0], copy->name) != -1 || search_e(copy->name , get[1]) != -1) { tmp = copy; ok = true; } } (!ok && LOG) ? put_err("bad sound name in set_sound_volume()\n") : 0; free_array(get); return (tmp); } void starset_set_sound_volume(entities_t *entities, char *name , char *sound_name, int volume) { sfBool ok = false; char **get = internal__get_class(name); audio_t *audio = NULL; for (entities_t *copy = entities; copy != NULL; copy = copy->next) { if (search_e(get[0], copy->name) != -1 || search_e(copy->name , get[1]) != -1) { audio = internal__get_audio(copy->audio, sound_name); ok = true; } } if (audio != NULL) audio->volume = volume; (!ok && LOG) ? put_err("bad entities in set_sound_volume()\n") : 0; free_array(get); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
test-src/main.c
<reponame>Fosowl/S.T.A.R.S.E.T-Game-Engine /* ** EPITECH PROJECT, 2020 ** S.T.A.R.S.E.T-Graphics-Engine ** File description: ** main */ #include "project.h" #include "starset_engine.h" /* the following code is just a small demo of the engine to play with it , not all of the function or capabilities of the engine are displayed. */ int animator_set(entities_t *entities) { // create new animation named left for all entities of class "zombie" starset_add_animation(entities, "zombie", "left", (sfVector2u){25, 48}); // add an animation key starset_add_animation_key(entities, "zombie", "left", (sfVector2f){90, 50}); starset_add_animation_key(entities, "zombie", "left", (sfVector2f){123, 50}); starset_add_animation_key(entities, "zombie", "left", (sfVector2f){156, 50}); starset_add_animation_key(entities, "zombie", "left", (sfVector2f){189, 50}); return (0); } int main (int ac, char **argv) { // set window with name "engine" and running at 60fps sfRenderWindow *window = starset_set_window((sfVector2u){700, 600}, "engine", 60); sfEvent event; sfVector2f mouse_pos; // set background image entities_t *object_list = starset_set_background(NULL, "./assets/back.jpg"); // add entities to the scene, both mathis and daniel are of class "zombie". object_list = starset_entities_add(object_list, "./assets/zombie.jpg", "zombie:daniel", 0); object_list = starset_entities_add(object_list, "./assets/zombie.jpg", "zombie:mathis", 0); object_list = starset_entities_add(object_list, "./assets/survivor.png", "player", 0); // add zound to play for all zombie starset_add_entities_sound(object_list, "zombie", "zombie_sound", "./assets/audio.ogg"); animator_set(object_list); while (starset_running(window, &event)) { // get name of object colliding with zombie entities_t *collide = starset_entities_get_propreties(object_list, "zombie")->collision; // play sound if collide with player if (collide != NULL && compare_e(collide->name, "player")) starset_entities_play_sound(object_list, "zombie", "zombie_sound", true); mouse_pos.x = (float)sfMouse_getPositionRenderWindow(window).x; mouse_pos.y = (float)sfMouse_getPositionRenderWindow(window).y; starset_entities_move_to_other(object_list, "mathis", "player"); starset_entities_move_to_other(object_list, "daniel", "player"); // move player toward the mouse starset_entities_move(object_list, "player", mouse_pos.x, mouse_pos.y); // rotate player toward the mouse starset_entities_rotate_to(object_list, "player", mouse_pos); // play "left" animation at speed 2 frame per second for all zombie. starset_play_animation(object_list, "zombie", "left", 2); // update engine, collision, rendering... starset_update_engine(object_list, window, NULL); sfRenderWindow_display(window); sfRenderWindow_clear(window, sfBlack); usleep(20000); } // destroy all entities in the scene starset_entities_destroy_all(object_list); sfRenderWindow_close(window); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/physics/collision.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** collision handler for engine core */ #include "../../include/internal.h" typedef struct point_t { float first; float second; } point_t; static sfBool internal__mouse_hover(entities_t *entitie_1 , sfRenderWindow *window) { sfVector2i mouse = sfMouse_getPositionRenderWindow(window); point_t Ax; point_t Ay; Ax.first = entitie_1->spot.x - (entitie_1->size.x / 2); Ax.second = entitie_1->spot.x + (entitie_1->size.x / 2); Ay.first = entitie_1->spot.y - (entitie_1->size.y / 2); Ay.second = entitie_1->spot.y + (entitie_1->size.y / 2); if ((float)mouse.x > Ax.first && (float)mouse.x < Ax.second && (float)mouse.y > Ay.first && (float)mouse.y < Ay.second) return (true); return (false); } static sfVector2i internal__entities_collide(entities_t *entitie_1 , entities_t *entitie_2) { sfVector2i vector = (sfVector2i){0, 0}; point_t Ax; point_t Ay; point_t Bx; point_t By; Ax.first = entitie_1->spot.x - (entitie_1->size.x / 2); Ax.second = entitie_1->spot.x + (entitie_1->size.x / 2); Ay.first = entitie_1->spot.y - (entitie_1->size.y / 2); Ay.second = entitie_1->spot.y + (entitie_1->size.y / 2); Bx.first = entitie_2->spot.x - (entitie_2->size.x / 2); Bx.second = entitie_2->spot.x + (entitie_2->size.x / 2); By.first = entitie_2->spot.y - (entitie_2->size.y / 2); By.second = entitie_2->spot.y + (entitie_2->size.y / 2); (Ax.first < Bx.first && Bx.first < Ax.second) ? vector.x = 1 : 0; (Ax.first < Bx.second && Bx.second < Ax.second) ? vector.x = -1 : 0; (By.second > Ay.first && By.second < Ay.second) ? vector.y = -1 : 0; (By.first > Ay.first && By.first < Ay.second) ? vector.y = 1 : 0; return (vector); } void internal__collider_update(entities_t *entities, sfRenderWindow *window) { entities_t *copy = entities; sfVector2i collision_vector = (sfVector2i){0, 0}; while (copy != NULL) { copy->collision = NULL; copy->mouse_hover = internal__mouse_hover(copy, window); for (entities_t *sub_copy = entities; sub_copy != NULL ; sub_copy = sub_copy->next) { if (compare_e(copy->name, sub_copy->name) == true) continue; collision_vector = internal__entities_collide(copy, sub_copy); if (collision_vector.x != 0 && collision_vector.y != 0 && !copy->collision) copy->collision = sub_copy; if (copy->is_trigger != true && sub_copy->is_trigger != true) internal__collision_physics(copy, sub_copy, collision_vector); } copy = copy->next; } }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/core/dynamic_sound.c
<filename>engine/src/core/dynamic_sound.c /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** play sound during engine call */ #include "../../include/internal.h" static void internal__apply_sound(audio_t *copy) { if (sfTime_asMilliseconds(copy->delay) > sfTime_asMilliseconds (copy->duration)) { if (copy->playing == true) { sfSound_play(copy->sound); } sfClock_restart(copy->timer); if (copy->loop == false) copy->playing = 0; } copy->delay = sfClock_getElapsedTime(copy->timer); sfSound_setLoop(copy->sound, copy->loop); sfSound_setPosition(copy->sound, copy->binaural); sfSound_setVolume(copy->sound, copy->volume); } static void internal__set_binaural_effect(audio_t *audio, sfVector3f *vector) { audio_t *copy = audio; while (copy != NULL) { copy->binaural.x = vector->x; copy->binaural.y = vector->y; copy->binaural.z = vector->z; internal__apply_sound(copy); copy = copy->next; } } void internal__dynamic_sound(entities_t *this, entities_t *player) { sfVector3f vector = (sfVector3f){0.0f, 0.0f, 0.0f}; if (!this) return; if (player != NULL) { if (starset_get_distance(player->spot, this->spot) < 70) vector = (sfVector3f){0.0f, 0.0f, 0.0f}; else { if (player->spot.x < this->spot.x) vector.x = -30.0f; else vector.x = -0.0f; if (player->spot.y < this->spot.y) vector.z = -30.0f; else vector.z = 30.0f; } } internal__set_binaural_effect(this->audio, &vector); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/include/struct.h
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** struct */ #ifndef STRUCT_H_ #define STRUCT_H_ #include "dependancies.h" typedef struct audio_t { char *name; int volume; sfSound *sound; sfVector3f binaural; sfBool playing; sfBool loop; sfTime duration; sfClock *timer; sfTime delay; struct audio_t *next; } audio_t; typedef struct component_t { char *name; int id; sfBool active; int (*pointer)(); struct component_t *next; struct component_t *back; } component_t; typedef struct animator_t { char *name; sfVector2u size; int max; int index; int frame; sfClock *delay; sfTime t; sfVector2f spot[50]; struct animator_t *next; } animator_t; typedef struct sheet_t { sfIntRect rect; sfVector2f current; animator_t *a; } sheet_t; typedef struct aspect_t { sfVector2f offset; sfTexture *texture; sfSprite *sprite; float rotation; sheet_t *sheet; struct aspect_t *next; } aspect_t; typedef struct sound_control_t { int wait; sfTime delay; sfClock *timer; } sound_control_t; typedef struct entities_t { sfBool visible; int id; char *name; float restitution; struct entities_t *collision; sfBool is_trigger; sfBool fixed; sfBool mouse_hover; sfVector2f spot; sfVector2u size; int life; float speed; int direction; float angle; float mass; char *terrain; aspect_t *aspect; component_t *component; audio_t *audio; sound_control_t control; struct entities_t *next; struct entities_t *back; sfVector2i collision_vector; } entities_t; #endif /* !STRUCT_H_ */
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/include/component.h
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** component */ #ifndef COMPONENT_H_ #define COMPONENT_H_ #include "dependancies.h" typedef struct color_ref_t { sfColor color; char *name; } color_ref_t; typedef struct area_t { sfColor right; sfColor left; sfColor up; sfColor down; sfColor center; } area_t; char *component__terrain_scanner(entities_t *entitie, ...); char *terrain__destroy_reference(color_ref_t **reference, int index); #endif /* !COMPONENT_H_ */
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/tiny_lib/output.c
<filename>engine/src/tiny_lib/output.c /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** output */ #include "../../include/dependancies.h" void put_err(char *str) { write(2, "\033[1;33m[error] \033[1;39m", 22); write(2, str, my_strlen_e(str)); } int error_e(long long int check, char *text) { if (check <= 0) { put_err(text); return (1); } return (0); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/destroy/audio_destroy.c
<filename>engine/src/destroy/audio_destroy.c /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** audio_destroy */ #include "../../include/starset_engine.h" void internal__destroy_audio(audio_t *audio) { audio_t *tmp = NULL; while (audio != NULL) { tmp = audio; audio = audio->next; if (tmp->name != NULL) free(tmp->name); if (tmp->sound != NULL) sfSound_destroy(tmp->sound); } }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/creator/create_component.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** create and add new component */ #include "../../include/internal.h" static component_t *internal__create_new_component(int (*pointer)() , char *name, int id) { component_t *component = malloc(sizeof(component_t)); if (component == NULL) return (NULL); component->pointer = pointer; component->active = true; component->next = NULL; component->id = id; component->name = fill_e(name); return (component); } static component_t *internal__add_component(component_t *component , int (*pointer)(), char *ptr_name, int id) { component_t *new = NULL; component_t *copy_component = component; component_t *tmp = NULL; if (component == NULL) new = internal__create_new_component(pointer, ptr_name, id); else { for (copy_component = component; copy_component->next != NULL; copy_component = copy_component->next); copy_component->next = internal__create_new_component(pointer , ptr_name, id); copy_component->back = tmp; tmp = copy_component; } new = component; return (new); } void starset_add_component(entities_t *entities, char *name , int (*pointer)(), char *ptr_name) { entities_t *copy = NULL; static int id = 0; char **get = internal__get_class(name); for (copy = entities; copy != NULL ; copy = copy->next) { if (search_e(get[0], copy->name) != -1 || search_e(get[1], copy->name) != -1) { copy->component = internal__add_component(copy->component, pointer , ptr_name, id); } } free_array(get); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/tiny_lib/converter.c
<filename>engine/src/tiny_lib/converter.c<gh_stars>1-10 /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** converter */ #include "../../include/dependancies.h" long long my_atoi_e(char *str) { int val = 0; int i = 0; if (my_strlen_e(str) > 18) return (0); for (i = 0; str[i] != '\0'; i++) { if (str[i] < 48 || str[i] > 57) return (-84); } for (; *str; str++) { if (*str >= '0' && *str <= '9') { val *= 10; val += *str - '0'; } else return (val); } return (val); } char *my_itoa_e(int nb) { char *str = malloc(sizeof(char) * 100); int i = 0; while (nb > 9) { str[i] = nb % 10 + 48; nb = nb / 10; i++; } str[i] = nb % 10 + 48; str[i + 1] = '\0'; str = my_revstr_e(str); return (str); } char *my_revstr_e(char *str) { int l = my_strlen_e(str) - 1; char t; for (int i = 0, r = 0, lenght = l; i < lenght / 2 + lenght % 2 ; i++, r++, l--) { t = str[r]; str[r] = str[l]; str[l] = t; if (l <= r) break; } return (str); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/physics/math_misc.c
<reponame>Fosowl/S.T.A.R.S.E.T-Game-Engine /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** math_misc */ #include "../../include/dependancies.h" sfVector2f starset_random_spot(int nb_1, int nb_2, int nb_3, int nb_4) { sfVector2f spot; spot.x = nb_1 + (rand() % nb_2); spot.y = nb_3 + (rand() % nb_4); return (spot); } int starset_get_distance(sfVector2f vector_1, sfVector2f vector_2) { float x; float y; int d = 0; x = vector_2.x - vector_1.x; y = vector_2.y - vector_1.y; d = sqrt(pow(y, 2) + pow(x, 2)); return (d); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/include/internal.h
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** internal */ #ifndef INTERNAL_H_ #define INTERNAL_H_ #include "starset_engine.h" typedef struct thread_pass_t { entities_t *entities; sfRenderWindow *window; sfImage *image; } thread_pass_t; int internal__get_vector_direction(float x, float y); int internal__follow_vector(sfVector2f *vector_1, sfVector2f *vector_2 , float average_speed); sfVector2i internal__invert_vector(sfVector2i vector); void internal__collider_update(entities_t *entities, sfRenderWindow *window); void internal__collision_physics(entities_t *entitie_1 , entities_t *entitie_2, sfVector2i collision_vector); void internal__destroy_audio(audio_t *audio); void internal__destroy_component(component_t *component); sfColor internal__image_average_color(sfImage *image, sfVector2i vector , sfVector2i size); float internal__get_magnitude(sfVector2f vector); float internal__vector_angle(sfVector2f spot_1, sfVector2f spot_2); float internal__dot_product(sfVector2f spot_1, sfVector2f spot_2); void internal__dynamic_engine(void *ptr); void internal__collider_call(void *pass); char **internal__get_class(char *name); void internal__dynamic_sound(entities_t *this, entities_t *player); sheet_t *internal__create_sheet(sfVector2u size); void internal__set_entities_value(entities_t *entitie , int new_id, char *name, sfBool fixed); int internal__test_class(char *name, char *check_name); #endif /* !INTERNAL_H_ */
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/creator/create_animator.c
<reponame>Fosowl/S.T.A.R.S.E.T-Game-Engine /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** animator */ #include "../../include/internal.h" static animator_t *internal__create_animation(char *a_name, sfVector2u size) { animator_t *animator = malloc(sizeof(animator_t)); if (!animator) return (NULL); animator->size.x = size.x; animator->size.y = size.y; animator->name = fill_e(a_name); animator->next = NULL; animator->index = 0; animator->max = 0; animator->delay = NULL; return (animator); } static void internal__add_animation_to(entities_t *this, char *a_name , sfVector2u size) { animator_t *copy = NULL; if (this->aspect->sheet->a == NULL) { this->aspect->sheet->a = internal__create_animation(a_name, size); } else { for (copy = this->aspect->sheet->a; copy->next != NULL; ) { copy = copy->next; } copy->next = internal__create_animation(a_name, size); } } void starset_add_animation(entities_t *entities, char *e_name, char *a_name , sfVector2u size) { sfBool ok = false; char **get = internal__get_class(e_name); for (entities_t *copy = entities; copy != NULL; copy = copy->next) { if (search_e(get[0], copy->name) != -1 || search_e(get[1], copy->name) != -1) { internal__add_animation_to(copy, a_name, size); ok = true; } } starset_play_animation(entities, e_name, a_name, 0); if (!ok && LOG) put_err("bad entities name in add_animation()\n"); free_array(get); } static void internal__add_keyframe_to(sheet_t *this, char *a_name , sfVector2f keyframe) { animator_t *copy = this->a; sfBool ok = false; for ( ; copy != NULL; copy = copy->next) { if (compare_e(copy->name, a_name) == true) { copy->spot[copy->index].x = keyframe.x; copy->spot[copy->index].y = keyframe.y; if (copy->index < 50) copy->index += 1; ok = true; copy->max = copy->index; } } if (!ok && LOG) put_err("bad animation name in add_keyframe()\n"); } void starset_add_animation_key(entities_t *entities, char *e_name , char *a_name, sfVector2f keyframe) { sfBool ok = false; char **get = internal__get_class(e_name); for (entities_t *copy = entities; copy != NULL; copy = copy->next) { if (search_e(get[0], copy->name) != -1 || search_e(get[1], copy->name) != -1) { internal__add_keyframe_to(copy->aspect->sheet, a_name, keyframe); ok = true; } } if (!ok && LOG) put_err("bad entities name in add_animation_key()\n"); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/physics/math_vector.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** multiple calculation for physics handling */ #include "../../include/dependancies.h" float internal__get_magnitude(sfVector2f vector) { if (abs((int)sqrt(pow(vector.x, 2) + pow(vector.y, 2))) < 50) return (sqrt(pow(vector.x, 2) + pow(vector.y, 2))); return (1.0f); } float internal__vector_angle(sfVector2f spot_1, sfVector2f spot_2) { float angle = 0.0f; sfVector2f vector; vector.x = spot_2.x - spot_1.x; vector.y = spot_2.y - spot_1.y; angle = atan2(vector.y, vector.x) * 57 * -1; return (angle); } float internal__dot_product(sfVector2f spot_1, sfVector2f spot_2) { float product = 0.0f; float angle = internal__vector_angle(spot_1, spot_2); product = internal__get_magnitude(spot_1)* internal__get_magnitude(spot_2) * cos(angle); return (product); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/core/move_by_id.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** move_by_id */ #include "../../include/macro.h" #include "../../include/internal.h" void starset_entities_teleport_by_id(entities_t *entities, int id , float x, float y) { entities_t *copy = entities; sfVector2f vector; while (copy != NULL) { if (id == copy->id) { vector.x = entities->spot.x - x; vector.y = entities->spot.y - y; copy->direction = internal__get_vector_direction(vector.x , vector.y); copy->spot.x = x; copy->spot.y = y; } copy = copy->next; } }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/include/macro.h
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** macro for starset engine */ #ifndef MACRO_H_ #define MACRO_H_ #define STATIC -1 enum move { UP, DOWN, LEFT, RIGHT, UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT }; #define LOOP 1 #define NO_LOOP 0 #define PLAY 1 #define STOP 0 #endif /* !MACRO_H_ */
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/core/calculation.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** calculation needed by engine */ #include "../../include/macro.h" #include "../../include/internal.h" int internal__get_vector_direction(float x, float y) { int direction = RIGHT; SWITCH_E CASE_E__O (y == 0 && x < 0) CASE_E__C direction = LEFT; CASE_E__O (y == 0 && x > 0) CASE_E__C direction = RIGHT; CASE_E__O (y < 0 && x == 0) CASE_E__C direction = UP; CASE_E__O (y > 0 && x == 0) CASE_E__C direction = DOWN; CASE_E__O (y > 0 && x < 0) CASE_E__C direction = DOWN_LEFT; CASE_E__O (y > 0 && x > 0) CASE_E__C direction = DOWN_RIGHT; CASE_E__O (y < 0 && x < 0) CASE_E__C direction = UP_LEFT; CASE_E__O (y < 0 && x > 0) CASE_E__C direction = UP_RIGHT; return (direction); } int internal__follow_vector(sfVector2f *vector_1, sfVector2f *vector_2 , float average_speed) { float x = 0.0f; float y = 0.0f; float angle = -1.0f; sfVector2f speed; float d = LEFT; x = vector_2->x - vector_1->x; y = vector_2->y - vector_1->y; d = sqrt(pow(y, 2) + pow(x, 2)); if (d >= 35.0f) { angle = atan2(y, x) * 57 * -1; speed.x = 2 * cos(angle) * -1; speed.y = 2 * sin(180 - (angle + 90)); vector_1->x += speed.x * average_speed; vector_1->y += speed.y * average_speed; } d = internal__get_vector_direction(speed.x, speed.y); return (d); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/tiny_lib/special.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** special */ #include "../../include/dependancies.h" int emulate_else_if_e(int *pass, int true_condition) { *pass += 1; if (true_condition == 1) return (1); else return (0); } int longest_word_e(char *buffer) { int longest = 0; int temp = 0; for (int i = 0; buffer[i] != '\0'; i++) { if (buffer[i] != ' ' && buffer[i] != '\t') temp++; else { if (temp > longest) longest = temp; temp = 0; } } if (temp > longest) longest = temp; return (longest); } void free_array(char **array) { return; if (array == NULL) return; for (int i = 0; array[i] != NULL && array[i][0] != '\0'; i++) { free(array[i]); } free(array); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/include/starset_engine.h
/* ** EPITECH PROJECT, 2020 ** S.T.A.R.S.E.T-Graphics-Engine ** File description: ** startset-engine */ #ifndef STARTSET_ENGINE_H_ #define STARTSET_ENGINE_H_ #include "dependancies.h" #include "struct.h" #define LOG 0 // UPDATE & SET sfRenderWindow *starset_set_window(sfVector2u size, char *name , int fps); sfBool starset_running(sfRenderWindow *window, sfEvent *event); int starset_update_engine(entities_t *entities, sfRenderWindow *window , sfImage *image); entities_t *starset_entities_get_propreties(entities_t *entities, char *name); entities_t *starset_set_background(entities_t *list, char *path); entities_t *starset_get_next(entities_t *entities, char *name); void starset_reset_value(float *value, float timeout, float reset); entities_t *starset_get_closest(entities_t *entities, char *name); // MATH sfVector2f starset_random_spot(int nb_1, int nb_2, int nb_3, int nb_4); int starset_get_distance(sfVector2f vector_1, sfVector2f vector_2); // CREATE entities_t *starset_entities_add(entities_t *entities_list , char *source, char *name, sfBool fixed); entities_t *starset_add_obstacle_entities(entities_t *entities_list , sfVector2f spot, sfVector2f size); void starset_add_component(entities_t *entities, char *name , int (*pointer)(), char *ptr_name); void starset_add_animation(entities_t *entities, char *e_name, char *a_name , sfVector2u size); void starset_add_animation_key(entities_t *entities, char *e_name , char *a_name, sfVector2f keyframe); void starset_add_entities_sound(entities_t *entities, char *name , char *sound_name, char *path); entities_t *starset_entities_add_from_prefab(entities_t *entities_list , sfSprite *prefab, char *name, sfBool fixed); sfSprite *starset_create_prefab(char *source); // DESTROY void starset_entities_destroy_all(entities_t *entities); entities_t *starset_entities_destroy(entities_t *entities, char *name); // ANIMATE int starset_play_animation(entities_t *entitie, char *e_name , char *a_name, int fps); // RENDER void starset_entities_render_single(entities_t *copy, sfRenderWindow *window); void starset_entities_render_all(entities_t *entities, sfRenderWindow *window); // SOUND void starset_single_play_sound(entities_t *entitie, char *sound_name , sfBool loop); void starset_entities_play_sound(entities_t *entities, char *name , char *sound_name, sfBool loop); void starset_set_sound_volume(entities_t *entities, char *name , char *sound_name, int volume); // MOVEMENT void starset_entities_teleport(entities_t *entities, char *name , float x, float y); void starset_entities_move(entities_t *entities, char *name, float x, float y); void starset_entities_move_to_other(entities_t *entities, char *first , char *second); float starset_entities_rotate_to(entities_t *entitie, char *name , sfVector2f target); float starset_entitites_rotate_to_other(entities_t *entitie, char *name , char *name_other); void starset_move_from_angle(entities_t *entities, char *name, float angle , int speed); void starset_entities_teleport_by_id(entities_t *entities, int id , float x, float y); // DEBUG void starset_debug_log(entities_t *entities, char *name); void starset_debug_graphics(entities_t *entities, char *name, sfRenderWindow *window); #endif /* !STARTSET_ENGINE_H_ */
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/core/misc.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** misc */ #include "../../include/internal.h" #include "../../include/dependancies.h" sfBool starset_running(sfRenderWindow *window, sfEvent *event) { if (!sfRenderWindow_isOpen(window)) return (false); while (sfRenderWindow_pollEvent(window, event)) { if (event->type == sfEvtClosed) return (false); } return (true); } sfRenderWindow *starset_set_window(sfVector2u size, char *name , int fps) { sfRenderWindow *window; sfVideoMode mode = {size.x, size.y, 32}; if (size.x < 20 || size.y < 20) put_err("that's really small for a window..\n"); window = sfRenderWindow_create(mode, name, sfResize | sfClose, NULL); if (!window) return (NULL); (fps >= 5) ? sfRenderWindow_setFramerateLimit(window, fps) : 0; return (window); } entities_t *starset_set_background(entities_t *list, char *path) { entities_t *new = NULL; sfVector2u size; sfTexture *texture = sfTexture_createFromFile(path, NULL); if (texture != NULL) size = sfTexture_getSize(texture); new = starset_entities_add(list, path, fill_e("reserved:background"), true); starset_entities_get_propreties(new, "background")->is_trigger = true; starset_entities_get_propreties(new, "background")->restitution = 0.0f; starset_entities_get_propreties(new, "background")->id = -1; starset_entities_get_propreties(new, "background")->spot = (sfVector2f) {size.x / 2, size.y / 2}; return (new); } void starset_reset_value(float *value, float timeout, float reset) { static sfClock *timer = NULL; sfTime delay = sfTime_Zero; if (!timer) timer = sfClock_create(); delay = sfClock_getElapsedTime(timer); if (sfTime_asMilliseconds(delay) / 1000 < timeout) return; *value = reset; sfClock_restart(timer); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
include/project.h
<filename>include/project.h /* ** EPITECH PROJECT, 2020 ** S.T.A.R.S.E.T-Graphics-Engine ** File description: ** project */ #ifndef PROJECT_H_ #define PROJECT_H_ #include <SFML/Graphics/RenderWindow.h> #include <SFML/Graphics/Texture.h> #include <SFML/Graphics/Sprite.h> #include <SFML/Audio.h> #include <SFML/Audio/Sound.h> #include <SFML/Audio/SoundBuffer.h> #include <SFML/Graphics.h> #include <SFML/System/Clock.h> #include <SFML/Window/Event.h> #include <SFML/Window/Export.h> #include <SFML/Window/Types.h> #include <SFML/System/Vector2.h> #include <SFML/Window/Mouse.h> #include <SFML/System/Clock.h> #endif /* !PROJECT_H_ */
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/core/renderer.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** render entities */ #include "../../include/starset_engine.h" void starset_entities_render_single(entities_t *copy, sfRenderWindow *window) { float rotation = 0.0f; int height = (int)copy->aspect->sheet->rect.height / 2; int width = (int)copy->aspect->sheet->rect.width / 2; copy->size.x = width; copy->size.y = height; if (copy->aspect == NULL || copy->aspect->sprite == NULL) { put_err("NULL aspect for entities when rendering"); return; } sfSprite_setOrigin(copy->aspect->sprite, (sfVector2f){width, height}); sfSprite_setTextureRect(copy->aspect->sprite, copy->aspect->sheet->rect); sfSprite_setPosition(copy->aspect->sprite, copy->spot); rotation = copy->angle + copy->aspect->rotation; sfSprite_setRotation(copy->aspect->sprite, rotation); if (copy->visible == true) sfRenderWindow_drawSprite(window, copy->aspect->sprite, NULL); } void starset_entities_render_all(entities_t *entities, sfRenderWindow *window) { entities_t *copy = entities; while (copy != NULL) { starset_entities_render_single(copy, window); copy = copy->next; } }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/debug/debug_log.c
/* ** EPITECH PROJECT, 2020 ** engine ** File description: ** output debug log in terminal */ #include "../../include/starset_engine.h" #include "../../include/internal.h" static void internal__show_entities_number(entities_t *tmp) { int nb_component = 0; int nb_sound = 0; for (component_t *c = tmp->component; c != NULL; c = c->next) { nb_component++; } for (audio_t *a = tmp->audio; a != NULL; a = a->next) { nb_sound++; } printf("number of component <%d>\n", nb_component); printf("number of sound <%d>\n", nb_sound); } static void internal__debug_single(entities_t *tmp) { printf("\n ----------------------------------- \n"); printf("name <%s> id <%d> life <%d> mass <%f> \n", tmp->name , tmp->id, tmp->life, tmp->mass); printf("visible : "); (tmp->visible) ? printf("yes ") : printf("no "); printf(", trigger : "); (tmp->is_trigger) ? printf("yes ") : printf("no "); printf(", fixed : "); (tmp->fixed) ? printf("yes ") : printf("no "); printf(", mouse hover : "); (tmp->mouse_hover) ? printf("yes\n") : printf("no\n"); if (tmp->collision) printf("collision with : %s\n", tmp->collision->name); else printf("no collision\n"); internal__show_entities_number(tmp); printf("\n ----------------------------------- \n"); } void starset_debug_log(entities_t *entities, char *name) { entities_t *tmp = NULL; char **get = internal__get_class(name); sfBool ok = false; for (entities_t *copy = entities; copy != NULL; copy = copy->next) { if (search_e(get[0], copy->name) != -1 || search_e(get[1], copy->name) != -1) { tmp = copy; ok = true; } } (!ok) ? put_err("bad entities name in ..debug_log\n") : 0; internal__debug_single(tmp); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/creator/prefab.c
<filename>engine/src/creator/prefab.c /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** prefab */ #include "../../include/macro.h" #include "../../include/internal.h" #include "../../include/starset_engine.h" static aspect_t *internal__create_aspect(sfSprite *prefab) { aspect_t *aspect = malloc(sizeof(aspect_t)); sfVector2u size; aspect->sprite = sfSprite_copy(prefab); aspect->offset = (sfVector2f){0, 0}; aspect->rotation = 0.0f; size.x = sfSprite_getScale(prefab).x; size.y = sfSprite_getScale(prefab).y; sfSprite_setOrigin(aspect->sprite, (sfVector2f){size.x / 2, size.y / 2}); aspect->sheet = internal__create_sheet(size); aspect->next = NULL; return (aspect); } static entities_t *internal__create_entities(sfSprite *prefab, char *name , sfBool fixed) { entities_t *entities = malloc(sizeof(entities_t)); static int new_id = 0; if (entities == NULL) return (NULL); internal__set_entities_value(entities, new_id, name, fixed); entities->aspect = internal__create_aspect(prefab); entities->size.x = sfSprite_getScale(prefab).x; entities->size.y = sfSprite_getScale(prefab).y; entities->mass = sqrt((entities->size.x * entities->size.y)) / 2; entities->control.timer = NULL; entities->control.delay = sfTime_Zero; new_id++; return (entities); } static void interal__switch_back_link(entities_t *entities_list , entities_t *copy, entities_t *tmp) { if (entities_list == NULL) copy->next->back = entities_list; else copy->next->back = tmp; } entities_t *starset_entities_add_from_prefab(entities_t *entities_list , sfSprite *prefab, char *name, sfBool fixed) { entities_t *new_entities = NULL; entities_t *copy = NULL; static entities_t *tmp = NULL; if (entities_list == NULL) { new_entities = internal__create_entities(prefab, name, fixed); tmp = new_entities; tmp->back = NULL; return (new_entities); } else { for (copy = entities_list; copy->next != NULL; copy = copy->next); copy->next = internal__create_entities(prefab, name, fixed); interal__switch_back_link(entities_list, copy, tmp); tmp = copy->next; } new_entities = entities_list; return (new_entities); } sfSprite *starset_create_prefab(char *source) { sfSprite *sprite = sfSprite_create(); sfTexture *texture = NULL; if (!sprite) return (NULL); texture = sfTexture_createFromFile(source, NULL); if (!texture) { put_err("bad path for texture in create_prefab !\n"); return (NULL); } sfSprite_setTexture(sprite, texture, sfFalse); return (sprite); }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/src/component/call.c
<gh_stars>1-10 /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** call component */ #include "../../include/internal.h" #include "../../include/component.h" void internal__play_component(entities_t *entitie, sfRenderWindow *window , sfImage *image) { component_t *copy = entitie->component; while (copy != NULL) { if (copy->active == true && copy->pointer != NULL) { copy->pointer(entitie, window, image); } copy = copy->next; } }
Fosowl/S.T.A.R.S.E.T-Game-Engine
engine/include/dependancies.h
<reponame>Fosowl/S.T.A.R.S.E.T-Game-Engine /* ** EPITECH PROJECT, 2020 ** engine ** File description: ** dependancies include */ #ifndef DEPENDANCIES_H_ #define DEPENDANCIES_H_ #include <SFML/Graphics/RenderWindow.h> #include <SFML/Graphics/Texture.h> #include <SFML/Graphics/Sprite.h> #include <SFML/Audio.h> #include <SFML/Audio/Sound.h> #include <SFML/Audio/SoundBuffer.h> #include <SFML/Graphics.h> #include <SFML/System/Clock.h> #include <SFML/Window/Event.h> #include <SFML/Window/Export.h> #include <SFML/Window/Types.h> #include <SFML/System/Vector2.h> #include <SFML/Window/Mouse.h> #include <SFML/System/Clock.h> #include <SFML/System/Mutex.h> #include <SFML/System/Thread.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdbool.h> #include <stdarg.h> int count_word_e(char *buffer); char **clean_double_alloc_e(int y, int x); int longest_word_e(char *buffer); char **divide_array_e(char *str, char separation); int my_strcpy_e(char *dest, char *src); long long my_atoi_e(char *str); char *my_itoa_e(int nb); int char_in_e(char c, char *str); int compare_e(char *str, char *try); int my_strlen_e(char *str); int search_e(char *this, char *in); void put_err(char *str); int error_e(long long int check, char *text); char *my_revstr_e(char *str); char *fill_e(char *with); char *clean_alloc_e(int size); void free_array(char **array); // dependancies for custom switch int emulate_else_if_e(int *pass, int true_condition); #define SWITCH_E int pass = 1; #define CASE_E__O if (emulate_else_if_e(&pass, #define CASE_E__C )) #define DEFAULT_E pass > 0 ? 0 : #endif /* !DEPENDANCIES_H_ */
sm-rana/Stormwater-Management-Model
src/main.c
//----------------------------------------------------------------------------- // main.c // // Project: EPA SWMM5 // Version: 5.1 // Date: 05/10/2018 // Author: <NAME> // Main stub for the command line version of EPA SWMM 5.1 // to be run with swmm5.dll. #include <stdio.h> #include <string.h> #include <time.h> #include "swmm5.h" #include "consts.h" int main(int argc, char *argv[]) // // Input: argc = number of command line arguments // argv = array of command line arguments // Output: returns error status // Purpose: runs the command line version of EPA SWMM 5.1. // // Command line is: swmm5 f1 f2 f3 // where f1 = name of input file, f2 = name of report file, and // f3 = name of binary output file if saved (or blank if not saved). // { char *inputFile; char *reportFile; char *binaryFile; char *arg1; char blank[] = ""; char errMsg[128]; int msgLen = 127; time_t start; double runTime; start = time(0); // --- check for proper number of command line arguments if (argc == 1) { printf("\nNot Enough Arguments (See Help --help)\n\n"); } else if (argc == 2) { // --- extract first argument arg1 = argv[1]; if (strcmp(arg1, "--help") == 0 || strcmp(arg1, "-h") == 0) { // Help printf("\n\nSTORMWATER MANAGEMENT MODEL (SWMM5) HELP\n\n"); printf("COMMANDS:\n"); printf("\t--help (-h) Help Docs\n"); printf("\t--version (-v) Build Version\n"); printf("\nRUNNING A SIMULATION:\n"); printf("\t swmm5 <input file> <report file> <output file>\n\n"); } else if (strcmp(arg1, "--version") == 0 || strcmp(arg1, "-v") == 0) { // Output version number printf("\n%s.%s.%s\n\n", SEMVERSION_MAJOR, SEMVERSION_MINOR, SEMVERSION_PATCH); } else { printf("\nUnknown Argument (See Help --help)\n\n"); } } else { // --- extract file names from command line arguments inputFile = argv[1]; reportFile = argv[2]; if (argc > 3) binaryFile = argv[3]; else binaryFile = blank; printf("\n... EPA-SWMM %s.%s (Build %s.%s.%s)\n", SEMVERSION_MAJOR, SEMVERSION_MINOR, SEMVERSION_MAJOR, SEMVERSION_MINOR, SEMVERSION_PATCH); // --- run SWMM swmm_run(inputFile, reportFile, binaryFile); // Display closing status on console runTime = difftime(time(0), start); printf("\n\n... EPA-SWMM completed in %.2f seconds.", runTime); if ( swmm_getError(errMsg, msgLen) > 0 ) printf(" There are errors.\n"); else if ( swmm_getWarnings() > 0 ) printf(" There are warnings.\n"); else printf("\n"); } // --- Use the code below if you need to keep the console window visible /* printf(" Press Enter to continue..."); getchar(); */ return 0; }
sm-rana/Stormwater-Management-Model
tools/swmm-output/src/swmm_output.c
<gh_stars>1-10 /* * swmm_output.c - SWMM Output API * * Author: <NAME> * US EPA - ORD/NHEERL * * Modified by: <NAME>, * <NAME> * */ #include "swmm_output.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include "errormanager.h" #include "messages.h" //#include "datetime.h" // NOTE: These depend on machine data model and may change when porting // F_OFF Must be a 8 byte / 64 bit integer for large file support #ifdef _WIN32 // Windows (32-bit and 64-bit) #define F_OFF __int64 #else // Other platforms #define F_OFF off_t #endif #define INT4 int // Must be a 4 byte / 32 bit integer type #define REAL4 float // Must be a 4 byte / 32 bit real type #define RECORDSIZE 4 // Memory alignment 4 byte word size for both int and real #define DATESIZE 8 // Dates are stored as 8 byte word size #define NELEMENTTYPES 4 // Number of element types #define MEMCHECK(x) (((x) == NULL) ? 414 : 0 ) struct IDentry { char* IDname; int length; }; typedef struct IDentry idEntry; //----------------------------------------------------------------------------- // Shared variables //----------------------------------------------------------------------------- typedef struct { char name[MAXFILENAME + 1]; // file path/name FILE* file; // FILE structure pointer struct IDentry *elementNames; // array of pointers to element names long Nperiods; // number of reporting periods int FlowUnits; // flow units code int Nsubcatch; // number of subcatchments int Nnodes; // number of drainage system nodes int Nlinks; // number of drainage system links int Npolluts; // number of pollutants tracked int SubcatchVars; // number of subcatch reporting variables int NodeVars; // number of node reporting variables int LinkVars; // number of link reporting variables int SysVars; // number of system reporting variables double StartDate; // start date of simulation int ReportStep; // reporting time step (seconds) F_OFF IDPos; // file position where object ID names start F_OFF ObjPropPos; // file position where object properties start F_OFF ResultsPos; // file position where results start F_OFF BytesPerPeriod; // bytes used for results in each period error_handle_t* error_handle; } data_t; //----------------------------------------------------------------------------- // Local functions //----------------------------------------------------------------------------- static void errorLookup(int errcode, char* errmsg, int length); static int validateFile(data_t* p_data); static void initElementNames(data_t* p_data); static void clearElementNames(data_t* p_data); static double getTimeValue(data_t* p_data, int timeIndex); static float getSubcatchValue(data_t* p_data, int timeIndex, int subcatchIndex, SMO_subcatchAttribute attr); static float getNodeValue(data_t* p_data, int timeIndex, int nodeIndex, SMO_nodeAttribute attr); static float getLinkValue(data_t* p_data, int timeIndex, int linkIndex, SMO_linkAttribute attr); static float getSystemValue(data_t* p_data, int timeIndex, SMO_systemAttribute attr); static int _fopen(FILE **f, const char *name, const char *mode); static int _fseek(FILE* stream, F_OFF offset, int whence); static F_OFF _ftell(FILE* stream); static float* newFloatArray(int n); static int* newIntArray(int n); static char* newCharArray(int n); int DLLEXPORT SMO_init(SMO_Handle* p_handle) // Purpose: Initialized pointer for the opaque SMO_Handle. // // Returns: Error code 0 on success, -1 on failure // // Note: The existence of this function has been carefully considered. // Don't change it. // { int errorcode = 0; data_t* priv_data; // Allocate memory for private data priv_data = (data_t*)calloc(1, sizeof(data_t)); if (priv_data != NULL){ priv_data->error_handle = new_errormanager(&errorLookup); *p_handle = priv_data; } else errorcode = -1; // TODO: Need to handle errors during initialization better. return errorcode; } int DLLEXPORT SMO_close(SMO_Handle* p_handle) // // Purpose: Clean up after and close Output API // { data_t* p_data; int errorcode = 0; p_data = (data_t*)*p_handle; if (p_data == NULL) errorcode = -1; else { clearElementNames(p_data); dst_errormanager(p_data->error_handle); if (p_data->file != NULL) fclose(p_data->file); free(p_data); *p_handle = NULL; } return errorcode; } int DLLEXPORT SMO_open(SMO_Handle p_handle, const char* path) // // Purpose: Open the output binary file and read the header. // { int err, errorcode = 0; F_OFF offset; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) return -1; else { strncpy(p_data->name, path, MAXFILENAME); // Attempt to open binary output file for reading only if ((_fopen(&(p_data->file), path, "rb")) != 0) errorcode = 434; // --- validate the output file else if ((err = validateFile(p_data)) != 0) errorcode = err; // If a warning is encountered read file header if (errorcode < 400 ) { // --- otherwise read additional parameters from start of file fseek(p_data->file, 3*RECORDSIZE, SEEK_SET); fread(&(p_data->Nsubcatch), RECORDSIZE, 1, p_data->file); fread(&(p_data->Nnodes), RECORDSIZE, 1, p_data->file); fread(&(p_data->Nlinks), RECORDSIZE, 1, p_data->file); fread(&(p_data->Npolluts), RECORDSIZE, 1, p_data->file); // Compute offset for saved subcatch/node/link input values offset = (p_data->Nsubcatch + 2) * RECORDSIZE // Subcatchment area + (3 * p_data->Nnodes + 4) * RECORDSIZE // Node type, invert & max depth + (5 * p_data->Nlinks + 6) * RECORDSIZE; // Link type, z1, z2, max depth & length offset += p_data->ObjPropPos; // Read number & codes of computed variables _fseek(p_data->file, offset, SEEK_SET); fread(&(p_data->SubcatchVars), RECORDSIZE, 1, p_data->file); // # Subcatch variables _fseek(p_data->file, p_data->SubcatchVars*RECORDSIZE, SEEK_CUR); fread(&(p_data->NodeVars), RECORDSIZE, 1, p_data->file); // # Node variables _fseek(p_data->file, p_data->NodeVars*RECORDSIZE, SEEK_CUR); fread(&(p_data->LinkVars), RECORDSIZE, 1, p_data->file); // # Link variables _fseek(p_data->file, p_data->LinkVars*RECORDSIZE, SEEK_CUR); fread(&(p_data->SysVars), RECORDSIZE, 1, p_data->file); // # System variables // --- read data just before start of output results offset = p_data->ResultsPos - 3 * RECORDSIZE; _fseek(p_data->file, offset, SEEK_SET); fread(&(p_data->StartDate), DATESIZE, 1, p_data->file); fread(&(p_data->ReportStep), RECORDSIZE, 1, p_data->file); // --- compute number of bytes of results values used per time period p_data->BytesPerPeriod = DATESIZE + (p_data->Nsubcatch*p_data->SubcatchVars + p_data->Nnodes*p_data->NodeVars + p_data->Nlinks*p_data->LinkVars + p_data->SysVars)*RECORDSIZE; } } // If error close the binary file if (errorcode > 400) { set_error(p_data->error_handle, errorcode); SMO_close(&p_handle); } return errorcode; } int DLLEXPORT SMO_getVersion(SMO_Handle p_handle, int* version) // // Input: p_handle = pointer to SMO_Handle struct // Output: version SWMM version // Returns: error code // // Purpose: Returns SWMM version that wrote binary file // { int errorcode = 0; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) return -1; else { fseek(p_data->file, 1*RECORDSIZE, SEEK_SET); if (fread(version, RECORDSIZE, 1, p_data->file) != 1) errorcode = 436; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getProjectSize(SMO_Handle p_handle, int** elementCount, int* length) // // Purpose: Returns project size. // { int errorcode = 0; int* temp = newIntArray(NELEMENTTYPES); data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else { temp[0] = p_data->Nsubcatch; temp[1] = p_data->Nnodes; temp[2] = p_data->Nlinks; temp[3] = p_data->Npolluts; *elementCount = temp; *length = NELEMENTTYPES; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getFlowUnits(SMO_Handle p_handle, int* unitFlag) // // Purpose: Returns unit flag for flow. // // Returns: // 0: CFS (cubic feet per second) // 1: GPM (gallons per minute) // 2: MGD (million gallons per day) // 3: CMS (cubic meters per second) // 4: LPS (liters per second) // 5: MLD (million liters per day) // { int errorcode = 0; data_t* p_data; *unitFlag = -1; p_data = (data_t*)p_handle; if (p_data == NULL) return -1; else { fseek(p_data->file, 2*RECORDSIZE, SEEK_SET); fread(unitFlag, RECORDSIZE, 1, p_data->file); } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getPollutantUnits(SMO_Handle p_handle, int** unitFlag, int* length) // // Purpose: // Return integer flag representing the units that the given pollutant is // measured in. Concentration units are located after the pollutant ID // names and before the object properties start, and are stored for each // pollutant. They're stored as 4-byte integers with the following codes: // 0: mg/L // 1: ug/L // 2: count/L // // Args: // pollutantIndex: valid values are 0 to Npolluts-1 { int errorcode = 0; int* temp; F_OFF offset; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (MEMCHECK(temp = newIntArray(p_data->Npolluts))) errorcode = 414; else { offset = p_data->ObjPropPos - (p_data->Npolluts * RECORDSIZE); _fseek(p_data->file, offset, SEEK_SET); fread(temp, RECORDSIZE, p_data->Npolluts, p_data->file); *unitFlag = temp; *length = p_data->Npolluts; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getStartDate(SMO_Handle p_handle, double* date) // // Purpose: Returns start date. // { int errorcode = 0; data_t* p_data; *date = -1.0; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else *date = p_data->StartDate; return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getTimes(SMO_Handle p_handle, SMO_time code, int* time) // // Purpose: Returns step size and number of periods. // { int errorcode = 0; data_t* p_data; *time = -1; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else { switch (code) { case SMO_reportStep: *time = p_data->ReportStep; break; case SMO_numPeriods: *time = p_data->Nperiods; break; default: errorcode = 421; } } return errorcode; } int DLLEXPORT SMO_getElementName(SMO_Handle p_handle, SMO_elementType type, int index, char** name, int* length) // // Purpose: Given an element index returns the element name. // { int idx = -1, errorcode = 0; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = 410; else if (p_data->file == NULL) errorcode = 411; else { // Lazy initialize the name array on demand if (p_data->elementNames == NULL) initElementNames(p_data); switch (type) { case SMO_subcatch: if (index < 0 || index >= p_data->Nsubcatch) errorcode = 423; else idx = index; break; case SMO_node: if (index < 0 || index >= p_data->Nnodes) errorcode = 423; else idx = p_data->Nsubcatch + index; break; case SMO_link: if (index < 0 || index >= p_data->Nlinks) errorcode = 423; else idx = p_data->Nsubcatch + p_data->Nnodes + index; break; case SMO_sys: if (index < 0 || index >= p_data->Npolluts) errorcode = 423; else idx = p_data->Nsubcatch + p_data->Nnodes + p_data->Nlinks + index; break; default: errorcode = 421; } if (!errorcode) { *length = p_data->elementNames[idx].length; *name = newCharArray(*length + 1); // Writes IDname and an additional null character to name strncpy(*name, p_data->elementNames[idx].IDname, (*length + 1)*sizeof(char)); } } return errorcode; } int DLLEXPORT SMO_getSubcatchSeries(SMO_Handle p_handle, int subcatchIndex, SMO_subcatchAttribute attr, int startPeriod, int endPeriod, float** outValueSeries, int* dim) // // Purpose: Get time series results for particular attribute. Specify series // start and length using timeIndex and length respectively. // { int k, length, errorcode = 0; float* temp; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (subcatchIndex < 0 || subcatchIndex > p_data->Nsubcatch) errorcode = 420; else if (startPeriod < 0 || startPeriod >= p_data->Nperiods || endPeriod <= startPeriod) errorcode = 422; // Check memory for outValues else if MEMCHECK(temp = newFloatArray(length = endPeriod - startPeriod)) errorcode = 411; else { // loop over and build time series for (k = 0; k < length; k++) temp[k] = getSubcatchValue(p_data, startPeriod + k, subcatchIndex, attr); *outValueSeries = temp; *dim = length; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getNodeSeries(SMO_Handle p_handle, int nodeIndex, SMO_nodeAttribute attr, int startPeriod, int endPeriod, float** outValueSeries, int* dim) // // Purpose: Get time series results for particular attribute. Specify series // start and length using timeIndex and length respectively. // { int k, length, errorcode = 0; float* temp; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (nodeIndex < 0 || nodeIndex > p_data->Nnodes) errorcode = 420; else if (startPeriod < 0 || startPeriod >= p_data->Nperiods || endPeriod <= startPeriod) errorcode = 422; // Check memory for outValues else if MEMCHECK(temp = newFloatArray(length = endPeriod - startPeriod)) errorcode = 411; else { // loop over and build time series for (k = 0; k < length; k++) temp[k] = getNodeValue(p_data, startPeriod + k, nodeIndex, attr); *outValueSeries = temp; *dim = length; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getLinkSeries(SMO_Handle p_handle, int linkIndex, SMO_linkAttribute attr, int startPeriod, int endPeriod, float** outValueSeries, int* dim) // // Purpose: Get time series results for particular attribute. Specify series // start and length using timeIndex and length respectively. // { int k, length, errorcode = 0; float* temp; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (linkIndex < 0 || linkIndex > p_data->Nlinks) errorcode = 420; else if (startPeriod < 0 || startPeriod >= p_data->Nperiods || endPeriod <= startPeriod) errorcode = 422; // Check memory for outValues else if MEMCHECK(temp = newFloatArray(length = endPeriod - startPeriod)) errorcode = 411; else { // loop over and build time series for (k = 0; k < length; k++) temp[k] = getLinkValue(p_data, startPeriod + k, linkIndex, attr); *outValueSeries = temp; *dim = length; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getSystemSeries(SMO_Handle p_handle, SMO_systemAttribute attr, int startPeriod, int endPeriod, float** outValueSeries, int* dim) // // Purpose: Get time series results for particular attribute. Specify series // start and length using timeIndex and length respectively. // { int k, length, errorcode = 0; float* temp; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (startPeriod < 0 || startPeriod >= p_data->Nperiods || endPeriod <= startPeriod) errorcode = 422; // Check memory for outValues else if MEMCHECK(temp = newFloatArray(length = endPeriod - startPeriod)) errorcode = 411; else { // loop over and build time series for (k = 0; k < length; k++) temp[k] = getSystemValue(p_data, startPeriod + k, attr); *outValueSeries = temp; *dim = length; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getSubcatchAttribute(SMO_Handle p_handle, int periodIndex, SMO_subcatchAttribute attr, float** outValueArray, int* length) // // Purpose: For all subcatchments at given time, get a particular attribute. // { int k, errorcode = 0; float* temp; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (periodIndex < 0 || periodIndex >= p_data->Nperiods) errorcode = 422; // Check memory for outValues else if MEMCHECK(temp = newFloatArray(p_data->Nsubcatch)) errorcode = 411; else { // loop over and pull result for (k = 0; k < p_data->Nsubcatch; k++) temp[k] = getSubcatchValue(p_data, periodIndex, k, attr); *outValueArray = temp; *length = p_data->Nsubcatch; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getNodeAttribute(SMO_Handle p_handle, int periodIndex, SMO_nodeAttribute attr, float** outValueArray, int* length) // // Purpose: For all nodes at given time, get a particular attribute. // { int k, errorcode = 0; float* temp; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (periodIndex < 0 || periodIndex >= p_data->Nperiods) errorcode = 422; // Check memory for outValues else if MEMCHECK(temp = newFloatArray(p_data->Nnodes)) errorcode = 411; else { // loop over and pull result for (k = 0; k < p_data->Nnodes; k++) temp[k] = getNodeValue(p_data, periodIndex, k, attr); *outValueArray = temp; *length = p_data->Nnodes; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getLinkAttribute(SMO_Handle p_handle, int periodIndex, SMO_linkAttribute attr, float** outValueArray, int* length) // // Purpose: For all links at given time, get a particular attribute. // { int k, errorcode = 0; float* temp; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (periodIndex < 0 || periodIndex >= p_data->Nperiods) errorcode = 422; // Check memory for outValues else if MEMCHECK(temp = newFloatArray(p_data->Nlinks)) errorcode = 411; else { // loop over and pull result for (k = 0; k < p_data->Nlinks; k++) temp[k] = getLinkValue(p_data, periodIndex, k, attr); *outValueArray = temp; *length = p_data->Nlinks; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getSystemAttribute(SMO_Handle p_handle, int periodIndex, SMO_systemAttribute attr, float** outValueArray, int* length) // // Purpose: For the system at given time, get a particular attribute. // { int errorcode = 0; float temp; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (periodIndex < 0 || periodIndex >= p_data->Nperiods) errorcode = 422; else { // don't need to loop since there's only one system temp = getSystemValue(p_data, periodIndex, attr); *outValueArray = &temp; *length = 1; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getSubcatchResult(SMO_Handle p_handle, int periodIndex, int subcatchIndex, float** outValueArray, int* arrayLength) // // Purpose: For a subcatchment at given time, get all attributes. // { int errorcode = 0; float* temp; F_OFF offset; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (periodIndex < 0 || periodIndex >= p_data->Nperiods) errorcode = 422; else if (subcatchIndex < 0 || subcatchIndex > p_data->Nsubcatch) errorcode = 423; else if MEMCHECK(temp = newFloatArray(p_data->SubcatchVars)) errorcode = 411; else { // --- compute offset into output file offset = p_data->ResultsPos + (periodIndex)*p_data->BytesPerPeriod + 2 * RECORDSIZE; // add offset for subcatchment offset += (subcatchIndex*p_data->SubcatchVars)*RECORDSIZE; _fseek(p_data->file, offset, SEEK_SET); fread(temp, RECORDSIZE, p_data->SubcatchVars, p_data->file); *outValueArray = temp; *arrayLength = p_data->SubcatchVars; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getNodeResult(SMO_Handle p_handle, int periodIndex, int nodeIndex, float** outValueArray, int* arrayLength) // // Purpose: For a node at given time, get all attributes. // { int errorcode = 0; float* temp; F_OFF offset; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (periodIndex < 0 || periodIndex >= p_data->Nperiods) errorcode = 422; else if (nodeIndex < 0 || nodeIndex > p_data->Nnodes) errorcode = 423; else if MEMCHECK(temp = newFloatArray(p_data->NodeVars)) errorcode = 411; else { // calculate byte offset to start time for series offset = p_data->ResultsPos + (periodIndex)*p_data->BytesPerPeriod + 2 * RECORDSIZE; // add offset for subcatchment and node offset += (p_data->Nsubcatch*p_data->SubcatchVars + nodeIndex*p_data->NodeVars)*RECORDSIZE; _fseek(p_data->file, offset, SEEK_SET); fread(temp, RECORDSIZE, p_data->NodeVars, p_data->file); *outValueArray = temp; *arrayLength = p_data->NodeVars; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getLinkResult(SMO_Handle p_handle, int periodIndex, int linkIndex, float** outValueArray, int* arrayLength) // // Purpose: For a link at given time, get all attributes. // { int errorcode = 0; float* temp; F_OFF offset; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (periodIndex < 0 || periodIndex >= p_data->Nperiods) errorcode = 422; else if (linkIndex < 0 || linkIndex > p_data->Nlinks) errorcode = 423; else if MEMCHECK(temp = newFloatArray(p_data->LinkVars)) errorcode = 411; else { // calculate byte offset to start time for series offset = p_data->ResultsPos + (periodIndex)*p_data->BytesPerPeriod + 2 * RECORDSIZE; // add offset for subcatchment and node and link offset += (p_data->Nsubcatch*p_data->SubcatchVars + p_data->Nnodes*p_data->NodeVars + linkIndex*p_data->LinkVars)*RECORDSIZE; _fseek(p_data->file, offset, SEEK_SET); fread(temp, RECORDSIZE, p_data->LinkVars, p_data->file); *outValueArray = temp; *arrayLength = p_data->LinkVars; } return set_error(p_data->error_handle, errorcode); } int DLLEXPORT SMO_getSystemResult(SMO_Handle p_handle, int periodIndex, int dummyIndex, float** outValueArray, int* arrayLength) // // Purpose: For the system at given time, get all attributes. // { int errorcode = 0; float* temp; F_OFF offset; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) errorcode = -1; else if (periodIndex < 0 || periodIndex >= p_data->Nperiods) errorcode = 422; else if MEMCHECK(temp = newFloatArray(p_data->SysVars)) errorcode = 411; { // calculate byte offset to start time for series offset = p_data->ResultsPos + (periodIndex)*p_data->BytesPerPeriod + 2 * RECORDSIZE; // add offset for subcatchment and node and link (system starts after the last link) offset += (p_data->Nsubcatch*p_data->SubcatchVars + p_data->Nnodes*p_data->NodeVars + p_data->Nlinks*p_data->LinkVars)*RECORDSIZE; _fseek(p_data->file, offset, SEEK_SET); fread(temp, RECORDSIZE, p_data->SysVars, p_data->file); *outValueArray = temp; *arrayLength = p_data->SysVars; } return set_error(p_data->error_handle, errorcode); } void DLLEXPORT SMO_free(void** array) // // Purpose: Frees memory allocated by API calls // { if (array != NULL) { free(*array); *array = NULL; } } void DLLEXPORT SMO_clearError(SMO_Handle p_handle) { data_t* p_data; p_data = (data_t*)p_handle; clear_error(p_data->error_handle); } int DLLEXPORT SMO_checkError(SMO_Handle p_handle, char** msg_buffer) { int errorcode = 0; char *temp = NULL; data_t* p_data; p_data = (data_t*)p_handle; if (p_data == NULL) return -1; else { errorcode = p_data->error_handle->error_status; if (errorcode) temp = check_error(p_data->error_handle); *msg_buffer = temp; } return errorcode; } void errorLookup(int errcode, char* dest_msg, int dest_len) // // Purpose: takes error code returns error message // { const char* msg; switch (errcode) { case 10: msg = WARN10; break; case 411: msg = ERR411; break; case 421: msg = ERR421; break; case 422: msg = ERR422; break; case 423: msg = ERR423; break; case 424: msg = ERR424; break; case 434: msg = ERR434; break; case 435: msg = ERR435; break; case 436: msg = ERR436; break; default: msg = ERR440; } strncpy(dest_msg, msg, MAXMSG); } // Local functions: int validateFile(data_t* p_data) { INT4 magic1, magic2, errcode; int errorcode = 0; // --- fast forward to end and read epilogue _fseek(p_data->file, -6 * RECORDSIZE, SEEK_END); fread(&(p_data->IDPos), RECORDSIZE, 1, p_data->file); fread(&(p_data->ObjPropPos), RECORDSIZE, 1, p_data->file); fread(&(p_data->ResultsPos), RECORDSIZE, 1, p_data->file); fread(&(p_data->Nperiods), RECORDSIZE, 1, p_data->file); fread(&errcode, RECORDSIZE, 1, p_data->file); fread(&magic2, RECORDSIZE, 1, p_data->file); // --- rewind and read magic number from beginning of the file _fseek(p_data->file, 0L, SEEK_SET); fread(&magic1, RECORDSIZE, 1, p_data->file); // Is this a valid SWMM binary output file? if (magic1 != magic2) errorcode = 435; // Does the binary file contain results? else if (p_data->Nperiods <= 0) errorcode = 436; // Were there problems with the model run? else if (errcode != 0) errorcode = 10; return errorcode; } void initElementNames(data_t* p_data) { int j, numNames; numNames = p_data->Nsubcatch + p_data->Nnodes + p_data->Nlinks + p_data->Npolluts; // allocate memory for array of idEntries p_data->elementNames = (idEntry*)calloc(numNames, sizeof(idEntry)); // Position the file to the start of the ID entries _fseek(p_data->file, p_data->IDPos, SEEK_SET); for(j=0;j<numNames;j++) { fread(&(p_data->elementNames[j].length), RECORDSIZE, 1, p_data->file); p_data->elementNames[j].IDname = (char*)calloc(p_data->elementNames[j].length + 1, sizeof(char)); fread(p_data->elementNames[j].IDname, sizeof(char), p_data->elementNames[j].length, p_data->file); } } void clearElementNames(data_t* p_data) { int i, n; if (p_data->elementNames != NULL) { n = p_data->Nsubcatch + p_data->Nnodes + p_data->Nlinks + p_data->Npolluts; for(i = 0; i < n; i++) free(p_data->elementNames[i].IDname); free(p_data->elementNames); } } double getTimeValue(data_t* p_data, int timeIndex) { F_OFF offset; double value; // --- compute offset into output file offset = p_data->ResultsPos + timeIndex*p_data->BytesPerPeriod; // --- re-position the file and read the result _fseek(p_data->file, offset, SEEK_SET); fread(&value, RECORDSIZE * 2, 1, p_data->file); return value; } float getSubcatchValue(data_t* p_data, int timeIndex, int subcatchIndex, SMO_subcatchAttribute attr) { F_OFF offset; float value; // --- compute offset into output file offset = p_data->ResultsPos + timeIndex*p_data->BytesPerPeriod + 2*RECORDSIZE; // offset for subcatch offset += RECORDSIZE*(subcatchIndex*p_data->SubcatchVars + attr); // --- re-position the file and read the result _fseek(p_data->file, offset, SEEK_SET); fread(&value, RECORDSIZE, 1, p_data->file); return value; } float getNodeValue(data_t* p_data, int timeIndex, int nodeIndex, SMO_nodeAttribute attr) { F_OFF offset; float value; // --- compute offset into output file offset = p_data->ResultsPos + timeIndex*p_data->BytesPerPeriod + 2*RECORDSIZE; // offset for node offset += RECORDSIZE*(p_data->Nsubcatch*p_data->SubcatchVars + nodeIndex*p_data->NodeVars + attr); // --- re-position the file and read the result _fseek(p_data->file, offset, SEEK_SET); fread(&value, RECORDSIZE, 1, p_data->file); return value; } float getLinkValue(data_t* p_data, int timeIndex, int linkIndex, SMO_linkAttribute attr) { F_OFF offset; float value; // --- compute offset into output file offset = p_data->ResultsPos + timeIndex*p_data->BytesPerPeriod + 2*RECORDSIZE; // offset for link offset += RECORDSIZE*(p_data->Nsubcatch*p_data->SubcatchVars + p_data->Nnodes*p_data->NodeVars + linkIndex*p_data->LinkVars + attr); // --- re-position the file and read the result _fseek(p_data->file, offset, SEEK_SET); fread(&value, RECORDSIZE, 1, p_data->file); return value; } float getSystemValue(data_t* p_data, int timeIndex, SMO_systemAttribute attr) { F_OFF offset; float value; // --- compute offset into output file offset = p_data->ResultsPos + timeIndex*p_data->BytesPerPeriod + 2*RECORDSIZE; // offset for system offset += RECORDSIZE*(p_data->Nsubcatch*p_data->SubcatchVars + p_data->Nnodes*p_data->NodeVars + p_data->Nlinks*p_data->LinkVars + attr); // --- re-position the file and read the result _fseek(p_data->file, offset, SEEK_SET); fread(&value, RECORDSIZE, 1, p_data->file); return value; } int _fopen(FILE **f, const char *name, const char *mode) { // // Purpose: Substitute for fopen_s on platforms where it doesn't exist // Note: fopen_s is part of C++11 standard // int ret = 0; #ifdef _MSC_VER ret = (int)fopen_s(f, name, mode); #else *f = fopen(name, mode); if (!*f) ret = -1; #endif return ret; } int _fseek(FILE* stream, F_OFF offset, int whence) // // Purpose: Selects platform fseek() for large file support // { #ifdef _MSC_VER #define FSEEK64 _fseeki64 #else #define FSEEK64 fseeko #endif return FSEEK64(stream, offset, whence); } F_OFF _ftell(FILE* stream) // // Purpose: Selects platform ftell() for large file support // { #ifdef _MSC_VER #define FTELL64 _ftelli64 #else #define FTELL64 ftello #endif return FTELL64(stream); } float* newFloatArray(int n) // // Warning: Caller must free memory allocated by this function. // { return (float*) malloc((n)*sizeof(float)); } int* newIntArray(int n) // // Warning: Caller must free memory allocated by this function. // { return (int*) malloc((n)*sizeof(int)); } char* newCharArray(int n) // // Warning: Caller must free memory allocated by this function. // { return (char*) malloc((n)*sizeof(char)); }
sm-rana/Stormwater-Management-Model
src/lid.c
<gh_stars>1-10 //----------------------------------------------------------------------------- // lid.c // // Project: EPA SWMM5 // Version: 5.1 // Date: 03/20/14 (Build 5.1.001) // 05/19/14 (Build 5.1.006) // 09/15/14 (Build 5.1.007) // 03/19/15 (Build 5.1.008) // 04/30/15 (Build 5.1.009) // 08/05/15 (Build 5.1.010) // 08/01/16 (Build 5.1.011) // 03/14/17 (Build 5.1.012) // 05/10/18 (Build 5.1.013) // Author: <NAME> (US EPA) // // This module handles all data processing involving LID (Low Impact // Development) practices used to treat runoff for individual subcatchments // within a project. The actual computation of LID performance is made by // functions within the lidproc.c module. See LidTypes below for the types // of LIDs that can be modeled. // // An LID process is described by the TLidProc data structure and consists of // size-independent design data for the different vertical layers that make // up a specific type of LID. The collection of these LID process designs is // stored in the LidProcs array. // // When a member of LidProcs is to be deployed in a particular subcatchment, // its sizing and treatment data are stored in a TLidUnit data structure. // The collection of all TLidUnits deployed in a subcatchment is held in a // TLidGroup list data structure. The LidGroups array contains a TLidGroup // list for each subcatchment in the project. // // During a runoff time step, each subcatchment calls the lid_getRunoff() // function to compute flux rates and a water balance through each layer // of each LID unit in the subcatchment. The resulting outflows (runoff, // drain flow, evaporation and infiltration) are added to those computed // for the non-LID portion of the subcatchment. // // An option exists for the detailed time series of flux rates and storage // levels for a specific LID unit to be written to a text file named by the // user for viewing outside of the SWMM program. // // Build 5.1.008: // - More input error reporting added. // - Rooftop Disconnection added to the types of LIDs. // - LID drain flows are now tracked separately. // - LID drain flows can now be routed to separate outlets. // - Check added to insure LID flows not returned to nonexistent pervious area. // // Build 5.1.009: // - Fixed bug where LID's could return outflow to non-LID area when LIDs // make up entire subcatchment. // // Build 5.1.010: // - Support for new Modified Green Ampt infiltration model added. // - Imported variable HasWetLids now properly initialized. // - Initial state of reporting (lidUnit->rptFile->wasDry) changed to // prevent duplicate printing of first line of detailed report file. // // Build 5.1.011: // - The top of the storage layer is no longer used as a limit for an // underdrain offset thus allowing upturned drains to be modeled. // - Column headings for the detailed LID report file were modified. // // Build 5.1.012: // - Redefined initialization of wasDry for LID reporting. // // Build 5.1.013: // - Support added for LID units treating pervious area runoff. // - Support added for open/closed head levels and multiplier v. head // control curve for underdrain flow. // - Support added for unclogging permeable pavement at fixed intervals. // - Support added for pollutant removal in underdrain flow. //----------------------------------------------------------------------------- #define _CRT_SECURE_NO_DEPRECATE #include <math.h> #include "headers.h" #include "lid.h" #define ERR_PAVE_LAYER " - check pavement layer parameters" #define ERR_SOIL_LAYER " - check soil layer parameters" #define ERR_STOR_LAYER " - check storage layer parameters" #define ERR_SWALE_SURF " - check swale surface parameters" #define ERR_GREEN_AMPT " - check subcatchment Green-Ampt parameters" #define ERR_DRAIN_OFFSET " - drain offset exceeds storage height" #define ERR_DRAIN_HEADS " - invalid drain open/closed heads" //(5.1.013) #define ERR_SWALE_WIDTH " - invalid swale width" //----------------------------------------------------------------------------- // Enumerations //----------------------------------------------------------------------------- enum LidLayerTypes { SURF, // surface layer SOIL, // soil layer STOR, // storage layer PAVE, // pavement layer DRAINMAT, // drainage mat layer DRAIN, // underdrain system REMOVALS}; // pollutant removals //(5.1.013) //// Note: DRAINMAT must be placed before DRAIN so the two keywords can /// be distinguished from one another when parsing a line of input. char* LidLayerWords[] = {"SURFACE", "SOIL", "STORAGE", "PAVEMENT", "DRAINMAT", "DRAIN", "REMOVALS", NULL}; //(5.1.013) char* LidTypeWords[] = {"BC", //bio-retention cell "RG", //rain garden "GR", //green roof "IT", //infiltration trench "PP", //porous pavement "RB", //rain barrel "VS", //vegetative swale "RD", //rooftop disconnection NULL}; //----------------------------------------------------------------------------- // Data Structures //----------------------------------------------------------------------------- // LID List - list of LID units contained in an LID group //----------------------------------------------------------------------------- // Shared Variables //----------------------------------------------------------------------------- static TLidProc* LidProcs; // array of LID processes static int LidCount; // number of LID processes static TLidGroup* LidGroups; // array of LID process groups static int GroupCount; // number of LID groups (subcatchments) static double EvapRate; // evaporation rate (ft/s) static double NativeInfil; // native soil infil. rate (ft/s) static double MaxNativeInfil; // native soil infil. rate limit (ft/s) //----------------------------------------------------------------------------- // Imported Variables (from SUBCATCH.C) //----------------------------------------------------------------------------- // Volumes (ft3) for a subcatchment over a time step extern double Vevap; // evaporation extern double Vpevap; // pervious area evaporation extern double Vinfil; // non-LID infiltration extern double VlidInfil; // infiltration from LID units extern double VlidIn; // impervious area flow to LID units extern double VlidOut; // surface outflow from LID units extern double VlidDrain; // drain outflow from LID units extern double VlidReturn; // LID outflow returned to pervious area extern char HasWetLids; // TRUE if any LIDs are wet // (from RUNOFF.C) //----------------------------------------------------------------------------- // External Functions (prototyped in lid.h) //----------------------------------------------------------------------------- // lid_create called by createObjects in project.c // lid_delete called by deleteObjects in project.c // lid_validate called by project_validate // lid_initState called by project_init // lid_readProcParams called by parseLine in input.c // lid_readGroupParams called by parseLine in input.c // lid_setOldGroupState called by subcatch_setOldState // lid_setReturnQual called by findLidLoads in surfqual.c // lid_getReturnQual called by subcatch_getRunon // lid_getPervArea called by subcatch_getFracPerv // lid_getFlowToPerv called by subcatch_getRunon // lid_getSurfaceDepth called by subcatch_getDepth // lid_getDepthOnPavement called by sweptSurfacesDry in subcatch.c // lid_getStoredVolume called by subcatch_getStorage // lid_getRunon called by subcatch_getRunon // lid_getRunoff called by subcatch_getRunoff // lid_addDrainRunon called by subcatch_getRunon // lid_addDrainLoads called by surfqual_getWashoff // lid_addDrainInflow called by addLidDrainInflows in routing.c // lid_writeSummary called by inputrpt_writeInput // lid_writeWaterBalance called by statsrpt_writeReport // lid_getLidUnitCount called by LID API toolkit in toolkitAPI.c // lid_getLidUnit called by LID API toolkit in toolkitAPI.c // lid_getLidProc called by LID API toolkit in toolkitAPI.c // lid_getLidGroup called by LID API toolkit in toolkitAPI.c // lid_validateLidProc called by LID API toolkit in toolkitAPI.c // lid_validateLidGroup called by LID API toolkit in toolkitAPI.c // lid_updateLidUnit called by LID API toolkit in toolkitAPI.c // lid_updateAllLidUnit called by LID API toolkit in toolkitAPI.c // lid_updateLidGroup called by LID API toolkit in toolkitAPI.c //----------------------------------------------------------------------------- // Local Functions //----------------------------------------------------------------------------- static void freeLidGroup(int j); static int readSurfaceData(int j, char* tok[], int ntoks); static int readPavementData(int j, char* tok[], int ntoks); static int readSoilData(int j, char* tok[], int ntoks); static int readStorageData(int j, char* tok[], int ntoks); static int readDrainData(int j, char* tok[], int ntoks); static int readDrainMatData(int j, char* toks[], int ntoks); static int readRemovalsData(int j, char* toks[], int ntoks); //(5.1.013) static int addLidUnit(int j, int k, int n, double x[], char* fname, int drainSubcatch, int drainNode); static int createLidRptFile(TLidUnit* lidUnit, char* fname); static void initLidRptFile(char* title, char* lidID, char* subcatchID, TLidUnit* lidUnit); static void validateLidProc(int j); static void validateLidGroup(int j); static int isLidPervious(int k); static double getImpervAreaRunoff(int j); static double getPervAreaRunoff(int j); //(5.1.013) static double getSurfaceDepth(int subcatch); static void findNativeInfil(int j, double tStep); static void evalLidUnit(int j, TLidUnit* lidUnit, double lidArea, double lidInflow, double tStep, double *qRunoff, double *qDrain, double *qReturn); //============================================================================= void lid_create(int lidCount, int subcatchCount) // // Purpose: creates an array of LID objects. // Input: n = number of LID processes // Output: none // { int j; //... assign NULL values to LID arrays LidProcs = NULL; LidGroups = NULL; LidCount = lidCount; //... create LID groups GroupCount = subcatchCount; if ( GroupCount > 0 ) { LidGroups = (TLidGroup *) calloc(GroupCount, sizeof(TLidGroup)); if ( LidGroups == NULL ) { ErrorCode = ERR_MEMORY; return; } } //... initialize LID groups for (j = 0; j < GroupCount; j++) LidGroups[j] = NULL; //... create LID objects if ( LidCount == 0 ) return; LidProcs = (TLidProc *) calloc(LidCount, sizeof(TLidProc)); if ( LidProcs == NULL ) { ErrorCode = ERR_MEMORY; return; } //... initialize LID objects for (j = 0; j < LidCount; j++) { LidProcs[j].lidType = -1; LidProcs[j].surface.thickness = 0.0; LidProcs[j].surface.voidFrac = 1.0; LidProcs[j].surface.roughness = 0.0; LidProcs[j].surface.surfSlope = 0.0; LidProcs[j].pavement.thickness = 0.0; LidProcs[j].soil.thickness = 0.0; LidProcs[j].storage.thickness = 0.0; LidProcs[j].storage.kSat = 0.0; LidProcs[j].drain.coeff = 0.0; LidProcs[j].drain.offset = 0.0; LidProcs[j].drainMat.thickness = 0.0; LidProcs[j].drainMat.roughness = 0.0; LidProcs[j].drainRmvl = NULL; //(5.1.013) LidProcs[j].drainRmvl = (double *) // calloc(Nobjects[POLLUT], sizeof(double)); // if (LidProcs[j].drainRmvl == NULL) // { // ErrorCode = ERR_MEMORY; // return; // } // } } //============================================================================= void lid_delete() // // Purpose: deletes all LID objects // Input: none // Output: none // { int j; for (j = 0; j < GroupCount; j++) freeLidGroup(j); FREE(LidGroups); for (j = 0; j < LidCount; j++) FREE(LidProcs[j].drainRmvl); //(5.1.013) FREE(LidProcs); GroupCount = 0; LidCount = 0; } //============================================================================= void freeLidGroup(int j) // // Purpose: frees all LID units associated with a subcatchment. // Input: j = group (or subcatchment) index // Output: none // { TLidGroup lidGroup = LidGroups[j]; TLidList* lidList; TLidUnit* lidUnit; TLidList* nextLidUnit; if ( lidGroup == NULL ) return; lidList = lidGroup->lidList; while (lidList) { lidUnit = lidList->lidUnit; if ( lidUnit->rptFile ) { if ( lidUnit->rptFile->file ) fclose(lidUnit->rptFile->file); free(lidUnit->rptFile); } nextLidUnit = lidList->nextLidUnit; free(lidUnit); free(lidList); lidList = nextLidUnit; } free(lidGroup); LidGroups[j] = NULL; } //============================================================================= int lid_readProcParams(char* toks[], int ntoks) // // Purpose: reads LID process information from line of input data file // Input: toks = array of string tokens // ntoks = number of tokens // Output: returns error code // // Format for first line that defines a LID process is: // LID_ID LID_Type // // Followed by some combination of lines below depending on LID_Type: // LID_ID SURFACE <parameters> // LID_ID PAVEMENT <parameters> // LID_ID SOIL <parameters> // LID_ID STORAGE <parameters> // LID_ID DRAIN <parameters> // LID_ID DRAINMAT <parameters> // LID_ID REMOVALS <parameters> //(5.1.013) // { int j, m; // --- check for minimum number of tokens if ( ntoks < 2 ) return error_setInpError(ERR_ITEMS, ""); // --- check that LID exists in database j = project_findObject(LID, toks[0]); if ( j < 0 ) return error_setInpError(ERR_NAME, toks[0]); // --- assign ID if not done yet if ( LidProcs[j].ID == NULL ) LidProcs[j].ID = project_findID(LID, toks[0]); // --- check if second token is the type of LID m = findmatch(toks[1], LidTypeWords); if ( m >= 0 ) { LidProcs[j].lidType = m; return 0; } // --- check if second token is name of LID layer else m = findmatch(toks[1], LidLayerWords); // --- read input parameters for the identified layer switch (m) { case SURF: return readSurfaceData(j, toks, ntoks); case SOIL: return readSoilData(j, toks, ntoks); case STOR: return readStorageData(j, toks, ntoks); case PAVE: return readPavementData(j, toks, ntoks); case DRAIN: return readDrainData(j, toks, ntoks); case DRAINMAT: return readDrainMatData(j, toks, ntoks); case REMOVALS: return readRemovalsData(j, toks, ntoks); //(5.1.013) } return error_setInpError(ERR_KEYWORD, toks[1]); } //============================================================================= int lid_readGroupParams(char* toks[], int ntoks) // // Purpose: reads input data for a LID unit placed in a subcatchment. // Input: toks = array of string tokens // ntoks = number of tokens // Output: returns error code // // Format of input data line is: // Subcatch_ID LID_ID Number Area Width InitSat FromImp ToPerv // (RptFile DrainTo FromPerv) //(5.1.013) // where: // Subcatch_ID = name of subcatchment // LID_ID = name of LID process // Number (n) = number of replicate units // Area (x[0]) = area of each unit // Width (x[1]) = outflow width of each unit // InitSat (x[2]) = % that LID is initially saturated // FromImp (x[3]) = % of impervious runoff sent to LID // ToPerv (x[4]) = 1 if outflow goes to pervious sub-area; 0 if not // RptFile = name of detailed results file (optional) // DrainTo = name of subcatch/node for drain flow (optional) // FromPerv (x[5]) = % of pervious runoff sent to LID //(5.1.013) // { int i, j, k, n; double x[6]; //(5.1.013) char* fname = NULL; int drainSubcatch = -1, drainNode = -1; //... check for valid number of input tokens if ( ntoks < 8 ) return error_setInpError(ERR_ITEMS, ""); //... find subcatchment j = project_findObject(SUBCATCH, toks[0]); if ( j < 0 ) return error_setInpError(ERR_NAME, toks[0]); //... find LID process in list of LID processes k = project_findObject(LID, toks[1]); if ( k < 0 ) return error_setInpError(ERR_NAME, toks[1]); //... get number of replicates n = atoi(toks[2]); if ( n < 0 ) return error_setInpError(ERR_NUMBER, toks[2]); if ( n == 0 ) return 0; //... convert next 4 tokens to doubles for (i = 3; i <= 7; i++) { if ( ! getDouble(toks[i], &x[i-3]) || x[i-3] < 0.0 ) return error_setInpError(ERR_NUMBER, toks[i]); } //... check for valid percentages on tokens 5 & 6 (x[2] & x[3]) for (i = 2; i <= 3; i++) if ( x[i] > 100.0 ) return error_setInpError(ERR_NUMBER, toks[i+3]); //... read optional report file name if ( ntoks >= 9 && strcmp(toks[8], "*") != 0 ) fname = toks[8]; //... read optional underdrain outlet if ( ntoks >= 10 && strcmp(toks[9], "*") != 0 ) { drainSubcatch = project_findObject(SUBCATCH, toks[9]); if ( drainSubcatch < 0 ) { drainNode = project_findObject(NODE, toks[9]); if ( drainNode < 0 ) return error_setInpError(ERR_NAME, toks[9]); } } //... read percent of pervious area treated by LID unit //(5.1.013) x[5] = 0.0; // if (ntoks >= 11) // { // if (!getDouble(toks[10], &x[5]) || x[5] < 0.0 || x[5] > 100.0) // return error_setInpError(ERR_NUMBER, toks[10]); // } // //... create a new LID unit and add it to the subcatchment's LID group return addLidUnit(j, k, n, x, fname, drainSubcatch, drainNode); } //============================================================================= int addLidUnit(int j, int k, int n, double x[], char* fname, int drainSubcatch, int drainNode) // // Purpose: adds an LID unit to a subcatchment's LID group. // Input: j = subcatchment index // k = LID control index // n = number of replicate units // x = LID unit's parameters // fname = name of detailed performance report file // drainSubcatch = index of subcatchment receiving underdrain flow // drainNode = index of node receiving underdrain flow // Output: returns an error code // { TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; //... create a LID group (pointer to an LidGroup struct) // if one doesn't already exist lidGroup = LidGroups[j]; if ( !lidGroup ) { lidGroup = (struct LidGroup *) malloc(sizeof(struct LidGroup)); if ( !lidGroup ) return error_setInpError(ERR_MEMORY, ""); lidGroup->lidList = NULL; LidGroups[j] = lidGroup; } //... create a new LID unit to add to the group lidUnit = (TLidUnit *) malloc(sizeof(TLidUnit)); if ( !lidUnit ) return error_setInpError(ERR_MEMORY, ""); lidUnit->rptFile = NULL; //... add the LID unit to the group lidList = (TLidList *) malloc(sizeof(TLidList)); if ( !lidList ) { free(lidUnit); return error_setInpError(ERR_MEMORY, ""); } lidList->lidUnit = lidUnit; lidList->nextLidUnit = lidGroup->lidList; lidGroup->lidList = lidList; //... assign parameter values to LID unit lidUnit->lidIndex = k; lidUnit->number = n; lidUnit->area = x[0] / SQR(UCF(LENGTH)); lidUnit->fullWidth = x[1] / UCF(LENGTH); lidUnit->initSat = x[2] / 100.0; lidUnit->fromImperv = x[3] / 100.0; lidUnit->toPerv = (x[4] > 0.0); lidUnit->fromPerv = x[5] / 100.0; //(5.1.013) lidUnit->drainSubcatch = drainSubcatch; lidUnit->drainNode = drainNode; //... open report file if it was supplied if ( fname != NULL ) { if ( !createLidRptFile(lidUnit, fname) ) return error_setInpError(ERR_RPT_FILE, fname); } return 0; } //============================================================================= int createLidRptFile(TLidUnit* lidUnit, char* fname) { TLidRptFile* rptFile; rptFile = (TLidRptFile *) malloc(sizeof(TLidRptFile)); if ( rptFile == NULL ) return 0; lidUnit->rptFile = rptFile; rptFile->file = fopen(fname, "wt"); if ( rptFile->file == NULL ) return 0; return 1; } //============================================================================= int readSurfaceData(int j, char* toks[], int ntoks) // // Purpose: reads surface layer data for a LID process from line of input // data file // Input: j = LID process index // toks = array of string tokens // ntoks = number of tokens // Output: returns error code // // Format of data is: // LID_ID SURFACE StorageHt VegVolFrac Roughness SurfSlope SideSlope DamHt // { int i; double x[5]; if ( ntoks < 7 ) return error_setInpError(ERR_ITEMS, ""); for (i = 2; i < 7; i++) { if ( ! getDouble(toks[i], &x[i-2]) || x[i-2] < 0.0 ) return error_setInpError(ERR_NUMBER, toks[i]); } if ( x[1] >= 1.0 ) return error_setInpError(ERR_NUMBER, toks[3]); if ( x[0] == 0.0 ) x[1] = 0.0; LidProcs[j].surface.thickness = x[0] / UCF(RAINDEPTH); LidProcs[j].surface.voidFrac = 1.0 - x[1]; LidProcs[j].surface.roughness = x[2]; LidProcs[j].surface.surfSlope = x[3] / 100.0; LidProcs[j].surface.sideSlope = x[4]; return 0; } //============================================================================= int readPavementData(int j, char* toks[], int ntoks) // // Purpose: reads pavement layer data for a LID process from line of input // data file // Input: j = LID process index // toks = array of string tokens // ntoks = number of tokens // Output: returns error code // // Format of data is: // LID_ID PAVEMENT Thickness VoidRatio FracImperv Permeability ClogFactor // (RegenDays RegenDegree) //(5.1.013) // { int i; double x[7]; //(5.1.013) if ( ntoks < 7 ) return error_setInpError(ERR_ITEMS, ""); for (i = 2; i < 7; i++) { if ( ! getDouble(toks[i], &x[i-2]) || x[i-2] < 0.0 ) return error_setInpError(ERR_NUMBER, toks[i]); } // ... read optional clogging regeneration properties //(5.1.013) x[5] = 0.0; // if (ntoks > 7) // { // if (!getDouble(toks[7], &x[5]) || x[5] < 0.0) // return error_setInpError(ERR_NUMBER, toks[7]); // } // x[6] = 0.0; // if (ntoks > 8) // { // if (!getDouble(toks[8], &x[6]) || x[6] < 0.0 || x[6] > 1.0) // return error_setInpError(ERR_NUMBER, toks[8]); // } // //... convert void ratio to void fraction x[1] = x[1]/(x[1] + 1.0); LidProcs[j].pavement.thickness = x[0] / UCF(RAINDEPTH); LidProcs[j].pavement.voidFrac = x[1]; LidProcs[j].pavement.impervFrac = x[2]; LidProcs[j].pavement.kSat = x[3] / UCF(RAINFALL); if (LidProcs[j].pavement.thickness > 0.0) { LidProcs[j].pavement.clogFactor = x[4] * LidProcs[j].pavement.thickness * LidProcs[j].pavement.voidFrac * (1.0 - LidProcs[j].pavement.impervFrac); } else { LidProcs[j].pavement.clogFactor = 0.0; } LidProcs[j].pavement.regenDays = x[5]; //(5.1.013) LidProcs[j].pavement.regenDegree = x[6]; // return 0; } //============================================================================= int readSoilData(int j, char* toks[], int ntoks) // // Purpose: reads soil layer data for a LID process from line of input // data file // Input: j = LID process index // toks = array of string tokens // ntoks = number of tokens // Output: returns error code // // Format of data is: // LID_ID SOIL Thickness Porosity FieldCap WiltPt Ksat Kslope Suction // { int i; double x[7]; if ( ntoks < 9 ) return error_setInpError(ERR_ITEMS, ""); for (i = 2; i < 9; i++) { if ( ! getDouble(toks[i], &x[i-2]) || x[i-2] < 0.0 ) return error_setInpError(ERR_NUMBER, toks[i]); } LidProcs[j].soil.thickness = x[0] / UCF(RAINDEPTH); LidProcs[j].soil.porosity = x[1]; LidProcs[j].soil.fieldCap = x[2]; LidProcs[j].soil.wiltPoint = x[3]; LidProcs[j].soil.kSat = x[4] / UCF(RAINFALL); LidProcs[j].soil.kSlope = x[5]; LidProcs[j].soil.suction = x[6] / UCF(RAINDEPTH); return 0; } //============================================================================= int readStorageData(int j, char* toks[], int ntoks) // // Purpose: reads drainage layer data for a LID process from line of input // data file // Input: j = LID process index // toks = array of string tokens // ntoks = number of tokens // Output: returns error code // // Format of data is: // LID_ID STORAGE Thickness VoidRatio Ksat ClogFactor // { int i; double x[6]; //... read numerical parameters if ( ntoks < 6 ) return error_setInpError(ERR_ITEMS, ""); for (i = 2; i < 6; i++) { if ( ! getDouble(toks[i], &x[i-2]) || x[i-2] < 0.0 ) return error_setInpError(ERR_NUMBER, toks[i]); } //... convert void ratio to void fraction x[1] = x[1]/(x[1] + 1.0); //... save parameters to LID storage layer structure LidProcs[j].storage.thickness = x[0] / UCF(RAINDEPTH); LidProcs[j].storage.voidFrac = x[1]; LidProcs[j].storage.kSat = x[2] / UCF(RAINFALL); if (LidProcs[j].storage.thickness > 0.0) { LidProcs[j].storage.clogFactor = x[3] * LidProcs[j].storage.thickness * LidProcs[j].storage.voidFrac; } else { LidProcs[j].storage.clogFactor = 0.0; } return 0; } //============================================================================= int readDrainData(int j, char* toks[], int ntoks) // // Purpose: reads underdrain data for a LID process from line of input // data file // Input: j = LID process index // toks = array of string tokens // ntoks = number of tokens // Output: returns error code // // Format of data is: // LID_ID DRAIN coeff expon offset delay hOpen hClose curve //(5.1.013) // { int i; double x[6]; //(5.1.013) //... read numerical parameters if ( ntoks < 6 ) return error_setInpError(ERR_ITEMS, ""); for (i = 0; i < 6; i++) x[i] = 0.0; //(5.1.013) for (i = 2; i < 8; i++) // { if ( ( ntoks > i && ! getDouble(toks[i], &x[i-2]) ) || x[i-2] < 0.0 ) //(5.1.013) return error_setInpError(ERR_NUMBER, toks[i]); } i = -1; //(5.1.013) if ( ntoks >= 9 ) // { // i = project_findObject(CURVE, toks[8]); // if (i < 0) return error_setInpError(ERR_NAME, toks[8]); // } // //... save parameters to LID drain layer structure LidProcs[j].drain.coeff = x[0]; LidProcs[j].drain.expon = x[1]; LidProcs[j].drain.offset = x[2] / UCF(RAINDEPTH); LidProcs[j].drain.delay = x[3] * 3600.0; LidProcs[j].drain.hOpen = x[4] / UCF(RAINDEPTH); //(5.1.013) LidProcs[j].drain.hClose = x[5] / UCF(RAINDEPTH); // LidProcs[j].drain.qCurve = i; // return 0; } //============================================================================= int readDrainMatData(int j, char* toks[], int ntoks) // // Purpose: reads drainage mat data for a LID process from line of input // data file // Input: j = LID process index // toks = array of string tokens // ntoks = number of tokens // Output: returns error code // // Format of data is: // LID_ID DRAINMAT thickness voidRatio roughness // { int i; double x[3]; //... read numerical parameters if ( ntoks < 5 ) return error_setInpError(ERR_ITEMS, ""); if ( LidProcs[j].lidType != GREEN_ROOF ) return 0; for (i = 2; i < 5; i++) { if ( ! getDouble(toks[i], &x[i-2]) || x[i-2] < 0.0 ) return error_setInpError(ERR_NUMBER, toks[i]); } //... save parameters to LID drain layer structure LidProcs[j].drainMat.thickness = x[0] / UCF(RAINDEPTH);; LidProcs[j].drainMat.voidFrac = x[1]; LidProcs[j].drainMat.roughness = x[2]; return 0; } //============================================================================= //// This function was added to release 5.1.013. //// //(5.1.013) int readRemovalsData(int j, char* toks[], int ntoks) // // Purpose: reads pollutant removal data for a LID process from line of input // data file // Input: j = LID process index // toks = array of string tokens // ntoks = number of tokens // Output: returns error code // // Format of data is: // LID_ID REMOVALS pollut1 %removal1 pollut2 %removal2 ... // { int i = 2; int p; double rmvl; //... start with 3rd token if (ntoks < 4) return error_setInpError(ERR_ITEMS, ""); while (ntoks > i) { //... find pollutant index from its name p = project_findObject(POLLUT, toks[i]); if (p < 0) return error_setInpError(ERR_NAME, toks[i]); //... check that a next token exists i++; if (ntoks == i) return error_setInpError(ERR_ITEMS, ""); //... get the % removal value from the next token if (!getDouble(toks[i], &rmvl) || rmvl < 0.0 || rmvl > 100.0) return error_setInpError(ERR_NUMBER, toks[i]); //... save the pollutant removal for the LID process as a fraction LidProcs[j].drainRmvl[p] = rmvl / 100.0; i++; } return 0; } //============================================================================= void lid_writeSummary() // // Purpose: writes summary of LID processes used to report file. // Input: none // Output: none // { int j, k; double pctArea; TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; fprintf(Frpt.file, "\n"); fprintf(Frpt.file, "\n"); fprintf(Frpt.file, "\n *******************"); fprintf(Frpt.file, "\n LID Control Summary"); fprintf(Frpt.file, "\n *******************"); fprintf(Frpt.file, "\n No. of Unit Unit %% Area %% Imperv %% Perv"); //(5.1.013) fprintf(Frpt.file, // "\n Subcatchment LID Control Units Area Width Covered Treated Treated"); // fprintf(Frpt.file, // "\n ---------------------------------------------------------------------------------------------------"); // for (j = 0; j < GroupCount; j++) { lidGroup = LidGroups[j]; if ( lidGroup == NULL ) continue; lidList = lidGroup->lidList; while ( lidList ) { lidUnit = lidList->lidUnit; k = lidUnit->lidIndex; pctArea = lidUnit->area * lidUnit->number / Subcatch[j].area * 100.0; fprintf(Frpt.file, "\n %-16s %-16s", Subcatch[j].ID, LidProcs[k].ID); fprintf(Frpt.file, "%6d %10.2f %10.2f %10.2f %10.2f %10.2f", //(5.1.013) lidUnit->number, lidUnit->area * SQR(UCF(LENGTH)), lidUnit->fullWidth * UCF(LENGTH), pctArea, lidUnit->fromImperv*100.0, lidUnit->fromPerv*100.0); //(5.1.013) lidList = lidList->nextLidUnit; } } } //============================================================================= void lid_validate() // // Purpose: validates LID process and group parameters. // Input: none // Output: none // { int j; for (j = 0; j < LidCount; j++) validateLidProc(j); for (j = 0; j < GroupCount; j++) validateLidGroup(j); } //============================================================================= void validateLidProc(int j) // // Purpose: validates LID process parameters. // Input: j = LID process index // Output: none // { int layerMissing = FALSE; //... check that LID type was supplied if ( LidProcs[j].lidType < 0 ) { report_writeErrorMsg(ERR_LID_TYPE, LidProcs[j].ID); return; } //... check that required layers were defined switch (LidProcs[j].lidType) { case BIO_CELL: case RAIN_GARDEN: if ( LidProcs[j].soil.thickness <= 0.0 ) layerMissing = TRUE; break; case GREEN_ROOF: if ( LidProcs[j].soil.thickness <= 0.0 ) layerMissing = TRUE; if ( LidProcs[j].drainMat.thickness <= 0.0) layerMissing = TRUE; break; case POROUS_PAVEMENT: if ( LidProcs[j].pavement.thickness <= 0.0 ) layerMissing = TRUE; break; case INFIL_TRENCH: if ( LidProcs[j].storage.thickness <= 0.0 ) layerMissing = TRUE; break; } if ( layerMissing ) { report_writeErrorMsg(ERR_LID_LAYER, LidProcs[j].ID); return; } //... check pavement layer parameters if ( LidProcs[j].lidType == POROUS_PAVEMENT ) { if ( LidProcs[j].pavement.thickness <= 0.0 || LidProcs[j].pavement.kSat <= 0.0 || LidProcs[j].pavement.voidFrac <= 0.0 || LidProcs[j].pavement.voidFrac > 1.0 || LidProcs[j].pavement.impervFrac > 1.0 ) { strcpy(Msg, LidProcs[j].ID); strcat(Msg, ERR_PAVE_LAYER); report_writeErrorMsg(ERR_LID_PARAMS, Msg); } } //... check soil layer parameters if ( LidProcs[j].soil.thickness > 0.0 ) { if ( LidProcs[j].soil.porosity <= 0.0 || LidProcs[j].soil.fieldCap >= LidProcs[j].soil.porosity || LidProcs[j].soil.wiltPoint >= LidProcs[j].soil.fieldCap || LidProcs[j].soil.kSat <= 0.0 || LidProcs[j].soil.kSlope < 0.0 ) { strcpy(Msg, LidProcs[j].ID); strcat(Msg, ERR_SOIL_LAYER); report_writeErrorMsg(ERR_LID_PARAMS, Msg); } } //... check storage layer parameters if ( LidProcs[j].storage.thickness > 0.0 ) { if ( LidProcs[j].storage.voidFrac <= 0.0 || LidProcs[j].storage.voidFrac > 1.0 ) { strcpy(Msg, LidProcs[j].ID); strcat(Msg, ERR_STOR_LAYER); report_writeErrorMsg(ERR_LID_PARAMS, Msg); } } //... if no storage layer adjust void fraction and drain offset else { LidProcs[j].storage.voidFrac = 1.0; LidProcs[j].drain.offset = 0.0; } //... check for invalid drain open/closed heads //(5.1.013) if (LidProcs[j].drain.hOpen > 0.0 && // LidProcs[j].drain.hOpen <= LidProcs[j].drain.hClose) // { // strcpy(Msg, LidProcs[j].ID); // strcat(Msg, ERR_DRAIN_HEADS); // report_writeErrorMsg(ERR_LID_PARAMS, Msg); // } // //... compute the surface layer's overland flow constant (alpha) if ( LidProcs[j].lidType == VEG_SWALE ) { if ( LidProcs[j].surface.roughness * LidProcs[j].surface.surfSlope <= 0.0 || LidProcs[j].surface.thickness == 0.0 ) { strcpy(Msg, LidProcs[j].ID); strcat(Msg, ERR_SWALE_SURF); report_writeErrorMsg(ERR_LID_PARAMS, Msg); } else LidProcs[j].surface.alpha = 1.49 * sqrt(LidProcs[j].surface.surfSlope) / LidProcs[j].surface.roughness; } else { //... compute surface overland flow coeff. if ( LidProcs[j].surface.roughness > 0.0 ) LidProcs[j].surface.alpha = 1.49 / LidProcs[j].surface.roughness * sqrt(LidProcs[j].surface.surfSlope); else LidProcs[j].surface.alpha = 0.0; } //... compute drainage mat layer's flow coeff. if ( LidProcs[j].drainMat.roughness > 0.0 ) { LidProcs[j].drainMat.alpha = 1.49 / LidProcs[j].drainMat.roughness * sqrt(LidProcs[j].surface.surfSlope); } else LidProcs[j].drainMat.alpha = 0.0; //... for certain LID types, immediate overflow of excess surface water // occurs if either the surface roughness or slope is zero LidProcs[j].surface.canOverflow = TRUE; switch (LidProcs[j].lidType) { case ROOF_DISCON: LidProcs[j].surface.canOverflow = FALSE; break; case INFIL_TRENCH: case POROUS_PAVEMENT: case BIO_CELL: case RAIN_GARDEN: case GREEN_ROOF: if ( LidProcs[j].surface.alpha > 0.0 ) LidProcs[j].surface.canOverflow = FALSE; } //... rain barrels have 100% void space and impermeable bottom if ( LidProcs[j].lidType == RAIN_BARREL ) { LidProcs[j].storage.voidFrac = 1.0; LidProcs[j].storage.kSat = 0.0; } //... set storage layer parameters of a green roof if ( LidProcs[j].lidType == GREEN_ROOF ) { LidProcs[j].storage.thickness = LidProcs[j].drainMat.thickness; LidProcs[j].storage.voidFrac = LidProcs[j].drainMat.voidFrac; LidProcs[j].storage.clogFactor = 0.0; LidProcs[j].storage.kSat = 0.0; } } //============================================================================= void validateLidGroup(int j) // // Purpose: validates properties of LID units grouped in a subcatchment. // Input: j = subcatchment index // Output: returns 1 if data are valid, 0 if not // { int k; double p[3]; double totalArea = Subcatch[j].area; double totalLidArea = 0.0; double fromImperv = 0.0; double fromPerv = 0.0; //(5.1.013) TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; lidGroup = LidGroups[j]; if ( lidGroup == NULL ) return; lidList = lidGroup->lidList; while ( lidList ) { lidUnit = lidList->lidUnit; k = lidUnit->lidIndex; //... update contributing fractions totalLidArea += (lidUnit->area * lidUnit->number); fromImperv += lidUnit->fromImperv; fromPerv += lidUnit->fromPerv; //(5.1.013) //... assign biocell soil layer infiltration parameters lidUnit->soilInfil.Ks = 0.0; if ( LidProcs[k].soil.thickness > 0.0 ) { p[0] = LidProcs[k].soil.suction * UCF(RAINDEPTH); p[1] = LidProcs[k].soil.kSat * UCF(RAINFALL); p[2] = (LidProcs[k].soil.porosity - LidProcs[k].soil.wiltPoint) * (1.0 - lidUnit->initSat); if ( grnampt_setParams(&(lidUnit->soilInfil), p) == FALSE ) { strcpy(Msg, LidProcs[k].ID); strcat(Msg, ERR_SOIL_LAYER); report_writeErrorMsg(ERR_LID_PARAMS, Msg); } } //... assign vegetative swale infiltration parameters if ( LidProcs[k].lidType == VEG_SWALE ) { if ( InfilModel == GREEN_AMPT || InfilModel == MOD_GREEN_AMPT ) { p[0] = GAInfil[j].S * UCF(RAINDEPTH); p[1] = GAInfil[j].Ks * UCF(RAINFALL); p[2] = GAInfil[j].IMDmax; if ( grnampt_setParams(&(lidUnit->soilInfil), p) == FALSE ) { strcpy(Msg, LidProcs[k].ID); strcat(Msg, ERR_GREEN_AMPT); report_writeErrorMsg(ERR_LID_PARAMS, Msg); } } if ( lidUnit->fullWidth <= 0.0 ) { strcpy(Msg, LidProcs[k].ID); strcat(Msg, ERR_SWALE_WIDTH); report_writeErrorMsg(ERR_LID_PARAMS, Msg); } } //... LID unit cannot send outflow back to subcatchment's // pervious area if none exists if ( Subcatch[j].fracImperv >= 0.999 ) lidUnit->toPerv = 0; //... assign drain outlet if not set by user if ( lidUnit->drainNode == -1 && lidUnit->drainSubcatch == -1 ) { lidUnit->drainNode = Subcatch[j].outNode; lidUnit->drainSubcatch = Subcatch[j].outSubcatch; } lidList = lidList->nextLidUnit; } //... check contributing area fractions if ( totalLidArea > 1.001 * totalArea ) { report_writeErrorMsg(ERR_LID_AREAS, Subcatch[j].ID); } if ( fromImperv > 1.001 || fromPerv > 1.001 ) //(5.1.013) { report_writeErrorMsg(ERR_LID_CAPTURE_AREA, Subcatch[j].ID); } //... Make subcatchment LID area equal total area if the two are close if ( totalLidArea > 0.999 * totalArea ) totalLidArea = totalArea; Subcatch[j].lidArea = totalLidArea; } //============================================================================= void lid_initState() // // Purpose: initializes the internal state of each LID in a subcatchment. // Input: none // Output: none // { int i, j, k; TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; double initVol; double initDryTime = StartDryDays * SECperDAY; HasWetLids = FALSE; for (j = 0; j < GroupCount; j++) { //... check if group exists lidGroup = LidGroups[j]; if ( lidGroup == NULL ) continue; //... initialize group variables lidGroup->pervArea = 0.0; lidGroup->flowToPerv = 0.0; lidGroup->oldDrainFlow = 0.0; lidGroup->newDrainFlow = 0.0; //... examine each LID in the group lidList = lidGroup->lidList; while ( lidList ) { //... initialize depth & moisture content lidUnit = lidList->lidUnit; k = lidUnit->lidIndex; lidUnit->surfaceDepth = 0.0; lidUnit->storageDepth = 0.0; lidUnit->soilMoisture = 0.0; lidUnit->paveDepth = 0.0; lidUnit->dryTime = initDryTime; lidUnit->volTreated = 0.0; //(5.1.013) lidUnit->nextRegenDay = LidProcs[k].pavement.regenDays; // initVol = 0.0; if ( LidProcs[k].soil.thickness > 0.0 ) { lidUnit->soilMoisture = LidProcs[k].soil.wiltPoint + lidUnit->initSat * (LidProcs[k].soil.porosity - LidProcs[k].soil.wiltPoint); initVol += lidUnit->soilMoisture * LidProcs[k].soil.thickness; } if ( LidProcs[k].storage.thickness > 0.0 ) { lidUnit->storageDepth = lidUnit->initSat * LidProcs[k].storage.thickness; initVol += lidUnit->storageDepth * LidProcs[k].storage.voidFrac; } if ( LidProcs[k].drainMat.thickness > 0.0 ) { lidUnit->storageDepth = lidUnit->initSat * LidProcs[k].drainMat.thickness; initVol += lidUnit->storageDepth * LidProcs[k].drainMat.voidFrac; } if ( lidUnit->initSat > 0.0 ) HasWetLids = TRUE; //... initialize water balance totals lidproc_initWaterBalance(lidUnit, initVol); //... initialize water rate lidproc_initWaterRate(lidUnit); lidUnit->volTreated = 0.0; //... initialize report file for the LID if ( lidUnit->rptFile ) { initLidRptFile(Title[0], LidProcs[k].ID, Subcatch[j].ID, lidUnit); } //... initialize drain flows lidUnit->oldDrainFlow = 0.0; lidUnit->newDrainFlow = 0.0; //... set previous flux rates to 0 for (i = 0; i < MAX_LAYERS; i++) { lidUnit->oldFluxRates[i] = 0.0; } //... initialize infiltration state variables if ( lidUnit->soilInfil.Ks > 0.0 ) grnampt_initState(&(lidUnit->soilInfil)); //... add contribution to pervious LID area if ( isLidPervious(lidUnit->lidIndex) ) lidGroup->pervArea += (lidUnit->area * lidUnit->number); lidList = lidList->nextLidUnit; } } } //============================================================================= void lid_setOldGroupState(int j) // // Purpose: saves the current drain flow rate for the LIDs in a subcatchment. // Input: j = subcatchment index // Output: none // { TLidList* lidList; if ( LidGroups[j] != NULL ) { LidGroups[j]->oldDrainFlow = LidGroups[j]->newDrainFlow; LidGroups[j]->newDrainFlow = 0.0; lidList = LidGroups[j]->lidList; while (lidList) { lidList->lidUnit->oldDrainFlow = lidList->lidUnit->newDrainFlow; lidList->lidUnit->newDrainFlow = 0.0; lidList = lidList->nextLidUnit; } } } //============================================================================= int isLidPervious(int k) // // Purpose: determines if a LID process allows infiltration or not. // Input: k = LID process index // Output: returns 1 if process is pervious or 0 if not // { return ( LidProcs[k].storage.thickness == 0.0 || LidProcs[k].storage.kSat > 0.0 ); } //============================================================================= double getSurfaceDepth(int j) // // Purpose: computes the depth (volume per unit area) of ponded water on the // surface of all LIDs within a subcatchment. // Input: j = subcatchment index // Output: returns volumetric depth of ponded water (ft) // { int k; double depth = 0.0; TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; lidGroup = LidGroups[j]; if ( lidGroup == NULL ) return 0.0; if ( Subcatch[j].lidArea == 0.0 ) return 0.0; lidList = lidGroup->lidList; while ( lidList ) { lidUnit = lidList->lidUnit; k = lidUnit->lidIndex; depth += lidUnit->surfaceDepth * LidProcs[k].surface.voidFrac * lidUnit->area * lidUnit->number; lidList = lidList->nextLidUnit; } return depth / Subcatch[j].lidArea; } //============================================================================= double lid_getPervArea(int j) // // Purpose: retrieves amount of pervious LID area in a subcatchment. // Input: j = subcatchment index // Output: returns amount of pervious LID area (ft2) // { if ( LidGroups[j] ) return LidGroups[j]->pervArea; else return 0.0; } //============================================================================= double lid_getFlowToPerv(int j) // // Purpose: retrieves flow returned from LID treatment to pervious area of // a subcatchment. // Input: j = subcatchment index // Output: returns flow returned to pervious area (cfs) // { if ( LidGroups[j] != NULL ) return LidGroups[j]->flowToPerv; return 0.0; } //============================================================================= double lid_getStoredVolume(int j) // // Purpose: computes stored volume of water for all LIDs // grouped within a subcatchment. // Input: j = subcatchment index // Output: returns stored volume of water (ft3) // { double total = 0.0; TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; lidGroup = LidGroups[j]; if ( lidGroup == NULL || Subcatch[j].lidArea == 0.0 ) return 0.0; lidList = lidGroup->lidList; while ( lidList ) { lidUnit = lidList->lidUnit; total += lidUnit->waterBalance.finalVol * lidUnit->area * lidUnit->number; lidList = lidList->nextLidUnit; } return total; } //============================================================================= double lid_getDrainFlow(int j, int timePeriod) // // Purpose: returns flow from all of a subcatchment's LID drains for // a designated time period // Input: j = subcatchment index // timePeriod = either PREVIOUS or CURRENT // Output: total drain flow (cfs) from the subcatchment. { if ( LidGroups[j] != NULL ) { if ( timePeriod == PREVIOUS ) return LidGroups[j]->oldDrainFlow; else return LidGroups[j]->newDrainFlow; } return 0.0; } //============================================================================= //// This function was modified for relelase 5.1.013. //// //(5.1.013) void lid_addDrainLoads(int j, double c[], double tStep) // // Purpose: adds pollutant loads routed from drains to system // mass balance totals. // Input: j = subcatchment index // c = array of pollutant washoff concentrations (mass/L) // tStep = time step (sec) // Output: none. // { int isRunoffLoad; // true if drain becomes external runoff load int p; // pollutant index double r; // pollutant fractional removal double w; // pollutant mass load (lb or kg) TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; //... check if LID group exists lidGroup = LidGroups[j]; if ( lidGroup != NULL ) { //... examine each LID unit in the group lidList = lidGroup->lidList; while ( lidList ) { lidUnit = lidList->lidUnit; //... see if unit's drain flow becomes external runoff isRunoffLoad = (lidUnit->drainNode >= 0 || lidUnit->drainSubcatch == j); //... for each pollutant not routed back on to subcatchment surface if (!lidUnit->toPerv) for (p = 0; p < Nobjects[POLLUT]; p++) { //... get mass load flowing through the drain w = lidUnit->newDrainFlow * c[p] * tStep * LperFT3 * Pollut[p].mcf; //... get fractional removal for this load r = LidProcs[lidUnit->lidIndex].drainRmvl[p]; //... update system mass balance totals massbal_updateLoadingTotals(BMP_REMOVAL_LOAD, p, r*w); if (isRunoffLoad) massbal_updateLoadingTotals(RUNOFF_LOAD, p, w*(1.0-r)); } // process next LID unit in the group lidList = lidList->nextLidUnit; } } } //============================================================================= void lid_addDrainRunon(int j) // // Purpose: adds drain flows from LIDs in a given subcatchment to the // subcatchments that were designated to receive them // Input: j = index of subcatchment contributing underdrain flows // Output: none. // { int i; // index of an LID unit's LID process //(5.1.013) int k; // index of subcatchment receiving LID drain flow int p; // pollutant index double q; // drain flow rate (cfs) double w; // mass of polllutant from drain flow //(5.1.013) TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; //... check if LID group exists lidGroup = LidGroups[j]; if ( lidGroup != NULL ) { //... examine each LID in the group lidList = lidGroup->lidList; while ( lidList ) { //... see if LID's drain discharges to another subcatchment lidUnit = lidList->lidUnit; i = lidUnit->lidIndex; //(5.1.013) k = lidUnit->drainSubcatch; if ( k >= 0 && k != j ) { //... distribute drain flow across subcatchment's areas q = lidUnit->oldDrainFlow; subcatch_addRunonFlow(k, q); //... add pollutant loads from drain to subcatchment // (newQual[] contains loading rate (mass/sec) at this // point which is converted later on to a concentration) for (p = 0; p < Nobjects[POLLUT]; p++) { w = q * Subcatch[j].oldQual[p] * LperFT3; //(5.1.013) w = w * (1.0 - LidProcs[i].drainRmvl[p]); // Subcatch[k].newQual[p] += w; // } } lidList = lidList->nextLidUnit; } } } //============================================================================= void lid_addDrainInflow(int j, double f) // // Purpose: adds LID drain flow to conveyance system nodes // Input: j = subcatchment index // f = time interval weighting factor // Output: none. // // Note: this function updates the total lateral flow (Node[].newLatFlow) // and pollutant mass (Node[].newQual[]) inflow seen by nodes that // receive drain flow from the LID units in subcatchment j. { int i, // LID process index //(5.1.013) k, // node index p; // pollutant index double q, // drain flow (cfs) w, w1, w2; // pollutant mass loads (mass/sec) TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; //... check if LID group exists lidGroup = LidGroups[j]; if ( lidGroup != NULL ) { //... examine each LID in the group lidList = lidGroup->lidList; while ( lidList ) { //... see if LID's drain discharges to conveyance system node lidUnit = lidList->lidUnit; i = lidUnit->lidIndex; //(5.1.013) k = lidUnit->drainNode; if ( k >= 0 ) { //... add drain flow to node's wet weather inflow q = (1.0 - f) * lidUnit->oldDrainFlow + f * lidUnit->newDrainFlow; Node[k].newLatFlow += q; massbal_addInflowFlow(WET_WEATHER_INFLOW, q); //... add pollutant load, based on parent subcatchment quality for (p = 0; p < Nobjects[POLLUT]; p++) { //... get previous & current drain loads w1 = lidUnit->oldDrainFlow * Subcatch[j].oldQual[p]; w2 = lidUnit->newDrainFlow * Subcatch[j].newQual[p]; //... add interpolated load to node's wet weather loading w = (1.0 - f) * w1 + f * w2; w = w * (1.0 - LidProcs[i].drainRmvl[p]); //(5.1.013) Node[k].newQual[p] += w; massbal_addInflowQual(WET_WEATHER_INFLOW, p, w); } } lidList = lidList->nextLidUnit; } } } //============================================================================= void lid_getRunoff(int j, double tStep) // // Purpose: computes runoff and drain flows from the LIDs in a subcatchment. // Input: j = subcatchment index // tStep = time step (sec) // Output: updates following global quantities after LID treatment applied: // Vevap, Vpevap, VlidInfil, VlidIn, VlidOut, VlidDrain. // { TLidGroup theLidGroup; // group of LIDs placed in the subcatchment TLidList* lidList; // list of LID units in the group TLidUnit* lidUnit; // a member of the list of LID units double lidArea; // area of an LID unit double qImperv = 0.0; // runoff from impervious areas (cfs) double qPerv = 0.0; // runoff from pervious areas (cfs) //(5.1.013) double lidInflow = 0.0; // inflow to an LID unit (ft/s) double qRunoff = 0.0; // surface runoff from all LID units (cfs) double qDrain = 0.0; // drain flow from all LID units (cfs) double qReturn = 0.0; // LID outflow returned to pervious area (cfs) //... return if there are no LID's theLidGroup = LidGroups[j]; if ( !theLidGroup ) return; lidList = theLidGroup->lidList; if ( !lidList ) return; //... determine if evaporation can occur EvapRate = Evap.rate; if ( Evap.dryOnly && Subcatch[j].rainfall > 0.0 ) EvapRate = 0.0; //... find subcatchment's infiltration rate into native soil findNativeInfil(j, tStep); //... get impervious and pervious area runoff from non-LID // portion of subcatchment (cfs) if ( Subcatch[j].area > Subcatch[j].lidArea ) { qImperv = getImpervAreaRunoff(j); qPerv = getPervAreaRunoff(j); //(5.1.013) } //... evaluate performance of each LID unit placed in the subcatchment while ( lidList ) { //... find area of the LID unit lidUnit = lidList->lidUnit; lidArea = lidUnit->area * lidUnit->number; //... if LID unit has area, evaluate its performance if ( lidArea > 0.0 ) { //... find runoff from non-LID area treated by LID area (ft/sec) lidInflow = (qImperv * lidUnit->fromImperv + //(5.1.013) qPerv * lidUnit->fromPerv) / lidArea; // //... update total runoff volume treated VlidIn += lidInflow * lidArea * tStep; //... add rainfall onto LID inflow (ft/s) lidInflow = lidInflow + Subcatch[j].rainfall; // ... add upstream runon only if LID occupies full subcatchment if ( Subcatch[j].area == Subcatch[j].lidArea ) { lidInflow += Subcatch[j].runon; } //... evaluate the LID unit's performance, updating the LID group's // total surface runoff, drain flow, and flow returned to // pervious area evalLidUnit(j, lidUnit, lidArea, lidInflow, tStep, &qRunoff, &qDrain, &qReturn); } lidList = lidList->nextLidUnit; } //... save the LID group's total drain & return flows theLidGroup->newDrainFlow = qDrain; theLidGroup->flowToPerv = qReturn; //... save the LID group's total surface, drain and return flow volumes VlidOut = qRunoff * tStep; VlidDrain = qDrain * tStep; VlidReturn = qReturn * tStep; } //============================================================================= void findNativeInfil(int j, double tStep) // // Purpose: determines a subcatchment's current infiltration rate into // its native soil. // Input: j = subcatchment index // tStep = time step (sec) // Output: sets values for module-level variables NativeInfil // { double nonLidArea; //... subcatchment has non-LID pervious area nonLidArea = Subcatch[j].area - Subcatch[j].lidArea; if ( nonLidArea > 0.0 && Subcatch[j].fracImperv < 1.0 ) { NativeInfil = Vinfil / nonLidArea / tStep; } //... otherwise find infil. rate for the subcatchment's rainfall + runon else { NativeInfil = infil_getInfil(j, InfilModel, tStep, Subcatch[j].rainfall, Subcatch[j].runon, getSurfaceDepth(j)); //(5.1.008) } //... see if there is any groundwater-imposed limit on infil. if ( !IgnoreGwater && Subcatch[j].groundwater ) { MaxNativeInfil = Subcatch[j].groundwater->maxInfilVol / tStep; } else MaxNativeInfil = BIG; } //============================================================================= double getImpervAreaRunoff(int j) // // Purpose: computes runoff from impervious area of a subcatchment that // is available for LID treatment. // Input: j = subcatchment index // Output: returns runoff flow rate (cfs) // { int i; double q = 0.0, // runoff rate (ft/sec) nonLidArea; // non-LID area (ft2) // --- runoff from impervious area w/ & w/o depression storage for (i = IMPERV0; i <= IMPERV1; i++) { q += Subcatch[j].subArea[i].runoff * Subcatch[j].subArea[i].fArea; } // --- adjust for any fraction of runoff sent to pervious area if ( Subcatch[j].subArea[IMPERV0].routeTo == TO_PERV && Subcatch[j].fracImperv < 1.0 ) { q *= Subcatch[j].subArea[IMPERV0].fOutlet; } nonLidArea = Subcatch[j].area - Subcatch[j].lidArea; return q * nonLidArea; } //============================================================================= //// This function was added for release 5.1.013. //// //(5.1.013) double getPervAreaRunoff(int j) // // Purpose: computes runoff from pervious area of a subcatchment that // is available for LID treatment. // Input: j = subcatchment index // Output: returns runoff flow rate (cfs) // { double q = 0.0, // runoff rate (ft/sec) nonLidArea; // non-LID area (ft2) // --- runoff from pervious area q = Subcatch[j].subArea[PERV].runoff * Subcatch[j].subArea[PERV].fArea; // --- adjust for any fraction of runoff sent to impervious area if (Subcatch[j].subArea[PERV].routeTo == TO_IMPERV && Subcatch[j].fracImperv > 0.0) { q *= Subcatch[j].subArea[PERV].fOutlet; } nonLidArea = Subcatch[j].area - Subcatch[j].lidArea; return q * nonLidArea; } //============================================================================= void evalLidUnit(int j, TLidUnit* lidUnit, double lidArea, double lidInflow, double tStep, double *qRunoff, double *qDrain, double *qReturn) // // Purpose: evaluates performance of a specific LID unit over current time step. // Input: j = subcatchment index // lidUnit = ptr. to LID unit being evaluated // lidArea = area of LID unit // lidInflow = inflow to LID unit (ft/s) // tStep = time step (sec) // Output: qRunoff = sum of surface runoff from all LIDs (cfs) // qDrain = sum of drain flows from all LIDs (cfs) // qReturn = sum of LID flows returned to pervious area (cfs) // { TLidProc* lidProc; // LID process associated with lidUnit double lidRunoff, // surface runoff from LID unit (cfs) lidEvap, // evaporation rate from LID unit (ft/s) lidInfil, // infiltration rate from LID unit (ft/s) lidDrain; // drain flow rate from LID unit (ft/s & cfs) //... identify the LID process of the LID unit being analyzed lidProc = &LidProcs[lidUnit->lidIndex]; //... initialize evap and infil losses lidEvap = 0.0; lidInfil = 0.0; //... find surface runoff from the LID unit (in cfs) lidRunoff = lidproc_getOutflow(lidUnit, lidProc, lidInflow, EvapRate, NativeInfil, MaxNativeInfil, tStep, &lidEvap, &lidInfil, &lidDrain) * lidArea; //... convert drain flow to CFS lidDrain *= lidArea; //... revise flows if LID outflow returned to pervious area if ( lidUnit->toPerv && Subcatch[j].area > Subcatch[j].lidArea ) { //... surface runoff is always returned *qReturn += lidRunoff; lidRunoff = 0.0; //... drain flow returned if it has same outlet as subcatchment if ( lidUnit->drainNode == Subcatch[j].outNode && lidUnit->drainSubcatch == Subcatch[j].outSubcatch ) { *qReturn += lidDrain; lidDrain = 0.0; } } //... update system flow balance if drain flow goes to a // conveyance system node if ( lidUnit->drainNode >= 0 ) { massbal_updateRunoffTotals(RUNOFF_DRAINS, lidDrain * tStep); } //... save new drain outflow lidUnit->newDrainFlow = lidDrain; //... update moisture losses (ft3) Vevap += lidEvap * tStep * lidArea; VlidInfil += lidInfil * tStep * lidArea; if ( isLidPervious(lidUnit->lidIndex) ) { Vpevap += lidEvap * tStep * lidArea; } //... update time since last rainfall (for Rain Barrel emptying) if ( Subcatch[j].rainfall > MIN_RUNOFF ) lidUnit->dryTime = 0.0; else lidUnit->dryTime += tStep; //... update LID water balance and save results lidproc_saveResults(lidUnit, UCF(RAINFALL), UCF(RAINDEPTH)); //... update LID group totals *qRunoff += lidRunoff; *qDrain += lidDrain; } //============================================================================= void lid_writeWaterBalance() // // Purpose: writes a LID performance summary table to the project's report file. // Input: none // Output: none // { int j; int k = 0; double ucf = UCF(RAINDEPTH); double inflow; double outflow; double err; TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; //... check that project has LIDs for ( j = 0; j < GroupCount; j++ ) { if ( LidGroups[j] ) k++; } if ( k == 0 ) return; //... write table header fprintf(Frpt.file, "\n" "\n ***********************" "\n LID Performance Summary" "\n ***********************\n"); fprintf(Frpt.file, "\n --------------------------------------------------------------------------------------------------------------------" "\n Total Evap Infil Surface Drain Initial Final Continuity" "\n Inflow Loss Loss Outflow Outflow Storage Storage Error"); if ( UnitSystem == US ) fprintf(Frpt.file, "\n Subcatchment LID Control in in in in in in in %%"); else fprintf(Frpt.file, "\n Subcatchment LID Control mm mm mm mm mm mm mm %%"); fprintf(Frpt.file, "\n --------------------------------------------------------------------------------------------------------------------"); //... examine each LID unit in each subcatchment for ( j = 0; j < GroupCount; j++ ) { lidGroup = LidGroups[j]; if ( !lidGroup || Subcatch[j].lidArea == 0.0 ) continue; lidList = lidGroup->lidList; while ( lidList ) { //... write water balance components to report file lidUnit = lidList->lidUnit; k = lidUnit->lidIndex; fprintf(Frpt.file, "\n %-16s %-16s", Subcatch[j].ID, LidProcs[k].ID); fprintf(Frpt.file, "%10.2f%10.2f%10.2f%10.2f%10.2f%10.2f%10.2f", lidUnit->waterBalance.inflow*ucf, lidUnit->waterBalance.evap*ucf, lidUnit->waterBalance.infil*ucf, lidUnit->waterBalance.surfFlow*ucf, lidUnit->waterBalance.drainFlow*ucf, lidUnit->waterBalance.initVol*ucf, lidUnit->waterBalance.finalVol*ucf); //... compute flow balance error inflow = lidUnit->waterBalance.initVol + lidUnit->waterBalance.inflow; outflow = lidUnit->waterBalance.finalVol + lidUnit->waterBalance.evap + lidUnit->waterBalance.infil + lidUnit->waterBalance.surfFlow + lidUnit->waterBalance.drainFlow; if ( inflow > 0.0 ) err = (inflow - outflow) / inflow; else err = 1.0; fprintf(Frpt.file, " %10.2f", err*100.0); lidList = lidList->nextLidUnit; } } } //============================================================================= void initLidRptFile(char* title, char* lidID, char* subcatchID, TLidUnit* lidUnit) // // Purpose: initializes the report file used for a specific LID unit // Input: title = project's title // lidID = LID process name // subcatchID = subcatchment ID name // lidUnit = ptr. to LID unit // Output: none // { static int colCount = 14; static char* head1[] = { "\n \t", " Elapsed\t", " Total\t", " Total\t", " Surface\t", " Pavement\t", " Soil\t", " Storage\t", " Surface\t", " Drain\t", " Surface\t", " Pavement\t", " Soil\t", " Storage"}; static char* head2[] = { "\n \t", " Time\t", " Inflow\t", " Evap\t", " Infil\t", " Perc\t", " Perc\t", " Exfil\t", " Runoff\t", " OutFlow\t", " Level\t", " Level\t", " Moisture\t", " Level"}; static char* units1[] = { "\nDate Time \t", " Hours\t", " in/hr\t", " in/hr\t", " in/hr\t", " in/hr\t", " in/hr\t", " in/hr\t", " in/hr\t", " in/hr\t", " inches\t", " inches\t", " Content\t", " inches"}; static char* units2[] = { "\nDate Time \t", " Hours\t", " mm/hr\t", " mm/hr\t", " mm/hr\t", " mm/hr\t", " mm/hr\t", " mm/hr\t", " mm/hr\t", " mm/hr\t", " mm\t", " mm\t", " Content\t", " mm"}; static char line9[] = " ---------"; int i; FILE* f = lidUnit->rptFile->file; //... check that file was opened if ( f == NULL ) return; //... write title lines fprintf(f, "SWMM5 LID Report File\n"); fprintf(f, "\nProject: %s", title); fprintf(f, "\nLID Unit: %s in Subcatchment %s\n", lidID, subcatchID); //... write column headings for ( i = 0; i < colCount; i++) fprintf(f, "%s", head1[i]); for ( i = 0; i < colCount; i++) fprintf(f, "%s", head2[i]); if ( UnitSystem == US ) { for ( i = 0; i < colCount; i++) fprintf(f, "%s", units1[i]); } else for ( i = 0; i < colCount; i++) fprintf(f, "%s", units2[i]); fprintf(f, "\n----------- --------"); for ( i = 1; i < colCount; i++) fprintf(f, "\t%s", line9); //... initialize LID dryness state lidUnit->rptFile->wasDry = 1; strcpy(lidUnit->rptFile->results, ""); } int lid_getLidUnitCount(int index) // Input: index = Index of desired subcatchment // Output: int = number of lid units for subcatchment // Return: number of lid units for subcatchment // Purpose: count number of lid units for subcatchment { int unitCount = 0; TLidList* lidList = NULL; TLidGroup lidGroup; lidGroup = LidGroups[index]; if (lidGroup) { lidList = lidGroup->lidList; while (lidList) { lidList = lidList->nextLidUnit; unitCount += 1; } } return unitCount; } TLidUnit* lid_getLidUnit(int index, int lidIndex, int* errcode) // // Input: index = Index of desired subcatchment // lidIndex = Index of desired lid control (subcatchment allow for multiple lids) // errcode = ptr to errcode // Output: TLidUnit = TLidUnit ptr // Return: TLidUnit ptr // Purpose: Gets lid unit (TLidUnit) ptr { int currLidIndex = 0; int unitCount = 1; TLidUnit* lidUnit = NULL; TLidList* lidList; TLidGroup lidGroup; lidGroup = LidGroups[index]; if (!lidGroup) { *errcode = ERR_API_UNDEFINED_LID; } else { lidList = lidGroup->lidList; // Patch solution for now // Realized the lid units are stored in reverse order of // how they are defined in the [LID USAGE] // For now, I will just count the number of Lid Units in Lid List unitCount = lid_getLidUnitCount(index); if (lidIndex > (unitCount - 1)) { *errcode = ERR_API_LIDUNIT_INDEX; return(NULL); } else { // update lidIndex due to reverse order lidIndex = unitCount - lidIndex - 1; // Traverse through lid list to find lid unit while ((lidList) && (currLidIndex <= lidIndex)) { lidUnit = lidList->lidUnit; currLidIndex += 1; lidList = lidList->nextLidUnit; } // Verify that the lid unit found matches the one specified by the user if (!((currLidIndex - 1) == lidIndex)) { *errcode = ERR_API_LIDUNIT_INDEX; lidUnit = NULL; } } } return lidUnit; } TLidProc* lid_getLidProc(int index) // // Input: index = Index of desired lid control // Output: ptr = TLidProc ptr // Return: TLidProc ptr // Purpose: Gets lid process (TLidProc) ptr { TLidProc* ptr; ptr = &LidProcs[index]; return ptr; } TLidGroup lid_getLidGroup(int index) // // Input: index = index of desired subcatchment // Output: result = result data desired // Return: TLidGroup ptr // Purpose: Gets lid group (TLidGroup) ptr { TLidGroup ptr; ptr = LidGroups[index]; return ptr; } void lid_validateLidProc(int index) // // Purpose: hook to lid internal function to validate LID process parameters. // Input: index = Index of desired subcatchment // Output: none { validateLidProc(index); } void lid_validateLidGroup(int index) // // Purpose: hook to lid internal function to validate LID process parameters. // Input: index = Index of desired subcatchment // Output: none { validateLidGroup(index); } void lid_updateLidUnit(TLidUnit* lidUnit, int subIndex) // // Purpose: update a lid unit parameters due to change in lid control parameters // Input: lidIndex = Index of desired lid control (subcatchment allow for multiple lids) // Output: none { int lidIndex; lidIndex = lidUnit->lidIndex; lidUnit->nextRegenDay = LidProcs[lidIndex].pavement.regenDays; lid_validateLidGroup(subIndex); if (LidProcs[lidIndex].soil.thickness > 0.0) { lidUnit->soilMoisture = LidProcs[lidIndex].soil.wiltPoint + lidUnit->initSat * (LidProcs[lidIndex].soil.porosity - LidProcs[lidIndex].soil.wiltPoint); } if (LidProcs[lidIndex].storage.thickness > 0.0) { lidUnit->storageDepth = lidUnit->initSat * LidProcs[lidIndex].storage.thickness; } if (LidProcs[lidIndex].drainMat.thickness > 0.0) { lidUnit->storageDepth = lidUnit->initSat * LidProcs[lidIndex].drainMat.thickness; } } void lid_updateLidGroup(int index) { int i; double area, nonLidArea; TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; TGroundwater *gw; TAquifer a; //... check if group exists lidGroup = LidGroups[index]; if (lidGroup == NULL) return; lidGroup->pervArea = 0.0; //... examine each LID in the group lidList = lidGroup->lidList; while (lidList) { lidUnit = lidList->lidUnit; if (isLidPervious(lidUnit->lidIndex)) { lidGroup->pervArea += (lidUnit->area * lidUnit->number); } lidList = lidList->nextLidUnit; } // recalculate subcatchment alpha nonLidArea = Subcatch[index].area; nonLidArea -= Subcatch[index].lidArea; for (i = IMPERV0; i <= PERV; i++) { if (i == PERV) { area = (1.0 - Subcatch[index].fracImperv) * nonLidArea; } else { area = Subcatch[index].fracImperv * nonLidArea; } Subcatch[index].subArea[i].alpha = 0.0; if (area > 0.0 && Subcatch[index].subArea[i].N > 0.0) { Subcatch[index].subArea[i].alpha = 1.49 * Subcatch[index].width / area * sqrt(Subcatch[index].slope) / Subcatch[index].subArea[i].N; } } // update GW max infil vol gw = Subcatch[index].groundwater; if (gw) { a = Aquifer[gw->aquifer]; gw->maxInfilVol = (gw->surfElev - gw->waterTableElev) * (a.porosity - gw->theta) / subcatch_getFracPerv(index); } } void lid_updateAllLidUnit(int lidIndex) { // // Purpose: update all lid unit parameters due to change in lid control parameters // Input: lidIndex = Index of desired lid control (subcatchment allow for multiple lids) // Output: none int j, k; TLidUnit* lidUnit; TLidList* lidList; TLidGroup lidGroup; for (j = 0; j < GroupCount; j++) { //... check if group exists lidGroup = LidGroups[j]; if (lidGroup == NULL) continue; //... examine each LID in the group lidList = lidGroup->lidList; while (lidList) { lidUnit = lidList->lidUnit; k = lidUnit->lidIndex; if (k == lidIndex) { lid_updateLidUnit(lidUnit, j); } lidList = lidList->nextLidUnit; } } }
rdadolf/torch-mlir
include/torch-mlir/Dialect/Torch/Utils/Utils.h
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // Also available under a BSD-style license. See LICENSE. // //===----------------------------------------------------------------------===// #ifndef TORCHMLIR_DIALECT_TORCH_UTILS_H #define TORCHMLIR_DIALECT_TORCH_UTILS_H #include "mlir/IR/PatternMatch.h" #include "mlir/IR/Value.h" #include "mlir/Support/LLVM.h" #include "torch-mlir/Dialect/Torch/Utils/TorchUpstream.h" namespace mlir { namespace torch { namespace Torch { int64_t toPositiveDim(int64_t dim, int64_t inputRank); bool isValidDim(int64_t dim, int64_t inputRank); bool getListConstructElements(Value v, SmallVectorImpl<Value> &elems); /// Returns the index indicated by `v` for a list of given `length`. /// If the index is negative, it is adjusted to `length` + `v`. /// `None` is returned the index is not an integer in the range [0,`length). llvm::Optional<int64_t> matchLegalConstantIndexIntoListOfSize(Value v, int64_t length); torch_upstream::ScalarType getScalarTypeForType(Type type); Type getTypeForScalarType( MLIRContext *context, torch_upstream::ScalarType dtypeInt, mlir::IntegerType::SignednessSemantics signedness = IntegerType::Signed); Value getDtypeIntValueForType(PatternRewriter &rewriter, Location loc, Type dtype); // Helper to convert a tensor to a specific scalar type. Value convertTensorToDtype(PatternRewriter &rewriter, Location loc, Value input, Type dtype); // Helper funtion to get rank of `Base tensor type`. // -1 is returned if the tensorRank can't be determined. int getTensorRank(Value tensor); } // namespace Torch } // namespace torch } // namespace mlir #endif // TORCHMLIR_DIALECT_TORCH_UTILS_H
rdadolf/torch-mlir
include/torch-mlir/Dialect/TorchConversion/Transforms/Passes.h
<gh_stars>100-1000 //===------------------------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // Also available under a BSD-style license. See LICENSE. // //===----------------------------------------------------------------------===// #ifndef TORCHMLIR_DIALECT_TORCHCONVERSION_TRANSFORMS_PASSES_H #define TORCHMLIR_DIALECT_TORCHCONVERSION_TRANSFORMS_PASSES_H #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/Pass/Pass.h" #include "torch-mlir/Dialect/Torch/Transforms/Passes.h" #include <memory> namespace mlir { class ModuleOp; namespace torch { namespace TorchConversion { /// Creates a pipeline that lowers from the torch backend contract to the /// linalg-on-tensors backend contract. void createTorchBackendToLinalgOnTensorsBackendPipeline( OpPassManager &pm, const torch::Torch::TorchLoweringPipelineOptions &options); /// Creates a pipeline that lowers from the torch backend contract to the /// TOSA backend contract. void createTorchBackendToTosaBackendPipeline( OpPassManager &pm, const torch::Torch::TorchLoweringPipelineOptions &options); std::unique_ptr<OperationPass<ModuleOp>> createVerifyInvariantsBeforeBackendLoweringPass(); std::unique_ptr<OperationPass<ModuleOp>> createFuncBackendTypeConversionPass(); std::unique_ptr<OperationPass<func::FuncOp>> createFinalizingBackendTypeConversionPass(); std::unique_ptr<OperationPass<ModuleOp>> createVerifyLinalgOnTensorsBackendContractPass(); std::unique_ptr<OperationPass<ModuleOp>> createVerifyTosaBackendContractPass(); } // namespace TorchConversion /// Registers all Torch transformation passes. void registerTorchConversionPasses(); } // namespace torch } // namespace mlir #endif // TORCHMLIR_DIALECT_TORCHCONVERSION_TRANSFORMS_PASSES_H
rdadolf/torch-mlir
python/torch_mlir/dialects/torch/importer/jit_ir/csrc/node_importer.h
//===- node_importer.h ------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // Also available under a BSD-style license. See LICENSE. // //===----------------------------------------------------------------------===// #ifndef TORCHMLIRJITIRIMPORTER_CSRC_NODE_IMPORTER_H #define TORCHMLIRJITIRIMPORTER_CSRC_NODE_IMPORTER_H #include <memory> #include "pybind.h" #include "mlir-c/IR.h" #include <torch/csrc/jit/api/compilation_unit.h> #include <torch/csrc/jit/ir/ir.h> namespace torch_mlir { using CreateTerminatorFn = std::function<void(c10::ArrayRef<MlirValue>, MlirBlock)>; /// Import `jitBlock` into a corresponding `MlirBlock`. /// /// Because `jit::Block` does not have a concept of terminator in the MLIR sense /// (it is kind of "built-in" to the block, and not a free op chosen by the /// enclosing op), the `createTerminator` function will be used to create the /// terminator for the created block. Type adjustments like handling /// derefinement can be handled there as well. /// /// `blockArgTypes`, if present, gives a set of types that the block arguments /// are required to be for correctness. The code will internally attempt to /// adjust the types to the block argument types. /// TODO: Formalize what type conversions are allowed here. MlirBlock importBlock( MlirContext context, torch::jit::Block *jitBlock, CreateTerminatorFn createTerminator, c10::optional<c10::ArrayRef<MlirType>> blockArgTypes = c10::nullopt); } // namespace torch_mlir #endif // TORCHMLIRJITIRIMPORTER_CSRC_NODE_IMPORTER_H
rdadolf/torch-mlir
include/torch-mlir/Conversion/TorchToStd/TorchToStd.h
//===------------------------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // Also available under a BSD-style license. See LICENSE. // //===----------------------------------------------------------------------===// #ifndef TORCHMLIR_CONVERSION_ATENTOSTD_ATENTOSTD_H #define TORCHMLIR_CONVERSION_ATENTOSTD_ATENTOSTD_H #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/Pass/Pass.h" #include <memory> namespace mlir { namespace torch { std::unique_ptr<OperationPass<func::FuncOp>> createConvertTorchToStdPass(); } } // namespace mlir #endif // TORCHMLIR_CONVERSION_ATENTOSTD_ATENTOSTD_H
isliulin/hv
unittest/sendmail_test.c
#include <stdio.h> #include "smtp.h" int main(int argc, char** argv) { if (argc < 8) { printf("Usage: sendmail smtp_server username password from to subject body\n"); } const char* smtp_server = argv[1]; const char* username = argv[2]; const char* password = argv[3]; mail_t mail; mail.from = argv[4]; mail.to = argv[5]; mail.subject = argv[6]; mail.body = argv[7]; int status_code = sendmail(smtp_server, username, password, &mail); printf("sendmail: %d %s\n", status_code, smtp_status_str((enum smtp_status)status_code)); return status_code == SMTP_STATUS_OK ? 0 : status_code; }
isliulin/hv
http/http2def.h
#ifndef HTTP2_DEF_H_ #define HTTP2_DEF_H_ #ifdef __cplusplus extern "C" { #endif #define HTTP2_MAGIC "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" #define HTTP2_MAGIC_LEN 24 // length:3bytes + type:1byte + flags:1byte + stream_id:4bytes = 9bytes #define HTTP2_FRAME_HDLEN 9 #define HTTP2_UPGRADE_RESPONSE \ "HTTP/1.1 101 Switching Protocols\r\n"\ "Connection: Upgrade\r\n"\ "Upgrade: h2c\r\n\r\n" typedef enum { HTTP2_DATA = 0, HTTP2_HEADERS = 0x01, HTTP2_PRIORITY = 0x02, HTTP2_RST_STREAM = 0x03, HTTP2_SETTINGS = 0x04, HTTP2_PUSH_PROMISE = 0x05, HTTP2_PING = 0x06, HTTP2_GOAWAY = 0x07, HTTP2_WINDOW_UPDATE = 0x08, HTTP2_CONTINUATION = 0x09, HTTP2_ALTSVC = 0x0a, HTTP2_ORIGIN = 0x0c } http2_frame_type; typedef enum { HTTP2_FLAG_NONE = 0, HTTP2_FLAG_END_STREAM = 0x01, HTTP2_FLAG_END_HEADERS = 0x04, HTTP2_FLAG_PADDED = 0x08, HTTP2_FLAG_PRIORITY = 0x20 } http2_flag; typedef struct { int length; http2_frame_type type; http2_flag flags; int stream_id; } http2_frame_hd; static inline void http2_frame_hd_pack(const http2_frame_hd* hd, unsigned char* buf) { // hton int length = hd->length; int stream_id = hd->stream_id; unsigned char* p = buf; *p++ = (length >> 16) & 0xFF; *p++ = (length >> 8) & 0xFF; *p++ = length & 0xFF; *p++ = (unsigned char)hd->type; *p++ = (unsigned char)hd->flags; *p++ = (stream_id >> 24) & 0xFF; *p++ = (stream_id >> 16) & 0xFF; *p++ = (stream_id >> 8) & 0xFF; *p++ = stream_id & 0xFF; } static inline void http2_frame_hd_unpack(const unsigned char* buf, http2_frame_hd* hd) { // ntoh const unsigned char* p = buf; hd->length = *p++ << 16; hd->length += *p++ << 8; hd->length += *p++; hd->type = (http2_frame_type)*p++; hd->flags = (http2_flag)*p++; hd->stream_id = *p++ << 24; hd->stream_id += *p++ << 16; hd->stream_id += *p++ << 8; hd->stream_id += *p++; } #ifdef __cplusplus } #endif #endif
isliulin/hv
base/htime.h
#ifndef HV_TIME_H_ #define HV_TIME_H_ #include "hexport.h" #include "hplatform.h" BEGIN_EXTERN_C #define SECONDS_PER_HOUR 3600 #define SECONDS_PER_DAY 86400 // 24*3600 #define SECONDS_PER_WEEK 604800 // 7*24*3600 #define IS_LEAP_YEAR(year) (((year)%4 == 0 && (year)%100 != 0) || (year)%100 == 0) typedef struct datetime_s { int year; int month; int day; int hour; int min; int sec; int ms; } datetime_t; #ifdef _MSC_VER /* @see winsock2.h // Structure used in select() call, taken from the BSD file sys/time.h struct timeval { long tv_sec; long tv_usec; }; */ struct timezone { int tz_minuteswest; /* of Greenwich */ int tz_dsttime; /* type of dst correction to apply */ }; #include <sys/timeb.h> static inline int gettimeofday(struct timeval *tv, struct timezone *tz) { struct _timeb tb; _ftime(&tb); if (tv) { tv->tv_sec = (long)tb.time; tv->tv_usec = tb.millitm * 1000; } if (tz) { tz->tz_minuteswest = tb.timezone; tz->tz_dsttime = tb.dstflag; } return 0; } #endif // sleep(s), msleep(ms), usleep(us) #ifdef OS_WIN static inline void sleep(unsigned int s) { Sleep(s * 1000); } static inline void msleep(unsigned int ms) { Sleep(ms); } static inline void usleep(unsigned int us) { Sleep(us / 1000); } #else static inline void msleep(unsigned int ms) { usleep(ms * 1000); } #endif // ms HV_EXPORT unsigned int gettick(); static inline unsigned long long gettimeofday_ms() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * (unsigned long long)1000 + tv.tv_usec/1000; } // us HV_EXPORT unsigned long long gethrtime_us(); HV_EXPORT datetime_t datetime_now(); HV_EXPORT time_t datetime_mktime(datetime_t* dt); HV_EXPORT datetime_t* datetime_past(datetime_t* dt, int days DEFAULT(1)); HV_EXPORT datetime_t* datetime_future(datetime_t* dt, int days DEFAULT(1)); #define TIME_FMT "%02d:%02d:%02d" #define TIME_FMT_BUFLEN 12 HV_EXPORT char* duration_fmt(int sec, char* buf); #define DATETIME_FMT "%04d-%02d-%02d %02d:%02d:%02d" #define DATETIME_FMT_BUFLEN 24 HV_EXPORT char* datetime_fmt(datetime_t* dt, char* buf); #define GMTIME_FMT "%.3s, %02d %.3s %04d %02d:%02d:%02d GMT" #define GMTIME_FMT_BUFLEN 30 HV_EXPORT char* gmtime_fmt(time_t time, char* buf); HV_EXPORT int days_of_month(int month, int year); HV_EXPORT int month_atoi(const char* month); HV_EXPORT const char* month_itoa(int month); HV_EXPORT int weekday_atoi(const char* weekday); HV_EXPORT const char* weekday_itoa(int weekday); HV_EXPORT datetime_t hv_compile_datetime(); /* * minute hour day week month action * 0~59 0~23 1~31 0~6 1~12 * 30 -1 -1 -1 -1 cron.hourly * 30 1 -1 -1 -1 cron.daily * 30 1 15 -1 -1 cron.monthly * 30 1 -1 0 -1 cron.weekly * 30 1 1 -1 10 cron.yearly */ HV_EXPORT time_t cron_next_timeout(int minute, int hour, int day, int week, int month); END_EXTERN_C #endif // HV_TIME_H_
isliulin/hv
base/hbase.h
#ifndef HV_BASE_H_ #define HV_BASE_H_ #include "hexport.h" #include "hplatform.h" // for bool #include "hdef.h" // for printd BEGIN_EXTERN_C //--------------------safe alloc/free--------------------------- HV_EXPORT void* safe_malloc(size_t size); HV_EXPORT void* safe_realloc(void* oldptr, size_t newsize, size_t oldsize); HV_EXPORT void* safe_calloc(size_t nmemb, size_t size); HV_EXPORT void* safe_zalloc(size_t size); HV_EXPORT void safe_free(void* ptr); #define HV_ALLOC(ptr, size)\ do {\ *(void**)&(ptr) = safe_zalloc(size);\ printd("alloc(%p, size=%llu)\tat [%s:%d:%s]\n", ptr, (unsigned long long)size, __FILE__, __LINE__, __FUNCTION__);\ } while(0) #define HV_ALLOC_SIZEOF(ptr) HV_ALLOC(ptr, sizeof(*(ptr))) #define HV_FREE(ptr)\ do {\ if (ptr) {\ safe_free(ptr);\ printd("free( %p )\tat [%s:%d:%s]\n", ptr, __FILE__, __LINE__, __FUNCTION__);\ ptr = NULL;\ }\ } while(0) HV_EXPORT long hv_alloc_cnt(); HV_EXPORT long hv_free_cnt(); static inline void hv_memcheck() { printf("Memcheck => alloc:%ld free:%ld\n", hv_alloc_cnt(), hv_free_cnt()); } #define HV_MEMCHECK atexit(hv_memcheck); //--------------------safe string------------------------------- HV_EXPORT char* strupper(char* str); HV_EXPORT char* strlower(char* str); HV_EXPORT char* strreverse(char* str); HV_EXPORT bool strstartswith(const char* str, const char* start); HV_EXPORT bool strendswith(const char* str, const char* end); HV_EXPORT bool strcontains(const char* str, const char* sub); // strncpy n = sizeof(dest_buf)-1 // safe_strncpy n = sizeof(dest_buf) HV_EXPORT char* safe_strncpy(char* dest, const char* src, size_t n); // strncat n = sizeof(dest_buf)-1-strlen(dest) // safe_strncpy n = sizeof(dest_buf) HV_EXPORT char* safe_strncat(char* dest, const char* src, size_t n); #if !HAVE_STRLCPY #define strlcpy safe_strncpy #endif #if !HAVE_STRLCAT #define strlcat safe_strncat #endif #define strrchr_dot(str) strrchr(str, '.') HV_EXPORT char* strrchr_dir(const char* filepath); // basename HV_EXPORT const char* hv_basename(const char* filepath); HV_EXPORT const char* hv_suffixname(const char* filename); // mkdir -p HV_EXPORT int hv_mkdir_p(const char* dir); // rmdir -p HV_EXPORT int hv_rmdir_p(const char* dir); // 1 y on yes true enable HV_EXPORT bool getboolean(const char* str); HV_EXPORT char* get_executable_path(char* buf, int size); HV_EXPORT char* get_executable_dir(char* buf, int size); HV_EXPORT char* get_executable_file(char* buf, int size); HV_EXPORT char* get_run_dir(char* buf, int size); END_EXTERN_C #endif // HV_BASE_H_
isliulin/hv
base/hssl.h
<reponame>isliulin/hv #ifndef HV_SSL_H_ #define HV_SSL_H_ #include "hexport.h" typedef void* hssl_ctx_t; ///> SSL_CTX typedef void* hssl_t; ///> SSL enum { HSSL_OK = 0, HSSL_WANT_READ = -2, HSSL_WANT_WRITE = -3, }; typedef struct { const char* crt_file; const char* key_file; const char* ca_file; short verify_peer; short endpoint; // 0: server 1: client } hssl_ctx_init_param_t; BEGIN_EXTERN_C HV_EXPORT hssl_ctx_t hssl_ctx_init(hssl_ctx_init_param_t* param); HV_EXPORT void hssl_ctx_cleanup(hssl_ctx_t ssl_ctx); HV_EXPORT hssl_ctx_t hssl_ctx_instance(); HV_EXPORT hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd); HV_EXPORT void hssl_free(hssl_t ssl); HV_EXPORT int hssl_accept(hssl_t ssl); HV_EXPORT int hssl_connect(hssl_t ssl); HV_EXPORT int hssl_read(hssl_t ssl, void* buf, int len); HV_EXPORT int hssl_write(hssl_t ssl, const void* buf, int len); HV_EXPORT int hssl_close(hssl_t ssl); END_EXTERN_C #endif // HV_SSL_H_
isliulin/hv
http/grpcdef.h
<filename>http/grpcdef.h #ifndef GRPC_DEF_H_ #define GRPC_DEF_H_ #ifdef __cplusplus extern "C" { #endif // Length-Prefixed-Message // flags:1byte + length:4bytes = 5bytes #define GRPC_MESSAGE_HDLEN 5 typedef struct { unsigned char flags; int length; } grpc_message_hd; typedef struct { unsigned char flags; int length; unsigned char* message; } grpc_message; static inline void grpc_message_hd_pack(const grpc_message_hd* hd, unsigned char* buf) { // hton int length = hd->length; unsigned char* p = buf; *p++ = hd->flags; *p++ = (length >> 24) & 0xFF; *p++ = (length >> 16) & 0xFF; *p++ = (length >> 8) & 0xFF; *p++ = length & 0xFF; } static inline void grpc_message_hd_unpack(const unsigned char* buf, grpc_message_hd* hd) { // ntoh const unsigned char* p = buf; hd->flags = *p++; hd->length = *p++ << 24; hd->length += *p++ << 16; hd->length += *p++ << 8; hd->length += *p++; } // protobuf // tag = field_num << 3 | wire_type // varint(tag) [+ varint(length_delimited)] + value; typedef enum { WIRE_TYPE_VARINT = 0, WIRE_TYPE_FIXED64 = 1, WIRE_TYPE_LENGTH_DELIMITED = 2, WIRE_TYPE_START_GROUP = 3, WIRE_TYPE_END_GROUP = 4, WIRE_TYPE_FIXED32 = 5, } wire_type; typedef enum { FIELD_TYPE_DOUBLE = 1, FIELD_TYPE_FLOAT = 2, FIELD_TYPE_INT64 = 3, FIELD_TYPE_UINT64 = 4, FIELD_TYPE_INT32 = 5, FIELD_TYPE_FIXED64 = 6, FIELD_TYPE_FIXED32 = 7, FIELD_TYPE_BOOL = 8, FIELD_TYPE_STRING = 9, FIELD_TYPE_GROUP = 10, FIELD_TYPE_MESSAGE = 11, FIELD_TYPE_BYTES = 12, FIELD_TYPE_UINT32 = 13, FIELD_TYPE_ENUM = 14, FIELD_TYPE_SFIXED32 = 15, FIELD_TYPE_SFIXED64 = 16, FIELD_TYPE_SINT32 = 17, FIELD_TYPE_SINT64 = 18, MAX_FIELD_TYPE = 18, } field_type; #define PROTOBUF_MAKE_TAG(field_number, wire_type) ((field_number) << 3 | (wire_type)) #define PROTOBUF_FILED_NUMBER(tag) ((tag) >> 3) #define PROTOBUF_WIRE_TYPE(tag) ((tag) & 0x07) // varint little-endian // MSB static inline int varint_encode(long long value, unsigned char* buf) { unsigned char ch; unsigned char *p = buf; int bytes = 0; do { ch = value & 0x7F; value >>= 7; *p++ = value == 0 ? ch : (ch | 0x80); ++bytes; } while (value); return bytes; } // @param[IN|OUT] len: in=>buflen, out=>varint bytesize static inline long long varint_decode(const unsigned char* buf, int* len) { long long ret = 0; int bytes = 0; int bits = 0; const unsigned char *p = buf; unsigned char ch; do { if (len && *len && bytes == *len) { break; } ch = *p & 0x7F; ret |= (ch << bits); bits += 7; ++bytes; if (!(*p & 0x80)) break; ++p; } while(bytes < 10); *len = bytes; return ret; } #ifdef __cplusplus } #endif #endif // GRPC_DEF_H_
isliulin/hv
unittest/connect_test.c
#include "hsocket.h" #include "htime.h" int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage: cmd ip port\n"); return -10; } const char* ip = argv[1]; int port = atoi(argv[2]); unsigned int start_time = gettick(); int ret = ConnectNonblock(ip, port); unsigned int end_time = gettick(); printf("ConnectNonblock[%s:%d] retval=%d cost=%ums\n", ip, port, ret, end_time-start_time); start_time = gettick(); ret = ConnectTimeout(ip, port, 3000); end_time = gettick(); printf("ConnectTimeout[%s:%d] retval=%d cost=%ums\n", ip, port, ret, end_time-start_time); start_time = gettick(); ret = Connect(ip, port, 0); end_time = gettick(); printf("ConnectBlock[%s:%d] retval=%d cost=%ums\n", ip, port, ret, end_time-start_time); return 0; }
isliulin/hv
base/hstring.h
#ifndef HV_STRING_H_ #define HV_STRING_H_ #include <string> #include <vector> #include <sstream> #include "hexport.h" #include "hbase.h" #include "hmap.h" using std::string; typedef std::vector<string> StringList; // std::map<std::string, std::string, StringCaseLess> class StringCaseLess : public std::less<std::string> { public: bool operator()(const std::string& lhs, const std::string& rhs) const { return strcasecmp(lhs.c_str(), rhs.c_str()) < 0; } }; namespace hv { // NOTE: low-version NDK not provide std::to_string template<typename T> static inline std::string to_string(const T& t) { std::ostringstream oss; oss << t; return oss.str(); } template<typename T> static inline T from_string(const std::string& str) { T t; std::istringstream iss(str); iss >> t; return t; } } #define SPACE_CHARS " \t\r\n" #define PAIR_CHARS "{}[]()<>\"\"\'\'``" HV_EXPORT string asprintf(const char* fmt, ...); // x,y,z HV_EXPORT StringList split(const string& str, char delim = ','); // user=amdin&pswd=123456 HV_EXPORT hv::KeyValue splitKV(const string& str, char kv_kv = '&', char k_v = '='); HV_EXPORT string trim(const string& str, const char* chars = SPACE_CHARS); HV_EXPORT string trimL(const string& str, const char* chars = SPACE_CHARS); HV_EXPORT string trimR(const string& str, const char* chars = SPACE_CHARS); HV_EXPORT string trim_pairs(const string& str, const char* pairs = PAIR_CHARS); HV_EXPORT string replace(const string& str, const string& find, const string& rep); // str=/mnt/share/image/test.jpg // basename=test.jpg // dirname=/mnt/share/image // filename=test // suffixname=jpg HV_EXPORT string basename(const string& str); HV_EXPORT string dirname(const string& str); HV_EXPORT string filename(const string& str); HV_EXPORT string suffixname(const string& str); #endif // HV_STRING_H_
isliulin/hv
examples/tcp_proxy_server.c
/* * tcp proxy server * * @build: make examples * @http_server: bin/httpd -d * @proxy_server: bin/tcp_proxy_server 1234 127.0.0.1:8080 * bin/tcp_proxy_server 1234 www.baidu.com * @client: bin/curl -v 127.0.0.1:1234 * bin/nc 127.0.0.1 1234 * > GET / HTTP/1.1 * > Connection: close * > [Enter] * > GET / HTTP/1.1 * > Connection: keep-alive * > [Enter] */ #include "hloop.h" #include "hsocket.h" // hloop_create_tcp_server // on_accept(connio) => proxyio = hloop_create_tcp_client // on_proxy_connect(proxyio) => hio_read(connio) hio_read(proxyio) // on_recv(connio) => hio_write(proxyio) // on_proxy_recv(proxyio) => hio_write(connio) // on_close(connio) => hio_close(proxyio) // on_proxy_close(proxyio) => hio_close(connio) static char proxy_host[64] = "127.0.0.1"; static int proxy_port = 80; static void on_proxy_close(hio_t* proxyio) { hio_t* connio = (hio_t*)hevent_userdata(proxyio); if (connio) { hevent_set_userdata(proxyio, NULL); hio_close(connio); } } static void on_proxy_recv(hio_t* proxyio, void* buf, int readbytes) { hio_t* connio = (hio_t*)hevent_userdata(proxyio); assert(connio != NULL); hio_write(connio, buf, readbytes); } static void on_proxy_connect(hio_t* proxyio) { hio_t* connio = (hio_t*)hevent_userdata(proxyio); assert(connio != NULL); hio_read(connio); hio_setcb_close(proxyio, on_proxy_close); hio_setcb_read(proxyio, on_proxy_recv); hio_read(proxyio); } static void on_close(hio_t* io) { printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); hio_t* proxyio = (hio_t*)hevent_userdata(io); if (proxyio) { hevent_set_userdata(io, NULL); hio_close(proxyio); } } static void on_recv(hio_t* io, void* buf, int readbytes) { printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); printf("< %.*s", readbytes, (char*)buf); hio_t* proxyio = (hio_t*)hevent_userdata(io); assert(proxyio != NULL); hio_write(proxyio, buf, readbytes); } static void on_accept(hio_t* io) { printf("on_accept connfd=%d\n", hio_fd(io)); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); hio_t* proxyio = hloop_create_tcp_client(hevent_loop(io), proxy_host, proxy_port, on_proxy_connect); if (proxyio == NULL) { hio_close(io); return; } hio_setcb_read(io, on_recv); hio_setcb_close(io, on_close); hevent_set_userdata(io, proxyio); hevent_set_userdata(proxyio, io); } int main(int argc, char** argv) { if (argc < 3) { printf("Usage: %s port proxy_host:proxy_port\n", argv[0]); return -10; } int port = atoi(argv[1]); char* pos = strchr(argv[2], ':'); if (pos) { int len = pos - argv[2]; if (len > 0) { memcpy(proxy_host, argv[2], len); proxy_host[len] = '\0'; } proxy_port = atoi(pos + 1); } else { strncpy(proxy_host, argv[2], sizeof(proxy_host)); } if (proxy_port == 0) proxy_port = 80; printf("proxy: [%s:%d]\n", proxy_host, proxy_port); hloop_t* loop = hloop_new(0); hio_t* listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept); if (listenio == NULL) { return -20; } printf("listenfd=%d\n", hio_fd(listenio)); hloop_run(loop); hloop_free(&loop); return 0; }
isliulin/hv
evpp/UdpClient.h
#ifndef HV_UDP_CLIENT_HPP_ #define HV_UDP_CLIENT_HPP_ #include "hsocket.h" #include "EventLoopThread.h" #include "Callback.h" #include "Channel.h" namespace hv { class UdpClient { public: UdpClient() { } virtual ~UdpClient() { } EventLoopPtr loop() { return loop_thread.loop(); } //@retval >=0 sockfd, <0 error int createsocket(int port, const char* host = "127.0.0.1") { hio_t* io = hloop_create_udp_client(loop_thread.hloop(), host, port); if (io == NULL) return -1; channel.reset(new SocketChannel(io)); return channel->fd(); } void start(bool wait_threads_started = true) { loop_thread.start(wait_threads_started, [this]() { assert(channel != NULL); channel->onread = [this](Buffer* buf) { if (onMessage) { onMessage(channel, buf); } }; channel->onwrite = [this](Buffer* buf) { if (onWriteComplete) { onWriteComplete(channel, buf); } }; channel->startRead(); return 0; } ); } void stop(bool wait_threads_stopped = true) { loop_thread.stop(wait_threads_stopped); } int sendto(Buffer* buf) { if (channel == NULL) return 0; return channel->write(buf); } int sendto(const std::string& str) { if (channel == NULL) return 0; return channel->write(str); } public: SocketChannelPtr channel; // Callback MessageCallback onMessage; WriteCompleteCallback onWriteComplete; private: EventLoopThread loop_thread; }; } #endif // HV_UDP_CLIENT_HPP_
isliulin/hv
base/hbase.c
<filename>base/hbase.c #include "hbase.h" #ifdef OS_DARWIN #include <mach-o/dyld.h> // for _NSGetExecutablePath #endif #include "hatomic.h" static hatomic_t s_alloc_cnt = HATOMIC_VAR_INIT(0); static hatomic_t s_free_cnt = HATOMIC_VAR_INIT(0); long hv_alloc_cnt() { return s_alloc_cnt; } long hv_free_cnt() { return s_free_cnt; } void* safe_malloc(size_t size) { hatomic_inc(&s_alloc_cnt); void* ptr = malloc(size); if (!ptr) { fprintf(stderr, "malloc failed!\n"); exit(-1); } return ptr; } void* safe_realloc(void* oldptr, size_t newsize, size_t oldsize) { hatomic_inc(&s_alloc_cnt); hatomic_inc(&s_free_cnt); void* ptr = realloc(oldptr, newsize); if (!ptr) { fprintf(stderr, "realloc failed!\n"); exit(-1); } if (newsize > oldsize) { memset((char*)ptr + oldsize, 0, newsize - oldsize); } return ptr; } void* safe_calloc(size_t nmemb, size_t size) { hatomic_inc(&s_alloc_cnt); void* ptr = calloc(nmemb, size); if (!ptr) { fprintf(stderr, "calloc failed!\n"); exit(-1); } return ptr; } void* safe_zalloc(size_t size) { hatomic_inc(&s_alloc_cnt); void* ptr = malloc(size); if (!ptr) { fprintf(stderr, "malloc failed!\n"); exit(-1); } memset(ptr, 0, size); return ptr; } void safe_free(void* ptr) { if (ptr) { free(ptr); ptr = NULL; hatomic_inc(&s_free_cnt); } } char* strupper(char* str) { char* p = str; while (*p != '\0') { if (*p >= 'a' && *p <= 'z') { *p &= ~0x20; } ++p; } return str; } char* strlower(char* str) { char* p = str; while (*p != '\0') { if (*p >= 'A' && *p <= 'Z') { *p |= 0x20; } ++p; } return str; } char* strreverse(char* str) { if (str == NULL) return NULL; char* b = str; char* e = str; while(*e) {++e;} --e; char tmp; while (e > b) { tmp = *e; *e = *b; *b = tmp; --e; ++b; } return str; } // n = sizeof(dest_buf) char* safe_strncpy(char* dest, const char* src, size_t n) { assert(dest != NULL && src != NULL); char* ret = dest; while (*src != '\0' && --n > 0) { *dest++ = *src++; } *dest = '\0'; return ret; } // n = sizeof(dest_buf) char* safe_strncat(char* dest, const char* src, size_t n) { assert(dest != NULL && src != NULL); char* ret = dest; while (*dest) {++dest;--n;} while (*src != '\0' && --n > 0) { *dest++ = *src++; } *dest = '\0'; return ret; } bool strstartswith(const char* str, const char* start) { assert(str != NULL && start != NULL); while (*str && *start && *str == *start) { ++str; ++start; } return *start == '\0'; } bool strendswith(const char* str, const char* end) { assert(str != NULL && end != NULL); int len1 = 0; int len2 = 0; while (*str++) {++len1;} while (*end++) {++len2;} if (len1 < len2) return false; while (len2-- > 0) { --str; --end; if (*str != *end) { return false; } } return true; } bool strcontains(const char* str, const char* sub) { assert(str != NULL && sub != NULL); return strstr(str, sub) != NULL; } char* strrchr_dir(const char* filepath) { char* p = (char*)filepath; while (*p) ++p; while (--p >= filepath) { #ifdef OS_WIN if (*p == '/' || *p == '\\') #else if (*p == '/') #endif return p; } return NULL; } const char* hv_basename(const char* filepath) { const char* pos = strrchr_dir(filepath); return pos ? pos+1 : filepath; } const char* hv_suffixname(const char* filename) { const char* pos = strrchr_dot(filename); return pos ? pos+1 : ""; } int hv_mkdir_p(const char* dir) { if (access(dir, 0) == 0) { return EEXIST; } char tmp[MAX_PATH]; safe_strncpy(tmp, dir, sizeof(tmp)); char* p = tmp; char delim = '/'; while (*p) { #ifdef OS_WIN if (*p == '/' || *p == '\\') { delim = *p; #else if (*p == '/') { #endif *p = '\0'; hv_mkdir(tmp); *p = delim; } ++p; } if (hv_mkdir(tmp) != 0) { return EPERM; } return 0; } int hv_rmdir_p(const char* dir) { if (access(dir, 0) != 0) { return ENOENT; } if (rmdir(dir) != 0) { return EPERM; } char tmp[MAX_PATH]; safe_strncpy(tmp, dir, sizeof(tmp)); char* p = tmp; while (*p) ++p; while (--p >= tmp) { #ifdef OS_WIN if (*p == '/' || *p == '\\') { #else if (*p == '/') { #endif *p = '\0'; if (rmdir(tmp) != 0) { return 0; } } } return 0; } bool getboolean(const char* str) { if (str == NULL) return false; int len = strlen(str); if (len == 0) return false; switch (len) { case 1: return *str == '1' || *str == 'y' || *str == 'Y'; case 2: return stricmp(str, "on") == 0; case 3: return stricmp(str, "yes") == 0; case 4: return stricmp(str, "true") == 0; case 6: return stricmp(str, "enable") == 0; default: return false; } } char* get_executable_path(char* buf, int size) { #ifdef OS_WIN GetModuleFileName(NULL, buf, size); #elif defined(OS_LINUX) if (readlink("/proc/self/exe", buf, size) == -1) { return NULL; } #elif defined(OS_DARWIN) _NSGetExecutablePath(buf, (uint32_t*)&size); #endif return buf; } char* get_executable_dir(char* buf, int size) { char filepath[MAX_PATH]; get_executable_path(filepath, sizeof(filepath)); char* pos = strrchr_dir(filepath); if (pos) { *pos = '\0'; strncpy(buf, filepath, size); } return buf; } char* get_executable_file(char* buf, int size) { char filepath[MAX_PATH]; get_executable_path(filepath, sizeof(filepath)); char* pos = strrchr_dir(filepath); if (pos) { strncpy(buf, pos+1, size); } return buf; } char* get_run_dir(char* buf, int size) { return getcwd(buf, size); }
zxwnstn/Pomordor
PomordorEngine/src/Pome.h
#pragma once #include "Util.h" #include "Clock/Clock.h"
zxwnstn/Pomordor
PomordorUI/src/TimerPage/Titlebar.h
<gh_stars>0 #pragma once class TitleBar : public QFrame { public: TitleBar(QWidget* parent = nullptr); ~TitleBar(); protected: void mouseMoveEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override; private: uint32_t mouseX; uint32_t mouseY; uint32_t absX; uint32_t absY; QWidget* parent; bool inFirst = true; };
zxwnstn/Pomordor
PomordorUI/src/TimerPage/TrayIcon.h
<reponame>zxwnstn/Pomordor #pragma once class TrayIcon : public QSystemTrayIcon { Q_OBJECT public: TrayIcon(const QIcon& icon, class TimerPage* myTimer, QWidget* parent = nullptr); ~TrayIcon(); private slots: void OnClick(QSystemTrayIcon::ActivationReason Rw); public: TimerPage* m_MyTimer; QMenu* m_Menu; QAction* m_Close; QAction* m_Show; };
zxwnstn/Pomordor
PomordorUI/src/TimerPage/Timer.h
<filename>PomordorUI/src/TimerPage/Timer.h #pragma once class Timer { private: enum class TimerState { Porm, Break, None, }; public: Timer(class TimerPage* myPage); ~Timer(); public: void Update(); void Stop(); void Start(); private: void setTimerStateUi(); void updateSetCount(); void fillProgress(float percentage); private: //Timer TimerPage* m_MyPage; Pome::Clock m_EngineClock; TimerState m_CurState; QMetaObject::Connection m_PlayButtonConn; uint32_t m_SetTotal = 0; std::list<std::pair<TimerState, uint32_t>> m_ScheduleQueue; QString SSProgress_Porm = "QWidget{\n" " border-radius: 135px;\n" " background-color: qconicalgradient(cx:0.5, cy:0.5, angle:90, stop:{GradPoint_1} rgba(255, 255, 255, 0), stop:{GradPoint_2} rgba(255, 135, 135, 255));\n" "}"; QString SSProgress_Break = "QWidget{\n" " border-radius: 135px;\n" " background-color: qconicalgradient(cx:0.5, cy:0.5, angle:90, stop:{GradPoint_1} rgba(255, 255, 255, 0), stop:{GradPoint_2} rgba(158, 184, 154, 255));\n" "}"; QString SSProgress_Porm_bg = "QWidget{\n" "border-radius: 134px;\n" "background-color: qconicalgradient(cx : 0.5, cy : 0.5, angle : 90, stop : 0.0 rgba(255, 255, 255, 0), stop : 0.0 rgb(238, 213, 214));\n" "}"; QString SSProgress_Break_bg = "QWidget{\n" "border-radius: 134px;\n" "background-color: qconicalgradient(cx : 0.5, cy : 0.5, angle : 90, stop : 0.0 rgba(255, 255, 255, 0), stop : 0.0 rgb(233,235,233));\n" "}"; QString SSProgress; QString SSTimerState_Porm = "QWidget{ background-color : none; } QLabel{ color: rgb(255, 135, 135); font-size : 30px }"; QString SSTimerState_Break = "QWidget{ background-color : none; } QLabel{ color: rgb(158, 184, 154); font-size : 30px }"; QString SSTimerButton_Porm = "QPushButton{border:none; border-radius: 130px; background-color : rgb(240, 240, 240); color: rgb(255, 100, 100); font-size : 60px; font-weight : 100; }"; QString SSTimerButton_Break = "QPushButton{border:none; border-radius: 130px; background-color : rgb(240, 240, 240); color: rgb(158, 204, 154); font-size : 60px; font-weight : 100; }"; friend class TimerPage; friend class ScheduleDialog; };
zxwnstn/Pomordor
PomordorUI/src/TimerPage/TimerPage.h
#pragma once QT_BEGIN_NAMESPACE namespace Ui { class TimerPage; } QT_END_NAMESPACE class TimerPage : public QWidget { Q_OBJECT public: TimerPage(QWidget *parent = nullptr); ~TimerPage(); public: void ToastMessage(const QString& title, const QString& text, int duration_ms); private: void timerFinish(); private slots: void onTimerStart(); void onTimerStop(); void onTimerLoop(); void onToggleSchduleDialog(); private: //component Ui::TimerPage* ui; QTimer* m_Loop; QMetaObject::Connection m_PlayButtonConn; class Timer* m_Timer; class ScheduleDialog* m_ScheduleDialog; class TrayIcon* m_TrayIcon; friend class ScheduleDialog; friend class Timer; };
zxwnstn/Pomordor
PomordorEngine/src/pegpch.h
#pragma once #include "json/json.h" //stl #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <unordered_map> #include <set> #include <algorithm> #include <cassert> #include <chrono> #include <memory> #include <thread> #include <tuple> #include <string>
zxwnstn/Pomordor
PomordorEngine/src/Clock/Clock.h
<reponame>zxwnstn/Pomordor #pragma once #include <tuple> #include <stdint.h> #include <string> #include <chrono> namespace Pome { class Clock { //Time is sec, minute, hour; using Time = std::tuple<uint32_t, uint32_t, uint32_t>; public: Clock() = default; public: void Set(uint32_t sec, uint32_t minute, uint32_t hour); void Start(); void Start(uint32_t sec, uint32_t minute, uint32_t hour); void Start(std::string time); void Stop(); void Update(); inline bool isRunning() const { return OnRunning; } //Return tuple is in order sec, minute, hour Time GetRemainTime(); std::string GetStrRemainTime(); Time GetPastTime(); float GetRemainRatio(); float GetPastRatio(); private: Time ParsingStrTime(const std::string& time); private: bool OnRunning = false; bool Setted = false; uint32_t SettedSec; //sec std::chrono::system_clock::time_point Begin; std::chrono::duration<double> Duration; }; }
zxwnstn/Pomordor
PomordorEngine/src/Util.h
<reponame>zxwnstn/Pomordor<filename>PomordorEngine/src/Util.h #pragma once namespace Pome{ void printHello(); void printJson(); }
zxwnstn/Pomordor
PomordorUI/src/TimerPage/ScheduleDialog.h
<reponame>zxwnstn/Pomordor<filename>PomordorUI/src/TimerPage/ScheduleDialog.h #pragma once QT_BEGIN_NAMESPACE namespace Ui { class ScheduleDialog; } QT_END_NAMESPACE class ScheduleDialog : public QWidget { Q_OBJECT public: using Data = std::tuple<int, int, int>; //pomordor, break, set public: ScheduleDialog(class TimerPage* page, QWidget* parent = nullptr); ~ScheduleDialog(); Data GetData(); private slots: void OnClose(); void onScheduleValueChanged(); void applyScheduleValue(); private: Ui::ScheduleDialog* ui; TimerPage* m_MyPage; friend class TimerPage; };
zxwnstn/Pomordor
PomordorUI/src/MainWindow/mainwindow.h
#pragma once QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void onClickPushButton(); void onClickToggleButton(); void onClickCloseButton(); void onClickMaximizeButton(); void onClickMinimizeButton(); void tt(); void pormTimer(); private: Ui::MainWindow *ui; int mouseX; int mouseY; int absX; int absY; int justOneCount; void mouseMoveEvent(QMouseEvent *mouse); void mouseReleaseEvent(QMouseEvent *); protected: void paintEvent(QPaintEvent* e) override; };
bmbrina/BMCustomTableView
Example/Pods/Target Support Files/Pods-BMCustomTableView_Example/Pods-BMCustomTableView_Example-umbrella.h
<filename>Example/Pods/Target Support Files/Pods-BMCustomTableView_Example/Pods-BMCustomTableView_Example-umbrella.h #import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_BMCustomTableView_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_BMCustomTableView_ExampleVersionString[];
bmbrina/BMCustomTableView
Example/Pods/Target Support Files/Pods-BMCustomTableView_Tests/Pods-BMCustomTableView_Tests-umbrella.h
<gh_stars>100-1000 #import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_BMCustomTableView_TestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_BMCustomTableView_TestsVersionString[];
bmbrina/BMCustomTableView
Example/Pods/Target Support Files/BMCustomTableView/BMCustomTableView-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double BMCustomTableViewVersionNumber; FOUNDATION_EXPORT const unsigned char BMCustomTableViewVersionString[];
CorAlRe/CS300-Project-Two
menu.h
<reponame>CorAlRe/CS300-Project-Two #ifndef __PROJECT_TWO_MENU_H #define __PROJECT_TWO_MENU_H #include <iostream> using namespace std; /// <summary> /// Sets up a while loop that continues processing until the user /// chooses to exit. /// </summary> /// <param name=""></param> void commandLoop(void); #endif
CorAlRe/CS300-Project-Two
Course.h
#ifndef __PROJECT_TWO_COURSE_H #define __PROJECT_TWO_COURSE_H #include <string> #include <iostream> #include <vector> using namespace std; class Course { private: string id; string title; vector<Course> prerequisites; public: /// <summary> /// Default constructor /// </summary> Course() { } /// <summary> /// Accessor method for Id /// </summary> /// <returns></returns> string getId() const { return this->id; } /// <summary> /// Accessor method for Title /// </summary> /// <returns></returns> string getTitle() const { return this->title; } /// <summary> /// Mutator method for Id /// </summary> /// <param name="id"></param> void setId(const string id) { this->id = id; } /// <summary> /// Mutator method for Title /// </summary> /// <param name="title"></param> void setTitle(const string title) { this->title = title; } /// <summary> /// Add a prerequisite /// </summary> /// <param name="course"></param> void addPrerequisite(const Course course) { prerequisites.push_back(course); } /// <summary> /// Display course Id, Title, and Prerequisites /// to stdout /// </summary> void print() const; }; #endif
CorAlRe/CS300-Project-Two
Courses.h
<reponame>CorAlRe/CS300-Project-Two #ifndef __PROJECT_TWO_COURSES_H #define __PROJECT_TWO_COURSES_H #include <stdexcept> #include <vector> #include <iostream> #include <fstream> #include <string> #include "Course.h" using namespace std; class Courses { private: /// <summary> /// Memory storage for the Course objects /// </summary> vector<Course> courses; /// <summary> /// High level, non-implementation specific method for adding a course /// to the underlying datatype. /// </summary> /// <param name="course"></param> void addCourse(const Course course); /// <summary> /// Called by addCourse /// Appends a course to the end of the data type /// Wraps the data type implementation /// Should call addCourse instead of this /// </summary> /// <param name="course"></param> void append(const Course course) { courses.push_back(course); } /// <summary> /// Called by addCourse /// Inserts a course somewhere into the data type /// Wraps the data type implementation /// Should call addCourse instead of this /// </summary> /// <param name="position">index of insertion</param> /// <param name="course">the course object to insert</param> void insert(const size_t position, const Course course) { vector<Course>::iterator iter; iter = courses.begin() + position; courses.insert(iter, course); } /// <summary> /// Wraps the data type at() call /// Use this instead of accessing the datatype directly /// </summary> /// <param name="index"></param> /// <returns></returns> Course at(const size_t index) const { return courses.at(index); } /// <summary> /// Performs a Binary Search of the data type /// The data type is expected to already be sorted /// Returns the midpoint regardless of found/not found /// in order to communicate the closest value /// The caller is responsible for checking the return value /// to determine a match or not. Caller should call getSize() /// before calling only call if > 0 /// </summary> size_t binarySearch(const string key) const; /// <summary> /// Calls binarySearch and then checks the return value /// On match will return the course found /// On no match will return a default Course object /// </summary> Course findCourse(const string courseId) const; /// <summary> /// Splits a string into a vector<string> of tokens by a delimiter /// </summary> vector<string> splitString(const string input, const string delimiter) const; public: /// <summary> /// Clear all the data. /// </summary> void clear() { courses.clear(); } /// <summary> /// Initialize the Courses object from a CSV file /// </summary> void loadFromCSV(const string filename, const string deliminator = ","); /// <summary> /// Print a specific course and its Prerequisites. /// </summary> void printCourse(const string courseId) const; /// <summary> /// Print all courses by Id and Title in alphanumeric order. /// </summary> void printAll() const; /// <summary> /// Wraps the data type size() call /// Use this instead of accessing the datatype directly /// </summary> /// <returns></returns> size_t getSize() const { return courses.size(); } }; #endif
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/Dictionary.h
/* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/DictionaryBase.h" #include "Common-cpp/inc/Helpers/IsSame.h" namespace ExitGames { namespace Common { template<typename EKeyType, typename EValueType> class Dictionary : public DictionaryBase { public: using ToString::toString; Dictionary(void); ~Dictionary(void); Dictionary(const Dictionary<EKeyType, EValueType>& toCopy); Dictionary& operator=(const Dictionary<EKeyType, EValueType>& toCopy); bool operator==(const Dictionary<EKeyType, EValueType>& toCompare) const; bool operator!=(const Dictionary<EKeyType, EValueType>& toCompare) const; const EValueType& operator[](unsigned int index) const; EValueType& operator[](unsigned int index); const nByte* getKeyTypes(void) const; const nByte* getValueTypes(void) const; const unsigned int* getValueDimensions(void) const; void put(const Dictionary<EKeyType, EValueType>& src); void put(const EKeyType& key, const EValueType& val); void put(const EKeyType& key); void put(const EKeyType& key, const EValueType pVal, typename Common::Helpers::ArrayLengthType<EValueType>::type size); void put(const EKeyType& key, const EValueType pVal, const short* sizes); const EValueType* getValue(const EKeyType& key) const; JVector<EKeyType> getKeys(void) const; void remove(const EKeyType& key); bool contains(const EKeyType& key) const; JString typeToString(void) const; JString& toString(JString& retStr, bool withTypes=false) const; protected: virtual Dictionary<EKeyType, EValueType>& assign(const DictionaryBase&); private: typedef DictionaryBase super; bool compare(const DictionaryBase &toCompare) const; DictionaryBase* copy(short amount) const; static bool mStaticMembersHaveBeenInitialized; template<typename EType> struct NestingDepth{static const unsigned int nestingDepth = 0;}; template<template<typename, typename> class EType, typename ENestedKeyType, typename ENestedValueType> struct NestingDepth<EType<ENestedKeyType, ENestedValueType> >{static const unsigned int nestingDepth = NestingDepth<ENestedValueType>::nestingDepth+1;}; static const unsigned int M_NESTING_DEPTH = NestingDepth<Dictionary<EKeyType, EValueType> >::nestingDepth; static nByte mpKeyTypes[M_NESTING_DEPTH+DEBUG_RELEASE(1, 0)]; // one unused byte at the end in debug config for easier debugging static nByte mpValueTypes[M_NESTING_DEPTH+DEBUG_RELEASE(1, 0)]; static unsigned int mpValueDimensions[M_NESTING_DEPTH+DEBUG_RELEASE(1, 0)]; template<typename EType, typename ERPType = typename Helpers::RemovePointer<EType>::type> struct NestedInfos{static void fillArrays(nByte keyTypes[M_NESTING_DEPTH], nByte valueTypes[M_NESTING_DEPTH], unsigned int valueDimensions[M_NESTING_DEPTH], unsigned int recursionDepth=0);}; template<typename EType, template<typename, typename> class ETemplate, typename ENestedKeyType, typename ENestedValueType> struct NestedInfos<EType, ETemplate<ENestedKeyType, ENestedValueType> >{static void fillArrays(nByte keyTypes[M_NESTING_DEPTH], nByte valueTypes[M_NESTING_DEPTH], unsigned int valueDimensions[M_NESTING_DEPTH], unsigned int recursionDepth=0);}; }; template<typename EKeyType, typename EValueType> bool Dictionary<EKeyType, EValueType>::mStaticMembersHaveBeenInitialized = false; template<typename EKeyType, typename EValueType> nByte Dictionary<EKeyType, EValueType>::mpKeyTypes[M_NESTING_DEPTH+DEBUG_RELEASE(1, 0)]; template<typename EKeyType, typename EValueType> nByte Dictionary<EKeyType, EValueType>::mpValueTypes[M_NESTING_DEPTH+DEBUG_RELEASE(1, 0)]; template<typename EKeyType, typename EValueType> unsigned int Dictionary<EKeyType, EValueType>::mpValueDimensions[M_NESTING_DEPTH+DEBUG_RELEASE(1, 0)]; /** @file */ /** @class Dictionary The Dictionary class template together with the Hashtable class is one of the two main container classes for objects to be transmitted over Photon when using the C++ Client. @details This class implements the well-known concept of a container structure storing an arbitrary number of key/value-pairs. In contrast to a Hashtable, the types of both the keys and also the values in a Dictionary have to be the same for all entries. This takes flexibility, but it also improves type safety and means, that the type infos only have to be stored twice for the whole Dictionary (once for the key and once for the value), while in a Hashtable they have to be stored twice per entry. Therefor with Dictionaries transferring the same amount of key-value pairs will cause less traffic than with Hashtables. Please have a look at the @link Datatypes Table of Datatypes\endlink for a list of types, that are supported as keys and as values. Please refer to the documentation for put() and getValue() to see how to store and access data in a Dictionary. @sa put(), getValue(), KeyObject, ValueObject, Hashtable, DictionaryBase */ /** @copydoc Hashtable::Hashtable(void) */ template<typename EKeyType, typename EValueType> Dictionary<EKeyType, EValueType>::Dictionary(void) { if(!mStaticMembersHaveBeenInitialized) { NestedInfos<Dictionary<EKeyType, EValueType> >::fillArrays(mpKeyTypes, mpValueTypes, mpValueDimensions); mStaticMembersHaveBeenInitialized = true; } } /** @copydoc DictionaryBase::~DictionaryBase(void) */ template<typename EKeyType, typename EValueType> Dictionary<EKeyType, EValueType>::~Dictionary(void) { } /** @copydoc DictionaryBase::DictionaryBase(const DictionaryBase&) */ template<typename EKeyType, typename EValueType> Dictionary<EKeyType, EValueType>::Dictionary(const Dictionary<EKeyType, EValueType>& toCopy) : DictionaryBase(toCopy) { } /** @copydoc DictionaryBase::operator=() */ template<typename EKeyType, typename EValueType> Dictionary<EKeyType, EValueType>& Dictionary<EKeyType, EValueType>::operator=(const Dictionary<EKeyType, EValueType>& toCopy) { return assign(toCopy); } /** @copydoc DictionaryBase::operator==() */ template<typename EKeyType, typename EValueType> bool Dictionary<EKeyType, EValueType>::operator==(const Dictionary<EKeyType, EValueType>& toCompare) const { return this->compare(toCompare); } /** @copydoc DictionaryBase::operator!=() */ template<typename EKeyType, typename EValueType> bool Dictionary<EKeyType, EValueType>::operator!=(const Dictionary<EKeyType, EValueType>& toCompare) const { return !this->compare(toCompare); } /** @copydoc Hashtable::operator[]() */ template<typename EKeyType, typename EValueType> const EValueType& Dictionary<EKeyType, EValueType>::operator[](unsigned int index) const { return getElementAt(index, reinterpret_cast<EValueType*>(NULL)); } /** @copydoc Hashtable::operator[]() */ template<typename EKeyType, typename EValueType> EValueType& Dictionary<EKeyType, EValueType>::operator[](unsigned int index) { return getElementAt(index, reinterpret_cast<EValueType*>(NULL)); } template<typename EKeyType, typename EValueType> Dictionary<EKeyType, EValueType>& Dictionary<EKeyType, EValueType>::assign(const DictionaryBase& toCopy) { super::assign(toCopy); return *this; } /** @copydoc ExitGames::Common::Hashtable::put(const Hashtable&) */ //NOTE: the "ExitGames::Common" part is needed here, as otherwise doxygen, although still actually finding the copydoc target, throws a warning about not being able to find it template<typename EKeyType, typename EValueType> void Dictionary<EKeyType, EValueType>::put(const Dictionary<EKeyType, EValueType>& src) { super::put(src.getHashtable()); } /** @copydoc Hashtable::put(const FKeyType&,const FValueType&) */ template<typename EKeyType, typename EValueType> void Dictionary<EKeyType, EValueType>::put(const EKeyType& key, const EValueType& val) { super::put(key, val); } /** @copydoc Hashtable::put(const FKeyType&) */ template<typename EKeyType, typename EValueType> void Dictionary<EKeyType, EValueType>::put(const EKeyType& key) { COMPILE_TIME_ASSERT2_TRUE_MSG((Helpers::IsDerivedFrom<EValueType, Object>::Is), ERROR_OMITTING_THE_VALUE_IS_NOT_SUPPORTED_FOR_DICTIONARIES_EXCEPT_WHEN_THE_VALUE_TYPE_IS_OBJECT); super::put(key); } /** @copydoc Hashtable::put(const FKeyType&,FValueType,typename Common::Helpers::ArrayLengthType<FValueType>::type) */ template<typename EKeyType, typename EValueType> void Dictionary<EKeyType, EValueType>::put(const EKeyType& key, const EValueType pVal, typename Common::Helpers::ArrayLengthType<EValueType>::type size) { super::put(key, pVal, size); } /** @copydoc Hashtable::put(const FKeyType&,FValueType,const short*) */ template<typename EKeyType, typename EValueType> void Dictionary<EKeyType, EValueType>::put(const EKeyType& key, const EValueType pVal, const short* const sizes) { super::put(key, pVal, sizes); } /** @copydoc Hashtable::getValue() */ template<typename EKeyType, typename EValueType> const EValueType* Dictionary<EKeyType, EValueType>::getValue(const EKeyType& key) const { return super::getValue(key, reinterpret_cast<EValueType*>(NULL)); } /** @copydoc Hashtable::getKeys() */ template<typename EKeyType, typename EValueType> JVector<EKeyType> Dictionary<EKeyType, EValueType>::getKeys(void) const { return super::getKeys(reinterpret_cast<EKeyType*>(NULL)); } /** @copydoc Hashtable::remove() */ template<typename EKeyType, typename EValueType> void Dictionary<EKeyType, EValueType>::remove(const EKeyType& key) { super::remove(key); } /** @copydoc Hashtable::contains() */ template<typename EKeyType, typename EValueType> bool Dictionary<EKeyType, EValueType>::contains(const EKeyType& key) const { return super::contains(key); } template<typename EKeyType, typename EValueType> const nByte* Dictionary<EKeyType, EValueType>::getKeyTypes(void) const { return mpKeyTypes; } template<typename EKeyType, typename EValueType> const nByte* Dictionary<EKeyType, EValueType>::getValueTypes(void) const { return mpValueTypes; } template<typename EKeyType, typename EValueType> const unsigned int* Dictionary<EKeyType, EValueType>::getValueDimensions(void) const { return mpValueDimensions; } template<typename EKeyType, typename EValueType> JString Dictionary<EKeyType, EValueType>::typeToString(void) const { return ToString::typeToString(); } template<typename EKeyType, typename EValueType> JString& Dictionary<EKeyType, EValueType>::toString(JString& retStr, bool withTypes) const { retStr += L"{"; for(unsigned int i=0; i<getSize(); i++) { Object::toStringHelper(getHashtable().getKeys()[i], retStr, withTypes, !Helpers::IsSame<EKeyType, Object>::is); retStr += L"="; Object::toStringHelper(getHashtable()[i], retStr, withTypes, !Helpers::IsSame<EValueType, Object>::is); if(i < getSize()-1) retStr += L", "; } retStr += L"}"; return retStr; } template<typename EKeyType, typename EValueType> bool Dictionary<EKeyType, EValueType>::compare(const DictionaryBase &toCompare) const { return getHashtable() == toCompare.getHashtable(); } template<typename EKeyType, typename EValueType> DictionaryBase* Dictionary<EKeyType, EValueType>::copy(short amount) const { DictionaryBase* pRetVal = MemoryManagement::allocateArray<Dictionary<EKeyType, EValueType> >(amount); for(short i=0; i<amount; i++) pRetVal[i] = this[i]; return pRetVal; } template<typename EKeyType, typename EValueType> template<typename EType, typename ERPType> void Dictionary<EKeyType, EValueType>::NestedInfos<EType, ERPType>::fillArrays(nByte[M_NESTING_DEPTH], nByte[M_NESTING_DEPTH], unsigned int[M_NESTING_DEPTH], unsigned int) { } template<typename EKeyType, typename EValueType> template<typename EType, template<typename, typename> class ETemplate, typename ENestedKeyType, typename ENestedValueType> void Dictionary<EKeyType, EValueType>::NestedInfos<EType, ETemplate<ENestedKeyType, ENestedValueType> >::fillArrays(nByte keyTypes[M_NESTING_DEPTH], nByte valueTypes[M_NESTING_DEPTH], unsigned int valueDimensions[M_NESTING_DEPTH], unsigned int recursionDepth) { keyTypes[recursionDepth] = Helpers::ConfirmAllowedKey<ENestedKeyType>::typeName; valueTypes[recursionDepth] = Helpers::ConfirmAllowed<ENestedValueType>::typeName; valueDimensions[recursionDepth] = Helpers::ConfirmAllowed<ENestedValueType>::dimensions; if(recursionDepth < M_NESTING_DEPTH) NestedInfos<ENestedValueType>::fillArrays(keyTypes, valueTypes, valueDimensions, recursionDepth+1); } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Internal/Enums/JoinMode.h
<gh_stars>0 /* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Common.h" namespace ExitGames { namespace LoadBalancing { namespace Internal { namespace JoinMode { static const nByte DEFAULT = 0; static const nByte CREATE_IF_NOT_EXISTS = 1; static const nByte JOIN_OR_REJOIN = 2; static const nByte REJOIN_ONLY = 3; } } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/AuthenticationValues.h
/* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "LoadBalancing-cpp/inc/Enums/CustomAuthenticationType.h" namespace ExitGames { namespace LoadBalancing { namespace Internal { class AuthenticationValuesSecretSetter; } class AuthenticationValues : public Common::Base { public: using Common::ToString::toString; AuthenticationValues(void); nByte getType(void) const; AuthenticationValues& setType(nByte type); const Common::JString& getParameters(void) const; AuthenticationValues& setParameters(const Common::JString& parameters); AuthenticationValues& setParametersWithUsernameAndToken(const Common::JString& username, const Common::JString& token); const Common::JVector<nByte>& getData(void) const; AuthenticationValues& setData(const Common::JVector<nByte>& data); const Common::JString& getSecret(void) const; const Common::JString& getUserID(void) const; AuthenticationValues& setUserID(const Common::JString& userID); virtual Common::JString& toString(Common::JString& retStr, bool withTypes=false) const; private: AuthenticationValues& setSecret(const Common::JString& secret); nByte mType; Common::JString mParameters; Common::JVector<nByte> mData; Common::JString mSecret; Common::JString mUserID; friend class Internal::AuthenticationValuesSecretSetter; }; } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/Object.h
<reponame>shirobusa1997/UE-PhotonSandbox<filename>Source/Photon/Common-cpp/inc/Object.h /* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Base.h" class EGUtilsHelper; namespace ExitGames { namespace Common { namespace Helpers { class SerializerImplementation; class DeSerializerImplementation; } class Object : public Base { public: using ToString::toString; Object(void); virtual ~Object(void); Object(const Object& toCopy); virtual Object& operator=(const Object& toCopy); bool operator==(const Object& toCompare) const; bool operator!=(const Object& toCompare) const; nByte getType(void) const; nByte getCustomType(void) const; const short* getSizes(void) const; unsigned int getDimensions(void) const; JString& toString(JString& retStr, bool withTypes=false) const; protected: Object(const void* data, nByte type, nByte customType, bool makeCopy); Object(const void* data, nByte type, nByte customType, int size, bool makeCopy); Object(const nByte* data, int size, bool makeCopy); Object(const void* data, nByte type, nByte customType, unsigned int dimensions, const short* sizes, bool makeCopy); const void* getData(void) const; const void* const* getDataPointer(void) const; virtual Object& assign(const Object& toCopy); private: union Data { nByte byteData; short shortData; int intData; int64 int64Data; float floatData; double doubleData; bool boolData; }; void setSizes(const short* sizes, unsigned int dimensions=1); void setDimensions(unsigned int dimensions); void setData(const void* data); void setDataNoCopy(void* data); void setType(nByte type); void setCustomType(nByte customType); void set(const void* data, nByte type, nByte customType, bool makeCopy); void set(const void* data, nByte type, nByte customType, int size, bool makeCopy); void set(const void* data, nByte type, nByte customType, unsigned int dimensions, const short* sizes, bool makeCopy); void setWithoutCleanup(const void* data, nByte type, nByte customType, bool makeCopy); void setWithoutCleanup(const void* data, nByte type, nByte customType, int size, bool makeCopy); void setWithoutCleanup(const void* data, nByte type, nByte customType, unsigned int dimensions, const short* sizes, bool makeCopy); void setToNULL(void); void cleanup(const void* pData=0, unsigned int recursionDepth=0); void copyArray(const void* pDataIn, void** pDataOut, unsigned int recursionDepth=0) const; bool equalsArray(const void* pData1, const void* pData2, unsigned int recursionDepth=0) const; static JString& toStringHelper(const Object& object, JString& retStr, bool withTypes=false, bool butWithOutTopLevelTypes=false); JString payloadTypeToString(void) const; bool compareHelper(const void* pData1, const void* pData2, nByte type, nByte customType, unsigned int dimensions, const short* arraySizes, unsigned int recursionDepth) const; static Data constructDataInstance(nByte payload); static Data constructDataInstance(short payload); static Data constructDataInstance(int payload); static Data constructDataInstance(int64 payload); static Data constructDataInstance(float payload); static Data constructDataInstance(double payload); static Data constructDataInstance(bool payload); Data mData; void* mpData; int mSize; short* mpSizes; nByte mType; nByte mCustomType; unsigned int mDimensions; friend class DictionaryBase; template<typename EKeyType, typename EValueType> friend class Dictionary; friend class Hashtable; friend class Helpers::SerializerImplementation; friend class Helpers::DeSerializerImplementation; friend class ::EGUtilsHelper; }; } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Internal/RoomPropertiesCacher.h
<gh_stars>0 /* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Common.h" namespace ExitGames { namespace LoadBalancing { class Client; class Room; namespace Internal { class RoomPropertiesCacher { static void cache(Room& room, const Common::Hashtable& properties); friend class LoadBalancing::Client; }; } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/MemoryManagement/Internal/MemoryPoolManager.h
<gh_stars>0 /* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include <limits.h> #include "Common-cpp/inc/Helpers/Spinlock.h" #include "Common-cpp/inc/MemoryManagement/AllocatorInterface.h" #include "Common-cpp/inc/MemoryManagement/Internal/MemoryPool.h" #if defined _EG_MARMALADE_PLATFORM && (defined EG_DEBUGGER || !defined _EG_MS_COMPILER) && defined I3D_ARCH_X86 # define EG_DEACTIVATE_MEMORY_MANAGER #endif namespace ExitGames { namespace Common { namespace MemoryManagement { namespace Internal { class MemoryPoolManager : public AllocatorInterface { public: MemoryPoolManager(void); void setMaxAllocSize(size_t maxAllocSize); void setCapacityIncrements(unsigned char count, size_t* capacityIncrements); void* alloc(size_t s); void dealloc(void* p); void* resize(void* p, size_t size); static MemoryPoolManager& get(void); #ifdef EG_DEBUGGER long long mCtrAllocs; long long mCtrDeallocs; long long mCtrBytes; #endif private: #ifndef EG_DEACTIVATE_MEMORY_MANAGER static const unsigned char M_POOL_COUNT = sizeof(size_t)*CHAR_BIT; MemoryPool mpPool[M_POOL_COUNT]; #endif Helpers::Spinlock mLock; }; } } } }
shirobusa1997/UE-PhotonSandbox
Source/PhotonSandbox/PhotonAPI2UE4/PA2U_LoadBalancingListener.h
<gh_stars>0 #pragma once #include "LoadBalancing-cpp/inc/Client.h" #include "PA2U_BaseView.h" struct LocalPlayerBase { LocalPlayerBase(); double x; double y; double z; }; class PA2U_LoadBalancingListener : public ExitGames::LoadBalancing::LoadBalancingListener { public: PA2U_LoadBalancingListener(PA2U_BaseView *pView){} ~PA2U_LoadBalancingListener(){} void setLoadBalancingClient(ExitGames::LoadBalancing::Client* pLBC); void connect(const ExitGames::Common::JString& userName); void service(); void createRoom(); bool setLocalPlayerTransform(double x, double y, double z); void moveLocalPlayerTransform(); private: // 共通実装になりそうなのでとりあえずサンプルの宣言をそのまま引用 (Mojatto, 2021/06/03) //From Common::BaseListener // receive and print out debug out here virtual void debugReturn(int debugLevel, const ExitGames::Common::JString& string); //From LoadBalancing::LoadBalancingListener // implement your error-handling here virtual void connectionErrorReturn(int errorCode); virtual void clientErrorReturn(int errorCode); virtual void warningReturn(int warningCode); virtual void serverErrorReturn(int errorCode); // events, triggered by certain operations of all players in the same room virtual void joinRoomEventAction(int playerNr, const ExitGames::Common::JVector<int>& playernrs, const ExitGames::LoadBalancing::Player& player); virtual void leaveRoomEventAction(int playerNr, bool isInactive); virtual void customEventAction(int playerNr, nByte eventCode, const ExitGames::Common::Object& eventContent); // callbacks for operations on PhotonLoadBalancing server virtual void connectReturn(int errorCode, const ExitGames::Common::JString& errorString, const ExitGames::Common::JString& region, const ExitGames::Common::JString& cluster); virtual void disconnectReturn(void); virtual void createRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& gameProperties, const ExitGames::Common::Hashtable& playerProperties, int errorCode, const ExitGames::Common::JString& errorString); virtual void joinOrCreateRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& gameProperties, const ExitGames::Common::Hashtable& playerProperties, int errorCode, const ExitGames::Common::JString& errorString); virtual void joinRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& gameProperties, const ExitGames::Common::Hashtable& playerProperties, int errorCode, const ExitGames::Common::JString& errorString); virtual void joinRandomRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& gameProperties, const ExitGames::Common::Hashtable& playerProperties, int errorCode, const ExitGames::Common::JString& errorString); virtual void leaveRoomReturn(int errorCode, const ExitGames::Common::JString& errorString); virtual void gotQueuedReturn(void); virtual void joinLobbyReturn(void); virtual void leaveLobbyReturn(void); virtual void onRoomListUpdate(void); virtual void onLobbyStatsUpdate(const ExitGames::Common::JVector<ExitGames::LoadBalancing::LobbyStatsResponse>& lobbyStats); virtual void onLobbyStatsResponse(const ExitGames::Common::JVector<ExitGames::LoadBalancing::LobbyStatsResponse>& lobbyStats); virtual void onRoomPropertiesChange(const ExitGames::Common::Hashtable& changes); void updateState(); void afterRoomJoined(int localPlayerNumber); ExitGames::LoadBalancing::Client* mpLBC; PA2U_BaseView* mpView; LocalPlayerBase mLocalPlayerBase; ExitGames::Common::JString mMap; int mLocalPlayerNumber; int mGridSize; };
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/platform_definition.h
#pragma once #define _EG_WINDOWS_PLATFORM 1
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Internal/Enums/EncryptionDataParameters.h
/* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Common.h" namespace ExitGames { namespace LoadBalancing { namespace Internal { namespace EncryptionDataParameters { static const nByte MODE = 0; static const nByte SECRET1 = 1; static const nByte SECRET2 = 2; } } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/platformLayer.h
/* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/defines.h" #ifdef _EG_UNIX_PLATFORM int getTimeUnix(void); # ifdef _EG_ANDROID_PLATFORM size_t EG_wcslen(const EG_CHAR* wcs); int EG_wcscmp (const EG_CHAR* src, const EG_CHAR* dst); EG_CHAR* EG_wcscpy(EG_CHAR * dst, const EG_CHAR * src); EG_CHAR* EG_wcscat (EG_CHAR * dst, const EG_CHAR * src); EG_CHAR* EG_wcsstr(const EG_CHAR* wcs1, const EG_CHAR* wcs2); size_t EG_wcsnlen(const EG_CHAR *s, size_t maxlen); EG_CHAR* EG_wcschr(const EG_CHAR * string, EG_CHAR ch); int EG_wcsncmp(const EG_CHAR * first, const EG_CHAR * last, size_t count); wchar_t * EG_wcsrchr (const EG_CHAR * string, EG_CHAR ch); # endif # if defined _EG_MARMALADE_PLATFORM && (!defined I3D_ARCH_X86 || !(defined _EG_MS_COMPILER || defined __clang__)) && !defined I3D_ARCH_64_BIT && !defined S3E_IPHONE_STATIC_LINK || defined _EG_ANDROID_PLATFORM || defined _EG_EMSCRIPTEN_PLATFORM int EG_vswprintf(EG_CHAR* wcs, size_t maxlen, const EG_CHAR* format, va_list args); int EG_swprintf(EG_CHAR* wcs, size_t maxlen, const EG_CHAR* format, ...); # endif #endif
shirobusa1997/UE-PhotonSandbox
Source/Photon/Photon-cpp/inc/Punchthrough/Puncher.h
<filename>Source/Photon/Photon-cpp/inc/Punchthrough/Puncher.h #pragma once #include "Common-cpp/inc/Common.h" namespace ExitGames { namespace Photon { namespace Internal { namespace Punchthrough { class PunchConn; class SocketImplementation; namespace Forwards { class StunMsgType; struct SockaddrIn; class PunchConnState; } } } namespace Punchthrough { class PunchListener; class RelayClient; class Puncher { public: Puncher(RelayClient* pRelayClient, const Common::Logger& logger); virtual ~Puncher(void); bool init(PunchListener* pPunchListener); void clear(void); bool startPunch(int remoteID); bool sendDirect(const Common::JVector<nByte>& buffer, int targetID, bool fallbackRelay); int sendDirect(const Common::JVector<nByte>& buffer, const Common::JVector<int>& targetIDs, bool fallbackRelay); bool processRelayPackage(const Common::JVector<nByte>& packet, int relayRemoteID); void service(void); private: const Internal::Punchthrough::Forwards::SockaddrIn* getEndpoint(int remoteID); bool getIsPunch(const Common::JVector<nByte>& packet); bool processPackage(const Common::JVector<nByte>& packet, bool relay, const Internal::Punchthrough::Forwards::SockaddrIn& directRemoteAddr, int relayRemoteID); bool processPunchPackage(const Common::JVector<nByte>& packet, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr); void socketService(void); // working with mConnections container bool hasConnection(int remoteID) const; Internal::Punchthrough::PunchConn* findConnection(int remoteID); Internal::Punchthrough::PunchConn* insertConnection(const Internal::Punchthrough::PunchConn& conn); bool removeConnection(int remoteID); void setConnectionState(Internal::Punchthrough::PunchConn& conn, Internal::Punchthrough::Forwards::PunchConnState state); // :: Handlers void handlerOffer(int idIncoming, const Internal::Punchthrough::Forwards::SockaddrIn& addrIncomingIntern, const Internal::Punchthrough::Forwards::SockaddrIn& addrIncomingExtern); void handlerAnswer(int idIncoming, const Internal::Punchthrough::Forwards::SockaddrIn& addrIncomingIntern, const Internal::Punchthrough::Forwards::SockaddrIn& addrIncomingExtern); void handlerPing(int idIncoming, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr); void handlerPong(int idIncoming, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr); // :: Senders bool sendOffer(int remoteid); bool sendAnswer(int remoteid); bool sendPing(Internal::Punchthrough::PunchConn& conn); bool sendPong(Internal::Punchthrough::PunchConn& conn, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr); bool sendStunRelay(int remoteid, Internal::Punchthrough::Forwards::StunMsgType stunMsgType, const nByte* pMsgID); bool sendStunDirect(const Internal::Punchthrough::PunchConn& conn, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr, Internal::Punchthrough::Forwards::StunMsgType stunMsgType, const nByte* pMsgID); bool sendRelay(const Common::JVector<nByte>& buffer, const Common::JVector<int>& targetIDs); // :: Builders Common::JVector<nByte> buildMsgBindingRequest(void); Common::JVector<nByte> buildStunImplementation(const Internal::Punchthrough::PunchConn* pConn, nByte id, Internal::Punchthrough::Forwards::StunMsgType stunMsgType, const nByte* pMsgID); // :: EndPoint Utils const Internal::Punchthrough::Forwards::SockaddrIn& getLocalEndpoint(void); void aquireExternalEndpoint(void); static const Common::JString addrToStr(const Internal::Punchthrough::Forwards::SockaddrIn& addr); Internal::Punchthrough::SocketImplementation* mpSocket; RelayClient* mpRelayClient; PunchListener* mpPunchListener; Common::Logger mLogger; Common::Helpers::UniquePointer<Internal::Punchthrough::Forwards::SockaddrIn> mupClientExternAddr; bool mValidExternalAddr; // Connections Common::Helpers::UniquePointer<Common::JVector<Internal::Punchthrough::PunchConn> > mupConnections; static const nByte mMsgBindingID[12]; static const nByte mMsgRequestID[12]; static const nByte mMsgResponseID[12]; static const nByte mUserMsgByte0; }; } } }
shirobusa1997/UE-PhotonSandbox
Source/PhotonSandbox/PhotonAPI2UE4/PA2U_DefaultConstants.h
<reponame>shirobusa1997/UE-PhotonSandbox<gh_stars>0 #pragma once // -------------------------------------------- // 定数マクロ宣言 // -------------------------------------------- // デフォルトマップ (ゲームプロジェクト側で指定するべきであるため,ここではデバッグ用マップを指定) #define DEFAULT_MAP "L_PA2U_BlankMap_0" // プレイヤーの状態の更新インターバル[ms] #define PLAYER_UPDATE_INTERVAL_MS 50
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Internal/Utils.h
<filename>Source/Photon/LoadBalancing-cpp/inc/Internal/Utils.h /* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Common.h" namespace ExitGames { namespace LoadBalancing { namespace Internal { namespace Utils { Common::Hashtable stripToCustomProperties(const Common::Hashtable& properties); Common::Hashtable stripKeysWithNullValues(const Common::Hashtable& orig); } } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Enums/DisconnectCause.h
/* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once namespace ExitGames { namespace LoadBalancing { /** Enumaration of causes for Disconnects (used in LoadBalancingClient.DisconnectedCause). Read the individual descriptions to find out what to do about this type of disconnect.*/ namespace DisconnectCause { static const int NONE = 0; ///<No error was tracked. static const int DISCONNECT_BY_SERVER_USER_LIMIT = 1; ///<OnStatusChanged: The CCUs count of your Photon Server License is exausted (temporarily). static const int EXCEPTION_ON_CONNECT = 2; ///<OnStatusChanged: The server is not available or the address is wrong. Make sure the port is provided and the server is up. static const int DISCONNECT_BY_SERVER = 3; ///<OnStatusChanged: The server disconnected this client. Most likely the server's send buffer is full (receiving too much from other clients). static const int DISCONNECT_BY_SERVER_LOGIC = 4; ///<OnStatusChanged: The server disconnected this client due to server's logic (received a disconnect command). static const int TIMEOUT_DISCONNECT = 5; ///<OnStatusChanged: This client detected that the server's responses are not received in due time. Maybe you send / receive too much? static const int EXCEPTION = 6; ///<OnStatusChanged: Some internal exception caused the socket code to fail. Contact Exit Games. static const int INVALID_AUTHENTICATION = 7; ///<OnOperationResponse: Authenticate in the Photon Cloud with invalid AppId. Update your subscription or contact Exit Games. static const int MAX_CCU_REACHED = 8; ///<OnOperationResponse: Authenticate (temporarily) failed when using a Photon Cloud subscription without CCU Burst. Update your subscription. static const int INVALID_REGION = 9; ///<OnOperationResponse: Authenticate when the app's Photon Cloud subscription is locked to some (other) region(s). Update your subscription or master server address. static const int OPERATION_NOT_ALLOWED_IN_CURRENT_STATE = 10; ///<OnOperationResponse: Operation that's (currently) not available for this client (not authorized usually). Only tracked for op Authenticate. static const int CUSTOM_AUTHENTICATION_FAILED = 11; ///<OnOperationResponse: Authenticate in the Photon Cloud with invalid client values or custom authentication setup in Cloud Dashboard. } /** @file */ } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/Hashtable.h
/* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Helpers/KeyToObject.h" #include "Common-cpp/inc/Helpers/ValueToObject.h" #include "Common-cpp/inc/JVector.h" namespace ExitGames { namespace Common { class Hashtable : public Base { public: using ToString::toString; Hashtable(void); ~Hashtable(void); Hashtable(const Hashtable& toCopy); Hashtable& operator=(const Hashtable& toCopy); bool operator==(const Hashtable& toCompare) const; bool operator!=(const Hashtable& toCompare) const; const Object& operator[](unsigned int index) const; Object& operator[](unsigned int index); void put(const Hashtable& src); template<typename FKeyType, typename FValueType> void put(const FKeyType& key, const FValueType& val); template<typename FKeyType> void put(const FKeyType& key); template<typename FKeyType, typename FValueType> void put(const FKeyType& key, const FValueType pVal, typename Helpers::ArrayLengthType<FValueType>::type size); template<typename FKeyType, typename FValueType> void put(const FKeyType& key, const FValueType pVal, const short* sizes); template<typename FKeyType> const Object* getValue(const FKeyType& key) const; unsigned int getSize(void) const; const JVector<Object>& getKeys(void) const; template<typename FKeyType> void remove(const FKeyType& key); template<typename FKeyType> bool contains(const FKeyType& key) const; void removeAllElements(void); JString& toString(JString& retStr, bool withTypes=false) const; private: static bool haveSameKey(const Object& one, const Object& two); void putImplementation(const Object& key, const Object& val); const Object* getValueImplementation(const Object& key) const; void removeImplementation(const Object& key); bool containsImplementation(const Object& key) const; JVector<Object> mKeytable; JVector<Object> mValtable; }; /** Adds a pair of a key and a corresponding value to the instance. @details If the key is already existing, then it's old value will be replaced with the new one. Please have a look at the @link Datatypes table of datatypes\endlink for a list of supported types for keys and values @param key the key to add @param val the value to add @returns nothing. */ template<typename FKeyType, typename FValueType> void Hashtable::put(const FKeyType& key, const FValueType& val) { typename Helpers::ConfirmAllowedKey<FKeyType>::type forceCompilationToFailForUnsupportedKeyTypes; (void)forceCompilationToFailForUnsupportedKeyTypes; typename Helpers::ConfirmAllowed<FValueType>::type forceCompilationToFailForUnsupportedValueTypes; (void)forceCompilationToFailForUnsupportedValueTypes; COMPILE_TIME_ASSERT2_TRUE_MSG(!Helpers::ConfirmAllowed<typename Helpers::ConfirmAllowed<FValueType>::type>::dimensions, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_SINGLE_VALUES); putImplementation(Helpers::KeyToObject::get(key), Helpers::ValueToObject::get(val)); } /** @overload @details This overload adds an empty object as value for the provided key. */ template<typename FKeyType> void Hashtable::put(const FKeyType& key) { putImplementation(Helpers::KeyToObject::get(key), Object()); } /** @overload @details This overload accepts singledimensional arrays and NULL-pointers passed for parameter pVal. NULL pointers are only legal input, if size is 0 @param key the key to add @param pVal the value array to add @param size the size of the value array */ template<typename FKeyType, typename FValueType> void Hashtable::put(const FKeyType& key, const FValueType pVal, typename Helpers::ArrayLengthType<FValueType>::type size) { typename Helpers::ConfirmAllowedKey<FKeyType>::type forceCompilationToFailForUnsupportedKeyTypes; (void)forceCompilationToFailForUnsupportedKeyTypes; typename Helpers::ConfirmAllowed<FValueType>::type forceCompilationToFailForUnsupportedValueTypes; (void)forceCompilationToFailForUnsupportedValueTypes; COMPILE_TIME_ASSERT2_TRUE_MSG(Helpers::ConfirmAllowed<typename Helpers::ConfirmAllowed<FValueType>::type>::dimensions==1, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_1D_ARRAYS); putImplementation(Helpers::KeyToObject::get(key), Helpers::ValueToObject::get(pVal, size)); } /** @overload @details This overload accepts multidimensional arrays and NULL-pointers passed for parameter pVal. The array that is passed for parameter pVal has to be a pointer of the correct abstraction level, meaning a normal pointer for a singledimensional array, a doublepointer for a twodimensional array, a triplepointer for a threedimensional array and so on. For pVal NULL pointers are only legal input, if sizes[0] is 0. For sizes NULL is no valid input. @param key the key to add @param pVal the value array to add @param sizes the sizes for every dimension of the value array - the length of this array has to match the dimensions of pVal */ template<typename FKeyType, typename FValueType> void Hashtable::put(const FKeyType& key, const FValueType pVal, const short* const sizes) { typename Helpers::ConfirmAllowedKey<FKeyType>::type forceCompilationToFailForUnsupportedKeyTypes; (void)forceCompilationToFailForUnsupportedKeyTypes; typename Helpers::ConfirmAllowed<FValueType>::type forceCompilationToFailForUnsupportedValueTypes; (void)forceCompilationToFailForUnsupportedValueTypes; COMPILE_TIME_ASSERT2_TRUE_MSG((bool)Helpers::ConfirmAllowed<typename Helpers::ConfirmAllowed<FValueType>::type>::dimensions, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_FOR_ARRAYS); putImplementation(Helpers::KeyToObject::get(key), Helpers::ValueToObject::get(pVal, sizes)); } /** Deletes the specified key and the corresponding value, if found in the Hashtable. @param key Pointer to the key of the key/value-pair to remove. @returns nothing. @sa removeAllElements() */ template<typename FKeyType> void Hashtable::remove(const FKeyType& key) { removeImplementation(Helpers::KeyToObject::get(key)); } /** Checks, whether the Hashtable contains a certain key. @param key Pointer to the key to look up. @returns true if the specified key was found, false otherwise. */ template<typename FKeyType> bool Hashtable::contains(const FKeyType& key) const { return containsImplementation(Helpers::KeyToObject::get(key)); } /** Returns the corresponding value for a specified key. @param key Reference to the key to return the corresponding value for. @returns a pointer to the corresponding value if the Hashtable contains the specified key, NULL otherwise. @sa put() */ template<typename FKeyType> const Object* Hashtable::getValue(const FKeyType& key) const { return getValueImplementation(Helpers::KeyToObject::get(key)); } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/RoomOptions.h
<reponame>shirobusa1997/UE-PhotonSandbox /* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "LoadBalancing-cpp/inc/Enums/DirectMode.h" #include "LoadBalancing-cpp/inc/Enums/LobbyType.h" namespace ExitGames { namespace LoadBalancing { class RoomOptions : public Common::Base { public: using Common::ToString::toString; RoomOptions(bool isVisible=true, bool isOpen=true, nByte maxPlayers=0, const Common::Hashtable& customRoomProperties=Common::Hashtable(), const Common::JVector<Common::JString>& propsListedInLobby=Common::JVector<Common::JString>(), const Common::JString& lobbyName=Common::JString(), nByte lobbyType=LobbyType::DEFAULT, int playerTtl=0, int emptyRoomTtl=0, bool suppressRoomEvents=false, const Common::JVector<Common::JString>* pPlugins=NULL, bool publishUserID=false, nByte directMode=DirectMode::NONE); ~RoomOptions(void); RoomOptions(const RoomOptions& toCopy); RoomOptions& operator=(const RoomOptions& toCopy); bool getIsVisible(void) const; RoomOptions& setIsVisible(bool isVisible); bool getIsOpen(void) const; RoomOptions& setIsOpen(bool isOpen); nByte getMaxPlayers(void) const; RoomOptions& setMaxPlayers(nByte maxPlayers); const Common::Hashtable& getCustomRoomProperties(void) const; RoomOptions& setCustomRoomProperties(const Common::Hashtable& customRoomProperties); const Common::JVector<Common::JString>& getPropsListedInLobby(void) const; RoomOptions& setPropsListedInLobby(const Common::JVector<Common::JString>& propsListedInLobby); const Common::JString& getLobbyName(void) const; RoomOptions& setLobbyName(const Common::JString& lobbyName); nByte getLobbyType(void) const; RoomOptions& setLobbyType(nByte lobbyType); int getPlayerTtl(void) const; RoomOptions& setPlayerTtl(int playerTtl); int getEmptyRoomTtl(void) const; RoomOptions& setEmptyRoomTtl(int emptyRoomTtl); bool getSuppressRoomEvents(void) const; RoomOptions& setSuppressRoomEvents(bool suppressRoomEvents); const Common::JVector<Common::JString>* getPlugins(void) const; RoomOptions& setPlugins(const Common::JVector<Common::JString>* pPlugins); bool getPublishUserID(void) const; RoomOptions& setPublishUserID(bool publishUserID); nByte getDirectMode(void) const; RoomOptions& setDirectMode(nByte directMode); virtual Common::JString& toString(Common::JString& retStr, bool withTypes=false) const; private: bool mIsVisible; bool mIsOpen; nByte mMaxPlayers; Common::Hashtable mCustomRoomProperties; Common::JVector<Common::JString> mPropsListedInLobby; Common::JString mLobbyName; nByte mLobbyType; int mPlayerTtl; int mEmptyRoomTtl; bool mSuppressRoomEvents; Common::Helpers::UniquePointer<Common::JVector<Common::JString> > mupPlugins; bool mPublishUserID; nByte mDirectMode; }; } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/Helpers/SmartPointers/SharedPointerBase.h
<gh_stars>0 /* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Helpers/SmartPointers/SmartPointerInterface.h" namespace ExitGames { namespace Common { namespace Helpers { template<typename Etype> class SharedPointerBase : public SmartPointerInterface<Etype> { protected: SharedPointerBase(void (*pDeleter)(const Etype*)); SharedPointerBase(Etype* pData, void (*pDeleter)(const Etype*)); virtual ~SharedPointerBase(void) = 0; SharedPointerBase(const SharedPointerBase<Etype>& toCopy); virtual SharedPointerBase& operator=(const SharedPointerBase<Etype>& toCopy); unsigned long long* mpRefCount; typedef SmartPointerInterface<Etype> super; }; template<typename Etype> SharedPointerBase<Etype>::SharedPointerBase(void (*pDeleter)(const Etype*)) : SmartPointerInterface<Etype>(pDeleter) { SharedPointerBase::mpRefCount = MemoryManagement::allocate<unsigned long long>(1); } template<typename Etype> SharedPointerBase<Etype>::SharedPointerBase(Etype* pData, void (*pDeleter)(const Etype*)) : SmartPointerInterface<Etype>(pData, pDeleter) { mpRefCount = MemoryManagement::allocate<unsigned long long>(1); } template<typename Etype> SharedPointerBase<Etype>::~SharedPointerBase(void) { if(--*mpRefCount) return; super::mpDeleter(super::mpData); MemoryManagement::deallocate(mpRefCount); } template<typename Etype> SharedPointerBase<Etype>::SharedPointerBase(const SharedPointerBase<Etype>& toCopy) : SmartPointerInterface<Etype>(toCopy) { super::mpData = NULL; mpRefCount = NULL; *this = toCopy; } template<typename Etype> SharedPointerBase<Etype>& SharedPointerBase<Etype>::operator=(const SharedPointerBase<Etype>& toCopy) { if(mpRefCount && !--*mpRefCount) { super::mpDeleter(super::mpData); MemoryManagement::deallocate(mpRefCount); } super::mpData = toCopy.mpData; super::mpDeleter = toCopy.mpDeleter; ++*(mpRefCount=toCopy.mpRefCount); return *this; } } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/Helpers/Spinlock.h
/* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Helpers/Thread.h" #ifdef EG_PLATFORM_SUPPORTS_ATOMICS # include <atomic> #endif namespace ExitGames { namespace Common { namespace Helpers { class Spinlock { public: Spinlock(void); void lock(void); void unlock(void); #ifdef EG_PLATFORM_SUPPORTS_ATOMICS private: std::atomic<Thread::ID> mLockOwner; nByte mLockCount; #endif }; } } }
shirobusa1997/UE-PhotonSandbox
Source/PhotonSandbox/PhotonAPI2UE4/PA2U_LBClientActor.h
#pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "PA2U_LoadBalancingListener.h" #include "PA2U_LBClientActor.generated.h" UCLASS() class PA2U_LBClientActor : public AActor, public PA2U_BaseView { GENERATED_BODY() public: PA2U_LBClientActor(){} ~PA2U_LBClientActor(){} UFUNCTION(BlueprintImplementableEvent, Category = "PhotonLB") void initPlayers(); private: void BeginPlay(); void Tick(float DeltaSeconds); };
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/ANSIString.h
/* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/BaseCharString.h" namespace ExitGames { namespace Common { class ANSIString : public BaseCharString { public: ANSIString(void); ANSIString(const ANSIString& str); ANSIString(const JString& str); ANSIString(const char* str); ANSIString(const EG_CHAR* str); ~ANSIString(void); ANSIString& operator=(const ANSIString& Rhs); ANSIString& operator=(const JString& Rhs); ANSIString& operator=(const char* Rhs); ANSIString& operator=(const EG_CHAR* Rhs); operator const char* (void) const; operator JString (void) const; JString JStringRepresentation(void) const; unsigned int size(void) const; private: class ANSIConverter : public Base { public: static char* Unicode2ANSI(const EG_CHAR* wstr, char* str, unsigned int strSize); static EG_CHAR* ANSI2Unicode(const char* str, EG_CHAR* wstr, unsigned int wstrLen); #ifdef _EG_PS4_PLATFORM private: static bool mInitialized; #endif }; }; } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Internal/PuncherClient.h
/* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Photon-cpp/inc/Punchthrough/Puncher.h" #include "Photon-cpp/inc/Punchthrough/PunchListener.h" #include "Photon-cpp/inc/Punchthrough/RelayClient.h" namespace ExitGames { namespace LoadBalancing { class Client; class Listener; namespace Internal { class PuncherClient : private Photon::Punchthrough::RelayClient, private Photon::Punchthrough::PunchListener { public: PuncherClient(Client& client, Listener& listener, const Common::Logger& logger); virtual ~PuncherClient(void); bool initPuncher(void); bool startPunch(int playerNr); bool sendDirect(const Common::JVector<nByte>& buffer, int targetID, bool fallbackRelay); int sendDirect(const Common::JVector<nByte>& buffer, const Common::JVector<int>& targetIDs, bool fallbackRelay); void service(void); bool processRelayPackage(const Common::JVector<nByte>& packet, int remoteID); private: Photon::Punchthrough::Puncher* mpPuncher; Client& mLoadBalancingClient; Listener& mLoadBalancingListener; const Common::Logger& mLogger; // PunchListener virtual void onDirectConnectionEstablished(int remoteID); virtual void onDirectConnectionFailedToEstablish(int /*remoteID*/); virtual void onReceiveDirect(const Common::JVector<nByte>& buffer, int remoteID, bool relay); // RelayClient virtual int getLocalID(void); virtual bool sendRelay(const Common::JVector<nByte>& buffer, const Common::JVector<int>& targetIDs); }; } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/Photon-cpp/inc/Version.h
#define EG_PHOTON_STRINGIFY3(param) L##param #define EG_PHOTON_STRINGIFY2(param) EG_PHOTON_STRINGIFY3(#param) #define EG_PHOTON_STRINGIFY(param) EG_PHOTON_STRINGIFY2(param) #define EG_PHOTON_PROTOCOL_VERSION_MAJOR 1 #define EG_PHOTON_PROTOCOL_VERSION_MINOR 6 #define EG_PHOTON_CLIENT_VERSION_MAJOR 4 #define EG_PHOTON_CLIENT_VERSION_SERVER_MINOR 1 #define EG_PHOTON_CLIENT_VERSION_CLIENT_MINOR 16 #define EG_PHOTON_CLIENT_VERSION_PATCH_RELEASE 5 #define EG_PHOTON_PROTOCOL_VERSION L"GpBinaryV" EG_PHOTON_STRINGIFY(EG_PHOTON_PROTOCOL_VERSION_MAJOR) EG_PHOTON_STRINGIFY(EG_PHOTON_PROTOCOL_VERSION_MINOR) #define EG_PHOTON_CLIENT_VERSION EG_PHOTON_STRINGIFY(EG_PHOTON_CLIENT_VERSION_MAJOR) L"." EG_PHOTON_STRINGIFY(EG_PHOTON_CLIENT_VERSION_SERVER_MINOR) L"." EG_PHOTON_STRINGIFY(EG_PHOTON_CLIENT_VERSION_CLIENT_MINOR) L"." EG_PHOTON_STRINGIFY(EG_PHOTON_CLIENT_VERSION_PATCH_RELEASE)
shirobusa1997/UE-PhotonSandbox
Source/PhotonSandbox/PhotonAPI2UE4/PA2U_Console.h
<reponame>shirobusa1997/UE-PhotonSandbox<gh_stars>0 #pragma once #include "PA2U_OutputListener.h" class ConsoleImplementation; class Console : public OutputListener { public: Console(void); ~Console(void); void update(void); void write(const ExitGames::Common::JString& str); void writeLine(const ExitGames::Common::JString& str=ExitGames::Common::JString()); static Console& get(void); private: ConsoleImplementation* mpImp; };
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Room.h
/* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "LoadBalancing-cpp/inc/Internal/RoomFactory.h" #include "LoadBalancing-cpp/inc/Internal/RoomPropertiesCacher.h" namespace ExitGames { namespace LoadBalancing { class Room : public Common::Base { public: using Common::ToString::toString; virtual ~Room(void); Room(const Room& toCopy); virtual Room& operator=(const Room& toCopy); const Common::JString& getName(void) const; virtual nByte getPlayerCount(void) const; nByte getMaxPlayers(void) const; bool getIsOpen(void) const; nByte getDirectMode(void) const; const Common::Hashtable& getCustomProperties(void) const; bool operator==(const Room& room) const; virtual Common::JString& toString(Common::JString& retStr, bool withTypes=false) const; virtual Common::JString toString(bool withTypes, bool withCustomProperties) const; protected: Room(const Common::JString& name, const Common::Hashtable& properties); virtual bool getIsMutable(void) const; virtual Room& assign(const Room& toCopy); virtual void cacheProperties(const Common::Hashtable& properties); virtual Common::JString payloadToString(bool withTypes=false, bool withCustomProperties=false) const; Common::JString mName; nByte mPlayerCount; nByte mMaxPlayers; bool mIsOpen; nByte mDirectMode; Common::Hashtable mCustomProperties; private: Room(void); friend class Internal::RoomFactory; friend class Internal::RoomPropertiesCacher; }; } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/Photon-cpp/inc/Punchthrough/PunchListener.h
#pragma once #include "Common-cpp/inc/Common.h" namespace ExitGames { namespace Photon { namespace Punchthrough { class PunchListener { public: virtual ~PunchListener(void){}; virtual void onDirectConnectionEstablished(int /*remoteID*/) {} virtual void onDirectConnectionFailedToEstablish(int /*remoteID*/) {} virtual void onReceiveDirect(const Common::JVector<nByte>& inBuf, int remoteID, bool relay) = 0; }; } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Enums/PeerStates.h
<gh_stars>0 /* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once namespace ExitGames { namespace LoadBalancing { namespace PeerStates { static const int Uninitialized = 0; static const int PeerCreated = 1; static const int ConnectingToNameserver = 2; static const int ConnectedToNameserver = 3; static const int DisconnectingFromNameserver = 4; static const int Connecting = 5; static const int Connected = 6; static const int WaitingForCustomAuthenticationNextStepCall = 7; static const int Authenticated = 8; static const int JoinedLobby = 9; static const int DisconnectingFromMasterserver = 10; static const int ConnectingToGameserver = 11; static const int ConnectedToGameserver = 12; static const int AuthenticatedOnGameServer = 13; static const int Joining = 14; static const int Joined = 15; static const int Leaving = 16; static const int Left = 17; static const int DisconnectingFromGameserver = 18; static const int ConnectingToMasterserver = 19; static const int ConnectedComingFromGameserver = 20; static const int AuthenticatedComingFromGameserver = 21; static const int Disconnecting = 22; static const int Disconnected = 23; } /** @file */ } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/Helpers/RemovePointer.h
/* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once namespace ExitGames { namespace Common { namespace Helpers { template<typename T> struct RemovePointer { typedef T type; }; template<typename T> struct RemovePointer<T*> { typedef T type; }; } } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/WebFlags.h
/* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Common.h" namespace ExitGames { namespace LoadBalancing { class WebFlags : public Common::Base { public: using Common::ToString::toString; WebFlags(nByte webFlags=0); nByte getFlags(void) const; WebFlags& setFlags(nByte webFlags); bool getHttpForward(void) const; WebFlags& setHttpForward(bool httpWebForward); bool getSendAuthCookie(void) const; WebFlags& setSendAuthCookie(bool sendAuthCookie); bool getSendSync(void) const; WebFlags& setSendSync(bool sendSync); bool getSendState(void) const; WebFlags& setSendState(bool sendState); virtual Common::JString& toString(Common::JString& retStr, bool withTypes=false) const; private: nByte mWebFlags; static const nByte M_HTTP_FORWARD = 0x01; static const nByte M_SEND_AUTH_COOKIE = 0x02; static const nByte M_SEND_SYNC = 0x04; static const nByte M_SEND_STATE = 0x08; }; } }
shirobusa1997/UE-PhotonSandbox
Source/PhotonSandbox/PhotonAPI2UE4/PA2U_OutputListener.h
<reponame>shirobusa1997/UE-PhotonSandbox #pragma once #include <iostream> #include "Common-cpp/inc/Common.h" #if defined _EG_ANDROID_PLATFORM # include <android/log.h> #elif defined _EG_SWITCH_WINDOWS_PLATFORM # include <nn/nn_Log.h> #endif class OutputListener : public virtual ExitGames::Common::BaseListener { protected: void log(const ExitGames::Common::JString& s, FColor color) { GEngine->AddOnScreenDebugMessage(-1, 5.f, color, s.UTF8Representation().cstr()); } public: virtual ~OutputListener(void){}; virtual void write(const ExitGames::Common::JString& str) = 0; virtual void writeLine(const ExitGames::Common::JString& str=ExitGames::Common::JString()) = 0; virtual void debugReturn(int debugLevel, const ExitGames::Common::JString& str) { switch(debugLevel) { case ExitGames::Common::DebugLevel::ALL: log(ExitGames::Common::JString(L"DEBUG: ")+str, FColor::White); break; case ExitGames::Common::DebugLevel::INFO: log(ExitGames::Common::JString(L"INFO: ")+str, FColor::Green); break; case ExitGames::Common::DebugLevel::WARNINGS: log(ExitGames::Common::JString(L"WARN: ")+str, FColor::Yellow); break; case ExitGames::Common::DebugLevel::ERRORS: log(ExitGames::Common::JString(L"ERROR: ")+str, FColor::Red); break; case ExitGames::Common::DebugLevel::OFF: default: log(ExitGames::Common::JString(L"FATAL: ")+str, FColor::Black); break; } # if defined _EG_SWITCH_WINDOWS_PLATFORM NN_LOG((str+L"\n").UTF8Representation().cstr()); # else std::wcerr << str << std::endl; # endif # if defined _EG_WINDOWS_PLATFORM || defined _EG_WINDOWSSTORE_PLATFORM || defined _EG_XB1_PLATFORM OutputDebugStringW((str+L"\n").cstr()); # endif # if defined _EG_ANDROID_PLATFORM int logLevel; switch(debugLevel) { case ExitGames::Common::DebugLevel::ALL: logLevel = ANDROID_LOG_DEBUG; break; case ExitGames::Common::DebugLevel::INFO: logLevel = ANDROID_LOG_INFO; break; case ExitGames::Common::DebugLevel::WARNINGS: logLevel = ANDROID_LOG_WARN; break; case ExitGames::Common::DebugLevel::ERRORS: logLevel = ANDROID_LOG_ERROR; break; case ExitGames::Common::DebugLevel::OFF: logLevel = ANDROID_LOG_FATAL; break; default: logLevel = ANDROID_LOG_FATAL; __android_log_write(logLevel, "Photon-Demo", "unknown log level"); break; } __android_log_write(logLevel, "Photon-Demo", str.UTF8Representation().cstr()); # endif } };
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Listener.h
<filename>Source/Photon/LoadBalancing-cpp/inc/Listener.h /* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Photon-cpp/inc/OperationResponse.h" #include "LoadBalancing-cpp/inc/LobbyStatsResponse.h" namespace ExitGames { namespace LoadBalancing { class Player; class Room; class Listener: public virtual Common::BaseListener { public: virtual ~Listener(void){} // receive and print out debug out here virtual void debugReturn(int debugLevel, const Common::JString& string) = 0; // implement your error-handling here virtual void connectionErrorReturn(int errorCode) = 0; virtual void clientErrorReturn(int errorCode) = 0; virtual void warningReturn(int warningCode) = 0; virtual void serverErrorReturn(int errorCode) = 0; // events, triggered by certain operations of all players in the same room virtual void joinRoomEventAction(int playerNr, const Common::JVector<int>& playernrs, const Player& player) = 0; virtual void leaveRoomEventAction(int playerNr, bool isInactive) = 0; virtual void customEventAction(int playerNr, nByte eventCode, const Common::Object& eventContent) = 0; // callbacks for operations on the server virtual void connectReturn(int errorCode, const Common::JString& errorString, const Common::JString& region, const Common::JString& cluster) = 0; virtual void disconnectReturn(void) = 0; virtual void createRoomReturn(int /*localPlayerNr*/, const Common::Hashtable& /*roomProperties*/, const Common::Hashtable& /*playerProperties*/, int /*errorCode*/, const Common::JString& /*errorString*/) {} virtual void joinOrCreateRoomReturn(int /*localPlayerNr*/, const Common::Hashtable& /*roomProperties*/, const Common::Hashtable& /*playerProperties*/, int /*errorCode*/, const Common::JString& /*errorString*/) {} virtual void joinRandomOrCreateRoomReturn(int /*localPlayerNr*/, const Common::Hashtable& /*roomProperties*/, const Common::Hashtable& /*playerProperties*/, int /*errorCode*/, const Common::JString& /*errorString*/) {} virtual void joinRoomReturn(int /*localPlayerNr*/, const Common::Hashtable& /*roomProperties*/, const Common::Hashtable& /*playerProperties*/, int /*errorCode*/, const Common::JString& /*errorString*/) {} virtual void joinRandomRoomReturn(int /*localPlayerNr*/, const Common::Hashtable& /*roomProperties*/, const Common::Hashtable& /*playerProperties*/, int /*errorCode*/, const Common::JString& /*errorString*/) {} virtual void leaveRoomReturn(int errorCode, const Common::JString& errorString) = 0; virtual void joinLobbyReturn(void) {} virtual void leaveLobbyReturn(void) {} virtual void onFindFriendsResponse(void) {} virtual void onLobbyStatsResponse(const Common::JVector<LobbyStatsResponse>& /*lobbyStats*/) {} virtual void webRpcReturn(int /*errorCode*/, const Common::JString& /*errorString*/, const Common::JString& /*uriPath*/, int /*resultCode*/, const Common::Dictionary<Common::Object, Common::Object>& /*returnData*/) {} // info, that certain values have been updated virtual void onRoomListUpdate(void) {} virtual void onRoomPropertiesChange(const Common::Hashtable& /*changes*/) {} virtual void onPlayerPropertiesChange(int /*playerNr*/, const Common::Hashtable& /*changes*/) {} virtual void onAppStatsUpdate(void) {} virtual void onLobbyStatsUpdate(const Common::JVector<LobbyStatsResponse>& /*lobbyStats*/) {} virtual void onCacheSliceChanged(int /*cacheSliceIndex*/) {} virtual void onMasterClientChanged(int /*id*/, int /*oldID*/) {} // custom authentication virtual void onCustomAuthenticationIntermediateStep(const Common::Dictionary<Common::JString, Common::Object>& /*customResponseData*/){} // receive the available server regions during the connect workflow (if you have specified in the constructor, that you want to select a region) virtual void onAvailableRegions(const Common::JVector<Common::JString>& /*availableRegions*/, const Common::JVector<Common::JString>& /*availableRegionServers*/){} virtual void onSecretReceival(const Common::JString& /*secret*/){} virtual void onDirectConnectionEstablished(int /*remoteID*/){} virtual void onDirectConnectionFailedToEstablish(int /*remoteID*/) {} virtual void onDirectMessage(const Common::Object& /*msg*/, int /*remoteID*/, bool /*relay*/) {} virtual void onCustomOperationResponse(const Photon::OperationResponse& /*operationResponse*/) {} virtual void onGetRoomListResponse(const Common::JVector<Common::Helpers::SharedPointer<Room> >& /*roomList*/, const Common::JVector<Common::JString>& /*roomNameList*/) {} }; /** @file */ } }