file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/12636604.c
/* vulp.c */ #include <stdio.h> #include <unistd.h> #include <string.h> int main() { char * fn = "/tmp/XYZ"; char buffer[60]; FILE *fp; /* get user input */ scanf("%50s", buffer ); if(!access(fn, W_OK)){ sleep(3); printf("\nRECEIVED STRING: %s\n", buffer); fp = fopen(fn, "a+"); printf("\nOpened file: %s\n", fn); fwrite(buffer, sizeof(char), strlen(buffer), fp); printf("\nWrote to file-1: %s\n", fn); fwrite("\n", sizeof(char), 1, fp); printf("\nWrote to file-2: %s\n", fn); fclose(fp); } else printf("No permission \n"); }
the_stack_data/11074275.c
#include <stdio.h> int main() { int i, j, k=7; for(i=1; i<10; i+=2) { for(j=k; j>k-3; j--) { printf("I=%d J=%d\n", i, j); } k=j+5; } return 0; }
the_stack_data/37637963.c
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <linux/stat.h> //#define FIFO_FILE "MYFIFO" int main(int argc, char *argv[]) { FILE *fp; int i; umask(0); char readbuf[80]; if ( argc<2 ) { printf("USAGE: fifoclient [string]\n"); exit(1); } else{ for(i=1;i<argc;i++){ mknod(argv[i], S_IFIFO|0666, 0); } while(1) { printf("Write message: "); fgets(readbuf,80, stdin); for(i=1;i<argc;i++){ if((fp = fopen(argv[i], "w")) == NULL) { perror("fopen"); exit(1); } fputs(readbuf, fp); fclose(fp); } } } return(0); }
the_stack_data/50138410.c
#include "syscall.h" int main(int argc, char** argv) { if(argc!=2) { printf("Usage: connect num num\n"); return 0; } connect(1,1); return 1; }
the_stack_data/244962.c
// panic: invalid allocation length: 0x0 (2) // https://syzkaller.appspot.com/bug?id=db3d758b925c38d8315465d3854168e2c8d16dcc // status:fixed // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff}; int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); long res = 0; syscall(__NR_socketpair, 1, 5, 0, 0); syscall(__NR_ioctl, -1, 0x8912, 0x400200); memcpy((void*)0x200002c0, "./bus\x00", 6); res = syscall(__NR_creat, 0x200002c0, 0); if (res != -1) r[0] = res; syscall(__NR_ftruncate, r[0], 0x8200); memcpy((void*)0x20000040, "./bus\x00", 6); res = syscall(__NR_open, 0x20000040, 0x141042, 0); if (res != -1) r[1] = res; syscall(__NR_mmap, 0x20001000, 0xa000, 0x800002, 0x11, r[1], 0); memcpy((void*)0x20000000, "/dev/full\x00", 10); res = syscall(__NR_openat, 0xffffffffffffff9c, 0x20000000, 0, 0); if (res != -1) r[2] = res; syscall(__NR_pread64, r[2], 0x20002640, 0xfffffede, 0); return 0; }
the_stack_data/624880.c
// 54321 // 4321 // 321 // 21 // 1 #include<stdio.h> int main (){ int i,j; for(i=5;i>=1;i--){ for(j=i;j>=1;j--){ printf("%d",j); } printf("\n"); } return 0; }
the_stack_data/142641.c
#include<stdio.h> int main() { int x; do { printf("Insira um valor maior que 10 para sair\n"); scanf("%d", &x); } while( x <= 10); printf("Parabén, vc conseguiu sair do programa!\n"); return 0; }
the_stack_data/165107.c
#include <stdio.h> int main () { int c,f; do { printf ("Ingrese un numero (-1 para salir)\n"); scanf("%d", &c); printf("El numero es %d\n", c); } while (c != -1); f=5; while (f != 10) { if (f == 0) { printf("Es un numero par \n"); }else{ if (f!=0) { printf ("Es un numero impar\n"); } } f++; } return 0; }
the_stack_data/104828771.c
#include <stdio.h> int iterativeBinarySearch(int array[], int start_index, int end_index, int element){ while (start_index <= end_index){ int middle = start_index + (end_index- start_index )/2; if (array[middle] == element) return middle; if (array[middle] < element) start_index = middle + 1; else end_index = middle - 1; } return -1; } int main(void){ int array[] = {1, 4, 7, 9, 16, 56, 70}; int n = 7; int element = 16; int found_index = iterativeBinarySearch(array, 0, n-1, element); if(found_index == -1 ) { printf("Element not found in the array "); } else { printf("Element found at index : %d",found_index); } return 0; }
the_stack_data/225143177.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int cnt = 0; int fib(int n) { cnt++; if(0 == n) return 1; else if(1 == n) return 2; else return fib(n-1) + fib(n-2); } int func1(long x) { int ret = 0; if(x&(x-1)) { ret = 0; } else { ret = 1; } return ret; } int func2(long x) { int i, ret = 0; unsigned char j; union { long x; unsigned char y[sizeof(long)]; } data; data.x = x; for(i=0; i<sizeof(long); i++) { j = data.y[i]; if(j==1 || j==2 || j==4 || j==8 || j==16 || j==32 || j==64 || j==128) { ret++; } else if(j != 0) { ret = 2; } } return 1==ret; } void test(int *p) { p = malloc(sizeof(int)*9); return ; } int main(int argc, char* argv[]) { int *p, array[10]; long d; if(argc == 2) { d = atol(argv[1]); } else { printf("input a number:"); scanf("%ld", &d); } printf("number: %ld\n", d); printf("func1 return: %d\n", func1(d)); printf("func2 return: %d\n", func2(d)); fib(8); printf("cnt: %d\n", cnt); printf("strlen: %lu\n", strlen("abc\101\0fghijk\0")); p = malloc(100); test(p); array[10] = 9; return 0; }
the_stack_data/1253379.c
char _version[] = "Version 3.0 Beta"; char _copyright[] = "Copyright (c) 1991 by Mark Williams Company, Northbrook, Illinois.";
the_stack_data/15762492.c
/* * simple-ls.c * Extremely low-power ls clone. * ./simple-ls . */ #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> void printOwner(char *name, struct stat sb) { struct passwd *pwd; pwd = getpwuid(sb.st_uid); printf("%s (%s)\n", name, pwd->pw_name); } int main(int argc, char **argv) { DIR *dp; struct dirent *dirp; if (argc != 2) { fprintf(stderr, "usage: %s dir_name\n", argv[0]); exit(1); } if ((dp = opendir(argv[1])) == NULL) { fprintf(stderr, "can't open '%s'\n", argv[1]); exit(1); } if (chdir(argv[1]) == -1) { fprintf(stderr, "can't chdir to '%s': %s\n", argv[1], strerror(errno)); exit(EXIT_FAILURE); } while ((dirp = readdir(dp)) != NULL) { struct stat sb; if (stat(dirp->d_name, &sb) == -1) { fprintf(stderr, "Can't stat %s: %s\n", dirp->d_name, strerror(errno)); continue; } printOwner(dirp->d_name, sb); } closedir(dp); return(0); }
the_stack_data/763679.c
/* <:copyright-BRCM:2016-2020:Apache:standard Copyright (c) 2016-2020 Broadcom. All Rights Reserved The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries 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. :> */ #ifdef ENABLE_LOG #include "bcm_dev_log_task.h" #include "bcm_dev_log_task_internal.h" #include "bcm_dev_log.h" #if defined(LINUX_KERNEL_SPACE) && !defined(__KERNEL__) #include "bcmos_mgmt_type.h" #include "bcmolt_dev_log_linux.h" #include "bcmolt_dev_log_linux_ud.h" #endif #ifdef DEV_LOG_SYSLOG #include <syslog.h> #endif #define USE_ANSI_ESCAPE_CODES #ifdef USE_ANSI_ESCAPE_CODES #define DEV_LOG_STYLE_NORMAL "\033[0m\033#5" #define DEV_LOG_STYLE_BOLD "\033[1m" #define DEV_LOG_STYLE_UNDERLINE "\033[4m" #define DEV_LOG_STYLE_BLINK "\033[5m" #define DEV_LOG_STYLE_REVERSE_VIDEO "\033[7m" #else #define DEV_LOG_STYLE_NORMAL " " #define DEV_LOG_STYLE_BOLD "*** " #define DEV_LOG_STYLE_UNDERLINE "___ " #define DEV_LOG_STYLE_BLINK "o_o " #define DEV_LOG_STYLE_REVERSE_VIDEO "!!! " #endif #define DEV_LOG_MSG_START_CHAR 0x1e /* record separator character */ #define MEM_FILE_HDR_SIZE sizeof(dev_log_mem_file_header) #define LOG_MIN(a,b) (((int)(a) <= (int)(b)) ? (a) : (b)) dev_log_id def_log_id; static int default_write_callback_unprotected(bcm_dev_log_file *file, const void *buf, uint32_t length); static bcm_dev_log_style dev_log_level2style[DEV_LOG_LEVEL_NUM_OF] = { [DEV_LOG_LEVEL_FATAL] = BCM_DEV_LOG_STYLE_NORMAL, [DEV_LOG_LEVEL_ERROR] = BCM_DEV_LOG_STYLE_NORMAL, [DEV_LOG_LEVEL_WARNING] = BCM_DEV_LOG_STYLE_NORMAL, [DEV_LOG_LEVEL_INFO] = BCM_DEV_LOG_STYLE_NORMAL, [DEV_LOG_LEVEL_DEBUG] = BCM_DEV_LOG_STYLE_NORMAL, }; static const char *dev_log_style_array[] = { [BCM_DEV_LOG_STYLE_NORMAL] = DEV_LOG_STYLE_NORMAL, [BCM_DEV_LOG_STYLE_BOLD] = DEV_LOG_STYLE_BOLD, [BCM_DEV_LOG_STYLE_UNDERLINE] = DEV_LOG_STYLE_UNDERLINE, [BCM_DEV_LOG_STYLE_BLINK] = DEV_LOG_STYLE_BLINK, [BCM_DEV_LOG_STYLE_REVERSE_VIDEO] = DEV_LOG_STYLE_REVERSE_VIDEO, }; bcm_dev_log dev_log = {{0}}; const char *log_level_str = "?FEWID"; #ifdef ENABLE_CLI static uint32_t _log_id_enum_len = 0; bcmcli_enum_val bcm_dev_log_cli_log_id_enum[DEV_LOG_MAX_IDS + 1]; #endif static void bcm_dev_log_shutdown_msg_release(bcmos_msg *m) { (void)m; /* do nothing, the message is statically allocated */ } static bcmos_msg shutdown_msg = { .release = bcm_dev_log_shutdown_msg_release }; static void bcm_dev_log_file_save_msg(bcm_dev_log_file *files, const char *message) { uint32_t i; uint32_t len = strlen(message) + 1; /* including 0 terminator */ for (i = 0; (i < DEV_LOG_MAX_FILES) && (files[i].file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID); i++) { files[i].file_parm.write_cb(&files[i], message, len); } } static void dev_log_save_task_format_message(dev_log_queue_msg *receive_msg, char *log_string, uint32_t log_string_size, ...) { uint32_t length; char time_str[17]; dev_log_id_parm *log_id = receive_msg->log_id; bcm_dev_log_level msg_level = receive_msg->msg_level; /* Build message header */ *log_string = '\0'; if (!(receive_msg->flags & BCM_LOG_FLAG_NO_HEADER)) { length = sizeof(time_str); dev_log.dev_log_parm.time_to_str_cb(receive_msg->time_stamp, time_str, length); snprintf( log_string, log_string_size, "[%s: %c %-20s] ", time_str, log_level_str[msg_level], log_id->name); } /* Modify the __FILE__ format so it would print the filename only without the path. * If using BCM_LOG_FLAG_CALLER_FMT, it is done in caller context, because filename might be long, taking a lot of * the space of the message itself. */ if ((receive_msg->flags & BCM_LOG_FLAG_FILENAME_IN_FMT) && !(receive_msg->flags & BCM_LOG_FLAG_CALLER_FMT)) { /* coverity[misra_violation] - cross-assignment under union is OK - they're both in the same union member */ receive_msg->u.fmt_args.fmt = dev_log_basename(receive_msg->u.fmt_args.fmt); } if (receive_msg->flags & BCM_LOG_FLAG_CALLER_FMT) { /* Copy user string to buffer */ strncat(log_string, receive_msg->u.str, log_string_size - strlen(log_string) - 1); } else { uint32_t offset = ((long)receive_msg->u.fmt_args.args % 8 == 0) ? 0 : 1; /* start on an 8-byte boundary */ #ifndef COMPILATION_32_BIT /* NOTE: why do we use so terrible input: * It is impossible to send va_list structure from bcm_dev_log.c. So we send array of arguments only. * The va_list maintains pointers to temporary memory on the stack. * After the function with variable args has returned, this automatic storage is gone and the contents are no longer usable. * Because of this, we cannot simply keep a copy of the va_list itself - the memory it references will contain unpredictable content. * In addition internal struct va_list is different in 64-bit and 32-bit, in ARM, in posix etc., so we cannot assume what exactly its fields contain */ snprintf(log_string + strlen(log_string), log_string_size - strlen(log_string), receive_msg->u.fmt_args.fmt, receive_msg->u.fmt_args.args[offset], receive_msg->u.fmt_args.args[offset+1], receive_msg->u.fmt_args.args[offset+2], receive_msg->u.fmt_args.args[offset+3], receive_msg->u.fmt_args.args[offset+4], receive_msg->u.fmt_args.args[offset+5], receive_msg->u.fmt_args.args[offset+6], receive_msg->u.fmt_args.args[offset+7], receive_msg->u.fmt_args.args[offset+8], receive_msg->u.fmt_args.args[offset+9], receive_msg->u.fmt_args.args[offset+10], receive_msg->u.fmt_args.args[offset+11], receive_msg->u.fmt_args.args[offset+12], receive_msg->u.fmt_args.args[offset+13], receive_msg->u.fmt_args.args[offset+14], receive_msg->u.fmt_args.args[offset+15], receive_msg->u.fmt_args.args[offset+16], receive_msg->u.fmt_args.args[offset+17], receive_msg->u.fmt_args.args[offset+18], receive_msg->u.fmt_args.args[offset+19], receive_msg->u.fmt_args.args[offset+20], receive_msg->u.fmt_args.args[offset+21], receive_msg->u.fmt_args.args[offset+22], receive_msg->u.fmt_args.args[offset+23], receive_msg->u.fmt_args.args[offset+24], receive_msg->u.fmt_args.args[offset+25], receive_msg->u.fmt_args.args[offset+26], receive_msg->u.fmt_args.args[offset+27], receive_msg->u.fmt_args.args[offset+28], receive_msg->u.fmt_args.args[offset+29], receive_msg->u.fmt_args.args[offset+30], receive_msg->u.fmt_args.args[offset+31], receive_msg->u.fmt_args.args[offset+32], receive_msg->u.fmt_args.args[offset+33], receive_msg->u.fmt_args.args[offset+34], receive_msg->u.fmt_args.args[offset+35]); #else va_list ap; *(void **)&ap = &receive_msg->u.fmt_args.args[offset]; /* Copy user string to buffer */ vsnprintf(log_string + strlen(log_string), log_string_size - strlen(log_string), receive_msg->u.fmt_args.fmt, ap); #endif } /* Force last char to be end of string */ log_string[MAX_DEV_LOG_STRING_SIZE - 1] = '\0'; } static void dev_log_save_task_handle_message(bcmos_msg *msg) { static char log_string[MAX_DEV_LOG_STRING_SIZE]; dev_log_queue_msg *receive_msg = msg->data; dev_log_id_parm *log_id = receive_msg->log_id; bcm_dev_log_level msg_level = receive_msg->msg_level; dev_log_save_task_format_message(receive_msg, log_string, sizeof(log_string)); /* At this point, if the message is going to be sent to the print task, save the formatted string then forward it. * Otherwise, we can release the message before writing it to RAM. */ if ((log_id->log_type & DEV_LOG_ID_TYPE_PRINT) && (msg_level <= log_id->log_level_print)) { if (!bcm_dev_log_level_is_error(msg_level) && (receive_msg->flags & BCM_LOG_FLAG_DONT_SKIP_PRINT) != 0 && bcm_dev_log_pool_occupancy_percent_get() >= DEV_LOG_SKIP_PRINT_THRESHOLD_PERCENT) { log_id->print_skipped_count++; bcmos_msg_free(msg); } else { strcpy(receive_msg->u.str, log_string); /* so the print task doesn't need to re-format it */ bcmos_msg_send(&dev_log.print_queue, msg, BCMOS_MSG_SEND_AUTO_FREE); } } else { bcmos_msg_free(msg); } /* Save to file */ if ((log_id->log_type & DEV_LOG_ID_TYPE_SAVE) && (msg_level <= log_id->log_level_save)) { bcm_dev_log_file_save_msg(dev_log.files, log_string); } } static void dev_log_print_task_handle_message(bcmos_msg *msg) { static char log_string[MAX_DEV_LOG_STRING_SIZE]; dev_log_queue_msg *receive_msg = msg->data; dev_log_id_parm *log_id = receive_msg->log_id; bcm_dev_log_level msg_level = receive_msg->msg_level; /* make a local copy of the pre-formatted string (it was formatted in the save task) */ strcpy(log_string, receive_msg->u.str); /* free the message ASAP since printing might take some time */ bcmos_msg_free(msg); if (log_id->style == BCM_DEV_LOG_STYLE_NORMAL && dev_log_level2style[msg_level] == BCM_DEV_LOG_STYLE_NORMAL) { dev_log.dev_log_parm.print_cb(dev_log.dev_log_parm.print_cb_arg, "%s", log_string); } else { /* If style was set per log id, then use it. */ if (log_id->style != BCM_DEV_LOG_STYLE_NORMAL) { dev_log.dev_log_parm.print_cb( dev_log.dev_log_parm.print_cb_arg, "%s%s%s", dev_log_style_array[log_id->style], log_string, dev_log_style_array[BCM_DEV_LOG_STYLE_NORMAL]); } else { /* Otherwise - style was set per log level. */ dev_log.dev_log_parm.print_cb( dev_log.dev_log_parm.print_cb_arg, "%s%s%s", dev_log_style_array[dev_log_level2style[msg_level]], log_string, dev_log_style_array[BCM_DEV_LOG_STYLE_NORMAL]); } } } static int dev_log_print_task(long data) { bcmos_msg *m; bcmos_errno error; const char error_str[MAX_DEV_LOG_STRING_SIZE] = "Error: Can't receive from queue - dev_log print task exit\n"; while (1) { error = bcmos_msg_recv(&dev_log.print_queue, BCMOS_WAIT_FOREVER, &m); if (error != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("%s", error_str); dev_log.dev_log_parm.print_cb(dev_log.dev_log_parm.print_cb_arg, "%s", error_str); bcm_dev_log_file_save_msg(dev_log.files, error_str); return (int)error; } if (m == &shutdown_msg) { break; /* shut down gracefully */ } else { dev_log_print_task_handle_message(m); } } bcmos_sem_post(&dev_log.print_task_is_terminated); return 0; } static int dev_log_save_task(long data) { bcmos_msg *m; bcmos_errno error; const char error_str[MAX_DEV_LOG_STRING_SIZE] = "Error: Can't receive from queue - dev_log save task exit\n"; while (1) { error = bcmos_msg_recv(&dev_log.save_queue, BCMOS_WAIT_FOREVER, &m); if (error != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("%s", error_str); dev_log.dev_log_parm.print_cb(dev_log.dev_log_parm.print_cb_arg, "%s", error_str); bcm_dev_log_file_save_msg(dev_log.files, error_str); return (int)error; } if (m == &shutdown_msg) { break; /* shut down gracefully */ } else { dev_log_save_task_handle_message(m); } } bcmos_sem_post(&dev_log.save_task_is_terminated); return 0; } extern const char * last_format; void dev_log_oops_complete_cb(void) { bcmos_msg *m; uint32_t i; if (last_format) { printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! last format %s \n ",last_format); } /* We start traversing print queue. Those are already formatted messages that were forwarded from the save task. * Then we proceed to traversing save queue. Those are messages that haven't reached the print task yet. * We read from queue with timeout=0, meaning non-blocking call (we cannot wait in oops time - all OS services are down). */ while (bcmos_msg_recv(&dev_log.print_queue, 0, &m) == BCM_ERR_OK) dev_log_print_task_handle_message(m); for (i = 0; (i < DEV_LOG_MAX_FILES) && (dev_log.files[i].file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID); i++) { if (dev_log.files[i].file_parm.type == BCM_DEV_LOG_FILE_MEMORY) dev_log.files[i].file_parm.write_cb = default_write_callback_unprotected; /* Avoid bcmos_mutex_lock()/bcmos_mutex_unlock() in regular (protected) version. */ } while (bcmos_msg_recv(&dev_log.save_queue, 0, &m) == BCM_ERR_OK) { static char log_string[MAX_DEV_LOG_STRING_SIZE]; dev_log_queue_msg *receive_msg; dev_log_id_parm *log_id; bcm_dev_log_level msg_level; receive_msg = m->data; log_id = receive_msg->log_id; msg_level = receive_msg->msg_level; dev_log_save_task_format_message(receive_msg, log_string, sizeof(log_string)); if ((log_id->log_type & DEV_LOG_ID_TYPE_PRINT) && (msg_level <= log_id->log_level_print)) { strcpy(receive_msg->u.str, log_string); dev_log_print_task_handle_message(m); } else { bcmos_msg_free(m); } /* Save to file */ if ((log_id->log_type & DEV_LOG_ID_TYPE_SAVE) && (msg_level <= log_id->log_level_save)) { bcm_dev_log_file_save_msg(dev_log.files, log_string); } } } static int default_time_to_str(uint32_t time_stamp, char *time_str, int time_str_size) { return snprintf(time_str, time_str_size, "%u", time_stamp); } static uint32_t default_get_time(void) { return 0; } static void default_print(void *arg, const char *format, ...) { va_list args; va_start(args, format); bcmos_vprintf(format, args); va_end(args); } static bcmos_errno default_open_callback_cond_reset(const bcm_dev_log_file_parm *file_parm, bcm_dev_log_file *file, bcmos_bool is_rewind) { bcmos_errno err; if (!file->file_parm.start_addr || file->file_parm.size <= MEM_FILE_HDR_SIZE) return BCM_ERR_PARM; /* Create file mutex */ err = bcmos_mutex_create(&file->u.mem_file.mutex, 0, NULL); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't create mutex (error: %d)\n", (int)err); return err; } /* Check file magic string */ memcpy(&file->u.mem_file.file_header, (uint8_t *)file->file_parm.start_addr, MEM_FILE_HDR_SIZE); if (memcmp(FILE_MAGIC_STR, file->u.mem_file.file_header.file_magic, FILE_MAGIC_STR_SIZE)) { DEV_LOG_INFO_PRINTF("No file magic string - file is empty/corrupt\n"); if (!is_rewind || !file->file_parm.rewind_cb) { bcmos_mutex_destroy(&file->u.mem_file.mutex); return BCM_ERR_NOENT; } return file->file_parm.rewind_cb(file); } DEV_LOG_INFO_PRINTF("Attached to existing file\n"); return BCM_ERR_OK; } static bcmos_errno default_open_callback(const bcm_dev_log_file_parm *file_parm, bcm_dev_log_file *file) { return default_open_callback_cond_reset(file_parm, file, BCMOS_TRUE); } static bcmos_errno default_close_callback(bcm_dev_log_file *file) { bcmos_mutex_destroy(&file->u.mem_file.mutex); return BCM_ERR_OK; } /* Look for start of msg character */ static int get_msg_start_offset(bcm_dev_log_file *file, uint32_t offset, uint32_t max_len) { uint8_t *buf, *msg; buf = (uint8_t *)file->file_parm.start_addr + offset + MEM_FILE_HDR_SIZE; msg = memchr(buf, DEV_LOG_MSG_START_CHAR, max_len); if (!msg) return -1; return (msg - buf + 1); } /* Look for 0-terminator */ static int get_msg_end_offset(bcm_dev_log_file *file, uint32_t offset, uint32_t max_len) { uint8_t *buf, *end; buf = (uint8_t *)file->file_parm.start_addr + offset + MEM_FILE_HDR_SIZE; end = memchr(buf, 0, max_len); if (!end) return -1; return (end - buf + 1); } static int default_read_callback(bcm_dev_log_file *log_file, uint32_t *p_offset, void *buf, uint32_t length) { uint32_t offset = *p_offset; uint32_t output_length = 0; uint32_t scan_length = 0; int start, end; bcmos_bool read_wrap = BCMOS_FALSE; /* If file wrapped around, offset is indeterminate, scan for start from current offset to end of file buffer, * if start not found, then try again from beginning of buffer up to write ptr */ if (log_file->u.mem_file.file_header.file_wrap_cnt) { scan_length = log_file->u.mem_file.file_header.data_size - offset; if (scan_length <= 0) { /* Insane offset passed in from user, reset it */ DEV_LOG_ERROR_PRINTF("%s: reset bad read offset:%d (> size of log buffer)\n", __FUNCTION__, offset); *p_offset = 0; return 0; } /* Find beginning of the next message */ start = get_msg_start_offset(log_file, offset, scan_length); if (start < 0) { /* Didn't find any up to the end of buffer. Scan again from the start, up to write offset */ offset = 0; if (!log_file->u.mem_file.file_header.write_offset) return 0; start = get_msg_start_offset(log_file, 0, log_file->u.mem_file.file_header.write_offset - 1); if (start <= 0) { return 0; } } } else { /* file not wrapped, scan from current offset up to write ptr */ scan_length = log_file->u.mem_file.file_header.write_offset - offset; /* Scan for start of message. Without wrap-around it should be between read offset, and the write ptr */ start = get_msg_start_offset(log_file, offset, scan_length); if (start <= 0) return 0; } offset += start; /* We have the beginning. Now find the end of message and copy to the user buffer if there is enough room */ if (offset + length > log_file->u.mem_file.file_header.data_size) { /* Possible read wrap may occur, scan up to end of file buffer first */ scan_length = log_file->u.mem_file.file_header.data_size - offset; end = get_msg_end_offset(log_file, offset, scan_length); if (end >= 0) { /* Found end before end of buffer, no read wrap, just copy and return */ memcpy(buf, (uint8_t *)log_file->file_parm.start_addr + MEM_FILE_HDR_SIZE + offset, end); *p_offset += start + end; return end; } /* Didn't find end of message in the end of file buffer. Copy first part from offset up to end of buffer, then wrap around */ memcpy(buf, (uint8_t *)log_file->file_parm.start_addr + MEM_FILE_HDR_SIZE + offset, scan_length); output_length = scan_length; buf = (uint8_t *)buf + scan_length; length -= scan_length; /* reduce remaining buffer space by size copied */ offset = 0; /* Reset to beginning of buffer for final "end" scan */ read_wrap = BCMOS_TRUE; scan_length = log_file->u.mem_file.file_header.write_offset - 1; /* Limit wrapped end scan from beginning of buffer up to write ptr */ } else { /* No read wrap, just scan for end from current offset to the end of the file , since the end might be past the buffer length */ scan_length = log_file->u.mem_file.file_header.data_size - offset; } end = get_msg_end_offset(log_file, offset, scan_length); if (end <= 0) { /* something is wrong. msg is not terminated */ DEV_LOG_ERROR_PRINTF("%s: no message end found!\n", __FUNCTION__); return 0; } /* If there is no room for the whole message - return overflow */ if (end > length) return (int)BCM_ERR_OVERFLOW; /* Copy whole message, or second part for wrapped read */ memcpy(buf, (uint8_t *)log_file->file_parm.start_addr + MEM_FILE_HDR_SIZE + offset, end); output_length += end; if (read_wrap) { *p_offset = end; } else *p_offset += start + output_length; /* Increment read ptr */ return output_length; } static int get_num_of_overwritten_messages(uint8_t *buf, uint32_t length) { uint8_t *p; int n = 0; do { p = memchr(buf, DEV_LOG_MSG_START_CHAR, length); if (p == NULL) break; ++n; length -= (p + 1 - buf); buf = p + 1; } while(length); return n; } static int default_write_callback_unprotected(bcm_dev_log_file *file, const void *buf, uint32_t length) { uint32_t offset, next_offset; uint8_t *p; int n_overwritten = 0; if ((file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_STOP_WHEN_FULL) && file->is_full) return 0; if (!length) return 0; offset = file->u.mem_file.file_header.write_offset; next_offset = offset + length + 1; /* 1 extra character for record delimiter */ /* Handle overflow */ if (next_offset >= file->u.mem_file.file_header.data_size) { uint32_t tail_length; /* Split buffer in 2 */ tail_length = next_offset - file->u.mem_file.file_header.data_size; /* 2nd segment length */ if ((file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_STOP_WHEN_FULL) && tail_length) { file->is_full = BCMOS_TRUE; return 0; } length -= tail_length; /* "if (next_offset >= file->u.mem_file.file_header.data_size)" condition * guarantees that there is room for at least 1 character in the end of file */ p = (uint8_t *)file->file_parm.start_addr + offset + MEM_FILE_HDR_SIZE; if (file->u.mem_file.file_header.file_wrap_cnt) n_overwritten += get_num_of_overwritten_messages(p, length + 1); *p = DEV_LOG_MSG_START_CHAR; if (length) { memcpy(p + 1, buf, length); buf = (const uint8_t *)buf + length; } if (tail_length) { p = (uint8_t *)file->file_parm.start_addr + MEM_FILE_HDR_SIZE; if (file->u.mem_file.file_header.file_wrap_cnt) n_overwritten += get_num_of_overwritten_messages(p, tail_length); memcpy(p, buf, tail_length); ++file->u.mem_file.file_header.file_wrap_cnt; } next_offset = tail_length; } else { p = (uint8_t *)file->file_parm.start_addr + MEM_FILE_HDR_SIZE + offset; if (file->u.mem_file.file_header.file_wrap_cnt) n_overwritten += get_num_of_overwritten_messages(p, length + 1); *(p++) = DEV_LOG_MSG_START_CHAR; memcpy(p, buf, length); } file->u.mem_file.file_header.write_offset = next_offset; file->u.mem_file.file_header.num_msgs += (1 - n_overwritten); /* update the header */ memcpy((uint8_t *)file->file_parm.start_addr, &file->u.mem_file.file_header, MEM_FILE_HDR_SIZE); /* send almost full indication if necessary */ if (file->almost_full.send_ind_cb && !file->almost_full.ind_sent && file->u.mem_file.file_header.write_offset > file->almost_full.threshold) { file->almost_full.ind_sent = (file->almost_full.send_ind_cb(file->almost_full.priv) == BCM_ERR_OK); } return length; } static int default_write_callback(bcm_dev_log_file *file, const void *buf, uint32_t length) { bcmos_mutex_lock(&file->u.mem_file.mutex); length = default_write_callback_unprotected(file, buf, length); bcmos_mutex_unlock(&file->u.mem_file.mutex); return length; } static bcmos_errno default_rewind_callback(bcm_dev_log_file *file) { bcmos_mutex_lock(&file->u.mem_file.mutex); DEV_LOG_INFO_PRINTF("Clear file\n"); file->u.mem_file.file_header.file_wrap_cnt = 0; file->u.mem_file.file_header.write_offset = 0; file->u.mem_file.file_header.data_size = file->file_parm.size - MEM_FILE_HDR_SIZE; file->u.mem_file.file_header.num_msgs = 0; strcpy(file->u.mem_file.file_header.file_magic, FILE_MAGIC_STR); memcpy((uint8_t *)file->file_parm.start_addr, &file->u.mem_file.file_header, MEM_FILE_HDR_SIZE); file->almost_full.ind_sent = BCMOS_FALSE; bcmos_mutex_unlock(&file->u.mem_file.mutex); return BCM_ERR_OK; } static void set_default_file_callbacks(bcm_dev_log_file *file) { file->file_parm.open_cb = default_open_callback; file->file_parm.close_cb = default_close_callback; file->file_parm.read_cb = default_read_callback; file->file_parm.write_cb = default_write_callback; file->file_parm.rewind_cb = default_rewind_callback; } static inline bcmos_bool bcm_dev_log_is_memory_file(bcm_dev_log_file *file) { return (file->file_parm.open_cb == default_open_callback); } bcmos_errno bcm_dev_log_file_clear(bcm_dev_log_file *file) { if (!file || !(file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID)) return BCM_ERR_PARM; if (!file->file_parm.rewind_cb) return BCM_ERR_NOT_SUPPORTED; return file->file_parm.rewind_cb(file); } /* File index to file handle */ bcm_dev_log_file *bcm_dev_log_file_get(uint32_t file_index) { bcm_dev_log_file *file = &dev_log.files[file_index]; if ((file_index >= DEV_LOG_MAX_FILES) || !(file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID)) return NULL; return file; } /* Read from file */ int bcm_dev_log_file_read(bcm_dev_log_file *file, uint32_t *offset, char *buf, uint32_t buf_len) { int len; if (!file || !buf || !(file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID)) return (int)BCM_ERR_PARM; len = file->file_parm.read_cb(file, offset, buf, buf_len); /* If nothing more to read and CLEAR_AFTER_READ mode, read again under lock and clear if no new records */ if (!len && bcm_dev_log_is_memory_file(file) && (file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_CLEAR_AFTER_READ)) { bcmos_mutex_lock(&file->u.mem_file.mutex); len = file->file_parm.read_cb(file, offset, buf, buf_len); if (!len) { file->file_parm.rewind_cb(file); *offset = 0; /* Also reset user read ptr when log file is cleared down! */ } bcmos_mutex_unlock(&file->u.mem_file.mutex); } return len; } /* Attach file to memory buffer */ bcmos_errno bcm_dev_log_file_attach(void *buf, uint32_t buf_len, bcm_dev_log_file *file) { bcmos_errno rc; dev_log_mem_file_header *hdr = (dev_log_mem_file_header *)buf; if (!buf || !file || buf_len <= MEM_FILE_HDR_SIZE) return BCM_ERR_PARM; if (memcmp(FILE_MAGIC_STR, hdr->file_magic, FILE_MAGIC_STR_SIZE)) return BCM_ERR_NOENT; #if DEV_LOG_ENDIAN != BCM_CPU_ENDIAN hdr->file_wrap_cnt = bcmos_endian_swap_u32(hdr->file_wrap_cnt); hdr->write_offset = bcmos_endian_swap_u32(hdr->write_offset); hdr->data_size = bcmos_endian_swap_u32(hdr->data_size); hdr->num_msgs = bcmos_endian_swap_u32(hdr->num_msgs); #endif memset(file, 0, sizeof(*file)); file->file_parm.start_addr = buf; file->file_parm.size = buf_len; file->file_parm.flags = BCM_DEV_LOG_FILE_FLAG_VALID; set_default_file_callbacks(file); rc = default_open_callback_cond_reset(&file->file_parm, file, BCMOS_FALSE); if (rc) return rc; if (!file->u.mem_file.file_header.num_msgs) return BCM_ERR_NOENT; return BCM_ERR_OK; } /* Detach file handle from memory buffer */ bcmos_errno bcm_dev_log_file_detach(bcm_dev_log_file *file) { if (!file || !(file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID)) return BCM_ERR_PARM; file->file_parm.flags = BCM_DEV_LOG_FILE_FLAG_VALID; bcmos_mutex_destroy(&file->u.mem_file.mutex); return BCM_ERR_OK; } #ifdef BCM_OS_POSIX /* Regular file callbacks */ /****************************************************************************************/ /* OPEN CALLBACK: open memory/file */ /* file_parm - file parameters */ /* file - file */ /****************************************************************************************/ static bcmos_errno _dev_log_reg_file_open(const bcm_dev_log_file_parm *file_parm, bcm_dev_log_file *file) { bcmos_errno err = BCM_ERR_OK; file->file_parm = *file_parm; file->u.reg_file_handle = fopen((char *)file_parm->udef_parms, "w+"); if (!file->u.reg_file_handle) { bcmos_printf("DEV_LOG: can't open file %s for writing\n", (char *)file_parm->udef_parms); err = BCM_ERR_IO; } return err; } /****************************************************************************************/ /* CLOSE CALLBACK: close memory/file */ /* file - file handle */ /****************************************************************************************/ static bcmos_errno _dev_log_reg_file_close(bcm_dev_log_file *file) { if (file->u.reg_file_handle) { fclose(file->u.reg_file_handle); /* coverity[misra_violation] - we're not "using" the closed file handle, we're invalidating it */ file->u.reg_file_handle = NULL; } return BCM_ERR_OK; } /****************************************************************************************/ /* REWIND CALLBACK: clears memory/file */ /* file - file handle */ /****************************************************************************************/ static bcmos_errno _dev_log_reg_file_rewind(bcm_dev_log_file *file) { bcmos_errno err = BCM_ERR_OK; FILE *f; if (file->u.reg_file_handle) { f = freopen((const char *)file->file_parm.udef_parms, "w+", file->u.reg_file_handle); if (NULL != f) { file->u.reg_file_handle = f; } else { err = BCM_ERR_IO; bcmos_printf("DEV_LOG: can't open file %s for writing\n", (char *)file->file_parm.udef_parms); } } return err; } /****************************************************************************************/ /* READ_CALLBACK: read form memory/file */ /* offset - the offset in bytes to read from, output */ /* buf - Where to put the result */ /* length - Buffer length */ /* This function should return the number of bytes actually read from file or 0 if EOF */ /****************************************************************************************/ static int _dev_log_reg_file_read(bcm_dev_log_file *file, uint32_t *offset, void *buf, uint32_t length) { int n = 0; if (file->u.reg_file_handle) { if (!fseek(file->u.reg_file_handle, SEEK_SET, *offset)) n = fread(buf, 1, length, file->u.reg_file_handle); *offset = ftell(file->u.reg_file_handle); } return (n < 0) ? 0 : n; } /****************************************************************************************/ /* WRITE_CALLBACK: write form memory/file */ /* buf - The buffer that should be written */ /* length - The number of bytes to write */ /* This function should return the number of bytes actually written to file or 0 if EOF */ /****************************************************************************************/ static int _dev_log_reg_file_write(bcm_dev_log_file *file, const void *buf, uint32_t length) { const char *cbuf = (const char *)buf; int n = 0; if (file->u.reg_file_handle) { /* Remove 0 terminator */ if (length && !cbuf[length-1]) --length; n = fwrite(buf, 1, length, file->u.reg_file_handle); fflush(file->u.reg_file_handle); } return n; } static void set_regular_file_callbacks(bcm_dev_log_file *file) { file->file_parm.open_cb = _dev_log_reg_file_open; file->file_parm.close_cb = _dev_log_reg_file_close; file->file_parm.read_cb = _dev_log_reg_file_read; file->file_parm.write_cb = _dev_log_reg_file_write; file->file_parm.rewind_cb = _dev_log_reg_file_rewind; } #endif /* #ifdef BCM_OS_POSIX */ #ifdef DEV_LOG_SYSLOG /* linux syslog integration */ /****************************************************************************************/ /* OPEN CALLBACK: open syslog interface */ /* file_parm->udef_parm contains optional log ident */ /****************************************************************************************/ static bcmos_errno _dev_log_syslog_file_open(const bcm_dev_log_file_parm *file_parm, bcm_dev_log_file *file) { file->file_parm = *file_parm; openlog((const char *)file_parm->udef_parms, 0, LOG_USER); return BCM_ERR_OK; } /****************************************************************************************/ /* CLOSE CALLBACK: close syslog interface */ /****************************************************************************************/ static bcmos_errno _dev_log_syslog_file_close(bcm_dev_log_file *file) { closelog(); return BCM_ERR_OK; } /****************************************************************************************/ /* REWIND CALLBACK: not supported by syslog. Return OK to prevent request failure */ /****************************************************************************************/ static bcmos_errno _dev_log_syslog_file_rewind(bcm_dev_log_file *file) { return BCM_ERR_OK; } /****************************************************************************************/ /* READ_CALLBACK: reading from syslog is not supported */ /****************************************************************************************/ static int _dev_log_syslog_file_read(bcm_dev_log_file *file, uint32_t *offset, void *buf, uint32_t length) { return 0; } /****************************************************************************************/ /* WRITE_CALLBACK: write to syslog */ /* buf - The buffer that should be written */ /* length - The number of bytes to write */ /* This function should return the number of bytes actually written to file or 0 if EOF */ /****************************************************************************************/ static int _dev_log_syslog_file_write(bcm_dev_log_file *file, const void *buf, uint32_t length) { const char *cbuf = (const char *)buf; static int log_priority = LOG_DEBUG; /* Identify log lovel */ if (cbuf && cbuf[0] == '[') { const char *clevel = strchr(cbuf, ' '); if (clevel) { switch (*(clevel + 1)) { case 'F': log_priority = LOG_CRIT; break; case 'E': log_priority = LOG_ERR; break; case 'W': log_priority = LOG_WARNING; break; case 'I': log_priority = LOG_INFO; break; case 'D': log_priority = LOG_DEBUG; break; default: break; } } } syslog(log_priority, "%s", cbuf); return length; } static void set_syslog_file_callbacks(bcm_dev_log_file *file) { file->file_parm.open_cb = _dev_log_syslog_file_open; file->file_parm.close_cb = _dev_log_syslog_file_close; file->file_parm.read_cb = _dev_log_syslog_file_read; file->file_parm.write_cb = _dev_log_syslog_file_write; file->file_parm.rewind_cb = _dev_log_syslog_file_rewind; } #endif /* #ifdef DEV_LOG_SYSLOG */ static bcmos_errno bcm_dev_log_create( const bcm_dev_log_parm *dev_log_parm, const bcmos_task_parm *save_task_parm, const bcmos_task_parm *print_task_parm, const bcmos_msg_queue_parm *save_queue_parm, const bcmos_msg_queue_parm *print_queue_parm, const bcmos_msg_pool_parm *pool_parm) { bcmos_errno err; int i; if (!dev_log_parm) return BCM_ERR_PARM; if (dev_log.state != BCM_DEV_LOG_STATE_UNINITIALIZED) return BCM_ERR_ALREADY; /* Set user callbacks */ dev_log.dev_log_parm = *dev_log_parm; if (!dev_log.dev_log_parm.print_cb) dev_log.dev_log_parm.print_cb = default_print; if (!dev_log.dev_log_parm.get_time_cb) dev_log.dev_log_parm.get_time_cb = default_get_time; if (!dev_log.dev_log_parm.time_to_str_cb) dev_log.dev_log_parm.time_to_str_cb = default_time_to_str; for (i = 0; (i < DEV_LOG_MAX_FILES) && (dev_log_parm->log_file[i].flags & BCM_DEV_LOG_FILE_FLAG_VALID); i++) { /* Copy log files */ dev_log.files[i].file_parm = dev_log_parm->log_file[i]; if (!dev_log.files[i].file_parm.open_cb) { if (dev_log.files[i].file_parm.type == BCM_DEV_LOG_FILE_MEMORY) set_default_file_callbacks(&dev_log.files[i]); #ifdef BCM_OS_POSIX else if (dev_log.files[i].file_parm.type == BCM_DEV_LOG_FILE_REGULAR) { set_regular_file_callbacks(&dev_log.files[i]); } #endif #ifdef DEV_LOG_SYSLOG else if (dev_log.files[i].file_parm.type == BCM_DEV_LOG_FILE_SYSLOG) set_syslog_file_callbacks(&dev_log.files[i]); #endif else { DEV_LOG_ERROR_PRINTF("file%d: open_cb must be set for user-defined file\n\n", i); continue; } } err = dev_log.files[i].file_parm.open_cb(&dev_log.files[i].file_parm, &dev_log.files[i]); if (err) { DEV_LOG_ERROR_PRINTF("file%d: open failed: %s (%d)\n\n", i, bcmos_strerror(err), err ); continue; } DEV_LOG_INFO_PRINTF("file: start_addr: 0x%p, size: %u, max msg size %u\n", dev_log.files[i].file_parm.start_addr, dev_log.files[i].file_parm.size, MAX_DEV_LOG_STRING_SIZE); } /* Create pool */ err = bcmos_msg_pool_create(&dev_log.pool, pool_parm); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't create pool (error: %d)\n", (int)err); return err; } /* Create message queues */ err = bcmos_msg_queue_create(&dev_log.save_queue, save_queue_parm); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("(%s) Error: Can't create save queue (error: %d)\n", __FUNCTION__, (int)err); return err; } err = bcmos_msg_queue_create(&dev_log.print_queue, print_queue_parm); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("(%s) Error: Can't create print queue (error: %d)\n", __FUNCTION__, (int)err); return err; } /* Create tasks */ err = bcmos_task_create(&dev_log.save_task, save_task_parm); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't spawn save task (error: %d)\n", (int)err); return err; } err = bcmos_task_create(&dev_log.print_task, print_task_parm); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't spawn print task (error: %d)\n", (int)err); return err; } err = bcmos_sem_create(&dev_log.save_task_is_terminated, 0, 0, "save_task_sem"); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't create save task sem (error: %d)\n", (int)err); return err; } err = bcmos_sem_create(&dev_log.print_task_is_terminated, 0, 0, "print_task_sem"); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't create print task sem (error: %d)\n", (int)err); return err; } for (i = 0; i < DEV_LOG_MAX_GROUPS; i++) dev_log.group_ids[i] = DEV_LOG_INVALID_ID; dev_log.state = BCM_DEV_LOG_STATE_ENABLED; return BCM_ERR_OK; } void bcm_dev_log_destroy(void) { bcmos_errno err; uint32_t i; bcmos_msg_send_flags msg_flags; if (dev_log.state == BCM_DEV_LOG_STATE_UNINITIALIZED) { return; } /* Send a shutdown message to each task. When received by the main loops, it will tear down the tasks gracefully. * If the flag is set to tear down immediately, we'll send an URGENT teardown message, so it'll be handled before * all oustanding log messages (the oustanding log messages will be freed during bcmos_msg_queue_destroy). */ msg_flags = BCMOS_MSG_SEND_NOLIMIT; if ((dev_log.flags & BCM_DEV_LOG_FLAG_DESTROY_IMMEDIATELY) != 0) msg_flags |= BCMOS_MSG_SEND_URGENT; /* The save task depends on the print task, so we terminate the save task first. */ bcmos_msg_send(&dev_log.save_queue, &shutdown_msg, msg_flags); bcmos_sem_wait(&dev_log.save_task_is_terminated, BCMOS_WAIT_FOREVER); bcmos_msg_send(&dev_log.print_queue, &shutdown_msg, msg_flags); bcmos_sem_wait(&dev_log.print_task_is_terminated, BCMOS_WAIT_FOREVER); bcmos_sem_destroy(&dev_log.save_task_is_terminated); bcmos_sem_destroy(&dev_log.print_task_is_terminated); err = bcmos_task_destroy(&dev_log.save_task); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't destroy dev_log save task (error: %d)\n", (int)err); } err = bcmos_task_destroy(&dev_log.print_task); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't destroy dev_log print task (error: %d)\n", (int)err); } err = bcmos_msg_queue_destroy(&dev_log.save_queue); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't destroy save queue (error: %d)\n", (int)err); } err = bcmos_msg_queue_destroy(&dev_log.print_queue); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't destroy print queue (error: %d)\n", (int)err); } err = bcmos_msg_pool_destroy(&dev_log.pool); if (err != BCM_ERR_OK) { DEV_LOG_ERROR_PRINTF("Error: Can't destroy pool (error: %d)\n", (int)err); } for (i = 0; (i < DEV_LOG_MAX_FILES) && (dev_log.dev_log_parm.log_file[i].flags & BCM_DEV_LOG_FILE_FLAG_VALID); i++) { dev_log.files[i].file_parm.close_cb(&dev_log.files[i]); } dev_log.state = BCM_DEV_LOG_STATE_UNINITIALIZED; } typedef struct { bcmos_msg msg; dev_log_queue_msg log_queue_msg; bcmos_bool lock; bcmos_fastlock fastlock; } bcm_dev_log_drop_msg; typedef struct { bcm_dev_log_drop_msg msg; uint32_t drops; uint32_t reported_drops; bcmos_timer timer; uint32_t last_report_timestamp; } bcm_dev_log_drop; static bcm_dev_log_drop dev_log_drop; static void bcm_dev_log_log_message_release_drop(bcmos_msg *m) { unsigned long flags; flags = bcmos_fastlock_lock(&dev_log_drop.msg.fastlock); dev_log_drop.msg.lock = BCMOS_FALSE; bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags); /* Schedule a timer to report extra drops, because we may not meet DEV_LOG_DROP_REPORT_DROP_THRESHOLD soon. */ bcmos_timer_start(&dev_log_drop.timer, DEV_LOG_DROP_REPORT_RATE_US); } static void _bcm_dev_log_drop_report(void) { bcmos_msg *msg; dev_log_queue_msg *log_queue_msg; static char drop_str[MAX_DEV_LOG_STRING_SIZE]; msg = &dev_log_drop.msg.msg; msg->release = bcm_dev_log_log_message_release_drop; log_queue_msg = &dev_log_drop.msg.log_queue_msg; log_queue_msg->flags = BCM_LOG_FLAG_DONT_SKIP_PRINT; log_queue_msg->time_stamp = dev_log.dev_log_parm.get_time_cb(); log_queue_msg->msg_level = DEV_LOG_LEVEL_ERROR; sprintf(drop_str, "Log message pool exhausted, dropped message count=%u\n", dev_log_drop.drops - dev_log_drop.reported_drops); log_queue_msg->u.fmt_args.fmt = (const char *)drop_str; log_queue_msg->log_id = (dev_log_id_parm *)def_log_id; log_queue_msg->time_stamp = dev_log.dev_log_parm.get_time_cb(); dev_log_drop.reported_drops = dev_log_drop.drops; dev_log_drop.last_report_timestamp = bcmos_timestamp(); msg->data = log_queue_msg; msg->size = sizeof(*log_queue_msg); bcmos_msg_send(&dev_log.save_queue, msg, BCMOS_MSG_SEND_AUTO_FREE); } void bcm_dev_log_drop_report(void) { unsigned long flags; dev_log_drop.drops++; flags = bcmos_fastlock_lock(&dev_log_drop.msg.fastlock); /* The 1st drop report will be done immediately, because although DEV_LOG_DROP_REPORT_DROP_THRESHOLD isn't reached, the time difference is greater than * DEV_LOG_DROP_REPORT_RATE_US. */ if (dev_log_drop.msg.lock || ((dev_log_drop.drops - dev_log_drop.reported_drops < DEV_LOG_DROP_REPORT_DROP_THRESHOLD) && (bcmos_timestamp() - dev_log_drop.last_report_timestamp < DEV_LOG_DROP_REPORT_RATE_US))) { bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags); return; } dev_log_drop.msg.lock = BCMOS_TRUE; bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags); /* Do the actual report. */ _bcm_dev_log_drop_report(); } static bcmos_timer_rc bcm_dev_log_drop_timer_cb(bcmos_timer *timer, long data) { unsigned long flags; flags = bcmos_fastlock_lock(&dev_log_drop.msg.fastlock); if (dev_log_drop.msg.lock) { bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags); /* Logger task hasn't released the lock yet. * bcm_dev_log_log_message_release_drop() will (re)start drop reporting timer eventually. */ } else { if (dev_log_drop.drops == dev_log_drop.reported_drops) { /* No new drops to report. */ bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags); return BCMOS_TIMER_OK; } dev_log_drop.msg.lock = BCMOS_TRUE; bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags); /* Do the actual report. */ _bcm_dev_log_drop_report(); } return BCMOS_TIMER_OK; } bcmos_errno bcm_dev_log_init_default_logger_ext( bcm_dev_log_parm *dev_log_parm, uint32_t num_files, uint32_t stack_size, bcmos_task_priority priority, uint32_t pool_size) { bcmos_errno err; bcmos_task_parm save_task_parm = {0}; bcmos_task_parm print_task_parm = {0}; bcmos_msg_queue_parm print_queue_parm = {0}; bcmos_msg_queue_parm save_queue_parm = {0}; bcmos_msg_pool_parm pool_parm = {0}; bcmos_timer_parm timer_params = { .name = "dev_log_drop_timer", .owner = BCMOS_MODULE_ID_NONE, /* Will be called in ISR context */ .handler = bcm_dev_log_drop_timer_cb, }; if (!dev_log_parm) { DEV_LOG_ERROR_PRINTF("Error: dev_log_parm must be set\n"); return BCM_ERR_PARM; } save_task_parm.priority = priority; save_task_parm.stack_size = stack_size; save_task_parm.name = "dev_log_save"; save_task_parm.handler = dev_log_save_task; save_task_parm.data = 0; print_task_parm.priority = priority; print_task_parm.stack_size = stack_size; print_task_parm.name = "dev_log_print"; print_task_parm.handler = dev_log_print_task; print_task_parm.data = 0; /* It is important to avoid terminating logger task during an exception, as logger task is low priority and might have backlog of unhandled messages. * Even if as a result of the exception the logger task will be in a deadlock waiting for a resource (semaphore/mutex/timer), it is in lower priority than CLI and thus should not block * CLI. */ save_task_parm.flags = BCMOS_TASK_FLAG_NO_SUSPEND_ON_OOPS; print_task_parm.flags = BCMOS_TASK_FLAG_NO_SUSPEND_ON_OOPS; save_queue_parm.name = "dev_log_save"; save_queue_parm.size = 0; /* unlimited */ print_queue_parm.name = "dev_log_print"; print_queue_parm.size = 0; /* unlimited */ pool_parm.name = "dev_log"; pool_parm.size = pool_size; pool_parm.data_size = sizeof(dev_log_queue_msg); def_log_id = bcm_dev_log_id_register("default", DEV_LOG_LEVEL_INFO, DEV_LOG_ID_TYPE_BOTH); err = bcmos_timer_create(&dev_log_drop.timer, &timer_params); BCMOS_TRACE_CHECK_RETURN(err, err, "bcmos_timer_create"); bcmos_fastlock_init(&dev_log_drop.msg.fastlock, 0); if (!dev_log_parm->get_time_cb) dev_log_parm->get_time_cb = bcmos_timestamp; err = bcm_dev_log_create( dev_log_parm, &save_task_parm, &print_task_parm, &save_queue_parm, &print_queue_parm, &pool_parm); BCMOS_TRACE_CHECK_RETURN(err, err, "bcm_dev_log_create"); /* Init the frontend */ bcm_dev_log_frontend_init(); return BCM_ERR_OK; } bcmos_errno bcm_dev_log_init_default_logger(void **start_addresses, uint32_t *sizes, bcm_dev_log_file_flags *flags, uint32_t num_files, uint32_t stack_size, bcmos_task_priority priority, uint32_t pool_size) { bcm_dev_log_parm dev_log_parm = {0}; uint32_t i; for (i = 0; i < num_files; i++) { dev_log_parm.log_file[i].start_addr = start_addresses[i]; dev_log_parm.log_file[i].size = sizes[i]; /* size[i] might be 0 in simulation build for sram buffer. */ dev_log_parm.log_file[i].flags = (bcm_dev_log_file_flags) ((sizes[i] ? BCM_DEV_LOG_FILE_FLAG_VALID : BCM_DEV_LOG_FILE_FLAG_NONE) | (flags ? flags[i] : BCM_DEV_LOG_FILE_FLAG_WRAP_AROUND)); } return bcm_dev_log_init_default_logger_ext(&dev_log_parm, num_files, stack_size, priority, pool_size); } /* Log entry timestamp formatting callback */ static int bcm_log_time_to_ms_str_cb(uint32_t time_stamp, char *time_str, int time_str_size) { return snprintf(time_str, time_str_size, "%u", time_stamp / 1000); /* convert from usec to msec. */ } /* Simplified init function intended mainly for host use */ bcmos_errno bcm_log_init(const dev_log_init_parms *init_parms) { bcmos_errno rc; bcm_dev_log_parm log_parms = {}; uint32_t queue_size; log_parms.time_to_str_cb = bcm_log_time_to_ms_str_cb; if (init_parms->type == BCM_DEV_LOG_FILE_MEMORY) { log_parms.log_file[0].size = init_parms->mem_size ? init_parms->mem_size : BCM_DEV_LOG_DEFAULT_MEM_SIZE; log_parms.log_file[0].start_addr = bcmos_calloc(log_parms.log_file[0].size); log_parms.log_file[0].flags = (bcm_dev_log_file_flags)(BCM_DEV_LOG_FILE_FLAG_WRAP_AROUND | BCM_DEV_LOG_FILE_FLAG_CLEAR_AFTER_READ); if (log_parms.log_file[0].start_addr == NULL) return BCM_ERR_NOMEM; } #ifdef BCM_OS_POSIX else if (init_parms->type == BCM_DEV_LOG_FILE_REGULAR) { if (init_parms->filename == NULL) { bcmos_printf("%s: filename is required for log type BCMOLT_LOG_TYPE_FILE\n", __FUNCTION__); return BCM_ERR_PARM; } log_parms.log_file[0].udef_parms = (char *)(long)init_parms->filename; } #endif else #ifdef DEV_LOG_SYSLOG if (init_parms->type != BCM_DEV_LOG_FILE_SYSLOG) #endif { bcmos_printf("%s: log type %d is invalid\n", __FUNCTION__, init_parms->type); return BCM_ERR_PARM; } log_parms.log_file[0].type = init_parms->type; log_parms.log_file[0].flags |= BCM_DEV_LOG_FILE_FLAG_VALID; queue_size = init_parms->queue_size ? init_parms->queue_size : BCM_DEV_LOG_DEFAULT_QUEUE_SIZE; /* Only init a single log file */ rc = bcm_dev_log_init_default_logger_ext(&log_parms, 1, 0x4000, TASK_PRIORITY_DEV_LOG, queue_size); BCMOS_TRACE_CHECK_RETURN(rc, rc, "bcm_dev_log_init_default_logger_ext()\n"); bcm_dev_log_level_set_style(DEV_LOG_LEVEL_WARNING, BCM_DEV_LOG_STYLE_BOLD); if (init_parms->post_init_cb != NULL) { rc = init_parms->post_init_cb(); BCMOS_TRACE_CHECK_RETURN(rc, rc, "%s: post_init_cb()\n", __FUNCTION__); } BCM_LOG(INFO, def_log_id, "Logging started\n"); return BCM_ERR_OK; } log_name_table logs_names[DEV_LOG_MAX_IDS]; uint8_t log_name_table_index = 0; static void dev_log_add_log_name_to_table(const char *name) { char _name[MAX_DEV_LOG_ID_NAME + 1] = {}; char *p = _name; char *p_end; int i = 0; long val = -1; strncpy(_name, name, MAX_DEV_LOG_ID_NAME); while (*p) { /* While there are more characters to process... */ if (isdigit(*p)) { /* Upon finding a digit, ... */ val = strtol(p, &p_end, 10); /* Read a number, ... */ if ((_name + strlen(_name)) != p_end) { DEV_LOG_ERROR_PRINTF("Error: dev_log_add_log_name_to_table %s)\n", name); } *p = '\0'; break; } else { /* Otherwise, move on to the next character. */ p++; } } for (i = 0; i < log_name_table_index; i++) { if (strcmp(_name, logs_names[i].name) == 0) { if (val < 0) { logs_names[i].has_non_instance = BCMOS_TRUE; } else { logs_names[i].has_instance = BCMOS_TRUE; if (val < logs_names[i].first_instance) { logs_names[i].first_instance = val; } if (val > logs_names[i].last_instance) { logs_names[i].last_instance = val; } } break; } } if ((i == log_name_table_index) && (i < DEV_LOG_MAX_IDS)) { bcmolt_strncpy(logs_names[i].name, _name, MAX_DEV_LOG_ID_NAME + 1); if (val < 0) { logs_names[i].has_non_instance = BCMOS_TRUE; } else { logs_names[i].has_instance = BCMOS_TRUE; logs_names[i].first_instance = val; logs_names[i].last_instance = val; } log_name_table_index++; } } void dev_log_get_log_name_table(char *buffer, uint32_t buf_len) { uint32_t i = 0; uint32_t buf_len_free = buf_len; buffer[0] = '\0'; for (i = 0; i < log_name_table_index; i++) { if (logs_names[i].has_non_instance) { snprintf(&buffer[strlen(buffer)], buf_len_free, "%s\n", logs_names[i].name); } if (logs_names[i].has_instance) { snprintf(&buffer[strlen(buffer)], buf_len_free, "%s %d - %d\n", logs_names[i].name, logs_names[i].first_instance, logs_names[i].last_instance); } buffer[buf_len - 1] = '\0'; buf_len_free = buf_len - strlen(buffer); if (buf_len_free <= 1) { DEV_LOG_ERROR_PRINTF("Error: dev_log_get_log_name_table too long\n"); break; } } } static dev_log_id _bcm_dev_log_id_get_by_name(const char *name) { uint32_t i; for (i = 0; i < BCM_SIZEOFARRAY(dev_log.ids); i++) { if (!dev_log.ids[i].is_active) continue; if (!strcmp(dev_log.ids[i].name, name)) { return (dev_log_id)&dev_log.ids[i]; } } return DEV_LOG_INVALID_ID; } static dev_log_id_parm *bcm_dev_log_get_free_id(void) { uint32_t i; for (i = 0; i < BCM_SIZEOFARRAY(dev_log.ids); i++) { if (!dev_log.ids[i].is_active) return &dev_log.ids[i]; } return NULL; } dev_log_id bcm_dev_log_id_register(const char *name, bcm_dev_log_level default_log_level, bcm_dev_log_id_type default_log_type) { dev_log_id_parm *new_id; /* Check that we have room for one more ID */ new_id = bcm_dev_log_get_free_id(); if (!new_id) { DEV_LOG_ERROR_PRINTF("Error: Failed to register log ID for '%s' - out of free log IDs\n", name); return DEV_LOG_INVALID_ID; } /* Check that the log name isn't already registered */ if (!(dev_log.flags & BCM_DEV_LOG_FLAG_ALLOW_DUPLICATES) && _bcm_dev_log_id_get_by_name(name) != DEV_LOG_INVALID_ID) { DEV_LOG_ERROR_PRINTF("Error: duplicate log name \"%s\"\n", name); return DEV_LOG_INVALID_ID; } /* Add prefix for kernel log_ids in order to avoid clash with similarly-names logs in the user space */ #ifdef __KERNEL__ strcpy(new_id->name, "k_"); #endif /* Set log_id parameters */ strncat(new_id->name, name, sizeof(new_id->name) - strlen(new_id->name)); new_id->name[MAX_DEV_LOG_ID_NAME - 1] = '\0'; new_id->default_log_type = default_log_type; new_id->default_log_level = default_log_level; dev_log_add_log_name_to_table(new_id->name); bcm_dev_log_id_set_level_and_type_to_default((dev_log_id)new_id); new_id->style = BCM_DEV_LOG_STYLE_NORMAL; new_id->is_active = BCMOS_TRUE; new_id->group_idx = DEV_LOG_MAX_GROUPS; new_id->group_membership_mask = 0; #ifdef ENABLE_CLI /* Update the CLI enum for log IDs. */ bcm_dev_log_cli_log_id_enum[_log_id_enum_len].name = new_id->name; bcm_dev_log_cli_log_id_enum[_log_id_enum_len].val = (dev_log_id)new_id; _log_id_enum_len++; #endif return (dev_log_id)new_id; } void bcm_dev_log_id_unregister(dev_log_id id) { dev_log_id_parm *parm = (dev_log_id_parm *)id; parm->is_active = BCMOS_FALSE; *parm->name = '\0'; if (parm->group_idx != DEV_LOG_MAX_GROUPS) { /* Remove all loggers from this group. */ dev_log_id log_id = DEV_LOG_INVALID_ID; while ((log_id = bcm_dev_log_group_log_id_get_next(id, log_id)) != DEV_LOG_INVALID_ID) { bcm_dev_log_group_remove_log_id(id, log_id); } dev_log.group_ids[parm->group_idx] = DEV_LOG_INVALID_ID; } #ifdef ENABLE_CLI /* Update the CLI enum for log IDs. */ { int i; int j; for (i = 0; i < _log_id_enum_len; i++) { if (bcm_dev_log_cli_log_id_enum[i].val == id) { for (j = i + 1; j < _log_id_enum_len; j++) { bcm_dev_log_cli_log_id_enum[j - 1] = bcm_dev_log_cli_log_id_enum[j]; } _log_id_enum_len--; bcm_dev_log_cli_log_id_enum[_log_id_enum_len].name = NULL; break; } } } #endif } bcmos_errno bcm_dev_log_id_set_type(dev_log_id id, bcm_dev_log_id_type log_type) { dev_log_id_parm *parm = (dev_log_id_parm *)id; if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } /* In linux kernel we only support save */ #ifdef __KERNEL__ if (log_type & DEV_LOG_ID_TYPE_BOTH) log_type = DEV_LOG_ID_TYPE_SAVE; #endif DEV_LOG_INFO_PRINTF("ID: 0x%lx, New log type: %d\n", id, (int)log_type); parm->log_type = log_type; /* In linux user space we need to notify kernel integration code */ #if defined(LINUX_KERNEL_SPACE) && !defined(__KERNEL__) if (using_inband_get()) { bcm_dev_log_linux_id_set_type_ud(id, log_type); } else { bcm_dev_log_linux_id_set_type(id, log_type); } #endif return BCM_ERR_OK; } bcmos_errno bcm_dev_log_id_set_level(dev_log_id id, bcm_dev_log_level log_level_print, bcm_dev_log_level log_level_save) { dev_log_id_parm *parm = (dev_log_id_parm *)id; if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } if ((log_level_print >= DEV_LOG_LEVEL_NUM_OF) || (log_level_save >= DEV_LOG_LEVEL_NUM_OF)) { DEV_LOG_ERROR_PRINTF("Error: wrong parameters\n"); return BCM_ERR_PARM; } DEV_LOG_INFO_PRINTF("ID: 0x%p, New: log_level_print=%u, log_level_save=%u\n", (void *)parm, log_level_print, log_level_save); parm->log_level_print = log_level_print; parm->log_level_save = log_level_save; /* In linux user space we need to notify kernel integration code */ #if defined(LINUX_KERNEL_SPACE) && !defined(__KERNEL__) if (using_inband_get()) { bcm_dev_log_linux_id_set_level_ud(id, log_level_print, log_level_save); } else { bcm_dev_log_linux_id_set_level(id, log_level_print, log_level_save); } #endif if (parm->group_idx != DEV_LOG_MAX_GROUPS) { /* Recursively set the log levels on all members of this group. */ dev_log_id log_id = DEV_LOG_INVALID_ID; while ((log_id = bcm_dev_log_group_log_id_get_next(id, log_id)) != DEV_LOG_INVALID_ID) { bcmos_errno rc = bcm_dev_log_id_set_level(log_id, log_level_print, log_level_save); if (rc != BCM_ERR_OK) return rc; } } return BCM_ERR_OK; } bcmos_errno bcm_dev_log_id_set_level_and_type_to_default(dev_log_id id) { dev_log_id_parm *parm = (dev_log_id_parm *)id; if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } parm->log_level_print = parm->default_log_level; parm->log_level_save = parm->default_log_level; parm->log_type = parm->default_log_type; #ifdef TRIGGER_LOGGER_FEATURE memset(&parm->throttle,0, sizeof(dev_log_id_throttle)); memset(&parm->trigger, 0, sizeof(dev_log_id_trigger)); parm->throttle_log_level = DEV_LOG_LEVEL_NO_LOG; parm->trigger_log_level = DEV_LOG_LEVEL_NO_LOG; #endif /* In linux kernel space we don't support PRINT, only SAVE */ #ifdef __KERNEL__ if (parm->log_type & DEV_LOG_ID_TYPE_BOTH) parm->log_type = DEV_LOG_ID_TYPE_SAVE; #endif return BCM_ERR_OK; } bcmos_errno bcm_dev_log_set_level_and_type_all(bcm_dev_log_id_set_all set_all) { dev_log_id log_id = DEV_LOG_INVALID_ID; bcmos_errno err; while ((log_id = bcm_dev_log_id_get_next(log_id)) != DEV_LOG_INVALID_ID) { if (set_all == DEV_LOG_ID_SET_ALL_NONE) { err = bcm_dev_log_id_set_type(log_id, DEV_LOG_ID_TYPE_NONE); if (err == BCM_ERR_OK) err = bcm_dev_log_id_set_level(log_id, DEV_LOG_LEVEL_NO_LOG, DEV_LOG_LEVEL_NO_LOG); } else err = bcm_dev_log_id_set_level_and_type_to_default(log_id); if (err != BCM_ERR_OK) return err; } return BCM_ERR_OK; } void bcm_dev_log_level_set_style(bcm_dev_log_level level, bcm_dev_log_style style) { dev_log_level2style[level] = style; } bcmos_errno bcm_dev_log_id_set_style(dev_log_id id, bcm_dev_log_style style) { dev_log_id_parm *parm = (dev_log_id_parm *)id; if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } parm->style = style; return BCM_ERR_OK; } bcmos_errno bcm_dev_log_id_clear_counters(dev_log_id id) { dev_log_id_parm *parm = (dev_log_id_parm *)id; if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } memset(parm->counters, 0, sizeof(parm->counters)); parm->lost_msg_cnt = 0; parm->print_skipped_count = 0; return BCM_ERR_OK; } bcmos_errno bcm_dev_log_id_get(dev_log_id id, dev_log_id_parm *parm) { if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } *parm = *(dev_log_id_parm *)id; return BCM_ERR_OK; } bcmos_errno bcm_dev_log_id_get_level(dev_log_id id, bcm_dev_log_level *p_log_level_print, bcm_dev_log_level *p_log_level_save) { dev_log_id_parm *parm = (dev_log_id_parm *)id; if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } if (p_log_level_print) *p_log_level_print = parm->log_level_print; if (p_log_level_save) *p_log_level_save = parm->log_level_save; return BCM_ERR_OK; } bcmos_errno bcm_dev_log_id_set(dev_log_id id, dev_log_id_parm *parm) { bcmos_errno rc; if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } /* The only parts of the logger params that make sense to set are level/type/style. * Everything else is dynamic internal information that should not be changed by the caller. */ rc = bcm_dev_log_id_set_level(id, parm->log_level_print, parm->log_level_save); rc = (rc != BCM_ERR_OK) ? rc : bcm_dev_log_id_set_type(id, parm->log_type); rc = (rc != BCM_ERR_OK) ? rc : bcm_dev_log_id_set_style(id, parm->style); return rc; } dev_log_id bcm_dev_log_id_get_by_index(uint32_t index) { if (index >= BCM_SIZEOFARRAY(dev_log.ids) || !dev_log.ids[index].is_active) return DEV_LOG_INVALID_ID; return (dev_log_id)&dev_log.ids[index]; } uint32_t bcm_dev_log_get_index_by_id(dev_log_id id) { uint32_t idx = (dev_log_id_parm *)id - &dev_log.ids[0]; if (idx >= BCM_SIZEOFARRAY(dev_log.ids)) idx = DEV_LOG_INVALID_INDEX; /* Return idx even is "is_active" is false. This is because the callers rely on this. */ return idx; } dev_log_id bcm_dev_log_id_get_next(dev_log_id id) { if (id == DEV_LOG_INVALID_ID) id = (dev_log_id)&dev_log.ids; else id = (dev_log_id)((dev_log_id_parm *)id + 1); for (; bcm_dev_log_get_index_by_id(id) != DEV_LOG_INVALID_INDEX && !((dev_log_id_parm *)id)->is_active; id = (dev_log_id)((dev_log_id_parm *)id + 1)); return bcm_dev_log_get_index_by_id(id) == DEV_LOG_INVALID_INDEX ? DEV_LOG_INVALID_ID : id; } dev_log_id bcm_dev_log_id_get_by_name(const char *name) { dev_log_id id; if (name == NULL) { return DEV_LOG_INVALID_ID; } id = _bcm_dev_log_id_get_by_name(name); if (id == DEV_LOG_INVALID_ID) { DEV_LOG_ERROR_PRINTF("Error: can't find name\n"); } return id; } bcmos_errno bcm_dev_log_group_add_log_id(dev_log_id group_id, dev_log_id log_id) { dev_log_id_parm *group_id_parm = (dev_log_id_parm *)group_id; dev_log_id_parm *log_id_parm = (dev_log_id_parm *)log_id; if (!log_id || (log_id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: log_id not valid (0x%x)\n", (unsigned int)log_id); return BCM_ERR_PARM; } if (!group_id || (group_id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: group_id not valid (0x%x)\n", (unsigned int)group_id); return BCM_ERR_PARM; } if (group_id_parm->group_idx == DEV_LOG_MAX_GROUPS) { /* The requested group logger isn't a group yet, so we need to allocate one. */ for (group_id_parm->group_idx = 0; group_id_parm->group_idx < DEV_LOG_MAX_GROUPS; group_id_parm->group_idx++) { if (dev_log.group_ids[group_id_parm->group_idx] == DEV_LOG_INVALID_ID) break; } if (group_id_parm->group_idx == DEV_LOG_MAX_GROUPS) { DEV_LOG_ERROR_PRINTF("Error: no more groups available\n"); return BCM_ERR_NO_MORE; } dev_log.group_ids[group_id_parm->group_idx] = group_id; } log_id_parm->group_membership_mask |= (1u << group_id_parm->group_idx); return BCM_ERR_OK; } bcmos_errno bcm_dev_log_group_remove_log_id(dev_log_id group_id, dev_log_id log_id) { dev_log_id_parm *group_id_parm = (dev_log_id_parm *)group_id; dev_log_id_parm *log_id_parm = (dev_log_id_parm *)log_id; if (!log_id || (log_id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: log_id not valid (0x%x)\n", (unsigned int)log_id); return BCM_ERR_PARM; } if (!group_id || (group_id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: group_id not valid (0x%x)\n", (unsigned int)group_id); return BCM_ERR_PARM; } if (group_id_parm->group_idx == DEV_LOG_MAX_GROUPS) { /* group_id isn't a group so by definition it doesn't contain any other log IDs. */ return BCM_ERR_OK; } log_id_parm->group_membership_mask &= ~(1u << group_id_parm->group_idx); return BCM_ERR_OK; } bcmos_bool bcm_dev_log_id_group_contains_log_id(dev_log_id group_id, dev_log_id log_id) { dev_log_id_parm *group_id_parm = (dev_log_id_parm *)group_id; dev_log_id_parm *log_id_parm = (dev_log_id_parm *)log_id; if (!log_id || (log_id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: log_id not valid (0x%x)\n", (unsigned int)log_id); return BCMOS_FALSE; } if (!group_id || (group_id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: group_id not valid (0x%x)\n", (unsigned int)group_id); return BCMOS_FALSE; } if (group_id_parm->group_idx == DEV_LOG_MAX_GROUPS) { /* group_id isn't a group so by definition it doesn't contain any other log IDs. */ return BCMOS_FALSE; } return ((log_id_parm->group_membership_mask & (1u << group_id_parm->group_idx)) != 0); } dev_log_id bcm_dev_log_group_log_id_get_next(dev_log_id group_id, dev_log_id log_id) { dev_log_id_parm *group_id_parm = (dev_log_id_parm *)group_id; if (!group_id || (group_id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: group_id not valid (0x%x)\n", (unsigned int)group_id); return DEV_LOG_INVALID_ID; } if (group_id_parm->group_idx < DEV_LOG_MAX_GROUPS) { while ((log_id = bcm_dev_log_id_get_next(log_id)) != DEV_LOG_INVALID_ID) { if (bcm_dev_log_id_group_contains_log_id(group_id, log_id)) return log_id; } } return DEV_LOG_INVALID_ID; } bcmos_bool bcm_dev_log_get_control(void) { return dev_log.state == BCM_DEV_LOG_STATE_ENABLED; } uint32_t bcm_dev_log_get_num_of_messages(const bcm_dev_log_file *file) { return file->u.mem_file.file_header.num_msgs; } void bcm_dev_log_set_control(bcmos_bool control) { if (control && dev_log.state == BCM_DEV_LOG_STATE_DISABLED) dev_log.state = BCM_DEV_LOG_STATE_ENABLED; else if (!control && dev_log.state == BCM_DEV_LOG_STATE_ENABLED) dev_log.state = BCM_DEV_LOG_STATE_DISABLED; } bcm_dev_log_file_flags bcm_dev_log_get_file_flags(uint32_t file_id) { return dev_log.files[file_id].file_parm.flags; } void bcm_dev_log_set_file_flags(uint32_t file_id, bcm_dev_log_file_flags flags) { dev_log.files[file_id].file_parm.flags = flags; } bcm_dev_log_flags bcm_dev_log_get_flags(void) { return dev_log.flags; } void bcm_dev_log_set_flags(bcm_dev_log_flags flags) { dev_log.flags = flags; } void bcm_dev_log_set_print_cb(bcm_dev_log_print_cb cb) { dev_log.dev_log_parm.print_cb = cb; } void bcm_dev_log_set_get_time_cb(bcm_dev_log_get_time_cb cb) { dev_log.dev_log_parm.get_time_cb = cb; } void bcm_dev_log_set_time_to_str_cb(bcm_dev_log_time_to_str_cb cb) { dev_log.dev_log_parm.time_to_str_cb = cb; } #ifdef TRIGGER_LOGGER_FEATURE /********************************************************************************************/ /* */ /* Name: bcm_dev_log_set_throttle */ /* */ /* Abstract: Set throttle level for the specific log is and its level */ /* */ /* Arguments: */ /* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */ /* - log_level - log level */ /* - throttle - throttle number, 0 - no throttle */ /* */ /* Return Value: */ /* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */ /* */ /********************************************************************************************/ bcmos_errno bcm_dev_log_set_throttle(dev_log_id id, bcm_dev_log_level log_level, uint32_t throttle) { dev_log_id_parm *parm = (dev_log_id_parm *)id; if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } parm->throttle_log_level = log_level; parm->throttle.threshold = throttle; parm->throttle.counter = 0; return BCM_ERR_OK; } /********************************************************************************************/ /* */ /* Name: bcm_dev_log_set_trigger */ /* */ /* Abstract: Set trigger counters for the specific log is and its level */ /* */ /* Arguments: */ /* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */ /* - log_level - log level */ /* - start - start printing after this number, 0 - no trigger */ /* - stop - stop printing after this number, 0 - do not stop */ /* - repeat - start printing after this number, 0 - no repeat, -1 always */ /* */ /* Return Value: */ /* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */ /* */ /********************************************************************************************/ bcmos_errno bcm_dev_log_set_trigger(dev_log_id id, bcm_dev_log_level log_level, uint32_t start, uint32_t stop, int32_t repeat) { dev_log_id_parm *parm = (dev_log_id_parm *)id; if (!id || (id == DEV_LOG_INVALID_ID)) { DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id); return BCM_ERR_PARM; } parm->trigger_log_level = log_level; parm->trigger.start_threshold = start; parm->trigger.stop_threshold = stop; parm->trigger.repeat_threshold = repeat; parm->trigger.counter = 0; parm->trigger.repeat = 0; return BCM_ERR_OK; } #endif /* TRIGGER_LOGGER_FEATURE */ /* Get file info: max data size, used bytes */ bcmos_errno bcm_dev_log_get_file_info(bcm_dev_log_file *file, uint32_t *file_size, uint32_t *used_bytes) { if (!file || !file_size || !used_bytes) return BCM_ERR_PARM; /* Only supported for memory files */ if (!bcm_dev_log_is_memory_file(file)) return BCM_ERR_NOT_SUPPORTED; *file_size = file->u.mem_file.file_header.data_size; *used_bytes = (file->u.mem_file.file_header.file_wrap_cnt || file->is_full) ? file->u.mem_file.file_header.data_size : file->u.mem_file.file_header.write_offset; return BCM_ERR_OK; } /* Register indication to be sent when file utilization crosses threshold */ bcmos_errno bcm_dev_log_almost_full_ind_register(bcm_dev_log_file *file, uint32_t used_bytes_threshold, F_dev_log_file_almost_full send_ind_cb, long ind_cb_priv) { if (!file || (used_bytes_threshold && !send_ind_cb)) return BCM_ERR_PARM; /* Only supported for memory files */ if (!bcm_dev_log_is_memory_file(file)) return BCM_ERR_NOT_SUPPORTED; bcmos_mutex_lock(&file->u.mem_file.mutex); file->almost_full.threshold = used_bytes_threshold; file->almost_full.send_ind_cb = send_ind_cb; file->almost_full.priv = ind_cb_priv; file->almost_full.ind_sent = BCMOS_FALSE; bcmos_mutex_unlock(&file->u.mem_file.mutex); return BCM_ERR_OK; } #endif /* ENABLE_LOG */
the_stack_data/234518287.c
/* Getopt tests */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <getopt.h> int main (int argc, char **argv) { int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; c = getopt (argc, argv, "abc:d:0123456789"); if (c == EOF) break; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (digit_optind != 0 && digit_optind != this_option_optind) printf ("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf ("option %c\n", c); break; case 'a': printf ("option a\n"); break; case 'b': printf ("option b\n"); break; case 'c': printf ("option c with value `%s'\n", optarg); break; case '?': break; default: printf ("?? getopt returned character code 0%o ??\n", c); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); } exit (0); }
the_stack_data/709168.c
/* { dg-do compile } */ void ldt_add_entry(void) { __asm__ ("" :: "m"(({unsigned __v; __v;}))); /* { dg-warning "memory input 0 is not directly addressable" } */ }
the_stack_data/128150.c
// KASAN: slab-out-of-bounds Write in prb_fill_curr_block // https://syzkaller.appspot.com/bug?id=6363a526e7fb768fb443c8d7615e16f75c2fee1d // status:fixed // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <endian.h> #include <errno.h> #include <errno.h> #include <errno.h> #include <fcntl.h> #include <fcntl.h> #include <linux/capability.h> #include <linux/if.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/ip.h> #include <linux/tcp.h> #include <net/if_arp.h> #include <sched.h> #include <signal.h> #include <stdarg.h> #include <stdarg.h> #include <stdbool.h> #include <stdbool.h> #include <stdio.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <unistd.h> __attribute__((noreturn)) static void doexit(int status) { volatile unsigned i; syscall(__NR_exit_group, status); for (i = 0;; i++) { } } #include <errno.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string.h> #include <sys/stat.h> const int kFailStatus = 67; const int kRetryStatus = 69; static void fail(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus); } static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* uctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) && (addr < prog_start || addr > prog_end)) { _longjmp(segv_env, 1); } doexit(sig); } static void install_segv_handler() { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8); syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = segv_handler; sa.sa_flags = SA_NODEFER | SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #define NONFAILING(...) \ { \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ } static void use_temporary_dir() { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) fail("failed to mkdtemp"); if (chmod(tmpdir, 0777)) fail("failed to chmod"); if (chdir(tmpdir)) fail("failed to chdir"); } static void vsnprintf_check(char* str, size_t size, const char* format, va_list args) { int rv; rv = vsnprintf(str, size, format, args); if (rv < 0) fail("tun: snprintf failed"); if ((size_t)rv >= size) fail("tun: string '%s...' doesn't fit into buffer", str); } #define COMMAND_MAX_LEN 128 #define PATH_PREFIX \ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin " #define PATH_PREFIX_LEN (sizeof(PATH_PREFIX) - 1) static void execute_command(bool panic, const char* format, ...) { va_list args; char command[PATH_PREFIX_LEN + COMMAND_MAX_LEN]; int rv; va_start(args, format); memcpy(command, PATH_PREFIX, PATH_PREFIX_LEN); vsnprintf_check(command + PATH_PREFIX_LEN, COMMAND_MAX_LEN, format, args); va_end(args); rv = system(command); if (rv) { if (panic) fail("command '%s' failed: %d", &command[0], rv); } } static int tunfd = -1; static int tun_frags_enabled; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define TUN_IFACE "syz_tun" #define LOCAL_MAC "aa:aa:aa:aa:aa:aa" #define REMOTE_MAC "aa:aa:aa:aa:aa:bb" #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 252; if (dup2(tunfd, kTunFd) < 0) fail("dup2(tunfd, kTunFd) failed"); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNSETIFF) failed"); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNGETIFF) failed"); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; execute_command(1, "sysctl -w net.ipv6.conf.%s.accept_dad=0", TUN_IFACE); execute_command(1, "sysctl -w net.ipv6.conf.%s.router_solicitations=0", TUN_IFACE); execute_command(1, "ip link set dev %s address %s", TUN_IFACE, LOCAL_MAC); execute_command(1, "ip addr add %s/24 dev %s", LOCAL_IPV4, TUN_IFACE); execute_command(1, "ip -6 addr add %s/120 dev %s", LOCAL_IPV6, TUN_IFACE); execute_command(1, "ip neigh add %s lladdr %s dev %s nud permanent", REMOTE_IPV4, REMOTE_MAC, TUN_IFACE); execute_command(1, "ip -6 neigh add %s lladdr %s dev %s nud permanent", REMOTE_IPV6, REMOTE_MAC, TUN_IFACE); execute_command(1, "ip link set dev %s up", TUN_IFACE); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02hx" #define DEV_MAC "aa:aa:aa:aa:aa:%02hx" static void snprintf_check(char* str, size_t size, const char* format, ...) { va_list args; va_start(args, format); vsnprintf_check(str, size, format, args); va_end(args); } static void initialize_netdevices(void) { unsigned i; const char* devtypes[] = {"ip6gretap", "bridge", "vcan", "bond", "team"}; const char* devnames[] = {"lo", "sit0", "bridge0", "vcan0", "tunl0", "gre0", "gretap0", "ip_vti0", "ip6_vti0", "ip6tnl0", "ip6gre0", "ip6gretap0", "erspan0", "bond0", "veth0", "veth1", "team0", "veth0_to_bridge", "veth1_to_bridge", "veth0_to_bond", "veth1_to_bond", "veth0_to_team", "veth1_to_team"}; const char* devmasters[] = {"bridge", "bond", "team"}; for (i = 0; i < sizeof(devtypes) / (sizeof(devtypes[0])); i++) execute_command(0, "ip link add dev %s0 type %s", devtypes[i], devtypes[i]); execute_command(0, "ip link add type veth"); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { execute_command( 0, "ip link add name %s_slave_0 type veth peer name veth0_to_%s", devmasters[i], devmasters[i]); execute_command( 0, "ip link add name %s_slave_1 type veth peer name veth1_to_%s", devmasters[i], devmasters[i]); execute_command(0, "ip link set %s_slave_0 master %s0", devmasters[i], devmasters[i]); execute_command(0, "ip link set %s_slave_1 master %s0", devmasters[i], devmasters[i]); execute_command(0, "ip link set veth0_to_%s up", devmasters[i]); execute_command(0, "ip link set veth1_to_%s up", devmasters[i]); } execute_command(0, "ip link set bridge_slave_0 up"); execute_command(0, "ip link set bridge_slave_1 up"); for (i = 0; i < sizeof(devnames) / (sizeof(devnames[0])); i++) { char addr[32]; snprintf_check(addr, sizeof(addr), DEV_IPV4, i + 10); execute_command(0, "ip -4 addr add %s/24 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_IPV6, i + 10); execute_command(0, "ip -6 addr add %s/120 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_MAC, i + 10); execute_command(0, "ip link set dev %s address %s", devnames[i], addr); execute_command(0, "ip link set dev %s up", devnames[i]); } } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 160 << 20; setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 8 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } } static int real_uid; static int real_gid; __attribute__((aligned(64 << 10))) static char sandbox_stack[1 << 20]; static int namespace_sandbox_proc(void* arg) { sandbox_common(); write_file("/proc/self/setgroups", "deny"); if (!write_file("/proc/self/uid_map", "0 %d 1\n", real_uid)) fail("write of /proc/self/uid_map failed"); if (!write_file("/proc/self/gid_map", "0 %d 1\n", real_gid)) fail("write of /proc/self/gid_map failed"); if (unshare(CLONE_NEWNET)) fail("unshare(CLONE_NEWNET)"); initialize_tun(); initialize_netdevices(); if (mkdir("./syz-tmp", 0777)) fail("mkdir(syz-tmp) failed"); if (mount("", "./syz-tmp", "tmpfs", 0, NULL)) fail("mount(tmpfs) failed"); if (mkdir("./syz-tmp/newroot", 0777)) fail("mkdir failed"); if (mkdir("./syz-tmp/newroot/dev", 0700)) fail("mkdir failed"); unsigned mount_flags = MS_BIND | MS_REC | MS_PRIVATE; if (mount("/dev", "./syz-tmp/newroot/dev", NULL, mount_flags, NULL)) fail("mount(dev) failed"); if (mkdir("./syz-tmp/newroot/proc", 0700)) fail("mkdir failed"); if (mount(NULL, "./syz-tmp/newroot/proc", "proc", 0, NULL)) fail("mount(proc) failed"); if (mkdir("./syz-tmp/newroot/selinux", 0700)) fail("mkdir failed"); const char* selinux_path = "./syz-tmp/newroot/selinux"; if (mount("/selinux", selinux_path, NULL, mount_flags, NULL)) { if (errno != ENOENT) fail("mount(/selinux) failed"); if (mount("/sys/fs/selinux", selinux_path, NULL, mount_flags, NULL) && errno != ENOENT) fail("mount(/sys/fs/selinux) failed"); } if (mkdir("./syz-tmp/newroot/sys", 0700)) fail("mkdir failed"); if (mount(NULL, "./syz-tmp/newroot/sys", "sysfs", 0, NULL)) fail("mount(sysfs) failed"); if (mkdir("./syz-tmp/pivot", 0777)) fail("mkdir failed"); if (syscall(SYS_pivot_root, "./syz-tmp", "./syz-tmp/pivot")) { if (chdir("./syz-tmp")) fail("chdir failed"); } else { if (chdir("/")) fail("chdir failed"); if (umount2("./pivot", MNT_DETACH)) fail("umount failed"); } if (chroot("./newroot")) fail("chroot failed"); if (chdir("/")) fail("chdir failed"); struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) fail("capget failed"); cap_data[0].effective &= ~(1 << CAP_SYS_PTRACE); cap_data[0].permitted &= ~(1 << CAP_SYS_PTRACE); cap_data[0].inheritable &= ~(1 << CAP_SYS_PTRACE); if (syscall(SYS_capset, &cap_hdr, &cap_data)) fail("capset failed"); loop(); doexit(1); } static int do_sandbox_namespace(void) { int pid; real_uid = getuid(); real_gid = getgid(); mprotect(sandbox_stack, 4096, PROT_NONE); pid = clone(namespace_sandbox_proc, &sandbox_stack[sizeof(sandbox_stack) - 64], CLONE_NEWUSER | CLONE_NEWPID, 0); if (pid < 0) fail("sandbox clone failed"); return pid; } #ifndef __NR_bpf #define __NR_bpf 321 #endif uint64_t r[1] = {0xffffffffffffffff}; void loop() { long res = 0; NONFAILING(*(uint32_t*)0x20000000 = 0); NONFAILING(*(uint32_t*)0x20000004 = 3); NONFAILING(*(uint64_t*)0x20000008 = 0x20001000); NONFAILING(memcpy((void*)0x20001000, "\x7b\x1a\xf8\xff\x00\x00\x00\x00\x69" "\xa2\xf8\xce\xdd\x2e\x00\x0d\x5c\xc4" "\xb3\xaa\xb4\xff\x00\x00\x00", 25)); NONFAILING(*(uint64_t*)0x20000010 = 0x20000100); NONFAILING(memcpy((void*)0x20000100, "GPL", 4)); NONFAILING(*(uint32_t*)0x20000018 = 0); NONFAILING(*(uint32_t*)0x2000001c = 0); NONFAILING(*(uint64_t*)0x20000020 = 0); NONFAILING(*(uint32_t*)0x20000028 = 0); NONFAILING(*(uint32_t*)0x2000002c = 0); NONFAILING(*(uint8_t*)0x20000030 = 0); NONFAILING(*(uint8_t*)0x20000031 = 0); NONFAILING(*(uint8_t*)0x20000032 = 0); NONFAILING(*(uint8_t*)0x20000033 = 0); NONFAILING(*(uint8_t*)0x20000034 = 0); NONFAILING(*(uint8_t*)0x20000035 = 0); NONFAILING(*(uint8_t*)0x20000036 = 0); NONFAILING(*(uint8_t*)0x20000037 = 0); NONFAILING(*(uint8_t*)0x20000038 = 0); NONFAILING(*(uint8_t*)0x20000039 = 0); NONFAILING(*(uint8_t*)0x2000003a = 0); NONFAILING(*(uint8_t*)0x2000003b = 0); NONFAILING(*(uint8_t*)0x2000003c = 0); NONFAILING(*(uint8_t*)0x2000003d = 0); NONFAILING(*(uint8_t*)0x2000003e = 0); NONFAILING(*(uint8_t*)0x2000003f = 0); NONFAILING(*(uint32_t*)0x20000040 = 0); NONFAILING(*(uint32_t*)0x20000044 = 0); syscall(__NR_bpf, 5, 0x20000000, 0x48); NONFAILING(*(uint32_t*)0x20001000 = 0x10000); NONFAILING(*(uint32_t*)0x20001004 = 4); NONFAILING(*(uint32_t*)0x20001008 = 0x100); NONFAILING(*(uint32_t*)0x2000100c = 0x400); syscall(__NR_setsockopt, -1, 0x84, 0, 0x20001000, 6); res = syscall(__NR_socket, 0x11, 0x80002, 0); if (res != -1) r[0] = res; NONFAILING(*(uint32_t*)0x20788000 = 2); syscall(__NR_setsockopt, r[0], 0x107, 0xa, 0x20788000, 4); NONFAILING(*(uint16_t*)0x20000480 = 0x11); NONFAILING(*(uint16_t*)0x20000482 = htobe16(3)); NONFAILING(*(uint32_t*)0x20000484 = 0); NONFAILING(*(uint16_t*)0x20000488 = 1); NONFAILING(*(uint8_t*)0x2000048a = 0); NONFAILING(*(uint8_t*)0x2000048b = 6); NONFAILING(*(uint8_t*)0x2000048c = 0xaa); NONFAILING(*(uint8_t*)0x2000048d = 0xaa); NONFAILING(*(uint8_t*)0x2000048e = 0xaa); NONFAILING(*(uint8_t*)0x2000048f = 0xaa); NONFAILING(*(uint8_t*)0x20000490 = 0xaa); NONFAILING(*(uint8_t*)0x20000491 = 0xaa); NONFAILING(*(uint8_t*)0x20000492 = 0); NONFAILING(*(uint8_t*)0x20000493 = 0); syscall(__NR_bind, r[0], 0x20000480, 0x14); syscall(__NR_setsockopt, r[0], 0x107, 5, 0x20001000, 0xc5); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); install_segv_handler(); use_temporary_dir(); int pid = do_sandbox_namespace(); int status = 0; while (waitpid(pid, &status, __WALL) != pid) { } return 0; }
the_stack_data/187912.c
/* A bytecode interpeter that can perform simple mathematical operations and ternary logic It can print the result to the console using the Print opcode */ #include <assert.h> #include <stdbool.h> #include <stdio.h> #define STACK_DEPTH 255 typedef enum { Const, Add, Sub, Mul, Div, Gt, Lt, Gte, Lte, Eq, Select, Print, } OpKind; typedef struct { OpKind kind; int arg; } Opcode; typedef struct { int values[STACK_DEPTH]; int pc; } Stack; void stack_push(Stack *stack, int v) { stack->values[stack->pc++] = v; } int stack_pop(Stack *stack) { return stack->values[--stack->pc]; } int stack_peek(Stack *stack) { return stack->values[stack->pc - 1]; } vm_run(const Opcode *program, int programLen) { Stack stack = {0}; for (int i = 0; i < programLen; i++) { Opcode op = program[i]; switch (op.kind) { case Const: stack_push(&stack, op.arg); break; case Add: { assert(stack.pc >= 2 && "Add operation requires two arguments on the stack"); int b = stack_pop(&stack); int a = stack_pop(&stack); int c = a + b; stack_push(&stack, c); } break; case Sub: { assert(stack.pc >= 2 && "Sub operation requires two arguments on the stack"); int b = stack_pop(&stack); int a = stack_pop(&stack); int c = a - b; stack_push(&stack, c); } break; case Mul: { assert(stack.pc >= 2 && "Mul operation requires two arguments on the stack"); int b = stack_pop(&stack); int a = stack_pop(&stack); int c = a * b; stack_push(&stack, c); } break; case Div: { assert(stack.pc >= 2 && "Div operation requires two arguments on the stack"); int b = stack_pop(&stack); int a = stack_pop(&stack); int c = a / b; stack_push(&stack, c); } break; case Gt: { assert(stack.pc >= 2 && "Gt operation requires two arguments on the stack"); int b = stack_pop(&stack); int a = stack_pop(&stack); int c = a > b; stack_push(&stack, c); } break; case Lt: { assert(stack.pc >= 2 && "Lt operation requires two arguments on the stack"); int b = stack_pop(&stack); int a = stack_pop(&stack); int c = a < b; stack_push(&stack, c); } break; case Gte: { assert(stack.pc >= 2 && "Gte operation requires two arguments on the stack"); int b = stack_pop(&stack); int a = stack_pop(&stack); int c = a >= b; stack_push(&stack, c); } break; case Lte: { assert(stack.pc >= 2 && "Lte operation requires two arguments on the stack"); int b = stack_pop(&stack); int a = stack_pop(&stack); int c = a <= b; stack_push(&stack, c); } break; case Select: { assert(stack.pc >= 3 && "Select operation requires three arguments on the stack"); int b = stack_pop(&stack); int a = stack_pop(&stack); int cond = stack_pop(&stack); int c = cond ? a : b; stack_push(&stack, c); } break; case Print: { assert(stack.pc >= 1 && "Print operation requires one arguments on the stack"); int a = stack_peek(&stack); printf("VM:Print %d\n", a); } break; default: printf("Unhandled kind %d\n", op.kind); exit(1); break; } } printf("Stack size: %d\n", stack.pc); if (stack.pc > 0) { printf("Top: %d\n", stack_pop(&stack)); } } void main() { Opcode program[] = { {Const, 10}, {Const, 20}, {Gt}, {Const, 11}, {Const, 22}, {Select}, {Print}, }; int programLength = sizeof(program) / sizeof(Opcode); vm_run(program, programLength); }
the_stack_data/368302.c
/** Leia o valor do raio de um círculo e calcule a área do círculo correspondente. Imprima o resultado dessa operação. A área do círculo é 𝜋 ∗ 𝑟𝑎𝑖𝑜², considere 𝜋 = 3,141592 . **/ #include <stdio.h> int main () { }
the_stack_data/7950394.c
#include<stdio.h> #include<stdlib.h> #include<string.h> //Atributos de um produto typedef struct Produto{ char codigoBarras[8]; char descricao[20]; int categoria; float preco; }Produto; //Definição de um nodo struct Nodo{ Produto dado; struct Nodo *prox; }; typedef struct Nodo nodo; void iniciar(nodo *L) { L->prox = NULL; } int estaVazia(nodo *L) { if (L->prox == NULL) return 1; //vazia else return 0; } // funções para inserir um elemento na lista: void inserirInicio(nodo *L, Produto *dado) { nodo *novo = (nodo*) malloc(sizeof(nodo)); //Alocar espaço para um novo nodo strcpy(novo->dado.codigoBarras, dado->codigoBarras);// strcpy(novo->dado.descricao, dado->descricao);// novo->dado.categoria = dado->categoria;// novo->dado.preco = dado->preco;// Copiando os atributos para o novo nodo inserido //Inserir o novo nodo no inicio: novo->prox = L->prox; L->prox = novo->prox; } void inserirMeio (nodo *L, Produto *dado, char *produto) { nodo *novo = (nodo*) malloc(sizeof(nodo)); //Alocar espaço para um novo nodo strcpy(novo->dado.codigoBarras, dado->codigoBarras);// strcpy(novo->dado.descricao, dado->descricao);// novo->dado.categoria = dado->categoria;// novo->dado.preco = dado->preco;// Copiando os atributos para o novo nodo inserido // Verificar se está vazia if(estaVazia(L)) L->prox = novo; // Afirmativo: o novo nodo será o primeiro else { nodo *tmp = NULL; nodo *no = L->prox; while (no != NULL) { if (strcmp(no->dado.descricao, produto) == 0) { tmp = no->prox; no->prox = novo; novo->prox = tmp; } no = no->prox; } } } void inserirFinal(nodo *L, Produto *dado) { nodo *novo = (nodo*) malloc(sizeof(nodo)); strcpy(novo->dado.codigoBarras, dado->codigoBarras); strcpy(novo->dado.descricao, dado->descricao); novo->dado.categoria = dado->categoria; novo->dado.preco = dado->preco; if(estaVazia(L)) L->prox = novo; else { nodo *no = L->prox; while (no->prox != NULL) no = no->prox; no->prox = novo; novo->prox = NULL; // verificar } } // Funções de exlusão de elementos da lista: void excluirInicio(nodo *L) { nodo *noPrimeiro = L->prox; L->prox = noPrimeiro->prox; free(noPrimeiro); } void excluirMeio(nodo *L, char *produto) { nodo *noAnterior = L; nodo *noAtual = L->prox; while (noAtual->prox != NULL) { if(strcmp(noAtual->dado.descricao, produto) == 0) { noAnterior->prox = noAtual->prox; free(noAtual); return; } noAnterior = noAtual; noAtual = noAtual->prox; } } void excluirFinal(nodo *L) { nodo *noAnterior = L; nodo *noAtual = L->prox; while (noAtual->prox != NULL) { noAnterior = noAtual; noAtual = noAtual->prox; } noAnterior->prox = NULL; free(noAtual); } void liberar(nodo *L) { nodo *proximo; nodo *atual; atual = L; while (atual->prox != NULL) { proximo = atual->prox; atual->prox = NULL; free(atual); atual = proximo; } } //Funções de acesso/apoio à manipulação de uma lista: void primeiro(nodo *L) { if (estaVazia(L)) { printf("Lista vazia."); return; } nodo *no = L->prox; printf("%-8s %s \t%s %s \n", "Codigo", "Descricao", "Valor", "Categoria"); printf("%-8s %s \t%-6.2f %d \n", no->dado.codigoBarras, no->dado.descricao, no->dado.preco, no->dado.categoria); printf("\n\n"); } void ultimo(nodo *L) { if(estaVazia(L)) { printf("Lista vazia."); return; } nodo *no = L->prox; printf("%-8s %s \t%s %s \n", "Codigo", "Descricao", "Valor", "Categoria"); while(no->prox != NULL) { if (no->prox == NULL) { printf("%-8s %s \t%-6.2f %d \n", no->dado.codigoBarras, no->dado.descricao, no->dado.preco, no->dado.categoria); } no = no->prox; } printf("\n\n"); } void pesquisar(nodo *L, char *descricao) { if (estaVazia(L)) { printf("Lista vazia."); return; } nodo *no = L->prox; printf("%-8s %s \t%s %s \n", "Codigo", "Descricao", "Valor", "Categoria"); while (no != NULL) { if (strcmp(no->dado.descricao, descricao) == 0) { printf("%-8s %s \t%-6.2f %d \n", no->dado.codigoBarras, no->dado.descricao, no->dado.preco, no->dado.categoria); } no = no->prox; } printf("\n\n"); } void imprimir(nodo *L) { if (estaVazia(L)) { printf("Lista vazia."); return; } nodo *no = L->prox; printf("%-8s %s \t%s %s \n", "Codigo", "Descricao", "Valor", "Categoria"); while (no != NULL) { printf("%-8s %s \t%-6.2f %d \n", no->dado.codigoBarras, no->dado.descricao, no->dado.preco, no->dado.categoria); no = no->prox; } printf("\n\n"); } int main() { Produto produto[3]; nodo *L = (nodo*) malloc(sizeof(nodo)); iniciar(L); return 0; }
the_stack_data/21769.c
/* Copyright (C) 1992-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <stddef.h> /* For NULL. */ #include <sys/time.h> #include <time.h> /* Set the system clock to *WHEN. */ int stime (const time_t *when) { struct timeval tv; if (when == NULL) { __set_errno (EINVAL); return -1; } tv.tv_sec = *when; tv.tv_usec = 0; return __settimeofday (&tv, (struct timezone *) 0); }
the_stack_data/14200585.c
/* ============================================================================ Name : deikstra.c Author : qwinpin Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <time.h> #include <stdio.h> #include <stdlib.h> #include <omp.h> #define INF 1000000 #define TRUE 1 #define FALSE 0 void print_graph(int **a, int size); void test(); int find_single(int **a, int size) { int tmp; int *v = (int*) malloc(size * sizeof(int)); int *d = (int*) malloc(size * sizeof(int)); srand(time(NULL)); for (int i = 0; i < size; i++){ v[i] = TRUE; d[i] = INF; } d[0] = 0; int minindex = 0; int min = 0; while (minindex < INF){ minindex = INF; min = INF; for (int i = 0; i < size; i++){ if ((v[i]) && (d[i] < min)){ min = d[i]; minindex = i; } } if (minindex != INF){ for (int i = 0; i < size; i++){ if (a[minindex][i] > 0){ tmp = a[minindex][i] + min; if (tmp < d[i]){ d[i] = tmp; } } } v[minindex] = FALSE; } } return 0; } int find_parallel(int **a, int size, int threads){ int tmp, step; int *minArr = (int*) malloc(threads * sizeof(int)); int *minInd = (int*) malloc(threads * sizeof(int)); int i; int *v = (int*) malloc(size * sizeof(int)); int *d = (int*) malloc(size * sizeof(int)); step = size / threads; #pragma omp parallel num_threads(threads) { #pragma omp parallel for for (i = 0; i < size; i++){ v[i] = TRUE; d[i] = INF; } } d[0] = 0; int minindex = 0; int min = 0; #pragma omp parallel num_threads(threads) { #pragma omp parallel for for (i = 0; i < threads; i++){ minArr[i] = INF; minInd[i] = INF; } } while (minindex < INF){ minindex = INF; min = INF; // parallel part - split vector into chunks, find min in each, then compare #pragma omp parallel num_threads(threads) { #pragma omp for for (int j = 0; j < threads; j++){ for (int k = j * step; k < (j + 1)*step ; k++){ if ((v[k]) && (d[k]) < minArr[j]){ minArr[j] = d[k]; minInd[j] = k; } } } } for (int j = 0; j < threads; j++){ if (minArr[j] < min){ min = minArr[j]; minindex = minInd[j]; } minArr[j] = INF; minInd[j] = INF; } // process each vector element in parallel if (minindex != INF){ // #pragma omp parallel num_threads(threads) { // #pragma omp parallel for for (i = 0; i < size; i++){ if (a[minindex][i] > 0){ tmp = a[minindex][i] + min; if (tmp < d[i]){ d[i] = tmp; } } } v[minindex] = FALSE; } } } return 0; } void print_graph(int **a, int size){ printf("\nGraph\n"); for (int i = 0; i < size && i < 5; i++){ for (int j = 0; j < size && j < 5; j++){ printf("%d ", a[i][j]); } printf("\n"); } } int main(){ int evaluate; printf("Evaluate test or not? 1/0\n"); scanf("%d", &evaluate); if (evaluate){ test(); return 0; } int size; printf("Enter graph size\n"); scanf("%d", &size); if (size < 0 || size > 30000){ size = 10000; } int th; printf("Threads number\n"); scanf("%d", &th); if (th == 0){ printf("Bye"); } int **a = (int**) malloc(size * sizeof(int*)); int tmp; srand(time(NULL)); for (int i = 0; i < size; i++){ a[i] = (int*) malloc(size * sizeof(int)); } for (int i = 0; i < size; i++){ a[i][i] = 0; for (int j = i + 1; j < size; j++){ tmp = rand() % 10; a[i][j] = tmp; a[j][i] = tmp; } } clock_t start = clock(), diff; if (th == 1){ find_single(a, size); } else{ find_parallel(a, size, th); } diff = clock() - start; print_graph(a, size); printf("It took %li sec %li milisec", diff / CLOCKS_PER_SEC, diff * 1000 / CLOCKS_PER_SEC % 1000); for (int i = 0; i < size; i++){ free(a[i]); } free(a); return 0; } void test(){ int size = 1000; int threads = 17; int size_step = 1000; int size_max = 22000; unsigned short int tmp; srand(time(NULL)); FILE *f = fopen("d_process.txt", "w"); if (f == NULL) { printf("Error opening file!\n"); exit(1); } int **a = (int**) malloc(size_max * sizeof(int*)); for (int i = 0; i < size_max; i++){ a[i] = (int*) malloc(size_max * sizeof(unsigned short int*)); } for (int i = 0; i < size_max; i++){ a[i][i] = 0; for (int j = i + 1; j < size_max; j++){ tmp = rand() % 10; a[i][j] = tmp; a[j][i] = tmp; } } for (int th = 1; th < threads; th++){ printf("Threads num %d\n", th); fprintf(f, "\nThreads_num: %d\n ", th); size = 1000; while (size <= size_max){ printf("Size %d\n", size); clock_t start = clock(), diff; if (th == 1){ find_single(a, size); } else{ find_parallel(a, size, th); } diff = clock() - start; fprintf(f, "%f, ", (double)diff / CLOCKS_PER_SEC * 1000); size = size + size_step; } } for (int i = 0; i < size_max; i++){ free(a[i]); } free(a); }
the_stack_data/36074011.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> // ssize_t #include <sys/socket.h> // send(),recv() #include <netdb.h> // gethostbyname() /** * Client code * 1. Create a socket and connect to the server specified in the command arugments. * 2. Prompt the user for input and send that input as a message to the server. * 3. Print the message received from the server and exit the program. */ // Error function used for reporting issues void error(const char *msg) { perror(msg); exit(0); } // Set up the address struct void setupAddressStruct(struct sockaddr_in* address, int portNumber, char* hostname){ // Clear out the address struct memset((char*) address, '\0', sizeof(*address)); // The address should be network capable address->sin_family = AF_INET; // Store the port number address->sin_port = htons(portNumber); // Get the DNS entry for this host name struct hostent* hostInfo = gethostbyname(hostname); if (hostInfo == NULL) { fprintf(stderr, "CLIENT: ERROR, no such host\n"); exit(0); } // Copy the first IP address from the DNS entry to sin_addr.s_addr memcpy((char*) &address->sin_addr.s_addr, hostInfo->h_addr_list[0], hostInfo->h_length); } int main(int argc, char *argv[]) { int socketFD, portNumber, charsWritten, charsRead; struct sockaddr_in serverAddress; char buffer[140010], smBuff[1000]; int bufferIndex = 4, plaintextLen = 0, keyLen = 0; memset(buffer, '\0', 140010); memset(smBuff, '\0', 1000); // Check usage & args if (argc < 4) { fprintf(stderr,"USAGE: %s plaintext key port\n", argv[0]); exit(0); } // Create a socket socketFD = socket(AF_INET, SOCK_STREAM, 0); if (socketFD < 0){ error("CLIENT: ERROR opening socket"); } // Set up the server address struct setupAddressStruct(&serverAddress, atoi(argv[3]), "localhost"); // Connect to server if (connect(socketFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0){ error("CLIENT: ERROR connecting"); } buffer[0] = 'e'; buffer[1] = 'n'; buffer[2] = 'c'; buffer[3] = ';'; FILE *plaintext = fopen(argv[1], "r"); if(plaintext == NULL) { error("CLIENT: Error opening plaintext file!"); } else { int c; while((c = fgetc(plaintext)) != EOF) { if(c != '\n') { buffer[bufferIndex] = c; bufferIndex++; plaintextLen++; } } } fclose(plaintext); buffer[bufferIndex] = ';'; bufferIndex++; FILE *key = fopen(argv[2], "r"); if(key == NULL) { error("CLIENT: Error opening key file!"); } else { int c; while((c = fgetc(plaintext)) != EOF) { if(c != '\n') { buffer[bufferIndex] = c; bufferIndex++; keyLen++; } } } fclose(key); buffer[bufferIndex] = '@'; bufferIndex++; if(keyLen < plaintextLen) { error("ERROR: The selected key is too short"); } //printf("%s\n", buffer); buffer[strcspn(buffer, "\n")] = '\0'; // Plaintext check //loop here const char *p = buffer; int buffLength = strlen(buffer); while(buffLength > 0) { //printf("client sending\n"); charsWritten = send(socketFD, buffer, buffLength, 0); if (charsWritten <= 0){ error("CLIENT: ERROR writing to socket"); } p += charsWritten; buffLength -= charsWritten; } // Get return message from server // Clear out the buffer again for reuse memset(buffer, '\0', 140010); memset(smBuff, '\0', 1000); while(strstr(smBuff, "@") == NULL) { //printf("client receiving\n"); // Read data from the socket charsRead = recv(socketFD, smBuff, 1000, 0); if (charsRead < 0){ error("CLIENT: ERROR reading from socket"); } strcat(buffer, smBuff); } if(buffer[0] == ':' && buffer[1] == ':') { error("Wrong client connected"); } buffer[plaintextLen] = '\n'; for(int x = 0; x < plaintextLen + 1; x++) { fprintf(stdout, "%c", buffer[x]); } memset(buffer, '\0', 140010); // Close the socket close(socketFD); return 0; }
the_stack_data/176706819.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_numbers.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rodaniel <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/08/03 15:49:02 by rodaniel #+# #+# */ /* Updated: 2017/08/04 14:49:02 by rodaniel ### ########.fr */ /* */ /* ************************************************************************** */ void ft_putchar(char c); void ft_print_numbers(void) { int fesse; fesse = 48; while (fesse <= 57) { ft_putchar(fesse); fesse++; } return ; }
the_stack_data/98575666.c
/* u8g_dev_ssd1325_nhd27oled_bw.c 1-Bit (BW) Driver for SSD1325 Controller (OLED Display) Tested with NHD-2.7-12864UCY3 Universal 8bit Graphics Library Copyright (c) 2011, [email protected] All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. SSD130x Monochrom OLED Controller SSD131x Character OLED Controller SSD132x Graylevel OLED Controller SSD1331 Color OLED Controller */ #ifdef OBSOLETE_CODE #include "u8g.h" #define WIDTH 128 #define HEIGHT 64 #define PAGE_HEIGHT 8 /* http://www.newhavendisplay.com/app_notes/OLED_2_7_12864.txt */ static const uint8_t u8g_dev_ssd1325_1bit_nhd_27_12864ucy3_init_seq[] PROGMEM = { U8G_ESC_DLY(10), /* delay 10 ms */ U8G_ESC_CS(0), /* disable chip */ U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_RST(1), /* do reset low pulse with (1*16)+2 milliseconds */ U8G_ESC_CS(1), /* enable chip */ 0x0ae, /* display off, sleep mode */ 0x0b3, 0x091, /* set display clock divide ratio/oscillator frequency (set clock as 135 frames/sec) */ 0x0a8, 0x03f, /* multiplex ratio: 0x03f * 1/64 duty */ 0x0a2, 0x04c, /* display offset, shift mapping ram counter */ 0x0a1, 0x000, /* display start line */ 0x0ad, 0x002, /* master configuration: disable embedded DC-DC, enable internal VCOMH */ 0x0a0, 0x056, /* remap configuration, vertical address increment, enable nibble remap (upper nibble is left) */ 0x086, /* full current range (0x084, 0x085, 0x086) */ 0x0b8, /* set gray scale table */ 0x01, 0x011, 0x022, 0x032, 0x043, 0x054, 0x065, 0x076, 0x081, 0x070, /* contrast, brightness, 0..128, Newhaven: 0x040 */ 0x0b2, 0x051, /* frame frequency (row period) */ 0x0b1, 0x055, /* phase length */ 0x0bc, 0x010, /* pre-charge voltage level */ 0x0b4, 0x002, /* set pre-charge compensation level (not documented in the SDD1325 datasheet, but used in the NHD init seq.) */ 0x0b0, 0x028, /* enable pre-charge compensation (not documented in the SDD1325 datasheet, but used in the NHD init seq.) */ 0x0be, 0x01c, /* VCOMH voltage */ 0x0bf, 0x002|0x00d, /* VSL voltage level (not documented in the SDD1325 datasheet, but used in the NHD init seq.) */ 0x0a5, /* all pixel on */ 0x0af, /* display on */ U8G_ESC_DLY(100), /* delay 100 ms */ U8G_ESC_DLY(100), /* delay 100 ms */ 0x0a4, /* normal display mode */ U8G_ESC_CS(0), /* disable chip */ U8G_ESC_END /* end of sequence */ }; static const uint8_t u8g_dev_ssd1325_1bit_nhd_27_12864ucy3_prepare_page_seq[] PROGMEM = { U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_CS(1), /* enable chip */ 0x015, /* column address... */ 0x000, /* start at column 0 */ 0x03f, /* end at column 63 (which is y == 127), because there are two pixel in one column */ 0x075, /* row address... */ U8G_ESC_END /* end of sequence */ }; static void u8g_dev_ssd1325_1bit_prepare_page(u8g_t *u8g, u8g_dev_t *dev) { uint8_t page = ((u8g_pb_t *)(dev->dev_mem))->p.page; u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd1325_1bit_nhd_27_12864ucy3_prepare_page_seq); page <<= 3; u8g_WriteByte(u8g, dev, page); /* start at the selected page */ page += 7; u8g_WriteByte(u8g, dev, page); /* end within the selected page */ u8g_SetAddress(u8g, dev, 1); /* data mode */ } static void u8g_dev_ssd1325_1bit_2x_prepare_page(u8g_t *u8g, u8g_dev_t *dev, uint8_t is_odd) { uint8_t page = ((u8g_pb_t *)(dev->dev_mem))->p.page; u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd1325_1bit_nhd_27_12864ucy3_prepare_page_seq); page <<= 1; page += is_odd; page <<= 3; u8g_WriteByte(u8g, dev, page); /* start at the selected page */ page += 7; u8g_WriteByte(u8g, dev, page); /* end within the selected page */ u8g_SetAddress(u8g, dev, 1); /* data mode */ } /* assumes row autoincrement and activated nibble remap */ #ifdef OLD static void _OLD_u8g_dev_ssd1325_1bit_write_16_pixel(u8g_t *u8g, u8g_dev_t *dev, uint8_t left, uint8_t right) { uint8_t d, cnt; cnt = 8; do { d = 0; if ( left & 1 ) d |= 0x0f0; if ( right & 1 ) d |= 0x00f; u8g_WriteByte(u8g, dev, d); left >>= 1; right >>= 1; cnt--; }while ( cnt > 0 ); } #endif static void u8g_dev_ssd1325_1bit_write_16_pixel(u8g_t *u8g, u8g_dev_t *dev, uint8_t left, uint8_t right) { uint8_t d, cnt; static uint8_t buf[8]; cnt = 8; do { d = 0; if ( left & 128 ) d |= 0x0f0; if ( right & 128 ) d |= 0x00f; cnt--; buf[cnt] = d; left <<= 1; right <<= 1; }while ( cnt > 0 ); u8g_WriteSequence(u8g, dev, 8, buf); } static void u8g_dev_ssd1325_1bit_write_buffer(u8g_t *u8g, u8g_dev_t *dev, uint8_t is_odd) { uint8_t cnt, left, right; uint8_t *ptr; u8g_pb_t *pb = (u8g_pb_t *)(dev->dev_mem); ptr = pb->buf; cnt = pb->width; if ( is_odd ) ptr += cnt; cnt >>= 1; do { left = *ptr++; right = *ptr++; u8g_dev_ssd1325_1bit_write_16_pixel(u8g, dev, left, right); cnt--; } while( cnt > 0 ); } uint8_t u8g_dev_ssd1325_nhd27oled_bw_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg); uint8_t u8g_dev_ssd1325_nhd27oled_bw_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg) { switch(msg) { case U8G_DEV_MSG_INIT: u8g_InitCom(u8g, dev, U8G_SPI_CLK_CYCLE_300NS); u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd1325_1bit_nhd_27_12864ucy3_init_seq); break; case U8G_DEV_MSG_STOP: break; case U8G_DEV_MSG_PAGE_NEXT: { u8g_dev_ssd1325_1bit_prepare_page(u8g, dev); u8g_dev_ssd1325_1bit_write_buffer(u8g, dev, 0); u8g_SetChipSelect(u8g, dev, 0); } break; case U8G_DEV_MSG_CONTRAST: u8g_SetChipSelect(u8g, dev, 1); u8g_SetAddress(u8g, dev, 0); /* instruction mode */ u8g_WriteByte(u8g, dev, 0x081); u8g_WriteByte(u8g, dev, (*(uint8_t *)arg) >> 1); u8g_SetChipSelect(u8g, dev, 0); break; } return u8g_dev_pb8v1_base_fn(u8g, dev, msg, arg); } uint8_t u8g_dev_ssd1325_nhd27oled_2x_bw_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg); uint8_t u8g_dev_ssd1325_nhd27oled_2x_bw_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg) { switch(msg) { case U8G_DEV_MSG_INIT: u8g_InitCom(u8g, dev, U8G_SPI_CLK_CYCLE_300NS); u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd1325_1bit_nhd_27_12864ucy3_init_seq); break; case U8G_DEV_MSG_STOP: break; case U8G_DEV_MSG_PAGE_NEXT: { u8g_dev_ssd1325_1bit_2x_prepare_page(u8g, dev, 0); u8g_dev_ssd1325_1bit_write_buffer(u8g, dev, 0); u8g_dev_ssd1325_1bit_2x_prepare_page(u8g, dev, 1); u8g_dev_ssd1325_1bit_write_buffer(u8g, dev, 1); u8g_SetChipSelect(u8g, dev, 0); } break; case U8G_DEV_MSG_CONTRAST: u8g_SetChipSelect(u8g, dev, 1); u8g_SetAddress(u8g, dev, 0); /* instruction mode */ u8g_WriteByte(u8g, dev, 0x081); u8g_WriteByte(u8g, dev, (*(uint8_t *)arg) >> 1); u8g_SetChipSelect(u8g, dev, 0); break; } return u8g_dev_pb16v1_base_fn(u8g, dev, msg, arg); } /* disabled, see bw_new.c */ /* U8G_PB_DEV(u8g_dev_ssd1325_nhd27oled_bw_sw_spi , WIDTH, HEIGHT, PAGE_HEIGHT, u8g_dev_ssd1325_nhd27oled_bw_fn, U8G_COM_SW_SPI); U8G_PB_DEV(u8g_dev_ssd1325_nhd27oled_bw_hw_spi , WIDTH, HEIGHT, PAGE_HEIGHT, u8g_dev_ssd1325_nhd27oled_bw_fn, U8G_COM_HW_SPI); U8G_PB_DEV(u8g_dev_ssd1325_nhd27oled_bw_parallel , WIDTH, HEIGHT, PAGE_HEIGHT, u8g_dev_ssd1325_nhd27oled_bw_fn, U8G_COM_FAST_PARALLEL); */ /* uint8_t u8g_dev_ssd1325_nhd27oled_2x_bw_buf[WIDTH*2] U8G_NOCOMMON ; u8g_pb_t u8g_dev_ssd1325_nhd27oled_2x_bw_pb = { {16, HEIGHT, 0, 0, 0}, WIDTH, u8g_dev_ssd1325_nhd27oled_2x_bw_buf}; u8g_dev_t u8g_dev_ssd1325_nhd27oled_2x_bw_sw_spi = { u8g_dev_ssd1325_nhd27oled_2x_bw_fn, &u8g_dev_ssd1325_nhd27oled_2x_bw_pb, U8G_COM_SW_SPI }; u8g_dev_t u8g_dev_ssd1325_nhd27oled_2x_bw_hw_spi = { u8g_dev_ssd1325_nhd27oled_2x_bw_fn, &u8g_dev_ssd1325_nhd27oled_2x_bw_pb, U8G_COM_HW_SPI }; u8g_dev_t u8g_dev_ssd1325_nhd27oled_2x_bw_parallel = { u8g_dev_ssd1325_nhd27oled_2x_bw_fn, &u8g_dev_ssd1325_nhd27oled_2x_bw_pb, U8G_COM_FAST_PARALLEL }; */ #endif
the_stack_data/28263651.c
/* * COMPRESS.C: * * Routines to do LZW compression on the player data. * * Copyright (C) 1992 Brett J. Vickers * */ #ifdef COMPRESS #include <stdio.h> #include "mstruct.h" #include "mextern.h" #define FALSE 0 #define TRUE !FALSE #define TABSIZE 4096 #define STACKSIZE TABSIZE #define NO_PRED 0xFFFF #define EMPTY 0xFFFF #define NOT_FND 0xFFFF #define UEOF ((unsigned)EOF) #define UPDATE TRUE #define NO_UPDATE FALSE static struct entry { char used; unsigned int next; unsigned int predecessor; unsigned char follower; } string_tab[TABSIZE]; static char *start_inbuf, *start_outbuf; static char *inbuf, *outbuf; static int sizeof_inbuf, sizeof_outbuf; static unsigned int temp_inbuf; static unsigned int temp_outbuf; static char stack[STACKSIZE]; static int sp; unsigned int h(), eolist(), hash(), unhash(), getcode(), readc(), writec(); void init_tab(), upd_tab(), flushout(), putcode(), push(); int pop(), compress(), uncompress(); /* h uses the 'mid-square' algorithm. I.E. for a hash val of n bits */ /* hash = middle binary digits of (key * key). Upon collision, hash */ /* searches down linked list of keys that hashed to that key already. */ /* It will NOT notice if the table is full. This must be handled */ /* elsewhere */ unsigned int h(pred,foll) unsigned int pred; unsigned char foll; { long temp, local; local = (pred + foll) | 0x0800; temp = local * local; local = (temp >> 6) & 0x0FFF; return local; } /* return last element in a collision list */ unsigned int eolist(index) unsigned int index; { register int temp; while((temp = string_tab[index].next) != 0) index = temp; return index; } unsigned int hash(pred, foll, update) unsigned int pred; unsigned char foll; int update; { unsigned int local, tempnext; struct entry *ep; local = h(pred,foll); if(!string_tab[local].used) return local; else { local = eolist(local); tempnext = (local + 101) & 0x0FFF; ep = &string_tab[tempnext]; while (ep->used) { ++tempnext; if(tempnext == TABSIZE) { tempnext = 0; ep = string_tab; } else ep++; } if (update) string_tab[local].next = tempnext; return tempnext; } } /* unhash uses the 'next' field to go down the collision tree to find */ /* the entry corresponding to the passed key */ /* passed key and returns either the matching entry # or NOT_FND */ unsigned int unhash(pred, foll) unsigned int pred; unsigned char foll; { unsigned int local, offset; struct entry *ep; local = h(pred,foll); loop: ep = &string_tab[local]; if((ep->predecessor == pred) && (ep->follower == foll)) return local; if(!ep->next) return NOT_FND; local = ep->next; goto loop; } void init_tab() { int i; temp_outbuf = temp_inbuf = EMPTY; sp = 0; memset((char *)string_tab, 0, sizeof(string_tab)); for(i=0; i<256; i++) upd_tab(NO_PRED,i); } void upd_tab(pred, foll) unsigned int pred, foll; { struct entry *ep; ep = &string_tab[hash(pred,foll,UPDATE)]; ep->used = TRUE; ep->next = 0; ep->predecessor = pred; ep->follower = foll; } /* getcode and putcode 'gallop' through input and output - they either */ /* output two bytes or one depending on the contents of the buffer. */ unsigned int getcode() { unsigned int localbuf, returnval; if(temp_inbuf == EMPTY) { if((localbuf = readc()) == UEOF) return UEOF; localbuf &= 0xFF; if((temp_inbuf = readc()) == UEOF) return UEOF; temp_inbuf &= 0xFF; returnval = ((localbuf << 4) & 0xFF0) | ((temp_inbuf >> 4) & 0x00F); temp_inbuf &= 0x000F; } else { if((localbuf = readc()) == UEOF) return UEOF; localbuf &= 0xFF; returnval = localbuf | ((temp_inbuf << 8) & 0xF00); temp_inbuf = EMPTY; } return returnval; } void putcode(code) unsigned int code; { unsigned int localbuf; if(temp_outbuf == EMPTY) { writec((code >> 4) & 0xFF); temp_outbuf = code & 0x000F; } else { writec(((temp_outbuf << 4) & 0xFF0) | ((code >> 8) & 0x00F)); writec(code & 0x00FF); temp_outbuf = EMPTY; } } unsigned int readc() { if(inbuf - start_inbuf >= sizeof_inbuf) return(UEOF); else return((*(inbuf++) & 0xFF)); } unsigned int writec(ch) int ch; { *outbuf = (char)ch; outbuf++; sizeof_outbuf++; } /* flushout makes sure fractional output buffer gets written */ void flushout() { if(temp_outbuf != EMPTY) { *outbuf = (temp_outbuf << 4) & 0xFF0; outbuf++; sizeof_outbuf++; } } /* Compress routines */ int compress(in, out, size) char *in; char *out; int size; { unsigned int c, code, localcode; int code_count = TABSIZE - 256; start_inbuf = inbuf = in; start_outbuf = outbuf = out; sizeof_inbuf = size; sizeof_outbuf = 0; init_tab(); c = readc(); code = unhash(NO_PRED, c); while((c = readc()) != UEOF) { if((localcode = unhash(code, c)) != NOT_FND) { code = localcode; continue; } putcode(code); if(code_count) { upd_tab(code, c); code_count--; } code = unhash(NO_PRED, c); } putcode(code); flushout(); return sizeof_outbuf; } /* Uncompression routines */ int uncompress(in, out, size) char *in; char *out; int size; { unsigned int c, tempc, code, oldcode, incode, finchar, lastchar; char unknown = FALSE; int code_count = TABSIZE - 256; struct entry *ep; start_inbuf = inbuf = in; start_outbuf = outbuf = out; sizeof_inbuf = size; sizeof_outbuf = 0; init_tab(); code = oldcode = getcode(); c = string_tab[code].follower; writec(c); finchar = c; while ((code = incode = getcode()) != UEOF) { ep = &string_tab[code]; if(!ep->used) { lastchar = finchar; code = oldcode; unknown = TRUE; ep = &string_tab[code]; } while(ep->predecessor != NO_PRED) { push(ep->follower); code = ep->predecessor; ep = &string_tab[code]; } finchar = ep->follower; writec(finchar); while((tempc = pop()) != EMPTY) writec(tempc); if(unknown) { writec(finchar = lastchar); unknown = FALSE; } if(code_count) { upd_tab(oldcode,finchar); code_count--; } oldcode = incode; } flushout(); return sizeof_outbuf; } void push(c) int c; { stack[sp] = (char) c; sp++; if(sp >= STACKSIZE) merror(FATAL, "Stack overflow"); } int pop() { if(sp > 0) { sp--; return((int)stack[sp]); } else return EMPTY; } #endif
the_stack_data/215767918.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <openssl/err.h> #include <openssl/ui.h> /* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR # define ERR_FUNC(func) ERR_PACK(ERR_LIB_UI,func,0) # define ERR_REASON(reason) ERR_PACK(ERR_LIB_UI,0,reason) static ERR_STRING_DATA UI_str_functs[] = { {ERR_FUNC(UI_F_CLOSE_CONSOLE), "close_console"}, {ERR_FUNC(UI_F_ECHO_CONSOLE), "echo_console"}, {ERR_FUNC(UI_F_GENERAL_ALLOCATE_BOOLEAN), "general_allocate_boolean"}, {ERR_FUNC(UI_F_GENERAL_ALLOCATE_PROMPT), "general_allocate_prompt"}, {ERR_FUNC(UI_F_NOECHO_CONSOLE), "noecho_console"}, {ERR_FUNC(UI_F_OPEN_CONSOLE), "open_console"}, {ERR_FUNC(UI_F_UI_CREATE_METHOD), "UI_create_method"}, {ERR_FUNC(UI_F_UI_CTRL), "UI_ctrl"}, {ERR_FUNC(UI_F_UI_DUP_ERROR_STRING), "UI_dup_error_string"}, {ERR_FUNC(UI_F_UI_DUP_INFO_STRING), "UI_dup_info_string"}, {ERR_FUNC(UI_F_UI_DUP_INPUT_BOOLEAN), "UI_dup_input_boolean"}, {ERR_FUNC(UI_F_UI_DUP_INPUT_STRING), "UI_dup_input_string"}, {ERR_FUNC(UI_F_UI_DUP_VERIFY_STRING), "UI_dup_verify_string"}, {ERR_FUNC(UI_F_UI_GET0_RESULT), "UI_get0_result"}, {ERR_FUNC(UI_F_UI_NEW_METHOD), "UI_new_method"}, {ERR_FUNC(UI_F_UI_PROCESS), "UI_process"}, {ERR_FUNC(UI_F_UI_SET_RESULT), "UI_set_result"}, {0, NULL} }; static ERR_STRING_DATA UI_str_reasons[] = { {ERR_REASON(UI_R_COMMON_OK_AND_CANCEL_CHARACTERS), "common ok and cancel characters"}, {ERR_REASON(UI_R_INDEX_TOO_LARGE), "index too large"}, {ERR_REASON(UI_R_INDEX_TOO_SMALL), "index too small"}, {ERR_REASON(UI_R_NO_RESULT_BUFFER), "no result buffer"}, {ERR_REASON(UI_R_PROCESSING_ERROR), "processing error"}, {ERR_REASON(UI_R_RESULT_TOO_LARGE), "result too large"}, {ERR_REASON(UI_R_RESULT_TOO_SMALL), "result too small"}, {ERR_REASON(UI_R_SYSASSIGN_ERROR), "sys$assign error"}, {ERR_REASON(UI_R_SYSDASSGN_ERROR), "sys$dassgn error"}, {ERR_REASON(UI_R_SYSQIOW_ERROR), "sys$qiow error"}, {ERR_REASON(UI_R_UNKNOWN_CONTROL_COMMAND), "unknown control command"}, {ERR_REASON(UI_R_UNKNOWN_TTYGET_ERRNO_VALUE), "unknown ttyget errno value"}, {0, NULL} }; #endif int ERR_load_UI_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_func_error_string(UI_str_functs[0].error) == NULL) { ERR_load_strings(0, UI_str_functs); ERR_load_strings(0, UI_str_reasons); } #endif return 1; }
the_stack_data/150144087.c
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> /* 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20 */ bool isPrime(unsigned int number) { if (number <= 1) return false; // zero and one are not prime unsigned int i; for (i=2; i*i<=number; i++) { if (number % i == 0) return false; } return true; } int main(void) { int N; // number we want to find the largest evenly divisible by int k = 20; //end of range for numbers that go into finding largest number N int primes[9]; int pos = 10; int j = 0; for (int i = 0; i < k; i++){ if (isPrime(i) == true){ primes[j] = i; j++; } i++; } for (int a = 0; a < pos; a++){ printf("%d ", primes[a]); printf("\n"); } return 0; }
the_stack_data/36075399.c
#if TEST___PROGNAME int main(void) { extern char *__progname; return !__progname; } #endif /* TEST___PROGNAME */ #if TEST_ARC4RANDOM #include <stdlib.h> int main(void) { return (arc4random() + 1) ? 0 : 1; } #endif /* TEST_ARC4RANDOM */ #if TEST_B64_NTOP #include <netinet/in.h> #include <resolv.h> int main(void) { const char *src = "hello world"; char output[1024]; return b64_ntop((const unsigned char *)src, 11, output, sizeof(output)) > 0 ? 0 : 1; } #endif /* TEST_B64_NTOP */ #if TEST_CAPSICUM #include <sys/capsicum.h> int main(void) { cap_enter(); return(0); } #endif /* TEST_CAPSICUM */ #if TEST_ERR /* * Copyright (c) 2015 Ingo Schwarze <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <err.h> int main(void) { warnx("%d. warnx", 1); warn("%d. warn", 2); err(0, "%d. err", 3); /* NOTREACHED */ return 1; } #endif /* TEST_ERR */ #if TEST_EXPLICIT_BZERO #include <string.h> int main(void) { char foo[10]; explicit_bzero(foo, sizeof(foo)); return(0); } #endif /* TEST_EXPLICIT_BZERO */ #if TEST_GETPROGNAME #include <stdlib.h> int main(void) { const char * progname; progname = getprogname(); return progname == NULL; } #endif /* TEST_GETPROGNAME */ #if TEST_INFTIM /* * Linux doesn't (always?) have this. */ #include <poll.h> #include <stdio.h> int main(void) { printf("INFTIM is defined to be %ld\n", (long)INFTIM); return 0; } #endif /* TEST_INFTIM */ #if TEST_MD5 #include <sys/types.h> #include <md5.h> int main(void) { MD5_CTX ctx; MD5Init(&ctx); MD5Update(&ctx, "abcd", 4); return 0; } #endif /* TEST_MD5 */ #if TEST_MEMMEM #define _GNU_SOURCE #include <string.h> int main(void) { char *a = memmem("hello, world", strlen("hello, world"), "world", strlen("world")); return(NULL == a); } #endif /* TEST_MEMMEM */ #if TEST_MEMRCHR #if defined(__linux__) || defined(__MINT__) #define _GNU_SOURCE /* See test-*.c what needs this. */ #endif #include <string.h> int main(void) { const char *buf = "abcdef"; void *res; res = memrchr(buf, 'a', strlen(buf)); return(NULL == res ? 1 : 0); } #endif /* TEST_MEMRCHR */ #if TEST_MEMSET_S #include <string.h> int main(void) { char buf[10]; memset_s(buf, 0, 'c', sizeof(buf)); return 0; } #endif /* TEST_MEMSET_S */ #if TEST_PATH_MAX /* * POSIX allows PATH_MAX to not be defined, see * http://pubs.opengroup.org/onlinepubs/9699919799/functions/sysconf.html; * the GNU Hurd is an example of a system not having it. * * Arguably, it would be better to test sysconf(_SC_PATH_MAX), * but since the individual *.c files include "config.h" before * <limits.h>, overriding an excessive value of PATH_MAX from * "config.h" is impossible anyway, so for now, the simplest * fix is to provide a value only on systems not having any. * So far, we encountered no system defining PATH_MAX to an * impractically large value, even though POSIX explicitly * allows that. * * The real fix would be to replace all static buffers of size * PATH_MAX by dynamically allocated buffers. But that is * somewhat intrusive because it touches several files and * because it requires changing struct mlink in mandocdb.c. * So i'm postponing that for now. */ #include <limits.h> #include <stdio.h> int main(void) { printf("PATH_MAX is defined to be %ld\n", (long)PATH_MAX); return 0; } #endif /* TEST_PATH_MAX */ #if TEST_PLEDGE #include <unistd.h> int main(void) { return !!pledge("stdio", NULL); } #endif /* TEST_PLEDGE */ #if TEST_PROGRAM_INVOCATION_SHORT_NAME #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <errno.h> int main(void) { return !program_invocation_short_name; } #endif /* TEST_PROGRAM_INVOCATION_SHORT_NAME */ #if TEST_REALLOCARRAY #include <stdlib.h> int main(void) { return !reallocarray(NULL, 2, 2); } #endif /* TEST_REALLOCARRAY */ #if TEST_RECALLOCARRAY #include <stdlib.h> int main(void) { return !recallocarray(NULL, 0, 2, 2); } #endif /* TEST_RECALLOCARRAY */ #if TEST_SANDBOX_INIT #include <sandbox.h> int main(void) { char *ep; int rc; rc = sandbox_init(kSBXProfileNoInternet, SANDBOX_NAMED, &ep); if (-1 == rc) sandbox_free_error(ep); return(-1 == rc); } #endif /* TEST_SANDBOX_INIT */ #if TEST_SECCOMP_FILTER #include <sys/prctl.h> #include <linux/seccomp.h> #include <errno.h> int main(void) { prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, 0); return(EFAULT == errno ? 0 : 1); } #endif /* TEST_SECCOMP_FILTER */ #if TEST_SOCK_NONBLOCK /* * Linux doesn't (always?) have this. */ #include <sys/socket.h> int main(void) { int fd[2]; socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK, 0, fd); return 0; } #endif /* TEST_SOCK_NONBLOCK */ #if TEST_STRLCAT #include <string.h> int main(void) { char buf[3] = "a"; return ! (strlcat(buf, "b", sizeof(buf)) == 2 && buf[0] == 'a' && buf[1] == 'b' && buf[2] == '\0'); } #endif /* TEST_STRLCAT */ #if TEST_STRLCPY #include <string.h> int main(void) { char buf[2] = ""; return ! (strlcpy(buf, "a", sizeof(buf)) == 1 && buf[0] == 'a' && buf[1] == '\0'); } #endif /* TEST_STRLCPY */ #if TEST_STRNDUP #include <string.h> int main(void) { const char *foo = "bar"; char *baz; baz = strndup(foo, 1); return(0 != strcmp(baz, "b")); } #endif /* TEST_STRNDUP */ #if TEST_STRNLEN #include <string.h> int main(void) { const char *foo = "bar"; size_t sz; sz = strnlen(foo, 1); return(1 != sz); } #endif /* TEST_STRNLEN */ #if TEST_STRTONUM /* * Copyright (c) 2015 Ingo Schwarze <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdlib.h> int main(void) { const char *errstr; if (strtonum("1", 0, 2, &errstr) != 1) return 1; if (errstr != NULL) return 2; if (strtonum("1x", 0, 2, &errstr) != 0) return 3; if (errstr == NULL) return 4; if (strtonum("2", 0, 1, &errstr) != 0) return 5; if (errstr == NULL) return 6; if (strtonum("0", 1, 2, &errstr) != 0) return 7; if (errstr == NULL) return 8; return 0; } #endif /* TEST_STRTONUM */ #if TEST_SYS_QUEUE #include <sys/queue.h> #include <stddef.h> struct foo { int bar; TAILQ_ENTRY(foo) entries; }; TAILQ_HEAD(fooq, foo); int main(void) { struct fooq foo_q, *foo, *next; TAILQ_INIT(&foo_q); TAILQ_FOREACH_SAFE(foo, &foo_q, entries, next) { } return 0; } #endif /* TEST_SYS_QUEUE */ #if TEST_SYSTRACE #include <sys/param.h> #include <dev/systrace.h> #include <stdlib.h> int main(void) { return(0); } #endif /* TEST_SYSTRACE */ #if TEST_ZLIB #include <stddef.h> #include <zlib.h> int main(void) { gzFile gz; if (NULL == (gz = gzopen("/dev/null", "w"))) return(1); gzputs(gz, "foo"); gzclose(gz); return(0); } #endif /* TEST_ZLIB */
the_stack_data/212644080.c
#include <unistd.h> #include <stdlib.h> #include <stdio.h> /** * fork创建子进程。 * 通过打印发现子进程只是父进程的副本,globvar全局变量和var局部变量不共享 */ int globvar = 6; char buf[] = "A write to stdout\n"; int main(){ int var; // atomatic variable on the stack pid_t pid; var = 88; if(write(STDOUT_FILENO,buf, sizeof(buf)-1) != (sizeof(buf)-1)){ perror("write to console error"); } printf("before fork\n"); if((pid = fork()) < 0){ perror("fork error"); }else if(pid == 0){ printf("child process\n"); globvar++; var++; }else { printf("parent process\n"); sleep(5); // wait child } printf("pid= %d, glob = %d, var=%d\n", getpid(), globvar, var); exit(0); }
the_stack_data/247017712.c
#include<stdio.h> int main() { float a, b; printf("Enter two numbers \n"); scanf("%f%f", &a, &b); int sum =(int)(a + b); int sub; if(a>b) { sub =(int) (a - b); } else { sub = (int)(b - a); } int mul = (int)(a * b) ; float div = (a/b) ; printf("Sum of two numbers=%d \n", sum); printf("Difference of two numbers=%d \n", sub); printf("Product of two numbers=%d \n", mul); printf("Quotient of two numbers=%f \n", div); return 0; }
the_stack_data/19163.c
#include <stdbool.h> bool mgos_arduino_adafruit_ads1x15_init(void) { return true; }
the_stack_data/136394.c
//Calculando o desconto #include <stdio.h> int main(void){ float preco, desc,newValue; printf("Insira o preço do produto: \n"); scanf("%f",&preco); printf("Insira o valor do desconto: \n"); scanf("%f",&desc); newValue = preco - (preco * (desc / 100)); printf("O produto passa a custar: %.2f\n",newValue); return 0; }
the_stack_data/32950671.c
/* Disciplina: Computacao Concorrente */ /* Prof.: Silvana Rossetto */ /* Laboratório: 1 */ /* Codigo: "Hello World" usando threads em C */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NTHREADS 10 //--funcao executada pelas threads void *PrintHello (void *arg) { printf("Hello World\n"); pthread_exit(NULL); } //--funcao principal do programa int main(void) { pthread_t tid_sistema[NTHREADS]; //identificadoes das threads no sistema int t; //variavel auxiliar for(t=0; t<NTHREADS; t++) { printf("--Cria a thread %d\n", t); if (pthread_create(&tid_sistema[t], NULL, PrintHello, NULL)) { printf("--ERRO: pthread_create()\n"); exit(-1); } } printf("--Thread principal terminou\n"); pthread_exit(NULL); }
the_stack_data/1089226.c
/* * iobw.c - simple I/O bandwidth benchmark * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. * * Copyright (C) 2008 Andrea Righi <[email protected]> */ #define _GNU_SOURCE #define __USE_GNU #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <signal.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/wait.h> #ifndef PAGE_SIZE #define PAGE_SIZE sysconf(_SC_PAGE_SIZE) #endif #define align(x,a) __align_mask(x,(typeof(x))(a)-1) #define __align_mask(x,mask) (((x)+(mask))&~(mask)) #define kb(x) ((x) >> 10) const char usage[] = "Usage: iobw [-direct] threads chunk_size data_size\n"; const char child_fmt[] = "(%s) task %3d: time %4lu.%03lu bw %7lu KiB/s (%s)\n"; const char parent_fmt[] = "(%s) parent %d: time %4lu.%03lu bw %7lu KiB/s (%s)\n"; static int directio = 0; static size_t data_size = 0; static size_t chunk_size = 0; typedef enum { OP_WRITE, OP_READ, NUM_IOPS, } iops_t; static const char *iops[] = { "WRITE", "READ ", "TOTAL", }; static int threads; pid_t *children; char *mygroup; static void print_results(int id, iops_t op, size_t bytes, struct timeval *diff) { fprintf(stdout, id ? child_fmt : parent_fmt, mygroup, id, diff->tv_sec, diff->tv_usec / 1000, (bytes / (diff->tv_sec * 1000000L + diff->tv_usec)) * 1000000L / 1024, iops[op]); } static void thread(int id) { struct timeval start, stop, diff; int fd, i, ret; size_t n; void *buf; int flags = O_CREAT | O_RDWR | O_LARGEFILE; char filename[32]; ret = posix_memalign(&buf, PAGE_SIZE, chunk_size); if (ret < 0) { fprintf(stderr, "ERROR: task %d couldn't allocate %zu bytes (%s)\n", id, chunk_size, strerror(errno)); exit(1); } memset(buf, 0xaa, chunk_size); snprintf(filename, sizeof(filename), "%s-%d-iobw.tmp", mygroup, id); if (directio) flags |= O_DIRECT; fd = open(filename, flags, 0600); if (fd < 0) { fprintf(stderr, "ERROR: task %d couldn't open %s (%s)\n", id, filename, strerror(errno)); free(buf); exit(1); } /* Write */ lseek(fd, 0, SEEK_SET); n = 0; gettimeofday(&start, NULL); while (n < data_size) { i = write(fd, buf, chunk_size); if (i < 0) { fprintf(stderr, "ERROR: task %d writing to %s (%s)\n", id, filename, strerror(errno)); ret = 1; goto out; } n += i; } gettimeofday(&stop, NULL); timersub(&stop, &start, &diff); print_results(id + 1, OP_WRITE, data_size, &diff); /* Read */ lseek(fd, 0, SEEK_SET); n = 0; gettimeofday(&start, NULL); while (n < data_size) { i = read(fd, buf, chunk_size); if (i < 0) { fprintf(stderr, "ERROR: task %d reading to %s (%s)\n", id, filename, strerror(errno)); ret = 1; goto out; } n += i; } gettimeofday(&stop, NULL); timersub(&stop, &start, &diff); print_results(id + 1, OP_READ, data_size, &diff); out: close(fd); unlink(filename); free(buf); exit(ret); } static void spawn(int id) { pid_t pid; pid = fork(); switch (pid) { case -1: fprintf(stderr, "ERROR: couldn't fork thread %d\n", id); exit(1); case 0: thread(id); default: children[id] = pid; } } void signal_handler(int sig) { char filename[32]; int i; for (i = 0; i < threads; i++) if (children[i]) kill(children[i], SIGKILL); for (i = 0; i < threads; i++) { struct stat mystat; snprintf(filename, sizeof(filename), "%s-%d-iobw.tmp", mygroup, i); if (stat(filename, &mystat) < 0) continue; unlink(filename); } fprintf(stdout, "received signal %d, exiting\n", sig); exit(0); } unsigned long long memparse(char *ptr, char **retptr) { unsigned long long ret = strtoull(ptr, retptr, 0); switch (**retptr) { case 'G': case 'g': ret <<= 10; case 'M': case 'm': ret <<= 10; case 'K': case 'k': ret <<= 10; (*retptr)++; default: break; } return ret; } int main(int argc, char *argv[]) { struct timeval start, stop, diff; char *end; int i; if (argv[1] && strcmp(argv[1], "-direct") == 0) { directio = 1; argc--; argv++; } if (argc != 4) { fprintf(stderr, usage); exit(1); } if ((threads = atoi(argv[1])) == 0) { fprintf(stderr, usage); exit(1); } chunk_size = align(memparse(argv[2], &end), PAGE_SIZE); if (*end) { fprintf(stderr, usage); exit(1); } data_size = align(memparse(argv[3], &end), PAGE_SIZE); if (*end) { fprintf(stderr, usage); exit(1); } /* retrieve group name */ mygroup = getenv("MYGROUP"); if (!mygroup) { fprintf(stderr, "ERROR: undefined environment variable MYGROUP\n"); exit(1); } children = malloc(sizeof(pid_t) * threads); if (!children) { fprintf(stderr, "ERROR: not enough memory\n"); exit(1); } /* handle user interrupt */ signal(SIGINT, signal_handler); /* handle kill from shell */ signal(SIGTERM, signal_handler); fprintf(stdout, "chunk_size %zuKiB, data_size %zuKiB\n", kb(chunk_size), kb(data_size)); fflush(stdout); gettimeofday(&start, NULL); for (i = 0; i < threads; i++) spawn(i); for (i = 0; i < threads; i++) { int status; wait(&status); if (!WIFEXITED(status)) exit(1); } gettimeofday(&stop, NULL); timersub(&stop, &start, &diff); print_results(0, NUM_IOPS, data_size * threads * NUM_IOPS, &diff); fflush(stdout); free(children); exit(0); }
the_stack_data/31633.c
#include <stdio.h> #include <stdlib.h> const char *keywords[] = { "if", "for" }; char text[] = "int main(void) { \ const char text[] = \"Hello world\";\ if (true) {\ for (int i = 0; i < 10; i++) {\n\ printf(\"Hello w%crld\", \'o\');\ }\ }\ }"; #define TOKEN_DECL(enumerator, token, string) #define TOKEN_DECL_LIST \ TOKEN_DECL(TT_UNKNOWN, '\0', "unknown") \ TOKEN_DECL(TT_TEXT, '\0', "text") \ TOKEN_DECL(TT_TAB, '\t', "tab") \ TOKEN_DECL(TT_NEWLINE, '\n', "newline") \ TOKEN_DECL(TT_LITERAL, '"', "literal") \ TOKEN_DECL(TT_BRACKET_OPEN, '{', "bracket open") \ TOKEN_DECL(TT_BRACKET_CLOSE, '}', "bracket close") \ TOKEN_DECL(TT_PARENTHESES_OPEN, '(', "parenthesis open") \ TOKEN_DECL(TT_PARENTHESES_CLOSE, ')', "parenthesis close") #undef TOKEN_DECL #define TOKEN_DECL(enumerator, token, string) enumerator, enum token_types { TOKEN_DECL_LIST }; #undef TOKEN_DECL #define TOKEN_DECL(enumerator, token, string) string, static const char *token_names[] = { TOKEN_DECL_LIST }; #undef TOKEN_DECL struct token { enum token_types type; char *value; size_t len; size_t cap; struct token *next; }; struct token *token_new(struct token **prev) { struct token *new; struct token *last = NULL; if (*prev) { struct token *cur = *prev; last = cur; while (cur) { if (cur->next) last = cur->next; cur = cur->next; } } new = calloc(sizeof(struct token), 1); if (new) { new->type = TT_UNKNOWN; new->value = NULL; if (last) last->next = new; else *prev = new; } return new; } void token_free(struct token **head) { struct token *cur = *head; struct token *next; while (cur) { next = cur->next; free(cur->value); free(cur); cur = next; } *head = NULL; } void token_dump(struct token *head) { struct token *cur = head; while (cur) { printf("%p, type(%u): %s\n", cur, cur->type, token_names[cur->type]); if (cur->type == TT_TEXT) printf("\t%s\n", cur->value); cur = cur->next; } } void token_append(struct token *t, char c) { if (t->cap == 0) { t->value = calloc(1024, 1); t->cap = 1024; } else if (t->cap == t->len) { t->value = realloc(t->value, t->cap + 1024); t->cap += 1024; } // TODO realloc if (t->value) { t->value[t->len] = c; t->len++; } } int main(void) { unsigned int indent = 0; char *t = strtok(text, " "); char *c = t; const char *text = NULL; struct token *tlist = NULL; struct token *tcur = NULL; while (t) { while (*c) { switch (*c) { case '{': tcur = token_new(&tlist); tcur->type = TT_BRACKET_OPEN; break; case '}': tcur = token_new(&tlist); tcur->type = TT_BRACKET_CLOSE; break; case '(': tcur = token_new(&tlist); tcur->type = TT_PARENTHESES_OPEN; break; case ')': tcur = token_new(&tlist); tcur->type = TT_PARENTHESES_CLOSE; break; case '[': break; case ']': break; case '\t': tcur = token_new(&tlist); tcur->type = TT_TAB; indent++; break; case '\n': indent = 0; tcur = token_new(&tlist); tcur->type = TT_NEWLINE; break; case '"': tcur = token_new(&tlist); tcur->type = TT_LITERAL; break; case '\'': tcur = token_new(&tlist); tcur->type = TT_LITERAL; break; default: if (!tcur) { tcur = token_new(&tlist); tcur->type = TT_TEXT; } token_append(tcur, *c); break; } c++; } tcur = NULL; indent = 0; t = strtok(NULL, " "); c = t; } token_dump(tlist); token_free(&tlist); return 0; }
the_stack_data/139382.c
/* { dg-do compile } */ /* { dg-require-effective-target avr_tiny } */ typedef struct { char a, b, c; } abc_t; extern char varA __attribute__((absdata)); extern char varB __attribute__((absdata)); extern int arrayA[] __attribute__((absdata)); extern int arrayB[] __attribute__((absdata)); extern char arrayC[] __attribute__((address(0x80))); extern abc_t abc __attribute__((absdata)); char get_1 (void) { return varA; } int get_2 (void) { return arrayA[3]; } char get_3 (void) { return abc.a + abc.b + abc.c; } void put_1 (char b) { varB = b; } void put_2 (int b) { arrayB[3] = b; } void put_3 (void) { abc.a = abc.b = abc.c = 0; } void put_4 (void) { arrayC[0] = arrayC[1] = arrayC[2] = 0; } /* { dg-final { scan-assembler "lds r\[0-9\]+,varA" } } */ /* { dg-final { scan-assembler "lds r\[0-9\]+,arrayA\\+6" } } */ /* { dg-final { scan-assembler "lds r\[0-9\]+,arrayA\\+6\\+1" } } */ /* { dg-final { scan-assembler "lds r\[0-9\]+,abc" } } */ /* { dg-final { scan-assembler "lds r\[0-9\]+,abc\\+1" } } */ /* { dg-final { scan-assembler "lds r\[0-9\]+,abc\\+2" } } */ /* { dg-final { scan-assembler "sts varB," } } */ /* { dg-final { scan-assembler "sts arrayB\\+6," } } */ /* { dg-final { scan-assembler "sts arrayB\\+6\\+1," } } */ /* { dg-final { scan-assembler "sts arrayC," } } */ /* { dg-final { scan-assembler "sts arrayC\\+1," } } */ /* { dg-final { scan-assembler "sts arrayC\\+2," } } */ /* { dg-final { scan-assembler "sts abc," } } */ /* { dg-final { scan-assembler "sts abc\\+1," } } */ /* { dg-final { scan-assembler "sts abc\\+2," } } */
the_stack_data/16175.c
#include <stdio.h> #include <stdlib.h> char* reverse(char *p) { int l,i; char t; for(l=0;*(p+l)<'\0';l++); for(i=0;i<l/2;i++) { t=*(p+i); *(p+i)=*(p+l-1-i); *(p+l-1-i)=t; } return(p); } int length(char *p) { int i; for(i=0;*(p+i)!='\0';i++); return(i); } int main() { printf("%d",length("computer")); printf("%s",reverse("computer")); return 0; }
the_stack_data/247018704.c
#include <stdio.h> int main() { int i; for (i=32; i<127; i++) { printf("%d - %c\n", i, i); } return 0; }
the_stack_data/1069760.c
/* Test that ifcvt is not being too aggressive when -mrestrict-it. */ /* { dg-do compile } */ /* { dg-options "-O2 -mrestrict-it" } */ /* { dg-require-effective-target arm_thumb2_ok } */ int f1(int x, int y, int z) { if (x > 100) { x++; z = -z; } else { x = -x; y = -y; z = 1; } return x + y + z; } /* { dg-final { scan-assembler "b(gt|le)" } } */
the_stack_data/637701.c
/* Copyright (c) 2021, Daniel Florescu */ #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #define INITIAL_SIZE 3 static char *progname = ""; #define die(...) \ { \ fprintf(stderr, "%s: ", progname); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ exit(1); \ } #define warn(...) \ { \ fprintf(stderr, "%s: ", progname); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ } static bool a_flag = false; static int tee(const char **name_arr, FILE **fp_arr, size_t fp_len); int main(int argc, char *argv[]) { FILE **fp_arr = NULL; size_t fp_len = 0; const char **name_arr = NULL; int ch = 0, code = 0; progname = argv[0]; while ((ch = getopt(argc, argv, "ai")) != -1) { switch (ch) { case 'a': a_flag = true; break; case 'i':; sigset_t mask; sigaddset(&mask, SIGINT); sigprocmask(SIG_BLOCK, &mask, NULL); break; default: fprintf(stderr, "usage: %s [-ai] [file ...]\n", progname); return 1; } } argc -= optind; argv += optind; /* +1 Count stdin. */ fp_len = argc + 1; fp_arr = calloc(fp_len, sizeof(FILE*)); if (fp_arr == NULL) die("failed to allocate: %s", strerror(errno)); name_arr = calloc(fp_len, sizeof(char*)); if (name_arr == NULL) die("failed to allocate: %s", strerror(errno)); /* Open files. */ name_arr[0] = "stdout"; fp_arr[0] = stdout; setvbuf(stdout, NULL, _IONBF, 0); /* Disable buffering. */ for (size_t i = 1; i < fp_len; i++) { name_arr[i] = argv[i - 1]; fp_arr[i] = fopen(argv[i - 1], a_flag ? "a" : "w"); if (fp_arr[i] == NULL) { warn("%s: %s", argv[i - 1], strerror(errno)); i--; /* Start at same index as last. */ fp_len--; /* One less file opened. */ argv[i - 1] = NULL; /* Hide name. */ continue; } setvbuf(fp_arr[i], NULL, _IONBF, 0); /* Disable buffering. */ } /* R/W loop. */ code = tee(name_arr, fp_arr, fp_len); /* Cleanup */ for (size_t i = 1; i < fp_len; i++) { fclose(fp_arr[i]); fp_arr[i] = NULL; } free(fp_arr); return code; } static int tee(const char **name_arr, FILE **fp_arr, size_t fp_len) { char buffer[BUFSIZ] = {0}; size_t bytes = 0, failed_writes = 0; int code = 0; /* R/W loop */ while ((bytes = fread(buffer, 1, sizeof(buffer), stdin)) != 0) { failed_writes = 0; for (size_t i = 0; i < fp_len; i++) { if (fwrite(buffer, 1, bytes, fp_arr[i]) != bytes) { warn("%s: %s", name_arr[i], strerror(errno)); failed_writes++; } } if (failed_writes == fp_len) { die("failed to write to all"); } } if (ferror(stdin)) die("stdin: %s", strerror(errno)); return code; }
the_stack_data/95451002.c
/*Name: Sangeeta Singh Roll no: 22339 Batch: F7 */ #include <stdio.h> int main() { int n, sum = 0; printf("Enter a number: "); scanf("%d", &n); while (n > 0) { sum += n % 10; n = n / 10; } printf("The sum of the digits is %d \n", sum); return 0; }
the_stack_data/148578619.c
#include <stdio.h> #define IDX 0 typedef struct _Node { int index; int data; struct _Node * next; } Node; Node * node_delete(Node * head, int index); int main(void) { Node * head_main = NULL; head_main = node_delete(head_main, IDX); printf("%d", head_main->data); return 0; } Node * node_delete(Node * head_main, int index_main) { Node * head_local = head_main; while (head_local->index != index_main) { head_local = head_local->next; } return head_local; }
the_stack_data/232956520.c
#ifndef REGTEST #include <threads.h> int mtx_timedlock(mtx_t *restrict mtx, const struct timespec *restrict ts) { return mtx_lock(mtx); } #endif #ifdef TEST #include "_PDCLIB_test.h" int main( void ) { return TEST_RESULTS; } #endif
the_stack_data/101588.c
/* { dg-do compile } */ /* { dg-options "-mbig-endian" } */ typedef int __attribute__((vector_size(16))) v4si; struct S2823 {v4si a;int b[0];}; void checkx2823 (struct S2823 args){};
the_stack_data/92325124.c
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> int main(void) { char *out; int x = asprintf(&out, "Hello, world!\n"); if (x > 0) { printf("Stored at %p: %s\n", out, out); free(out); } return !(x > 0); }
the_stack_data/100141146.c
int main(){20-10*1+2 <= 2*7;}
the_stack_data/154831927.c
/* PsychToolbox3/Source/Linux/Screen/PsychWindowGlueWayland.c PLATFORMS: This is the Linux/Wayland version only. AUTHORS: Mario Kleiner mk [email protected] HISTORY: 04-Jan-2015 mk Created - Derived from Linux/Waffle version. DESCRIPTION: Functions in this file comprise an abstraction layer for probing and controlling window state, except for window content. This is the Wayland specific backend. NOTES: Preformatted via: indent -linux -l240 -i4 PsychWindowGlueWayland.c TO DO: */ /* Only enable the native Wayland backend at compile time if explicitely requested: */ #ifdef PTB_USE_WAYLAND /* At the moment we still depend on Waffle even for "native" Wayland support. * Waffle is mostly used for initial Wayland connection setup, window creation, * and interacting with EGL to get the rendering api's setup and attached, * OpenGL contexts created and managed, GL extensions bound etc. * * Plan is to mix Wayland specific code with "minimal" Waffle here, and then incrementally * replace Waffle bits with Wayland bits as far as this is neccessary or useful. */ #ifndef PTB_USE_WAFFLE #error PTB_USE_WAFFLE not defined for PTB_USE_WAYLAND build! We depend on Waffle at the moment, so this is a no-go! #endif #include "Screen.h" #include <waffle.h> #include <waffle_wayland.h> // Number of currently open onscreen windows: static int open_windowcount = 0; // Delay to add to targetTime when manual swap scheduling is used: static double delayFromFrameStart = 0; // Tracking of currently bound OpenGL rendering context for master-thread: static struct waffle_context *currentContext = NULL; // Forward define prototype for glewContextInit(), which is normally not a public function: GLenum glewContextInit(void); #include <wayland-client.h> // This header file and corresponding implementation file currently included in our // source tree, as permitted by license. There's probably a better way to do this? #include "presentation_timing-client-protocol.h" #define ARRAY_LENGTH(a) (sizeof (a) / sizeof (a)[0]) // These are defined in PsychScreenGlueWayland.c: extern struct waffle_display *waffle_display; extern struct wl_display* wl_display; extern struct wl_compositor* wl_compositor; extern EGLDisplay egl_display; extern uint32_t wayland_presentation_clock_id; // wl_output* for all screens, from PsychScreenGlueWayland.c: extern struct wl_output* displayWaylandOutputs[kPsychMaxPossibleDisplays]; // Read-only access this gem from PsychScreenGlue.c: extern psych_bool displayOriginalCGSettingsValid[kPsychMaxPossibleDisplays]; // From PsychScreenGlueWayland.c: struct presentation *get_wayland_presentation_extension(PsychWindowRecordType* windowRecord); // Container with feedback about a completed swap - the equivalent of // our good old INTEL_swap_event on X11/GLX, here for Wayland: struct wayland_feedback { PsychWindowRecordType *windowRecord; unsigned int present_status; // 0 == Pending, 1 = Completed, 2 = Skipped. psych_uint64 sbc; psych_uint64 msc; psych_uint64 ust; uint32_t present_flags; struct presentation_feedback *feedback; struct timespec commit; struct timespec target; struct wl_list link; struct timespec present; }; static void destroy_wayland_feedback(struct wayland_feedback *wayland_feedback) { if (wayland_feedback->feedback) presentation_feedback_destroy(wayland_feedback->feedback); wl_list_remove(&wayland_feedback->link); free(wayland_feedback); } static uint32_t timespec_to_ms(const struct timespec *ts) { return (uint32_t)ts->tv_sec * 1000 + ts->tv_nsec / 1000000; } static void timespec_from_proto(struct timespec *tm, uint32_t tv_sec_hi, uint32_t tv_sec_lo, uint32_t tv_nsec) { tm->tv_sec = ((uint64_t)tv_sec_hi << 32) + tv_sec_lo; tm->tv_nsec = tv_nsec; } static uint64_t timespec_to_us(const struct timespec *ts) { return (uint64_t) ts->tv_sec * 1000000 + ts->tv_nsec / 1000; } static int timespec_diff_to_usec(const struct timespec *a, const struct timespec *b) { time_t secs = a->tv_sec - b->tv_sec; long nsec = a->tv_nsec - b->tv_nsec; return secs * 1000000 + nsec / 1000; } static char * wayland_pflags_to_str(uint32_t flags, char *str, unsigned len) { static const struct { uint32_t flag; char sym; } desc[] = { { PRESENTATION_FEEDBACK_KIND_VSYNC, 's' }, { PRESENTATION_FEEDBACK_KIND_HW_CLOCK, 'c' }, { PRESENTATION_FEEDBACK_KIND_HW_COMPLETION, 'e' }, { PRESENTATION_FEEDBACK_KIND_ZERO_COPY, 'z' }, }; unsigned i; *str = '\0'; if (len < ARRAY_LENGTH(desc) + 1) return str; for (i = 0; i < ARRAY_LENGTH(desc); i++) str[i] = flags & desc[i].flag ? desc[i].sym : '_'; str[ARRAY_LENGTH(desc)] = '\0'; return str; } static void wayland_feedback_presented(void *data, struct presentation_feedback *presentation_feedback, uint32_t tv_sec_hi, uint32_t tv_sec_lo, uint32_t tv_nsec, uint32_t refresh_nsec, uint32_t seq_hi, uint32_t seq_lo, uint32_t flags) { struct wayland_feedback *wayland_feedback = data; PsychWindowRecordType *windowRecord = wayland_feedback->windowRecord; uint64_t msc = ((uint64_t) seq_hi << 32) + seq_lo; uint32_t commit, present; uint32_t f2c, c2p, f2p; int p2p, t2p; char flagstr[10]; // Translate protocol presentation timestamp to a timespec: timespec_from_proto(&wayland_feedback->present, tv_sec_hi, tv_sec_lo, tv_nsec); commit = timespec_to_ms(&wayland_feedback->commit); present = timespec_to_ms(&wayland_feedback->present); // Time delta in msecs between swap scheduled and completed: c2p = present - commit; // Compute delta in usecs between successive swaps: if (wayland_feedback->sbc > 1) { p2p = timespec_to_us(&wayland_feedback->present) - windowRecord->reference_ust; // Compute delta in usecs between target time and true time of swap: t2p = timespec_diff_to_usec(&wayland_feedback->present, &wayland_feedback->target); } else { p2p = 0; t2p = 0; } if (PsychPrefStateGet_Verbosity() > 4) { printf("PTB-DEBUG: SBC = %6lu: c2p %4u ms, p2p %5d us (refresh %6u us), t2p %6d us, [%s] MSC %" PRIu64 "\n", wayland_feedback->sbc, c2p, p2p, refresh_nsec / 1000, t2p, wayland_pflags_to_str(flags, flagstr, sizeof(flagstr)), msc); } // Record sbc, msc, ust, present flags of this completed swap: // Once for the feedback events used by our Screen('GetFlipInfo') logging functions: wayland_feedback->present_status = 1; // "Presented". wayland_feedback->present_flags = flags; wayland_feedback->msc = msc; wayland_feedback->ust = timespec_to_us(&wayland_feedback->present); // Once for the windowRecord for internal use by PsychOSGetSwapCompletionTimestamp() internal // timestamping and swap reliability asessment: windowRecord->reference_sbc = wayland_feedback->sbc; windowRecord->reference_msc = msc; windowRecord->reference_ust = wayland_feedback->ust; windowRecord->swapcompletiontype = flags; // Delete our own completion wayland_feedback container if swap completion logging // isn't enabled: if (windowRecord->swapevents_enabled == 0) destroy_wayland_feedback(wayland_feedback); return; } static void wayland_feedback_discarded(void *data, struct presentation_feedback *presentation_feedback) { struct wayland_feedback *wayland_feedback = data; PsychWindowRecordType *windowRecord = wayland_feedback->windowRecord; if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Wayland presentation request discarded for SBC = %lu !\n", wayland_feedback->sbc); // Once for the feedback events used by our Screen('GetFlipInfo') logging functions: wayland_feedback->present_status = 2; // "Discarded/Skipped". wayland_feedback->present_flags = 0; wayland_feedback->msc = 0; wayland_feedback->ust = 0; // Once for the windowRecord for internal use by PsychOSGetSwapCompletionTimestamp() internal // timestamping and swap reliability asessment: windowRecord->reference_sbc = wayland_feedback->sbc; windowRecord->reference_msc = 0; windowRecord->reference_ust = 0; windowRecord->swapcompletiontype = -1; // "Presentation discarded/Skipped" // Delete our own completion wayland_feedback container if swap completion logging // isn't enabled: if (windowRecord->swapevents_enabled == 0) destroy_wayland_feedback(wayland_feedback); } static void wayland_feedback_sync_output(void *data, struct presentation_feedback *presentation_feedback, struct wl_output *output) { struct wayland_feedback *wayland_feedback = data; PsychWindowRecordType *windowRecord = wayland_feedback->windowRecord; if (PsychPrefStateGet_Verbosity() > 10) { printf("PTB-INFO: Window %i uses Wayland output %p.\n", windowRecord->windowIndex, output); } } static const struct presentation_feedback_listener wayland_feedback_listener = { wayland_feedback_sync_output, wayland_feedback_presented, wayland_feedback_discarded }; static void wayland_window_create_feedback(PsychWindowRecordType* windowRecord) { struct presentation *wayland_pres = get_wayland_presentation_extension(windowRecord); struct wayland_feedback *wayland_feedback; struct wl_surface *wl_surface; struct waffle_wayland_window *wayland_window; struct waffle_window* window = windowRecord->targetSpecific.windowHandle; // Retrieve underlying native Wayland window: union waffle_native_window *wafflewin = waffle_window_get_native(window); wayland_window = wafflewin->wayland; wl_surface = wayland_window->wl_surface; free(wafflewin); wafflewin = NULL; // Noop if presentation_feedback extension unavailable: if (!wayland_pres) return; // Create our own wayland_feedback container for swap completion events: wayland_feedback = calloc(1, sizeof(*wayland_feedback)); if (!wayland_feedback) return; wayland_feedback->windowRecord = windowRecord; wayland_feedback->sbc = ++(windowRecord->submitted_sbc); // Create wayland present_feedback object, attach listener callbacks to it: wayland_feedback->feedback = presentation_feedback(wayland_pres, wl_surface); presentation_feedback_add_listener(wayland_feedback->feedback, &wayland_feedback_listener, wayland_feedback); // Record approximate time of swap submission according to the compositor clock: clock_gettime(wayland_presentation_clock_id, &wayland_feedback->commit); wayland_feedback->target = wayland_feedback->commit; // Add to our queue of pending swap completion events: wl_list_insert(&windowRecord->targetSpecific.presentation_feedback_list, &wayland_feedback->link); } // Perform OS specific processing of Window events: void PsychOSProcessEvents(PsychWindowRecordType *windowRecord, int flags) { int w, h, x, y; // Trigger event queue dispatch processing for GUI windows: if (windowRecord == NULL) { // No op, so far... return; } // No-Op if we don't have a valid Wayland window: if (!windowRecord->targetSpecific.xwindowHandle) return; // TODO: Probably call Wayland display sync and use info from surface configure // event. No-Op for now: return; // GUI windows need to behave GUIyee: if ((windowRecord->specialflags & kPsychGUIWindow) && PsychIsOnscreenWindow(windowRecord)) { // Update windows rect and globalrect, based on current size and location: PsychLockDisplay(); x = y = w = h = 0; PsychUnlockDisplay(); PsychMakeRect(windowRecord->globalrect, x, y, x + (int) w, y + (int) h); PsychNormalizeRect(windowRecord->globalrect, windowRecord->rect); PsychSetupClientRect(windowRecord); PsychSetupView(windowRecord, FALSE); } } /* PsychOSOpenOnscreenWindow() Creates the pixel format and the context objects and then instantiates the context onto the screen. -The pixel format and the context are stored in the target specific field of the window recored. Close should clean up by destroying both the pixel format and the context. -We mantain the context because it must be be made the current context by drawing functions to draw into the specified window. -We maintain the pixel format object because there seems to be now way to retrieve that from the context. -To tell the caller to clean up PsychOSOpenOnscreenWindow returns FALSE if we fail to open the window. It would be better to just issue an PsychErrorExit() and have that clean up everything allocated outside of PsychOpenOnscreenWindow(). */ psych_bool PsychOSOpenOnscreenWindow(PsychScreenSettingsType * screenSettings, PsychWindowRecordType * windowRecord, int numBuffers, int stereomode, int conserveVRAM) { char windowTitle[32]; PsychRectType screenrect; CGDirectDisplayID dpy; int scrnum; unsigned long mask; int i, x, y, width, height, nrconfigs, buffdepth; GLenum glerr; int32_t attrib[41]; int attribcount = 0; int stereoenableattrib = 0; int depth, bpc; int windowLevel; int32_t opengl_api; char backendname[16]; char backendname2[16]; struct waffle_config *config; struct waffle_window *window; union waffle_native_window *wafflewin; struct waffle_wayland_window *wayland_window; struct waffle_context *ctx; // Define default rendering backend: #ifdef PTB_USE_GLES1 opengl_api = WAFFLE_CONTEXT_OPENGL_ES1; #else opengl_api = WAFFLE_CONTEXT_OPENGL; #endif // Map the logical screen number to the corresponding X11 display connection handle // for the corresponding X-Server connection. PsychGetCGDisplayIDFromScreenNumber(&dpy, screenSettings->screenNumber); // TODO FIXME: We currently don't have any way of selecting the target X-Screen 'scrnum' for // our window, as Waffle does not yet support selection of X-Screen. It always opens // windows on the display's default screen. Therefore this is mostly a dead placeholder for now: scrnum = PsychGetXScreenIdForScreen(screenSettings->screenNumber); // Include onscreen window index in title: sprintf(windowTitle, "PTB Onscreen Window [%i]:", windowRecord->windowIndex); // Set windowing system backend type for this window to Wayland: windowRecord->winsysType = (int) WAFFLE_PLATFORM_WAYLAND; // Translate spec to human readable name and spec string: sprintf(backendname, "Wayland/EGL"); sprintf(backendname2, "wayland"); // Announce actual choice of backend to runtime environment. This is a marker // to, e.g., moglcore, so it can adapt its context/gl setup: setenv("PSYCH_USE_DISPLAY_BACKEND", backendname2, 1); if (PsychPrefStateGet_Verbosity() > 3) { printf("PTB-INFO: Wayland display backend '%s' initialized [%s].\n", backendname, backendname2); } // Allow usercode to override our default backend choice via environment variable: if (getenv("PSYCH_USE_GFX_BACKEND")) { if (!strcmp(getenv("PSYCH_USE_GFX_BACKEND"), "gl")) opengl_api = WAFFLE_CONTEXT_OPENGL; if (!strcmp(getenv("PSYCH_USE_GFX_BACKEND"), "gles1")) opengl_api = WAFFLE_CONTEXT_OPENGL_ES1; if (!strcmp(getenv("PSYCH_USE_GFX_BACKEND"), "gles2")) opengl_api = WAFFLE_CONTEXT_OPENGL_ES2; if (!strcmp(getenv("PSYCH_USE_GFX_BACKEND"), "gles3")) opengl_api = WAFFLE_CONTEXT_OPENGL_ES3; } switch (opengl_api) { case WAFFLE_CONTEXT_OPENGL: sprintf(backendname, "OpenGL"); break; case WAFFLE_CONTEXT_OPENGL_ES1: sprintf(backendname, "OpenGL-ES 1"); break; case WAFFLE_CONTEXT_OPENGL_ES2: sprintf(backendname, "OpenGL-ES 2"); break; case WAFFLE_CONTEXT_OPENGL_ES3: sprintf(backendname, "OpenGL-ES 3"); break; default: sprintf(backendname, "UNKNOWN"); } // Try the requested backend, try alternate backends on failure: if (!waffle_display_supports_context_api(waffle_display, opengl_api)) { if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Selected Waffle display backend does not support requested OpenGL rendering API '%s': %s. Trying fallbacks...\n", backendname, waffle_error_to_string(waffle_error_get_code())); // Try fallbacks: OpenGL > OpenGL-ES1 > OpenGL-ES2 > OpenGL-ES3 if (waffle_display_supports_context_api(waffle_display, WAFFLE_CONTEXT_OPENGL)) { opengl_api = WAFFLE_CONTEXT_OPENGL; } else if (waffle_display_supports_context_api(waffle_display, WAFFLE_CONTEXT_OPENGL_ES1)) { opengl_api = WAFFLE_CONTEXT_OPENGL_ES1; } else if (waffle_display_supports_context_api(waffle_display, WAFFLE_CONTEXT_OPENGL_ES2)) { opengl_api = WAFFLE_CONTEXT_OPENGL_ES2; } else if (waffle_display_supports_context_api(waffle_display, WAFFLE_CONTEXT_OPENGL_ES3)) { opengl_api = WAFFLE_CONTEXT_OPENGL_ES3; } else { // Game over: if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: Waffle display backend does not support any OpenGL rendering API: %s. Game over!\n", waffle_error_to_string(waffle_error_get_code())); return(FALSE); } } // Assign human readable name to selected OpenGL rendering api. Also assign // type flag for higher-level code: switch (opengl_api) { case WAFFLE_CONTEXT_OPENGL: sprintf(backendname, "OpenGL"); sprintf(backendname2, "gl"); windowRecord->glApiType = 0; break; case WAFFLE_CONTEXT_OPENGL_ES1: sprintf(backendname, "OpenGL-ES 1"); sprintf(backendname2, "gles1"); windowRecord->glApiType = 10; break; case WAFFLE_CONTEXT_OPENGL_ES2: sprintf(backendname, "OpenGL-ES 2"); sprintf(backendname2, "gles2"); windowRecord->glApiType = 20; break; case WAFFLE_CONTEXT_OPENGL_ES3: sprintf(backendname, "OpenGL-ES 3"); sprintf(backendname2, "gles3"); windowRecord->glApiType = 30; break; default: sprintf(backendname, "UNKNOWN"); sprintf(backendname2, "X"); windowRecord->glApiType = 0; } // Tell environment about our final rendering backend choice: setenv("PSYCH_USE_GFX_BACKEND", backendname2, 1); // OpenGL embedded subset api in use? if (windowRecord->glApiType > 0) { if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Waffle display backend connected to OpenGL rendering API '%s' [%s].\n", backendname, backendname2); // Yes: Try to disable all OpenGL error checking for now during initial OpenGL-ES support bringup. // We know there will be many errors due to incompatibilities but just try to keep going and rely // on external trace and debug tools to find and fix errors at this point: PsychPrefStateSet_ConserveVRAM(PsychPrefStateGet_ConserveVRAM() | kPsychAvoidCPUGPUSync); if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Will try to disable/suppress all internal OpenGL error reporting/handling for OpenGL-ES operation.\n"); } // Mark window as EGL controlled: windowRecord->specialflags |= kPsychIsEGLWindow; // Retrieve windowLevel, an indicator of where non-fullscreen windows should // be located wrt. to other windows. 0 = Behind everything else, occluded by // everything else. 1 - 999 = At layer windowLevel -> Occludes stuff on layers "below" it. // 1000 - 1999 = At highest level, but partially translucent / alpha channel allows to make // regions transparent. 2000 or higher: Above everything, fully opaque, occludes everything. // 2000 is the default. windowLevel = PsychPrefStateGet_WindowShieldingLevel(); // Init userspace GL context to safe default: windowRecord->targetSpecific.glusercontextObject = NULL; windowRecord->targetSpecific.glswapcontextObject = NULL; // Default to use of one shared x-display connection "dpy" for all onscreen windows // on a given x-display and x-screen: // windowRecord->targetSpecific.privDpy = dpy; // HACK TODO: windowRecord->targetSpecific.privDpy = NULL; // Check if this should be a fullscreen window: PsychGetScreenRect(screenSettings->screenNumber, screenrect); if (PsychMatchRect(screenrect, windowRecord->rect)) windowRecord->specialflags |= kPsychIsFullscreenWindow; PsychGetGlobalScreenRect(screenSettings->screenNumber, screenrect); if (PsychMatchRect(screenrect, windowRecord->rect)) windowRecord->specialflags |= kPsychIsFullscreenWindow; if (windowRecord->specialflags & kPsychIsFullscreenWindow) { // This is supposed to be a fullscreen window with the dimensions of // the current display/desktop: x = 0; y = 0; width = PsychGetWidthFromRect(screenrect); height = PsychGetHeightFromRect(screenrect); // Mark this window as fullscreen window: windowRecord->specialflags |= kPsychIsFullscreenWindow; // Copy absolute screen location and area of window to 'globalrect', // so functions like Screen('GlobalRect') can still query the real // bounding box of a window onscreen: PsychGetGlobalScreenRect(screenSettings->screenNumber, windowRecord->globalrect); } else { // Window size different from current screen size: // A regular desktop window with borders and control icons is requested, e.g., for debugging: // Extract settings: x = windowRecord->rect[kPsychLeft]; y = windowRecord->rect[kPsychTop]; width = PsychGetWidthFromRect(windowRecord->rect); height = PsychGetHeightFromRect(windowRecord->rect); // Copy absolute screen location and area of window to 'globalrect', // so functions like Screen('GlobalRect') can still query the real // bounding gox of a window onscreen: PsychCopyRect(windowRecord->globalrect, windowRecord->rect); } // Select OpenGL context API for use with this window: attrib[attribcount++] = WAFFLE_CONTEXT_API; attrib[attribcount++] = opengl_api; // Which display depth is supported? depth = PsychGetValueFromDepthStruct(0, &(screenSettings->depth)); // Select requested depth per color component 'bpc' for each channel: bpc = 8; // We default to 8 bpc == RGBA8 if (windowRecord->depth == 30) { bpc = 10; if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Trying to enable at least 10 bpc fixed point framebuffer.\n"); } if (windowRecord->depth == 33) { bpc = 11; if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Trying to enable at least 11 bpc fixed point framebuffer.\n"); } if (windowRecord->depth == 48) { bpc = 16; if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Trying to enable at least 16 bpc fixed point framebuffer.\n"); } if (windowRecord->depth == 64) { bpc = 16; if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Trying to enable 16 bpc fixed point framebuffer.\n"); } if (windowRecord->depth == 128) { bpc = 32; if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Trying to enable 32 bpc fixed point framebuffer.\n"); } attrib[attribcount++] = WAFFLE_RED_SIZE; // Setup requested minimum depth of each color channel: attrib[attribcount++] = (depth > 16) ? bpc : 1; attrib[attribcount++] = WAFFLE_GREEN_SIZE; attrib[attribcount++] = (depth > 16) ? bpc : 1; attrib[attribcount++] = WAFFLE_BLUE_SIZE; attrib[attribcount++] = (depth > 16) ? bpc : 1; attrib[attribcount++] = WAFFLE_ALPHA_SIZE; // Alpha channel needs special treatment: if ((bpc != 10) && (bpc != 11)) { // Non 10/11 bpc drawable: Request a 'bpc' alpha channel if the underlying framebuffer // is in true-color mode ( >= 24 bpp format). If framebuffer is in 16 bpp mode, we // don't have/request an alpha channel at all: attrib[attribcount++] = (depth > 16) ? bpc : 0; // In 16 bit mode, we don't request an alpha-channel. } else if (bpc == 10) { // 10 bpc drawable: We have a 32 bpp pixel format with R10G10B10 10 bpc per color channel. // There are at most 2 bits left for the alpha channel, so we request an alpha channel with // minimum size 1 bit --> Will likely translate into a 2 bit alpha channel: attrib[attribcount++] = 1; } else { // 11 bpc drawable - or more likely a 32 bpp drawable with R11G11B10, ie., all 32 bpp // used up by RGB color info and no space for alpha bits. Therefore do not request an // alpha channel: attrib[attribcount++] = 0; } // Stereo display support: If stereo display output is requested with OpenGL native stereo, // we request a stereo-enabled rendering context. Or at least we would, if Waffle would support this. if (stereomode == kPsychOpenGLStereo) { if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: OpenGL native quad-buffered stereomode requested, but this is not supported by the Wayland backend.\n"); } // Multisampling support: if (windowRecord->multiSample > 0) { // Request a multisample buffer: attrib[attribcount++] = WAFFLE_SAMPLE_BUFFERS; attrib[attribcount++] = 1; // Request at least multiSample samples per pixel: attrib[attribcount++] = WAFFLE_SAMPLES; attrib[attribcount++] = windowRecord->multiSample; } // Support for OpenGL 3D rendering requested? if (PsychPrefStateGet_3DGfx()) { // Yes. Allocate and attach a 24 bit depth buffer and 8 bit stencil buffer: attrib[attribcount++] = WAFFLE_DEPTH_SIZE; attrib[attribcount++] = 24; attrib[attribcount++] = WAFFLE_STENCIL_SIZE; attrib[attribcount++] = 8; // Alloc an accumulation buffer as well? if (PsychPrefStateGet_3DGfx() & 2) { // Yes: Allocate an accumulation buffer if possible: attrib[attribcount++] = WAFFLE_ACCUM_BUFFER; attrib[attribcount++] = 1; } } // Double buffering requested? attrib[attribcount++] = WAFFLE_DOUBLE_BUFFERED; attrib[attribcount++] = (numBuffers >= 2) ? 1 : 0; // Finalize attrib array: attrib[attribcount++] = 0; PsychLockDisplay(); // Choose waffle configuration for attrib's - the equivalent of // a pixelformat or framebuffer config in GLX speak: config = waffle_config_choose(waffle_display, attrib); if (!config) { // Failed to find matching visual: Could it be related to request for unsupported native 10/11/16 bpc framebuffer? if (((windowRecord->depth == 30) && (bpc == 10)) || ((windowRecord->depth == 33) && (bpc == 11)) || ((windowRecord->depth == 48) && (bpc == 16))) { // 10/11/16 bpc framebuffer requested: Let's see if we can get a visual by lowering our demand to 8 bpc: for (i = 0; i < attribcount && attrib[i] != WAFFLE_RED_SIZE; i++); attrib[i + 1] = 8; for (i = 0; i < attribcount && attrib[i] != WAFFLE_GREEN_SIZE; i++); attrib[i + 1] = 8; for (i = 0; i < attribcount && attrib[i] != WAFFLE_BLUE_SIZE; i++); attrib[i + 1] = 8; for (i = 0; i < attribcount && attrib[i] != WAFFLE_ALPHA_SIZE; i++); attrib[i + 1] = 1; // Retry: config = waffle_config_choose(waffle_display, attrib); } } if (!config) { // Failed to find matching visual: Could it be related to multisampling? if (windowRecord->multiSample > 0) { // Multisampling requested: Let's see if we can get a visual by // lowering our demand: for (i = 0; i < attribcount && attrib[i] != WAFFLE_SAMPLES; i++); while (!config && windowRecord->multiSample > 0) { attrib[i + 1]--; windowRecord->multiSample--; config = waffle_config_choose(waffle_display, attrib); } // Either we have a valid visual at this point or we still fail despite // requesting zero samples. if (!config) { // We still fail. Disable multisampling by requesting zero multisample buffers: for (i = 0; i < attribcount && attrib[i] != WAFFLE_SAMPLE_BUFFERS; i++); windowRecord->multiSample = 0; attrib[i + 1] = 0; config = waffle_config_choose(waffle_display, attrib); } } // Worked? If not, see if we can lower our 3D settings if in 3D mode: if (!config && PsychPrefStateGet_3DGfx()) { // Ok, retry with a 16 bit depth buffer... for (i = 0; i < attribcount && attrib[i] != WAFFLE_DEPTH_SIZE; i++); if (attrib[i] == WAFFLE_DEPTH_SIZE && i < attribcount) attrib[i + 1] = 16; if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Have to use 16 bit depth buffer instead of 24 bit buffer due to limitations of your gfx-hardware or driver. Accuracy of 3D-Gfx may be limited...\n"); config = waffle_config_choose(waffle_display, attrib); if (!config) { // Failed again. Retry with disabled stencil buffer: if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Have to disable stencil buffer due to limitations of your gfx-hardware or driver. Some 3D Gfx algorithms may fail...\n"); for (i = 0; i < attribcount && attrib[i] != WAFFLE_STENCIL_SIZE; i++); if (attrib[i] == WAFFLE_STENCIL_SIZE && i < attribcount) attrib[i + 1] = 0; config = waffle_config_choose(waffle_display, attrib); } } } if (!config) { // Ok, nothing worked. Require the absolute minimum configuration: if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Could not get any display configuration matching your minimum requirements. Trying to get the bare minimum config of a RGB framebuffer of arbitrarily low resolution now.\n"); attribcount = 0; attrib[attribcount++] = WAFFLE_CONTEXT_API; attrib[attribcount++] = opengl_api; attrib[attribcount++] = WAFFLE_RED_SIZE; attrib[attribcount++] = 1; attrib[attribcount++] = WAFFLE_GREEN_SIZE; attrib[attribcount++] = 1; attrib[attribcount++] = WAFFLE_BLUE_SIZE; attrib[attribcount++] = 1; attrib[attribcount++] = WAFFLE_ALPHA_SIZE; attrib[attribcount++] = WAFFLE_DONT_CARE; config = waffle_config_choose(waffle_display, attrib); } // Finally? if (!config) { // Game over: if (PsychPrefStateGet_Verbosity() > 0) printf("\nPTB-ERROR[waffle_config_choose() failed]: Couldn't get any suitable visual from display backend.\n\n"); PsychUnlockDisplay(); return (FALSE); } // Create our onscreen window: window = waffle_window_create(config, width, height); wafflewin = waffle_window_get_native(window); wayland_window = wafflewin->wayland; // Set hints for window sizing and positioning: // TODO FIXME Wayland... { XSizeHints sizehints; sizehints.x = x; sizehints.y = y; sizehints.width = width; sizehints.height = height; // Let window manager control window position if kPsychGUIWindowWMPositioned is set: sizehints.flags = USSize | (windowRecord->specialflags & kPsychGUIWindowWMPositioned) ? 0 : USPosition; } // Create associated OpenGL rendering context: We use ressource // sharing of textures, display lists, FBO's and shaders if 'slaveWindow' // is assigned for that purpose as master-window. ctx = waffle_context_create(config, ((windowRecord->slaveWindow) ? windowRecord->slaveWindow->targetSpecific.contextObject : NULL)); if (!ctx) { if (PsychPrefStateGet_Verbosity() > 0) printf("\nPTB-ERROR:[waffle_context_create() failed] OpenGL context creation failed: %s\n\n", waffle_error_to_string(waffle_error_get_code())); PsychUnlockDisplay(); return (FALSE); } // Store the handles: // windowHandle is a waffle_window*: windowRecord->targetSpecific.windowHandle = window; // xwindowHandle stores the underlying Wayland "window": windowRecord->targetSpecific.xwindowHandle = wayland_window->wl_surface; // Provide a pointer back to windowRecord in the wl_surface: wl_surface_set_user_data(wayland_window->wl_surface, (void *) windowRecord); // waffle_display* windowRecord->targetSpecific.deviceContext = waffle_display; // waffle_context* windowRecord->targetSpecific.contextObject = ctx; // Create rendering context for async flips with identical config as main context, share all heavyweight ressources with it: windowRecord->targetSpecific.glswapcontextObject = waffle_context_create(config, windowRecord->targetSpecific.contextObject); if (windowRecord->targetSpecific.glswapcontextObject == NULL) { if (PsychPrefStateGet_Verbosity() > 0) printf("\nPTB-ERROR[SwapContextCreation failed]: Creating a private OpenGL context for async flips failed for unknown reasons.\n\n"); PsychUnlockDisplay(); return (FALSE); } // External 3D graphics support enabled? if (PsychPrefStateGet_3DGfx()) { // Yes. We need to create an extra OpenGL rendering context for the external // OpenGL code to provide optimal state-isolation. The context shares all // heavyweight ressources likes textures, FBOs, VBOs, PBOs, display lists and // starts off as an identical copy of PTB's context as of here. // Create rendering context with identical config as main context, share all heavyweight ressources with it: windowRecord->targetSpecific.glusercontextObject = waffle_context_create(config, windowRecord->targetSpecific.contextObject); if (windowRecord->targetSpecific.glusercontextObject == NULL) { if (PsychPrefStateGet_Verbosity() > 0) printf("\nPTB-ERROR[UserContextCreation failed]: Creating a private OpenGL context for MOGL failed for unknown reasons.\n\n"); PsychUnlockDisplay(); return (FALSE); } } // Release config info: waffle_config_destroy(config); // Setup window transparency: if ((windowLevel >= 1000) && (windowLevel < 2000)) { // For windowLevels between 1000 and 1999, make the window background transparent, so standard GUI // would be visible, wherever nothing is drawn, i.e., where alpha channel is zero: // Levels 1000 - 1499 and 1500 to 1999 map to a master opacity level of 0.0 - 1.0: unsigned int opacity = (unsigned int)(0xffffffff * (((float)(windowLevel % 500)) / 499.0)); // TODO FIXME Wayland... } // If this window is a GUI window then enable all window decorations and // manipulations, except for the window close button, which would wreak havoc: if (windowRecord->specialflags & kPsychGUIWindow) { // TODO Wayland } // For windowLevels of at least 500, tell window manager to try to keep // our window above most other windows, by setting the state to WM_STATE_ABOVE: if (windowLevel >= 500) { // TODO Wayland } // Sync with server: wl_display_roundtrip(wl_display); // Show our new window: if (windowLevel != -1) { struct wl_region *region = wl_compositor_create_region(wl_compositor); // Is this window supposed to be transparent to user input (mouse, keyboard etc.)? if ((windowLevel >= 1000) && (windowLevel < 1500)) { // Yes. Assign our currently empty 'region' as input region, so // the surface doesn't care about input but input is sent to // surfaces below our onscreen windows surface: wl_surface_set_input_region(wayland_window->wl_surface, region); // Note: The default input region is infinite, covering the whole // surface, ie., the whole surface accepts user input. Therefore // nothing to do in the regular case. } // Is this window supposed to be opaque / non-transparent? if (windowLevel < 1000 || windowLevel >= 2000) { // Yes. Define an opaque region the full size of the windows area: wl_region_add(region, 0, 0, width, height); wl_surface_set_opaque_region(wayland_window->wl_surface, region); } // Done with defining input and display regions, so destroy our region: wl_region_destroy(region); // Is this supposed to be a fullscreen window? if ((windowRecord->specialflags & kPsychIsFullscreenWindow) && (windowLevel < 1000 || windowLevel >= 2000)) { // Opaque fullscreen onscreen window setup: // WL_SHELL_SURFACE_FULLSCREEN_METHOD_DRIVER - Switch video output to optimal resolution to accomodate the // size of the surface, ie., the mode with the smallest resolution that can contain the surface. Add black // borders for padding if a perfect fit isn't possible. // TODO implement: 0 = Target refresh rate -- Zero == Don't change rate. if (PsychPrefStateGet_Verbosity() > 3) { printf("PTB-INFO: Opening fullscreen onscreen wl_shell_surface() window on screen %i - wl_output %p\n", screenSettings->screenNumber, displayWaylandOutputs[screenSettings->screenNumber]); } // Video refresh rate switch requested? if (displayOriginalCGSettingsValid[screenSettings->screenNumber]) { // Video refresh rate switch requested: int milliHz = (int) (PsychGetNominalFramerate(screenSettings->screenNumber) * 1000.0 + 0.5); if (PsychPrefStateGet_Verbosity() > 3) { printf("PTB-INFO: Requesting video mode switch for fullscreen windw to a target of %i x %i pixels at %i milliHz.\n", width, height, milliHz); } wl_shell_surface_set_fullscreen(wayland_window->wl_shell_surface, WL_SHELL_SURFACE_FULLSCREEN_METHOD_DRIVER, milliHz, displayWaylandOutputs[screenSettings->screenNumber]); } else { // No video refresh rate switch requested: wl_shell_surface_set_fullscreen(wayland_window->wl_shell_surface, WL_SHELL_SURFACE_FULLSCREEN_METHOD_DRIVER, 0, displayWaylandOutputs[screenSettings->screenNumber]); } } else { // A windowed window aka non-fullscreen, or a transparent fullscreen window. if (windowRecord->specialflags & kPsychGUIWindow) { // A GUI window. Nothing to do yet. } // Show it as toplevel window: wl_shell_surface_set_toplevel(wayland_window->wl_shell_surface); } // Give the window a title: wl_shell_surface_set_title(wayland_window->wl_shell_surface, windowTitle); // Make it so! wl_display_roundtrip(wl_display); } // If windowLevel is zero, lower it to the bottom of the stack of windows: if (windowLevel == 0) { // TODO Wayland } if (!(windowRecord->specialflags & kPsychGUIWindowWMPositioned)) { // TODO Wayland // XMoveWindow(dpy, win, x, y); } // Ok, the onscreen window is ready on the screen. Time for OpenGL setup... // Activate the associated rendering context: waffle_make_current(waffle_display, window, ctx); // Running on top of a FOSS Mesa graphics driver? if ((open_windowcount == 0) && strstr((const char*) glGetString(GL_VERSION), "Mesa") && !getenv("PSYCH_DONT_LOCK_MOGLCORE")) { // Yes. At least as of Mesa 10.1 as shipped in Ubuntu 14.04-LTS, Mesa // will become seriously crashy if our Screen() mex files is flushed // from memory due to a clear all/mex/Screen and afterwards reloaded. // This because Mesa maintains pointers back into our library image, // which will turn into dangling pointers if we get unloaded/reloaded // into a new location. To prevent Mesa crashes on clear Screen -> reload, // prevent this mex file against clearing from Octave/Matlab address space. // An ugly solution which renders "clear Screen" useless, but the best i can // come up with at the moment :( if (PsychRuntimeEvaluateString("moglcore('LockModule');") > 0) { if (PsychPrefStateGet_Verbosity() > 1) { printf("PTB-WARNING: Failed to enable moglcore locking workaround for Mesa OpenGL bug. Trying alternative workaround.\n"); printf("PTB-WARNING: Calling 'clear all', 'clear mex', 'clear java', 'clear moglcore' is now unsafe and may crash if you try.\n"); printf("PTB-WARNING: You may add setenv('PSYCH_DONT_LOCK_MOGLCORE','1'); to your Octave/Matlab startup script to work around this issue in future sessions.\n"); } setenv("PSYCH_DONT_LOCK_MOGLCORE", "1", 0); } else { if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Workaround: Disabled ability to 'clear moglcore', as a workaround for a Mesa OpenGL bug. Sorry for the inconvenience.\n"); } } // Ok, the OpenGL rendering context is up and running. Auto-detect and bind all // available OpenGL extensions via GLEW. Must be careful to only call GLX independent // init code as we are not using the X11/GLX backend, so call glewContextInit() instead // of the regular glewInit(): glerr = glewContextInit(); if (GLEW_OK != glerr) { /* Problem: glewContextInit failed, something is seriously wrong. */ if (PsychPrefStateGet_Verbosity() > 0) printf("\nPTB-ERROR[GLEW init failed: %s]: Please report this to the forum. Will try to continue, but may crash soon!\n\n", glewGetErrorString(glerr)); } else { if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Using GLEW version %s for automatic detection of OpenGL extensions...\n", glewGetString(GLEW_VERSION)); } fflush(NULL); // Increase our own open window counter: open_windowcount++; // Disable screensavers: if (open_windowcount == 1) { // TODO Wayland } if (!egl_display && (PsychPrefStateGet_Verbosity() > 1)) { printf("PTB-WARNING: The Wayland display backend does not allow to control synchronization of bufferswap to vertical retrace.\n"); } PsychUnlockDisplay(); // Ok, we should be ready for OS independent setup... fflush(NULL); // First opened onscreen window? If so, we try to map GPU MMIO registers // to enable beamposition based timestamping and other special goodies: if (open_windowcount == 1) PsychScreenMapRadeonCntlMemory(); PsychLockDisplay(); // Retrieve modeline of current video mode on primary crtc for the screen to which // this onscreen window is assigned. Could also query useful info about crtc, but let's not // overdo it in the first iteration... XRRCrtcInfo *crtc_info = NULL; XRRModeInfo *mode = PsychOSGetModeLine(screenSettings->screenNumber, 0, &crtc_info); if (mode) { // Assign modes display height aka vactive or vdisplay as startline of vblank interval: windowRecord->VBL_Startline = mode->height; // Assign vbl endline as vtotal - 1: // TODO: Don't know how to get this on Wayland, but not critical, as it would // only be needed for the beamposition timestamping fallback, which itself // should usually not be needed due to present_feedback extension: // windowRecord->VBL_Endline = mode->vTotal - 1; // Check for output display rotation enabled. Will likely impair timing/timestamping // because it uses copy-swaps via an intermediate shadow framebuffer to do rotation // during copy-swap blit, instead of via rotated crtc scanout, as most crtc's don't // support this in hardware: // TODO: Wayland is more clever here, but need to investigate how this maps to // our standard method of solving such issues via imaging pipeline. Leave warning // of for the moment. //if ((crtc_info->rotation != RR_Rotate_0) && (PsychPrefStateGet_Verbosity() > 1)) { // printf("PTB-WARNING: Your primary output display has hardware rotation enabled. It is not displaying in upright orientation.\n"); // printf("PTB-WARNING: On many graphics cards, this will cause unreliable stimulus presentation timing and timestamping.\n"); // printf("PTB-WARNING: If you want non-upright stimulus presentation, look at 'help PsychImaging' on how to achieve this in\n"); // printf("PTB-WARNING: a way that doesn't impair timing. The subfunctions 'FlipHorizontal' and 'FlipVertical' are what you probably need.\n"); //} XRRFreeCrtcInfo(crtc_info); } PsychUnlockDisplay(); // Display unlocked from here on... // OpenGL-ES bindings needed? if (PsychIsGLES(windowRecord)) { // Yes: Allow userspace to force rebinding: psych_bool forceRebind = (getenv("PSYCH_FORCE_REBINDGLES")) ? TRUE : FALSE; // Which version of OpenGL-ES? Set proper selector: int32_t apidl = 0; if (windowRecord->glApiType < 20) { apidl = WAFFLE_DL_OPENGL_ES1; } else if (windowRecord->glApiType < 30) { apidl = WAFFLE_DL_OPENGL_ES2; } else if (windowRecord->glApiType < 40) { apidl = WAFFLE_DL_OPENGL_ES3; } else printf("PTB-WARNING: Unsupported OpenGL-ES API version >= 4.0! Update the code, this may end badly!!\n"); // Some diagnostics for forceRebind mode: if (forceRebind) printf("PTB-DEBUG: Forced rebinding of OpenGL-ES extensions requested.\n"); if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-DEBUG: Pre-GLES-Rebind: glBindFramebufferEXT = %p , glBindFramebuffer = %p \n", (void*) glBindFramebufferEXT, (void*) waffle_dl_sym(WAFFLE_DL_OPENGL_ES2, "glBindFramebuffer")); // Try to rebind OpenGL-ES specific entry points to standard desktop OpenGL entry // points of compatible syntax and semantics, so we don't need to rewrite lots of // desktop GL support code just to account for syntactic sugar. // Needed in imaging pipeline: ES implementations don't expose the ARB suffixed version anymore, // as glActiveTexture() is part of core-spec: if (NULL == glActiveTextureARB || forceRebind) glActiveTextureARB = waffle_dl_sym(apidl, "glActiveTexture"); // Fun with NVidia ES implementation, which defines glOrthof() but not glOrthofOES() on their // desktop drivers for GeForce and Quadro and their Tegra drivers for embedded. // It is crucial to force rebind here, especially on embedded, as the entry point might // be already bound to a dead zombie desktop GL implementation lib: glOrthofOES = waffle_dl_sym(WAFFLE_DL_OPENGL_ES1, "glOrthofOES"); if (NULL == glOrthofOES) glOrthofOES = waffle_dl_sym(WAFFLE_DL_OPENGL_ES1, "glOrthof"); if (NULL == glOrthofOES) { printf("PTB-ERROR: NO glOrthofOES() or glOrthof() available under OpenGL-ES api! This will not work with OpenGL-ES! Aborting.\n"); return(FALSE); } // Bind glBlitFrameBuffer() if provided by extension or by core OpenGL-ES3: if (strstr(glGetString(GL_EXTENSIONS), "GL_NV_framebuffer_blit") || (windowRecord->glApiType >= 30)) { glBlitFramebufferEXT = waffle_dl_sym(apidl, "glBlitFramebufferNV"); if (NULL == glBlitFramebufferEXT) glBlitFramebufferEXT = waffle_dl_sym(WAFFLE_DL_OPENGL_ES3, "glBlitFramebuffer"); if (NULL == glBlitFramebufferEXT) printf("PTB-ERROR: Could not bind glBlitFramebuffer() function as expected! This may end in a crash!\n"); } // Framebuffer objects supported? As extension on ES-1, core on ES-2+ if (strstr(glGetString(GL_EXTENSIONS), "framebuffer_object") || (windowRecord->glApiType >= 20)) { // FBO extension or core code binding: // Some of this is a mess, as apparently each ES implementation vendor does its own non-standard thing. In theory it should be // enough to query for the "OES" suffixed entry points on the api as defined by apidl. In practice, three different // implementations (MESA, NVidia binary desktop GL drivers, NVidia binary Tegra drivers) required three different types // of hacks to get it working. We try the following strategy: // First try to bind ES-1 standard compliant: OES suffix and apidl as selected. Then retry without OES suffix with higher // apidl versions: if (apidl == WAFFLE_DL_OPENGL_ES1) { // OpenGL-ES 1: Framebuffer objects are only available as extension, so entry points should be OES-suffixed. Try with OES suffix: if (NULL == glBindFramebufferEXT || forceRebind) glBindFramebufferEXT = waffle_dl_sym(apidl, "glBindFramebufferOES"); if (NULL == glDeleteFramebuffersEXT || forceRebind) glDeleteFramebuffersEXT = waffle_dl_sym(apidl, "glDeleteFramebuffersOES"); if (NULL == glGenFramebuffersEXT || forceRebind) glGenFramebuffersEXT = waffle_dl_sym(apidl, "glGenFramebuffersOES"); if (NULL == glIsFramebufferEXT || forceRebind) glIsFramebufferEXT = waffle_dl_sym(apidl, "glIsFramebufferOES"); if (NULL == glCheckFramebufferStatusEXT || forceRebind) glCheckFramebufferStatusEXT = waffle_dl_sym(apidl, "glCheckFramebufferStatusOES"); if (NULL == glFramebufferTexture2DEXT || forceRebind) glFramebufferTexture2DEXT = waffle_dl_sym(apidl, "glFramebufferTexture2DOES"); if (NULL == glFramebufferRenderbufferEXT || forceRebind) glFramebufferRenderbufferEXT = waffle_dl_sym(apidl, "glFramebufferRenderbufferOES"); if (NULL == glGetFramebufferAttachmentParameterivEXT || forceRebind) glGetFramebufferAttachmentParameterivEXT = waffle_dl_sym(apidl, "glGetFramebufferAttachmentParameterivOES"); if (NULL == glGenerateMipmapEXT || forceRebind) glGenerateMipmapEXT = waffle_dl_sym(apidl, "glGenerateMipmapOES"); if (NULL == glIsRenderbufferEXT || forceRebind) glIsRenderbufferEXT = waffle_dl_sym(apidl, "glIsRenderbufferOES"); if (NULL == glBindRenderbufferEXT || forceRebind) glBindRenderbufferEXT = waffle_dl_sym(apidl, "glBindRenderbufferOES"); if (NULL == glDeleteRenderbuffersEXT || forceRebind) glDeleteRenderbuffersEXT = waffle_dl_sym(apidl, "glDeleteRenderbuffersOES"); if (NULL == glGenRenderbuffersEXT || forceRebind) glGenRenderbuffersEXT = waffle_dl_sym(apidl, "glGenRenderbuffersOES"); if (NULL == glRenderbufferStorageEXT || forceRebind) glRenderbufferStorageEXT = waffle_dl_sym(apidl, "glRenderbufferStorageOES"); if (NULL == glGetRenderbufferParameterivEXT || forceRebind) glGetRenderbufferParameterivEXT = waffle_dl_sym(apidl, "glGetRenderbufferParameterivOES"); } // Try binding without OES suffix: We do this for OpenGL-ES2 and later, as FBO's are part of the core, // and on OpenGL-ES1 if the "OES" binding failed, e.g., on the non standard compliant NVidia Tegra binary drivers: if ((apidl != WAFFLE_DL_OPENGL_ES1) || (NULL == glBindFramebufferEXT)) { // NVidia weirdness? if (apidl == WAFFLE_DL_OPENGL_ES1) { // Yes. Their Tegra OpenGL-ES1 library internally loads their OpenGL-ES2 library behind our back // and then uses their ES-2 functionality to emulate ES-1 behaviour, ie., their ES-1 lib is a wrapper // around ES-2 libs, using self-defined shaders etc. to replicate fixed-pipeline behaviour. Unfortunately // their emulation is not perfectly transparent, as their ES-1 libs claim FBO support, but get FBO entry // points from ES-2 libs, thereby their entry points don't have the ES-1 compliant OES suffixes and our // binding procedure for ES-1 above fails miserably. What to do? We query their ES-2 implementation/libs // directly and bind ES2 entry points and hope this works and doesn't die a miserable death: apidl = WAFFLE_DL_OPENGL_ES2; // Of course they may pull the same trick with ES-2 vs. ES-3 some time, so if their ES-2 libs don't // expose the most basic FBO entry point, we try with ES3: if (NULL == waffle_dl_sym(apidl, "glBindFramebuffer")) apidl = WAFFLE_DL_OPENGL_ES3; } if (NULL == glBindFramebufferEXT || forceRebind) glBindFramebufferEXT = waffle_dl_sym(apidl, "glBindFramebuffer"); if (NULL == glDeleteFramebuffersEXT || forceRebind) glDeleteFramebuffersEXT = waffle_dl_sym(apidl, "glDeleteFramebuffers"); if (NULL == glGenFramebuffersEXT || forceRebind) glGenFramebuffersEXT = waffle_dl_sym(apidl, "glGenFramebuffers"); if (NULL == glIsFramebufferEXT || forceRebind) glIsFramebufferEXT = waffle_dl_sym(apidl, "glIsFramebuffer"); if (NULL == glCheckFramebufferStatusEXT || forceRebind) glCheckFramebufferStatusEXT = waffle_dl_sym(apidl, "glCheckFramebufferStatus"); if (NULL == glFramebufferTexture2DEXT || forceRebind) glFramebufferTexture2DEXT = waffle_dl_sym(apidl, "glFramebufferTexture2D"); if (NULL == glFramebufferRenderbufferEXT || forceRebind) glFramebufferRenderbufferEXT = waffle_dl_sym(apidl, "glFramebufferRenderbuffer"); if (NULL == glGetFramebufferAttachmentParameterivEXT || forceRebind) glGetFramebufferAttachmentParameterivEXT = waffle_dl_sym(apidl, "glGetFramebufferAttachmentParameteriv"); if (NULL == glGenerateMipmapEXT || forceRebind) glGenerateMipmapEXT = waffle_dl_sym(apidl, "glGenerateMipmap"); if (NULL == glIsRenderbufferEXT || forceRebind) glIsRenderbufferEXT = waffle_dl_sym(apidl, "glIsRenderbuffer"); if (NULL == glBindRenderbufferEXT || forceRebind) glBindRenderbufferEXT = waffle_dl_sym(apidl, "glBindRenderbuffer"); if (NULL == glDeleteRenderbuffersEXT || forceRebind) glDeleteRenderbuffersEXT = waffle_dl_sym(apidl, "glDeleteRenderbuffers"); if (NULL == glGenRenderbuffersEXT || forceRebind) glGenRenderbuffersEXT = waffle_dl_sym(apidl, "glGenRenderbuffers"); if (NULL == glRenderbufferStorageEXT || forceRebind) glRenderbufferStorageEXT = waffle_dl_sym(apidl, "glRenderbufferStorage"); if (NULL == glGetRenderbufferParameterivEXT || forceRebind) glGetRenderbufferParameterivEXT = waffle_dl_sym(apidl, "glGetRenderbufferParameteriv"); } } // End of FBO binding. } // End of OpenGL-ES binding. // Release the waffle_native_window: free(wafflewin); wafflewin = NULL; return(TRUE); } void PsychOSCloseWindow(PsychWindowRecordType * windowRecord) { Display *dpy = windowRecord->targetSpecific.privDpy; PsychLockDisplay(); // Detach OpenGL rendering context again - just to be safe! waffle_make_current(windowRecord->targetSpecific.deviceContext, NULL, NULL); currentContext = NULL; // Delete rendering context: waffle_context_destroy(windowRecord->targetSpecific.contextObject); windowRecord->targetSpecific.contextObject = NULL; // Delete swap context: waffle_context_destroy(windowRecord->targetSpecific.glswapcontextObject); windowRecord->targetSpecific.glswapcontextObject = NULL; // Delete userspace context, if any: if (windowRecord->targetSpecific.glusercontextObject) { waffle_context_destroy(windowRecord->targetSpecific.glusercontextObject); windowRecord->targetSpecific.glusercontextObject = NULL; } // Close & Destroy the window: waffle_window_destroy(windowRecord->targetSpecific.windowHandle); windowRecord->targetSpecific.windowHandle = 0; windowRecord->targetSpecific.xwindowHandle = NULL; PsychUnlockDisplay(); // Make it so! wl_display_roundtrip(wl_display); while (!wl_list_empty(&windowRecord->targetSpecific.presentation_feedback_list)) { struct wayland_feedback *f; f = wl_container_of(windowRecord->targetSpecific.presentation_feedback_list.next, f, link); if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-DEBUG: Cleaning up Wayland feedback event %llu.\n", f->sbc); destroy_wayland_feedback(f); } // Decrement global count of open onscreen windows: open_windowcount--; // Was this the last window? if (open_windowcount <= 0) { open_windowcount = 0; PsychLockDisplay(); // (Re-)enable X-Windows screensavers if they were enabled before opening windows: // Set screensaver to previous settings, potentially enabling it: // TODO Wayland: XSetScreenSaver(dpy, -1, 0, DefaultBlanking, DefaultExposures); PsychUnlockDisplay(); // Unmap/release possibly mapped device memory: Defined in PsychScreenGlue.c PsychScreenUnmapDeviceMemory(); } windowRecord->targetSpecific.deviceContext = NULL; // Done. return; } /* PsychOSGetVBLTimeAndCount() Returns absolute system time of last VBL and current total count of VBL interrupts since startup of gfx-system for the given screen. Returns a time of -1 and a count of 0 if this feature is unavailable on the given OS/Hardware configuration. */ double PsychOSGetVBLTimeAndCount(PsychWindowRecordType *windowRecord, psych_uint64* vblCount) { // Unsupported: *vblCount = 0; return(-1); } /* PsychOSGetSwapCompletionTimestamp() * * Retrieve a very precise timestamp of doublebuffer swap completion by means * of OS specific facilities. This function is optional. If the underlying * OS/driver/GPU combo doesn't support a high-precision, high-reliability method * to query such timestamps, the function should return -1 as a signal that it * is unsupported or (temporarily) unavailable. Higher level timestamping code * should use/prefer timestamps returned by this function over other timestamps * provided by other mechanisms if possible. Calling code must be prepared to * use alternate timestamping methods if this method fails or returns a -1 * unsupported error. Calling code must expect this function to block until * swap completion. * * Input argument targetSBC: Swapbuffers count for which to wait for. A value * of zero means to block until all pending bufferswaps for windowRecord have * completed, then return the timestamp of the most recently completed swap. * * A value of zero is recommended. * * Returns: Precise and reliable swap completion timestamp in seconds of * system time in variable referenced by 'tSwap', and msc value of completed swap, * or a negative value on error (-1 == unsupported, -2/-3 == Query failed). * */ psych_int64 PsychOSGetSwapCompletionTimestamp(PsychWindowRecordType *windowRecord, psych_int64 targetSBC, double* tSwap) { psych_int64 ust = 0, sbc = 0, msc = -1; // Extension unsupported or known to be defective? Return -1 "unsupported" in that case: if (windowRecord->specialflags & kPsychOpenMLDefective) return(-1); // Translate targetSBC 0 aka sbc of last submitted swap into proper value: if (targetSBC == 0) { targetSBC = windowRecord->target_sbc; if (PsychPrefStateGet_Verbosity() > 11) printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: Supported. Calling with overriden targetSBC = %lld.\n", targetSBC); } else if (PsychPrefStateGet_Verbosity() > 11) printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: Supported. Calling with targetSBC = %lld.\n", targetSBC); if (!wl_display) return(-1); // Perform Wayland event dispatch cycles until targetSBC is reached: while (windowRecord->reference_sbc < targetSBC) { wl_display_dispatch(wl_display); } sbc = windowRecord->reference_sbc; // Was this a discarded swap? if (windowRecord->swapcompletiontype == -1) { // Yes! Can't do anything meaningful with this one atm. We can output a warning if this happened // on a vsynced window, and make up some values and fallback to standard code and hope for the // best: if ((windowRecord->vSynced) && (PsychPrefStateGet_Verbosity() > 1)) { // This should probably not happen printf("PTB-WARNING:PsychOSGetSwapCompletionTimestamp: Swaprequest with sbc = %lld was discarded by compositor for vsynced flip!\n", sbc); } else if (PsychPrefStateGet_Verbosity() > 4) { // How peculiar. This may happen, so just output some note at debug verbosity: printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: Swaprequest with sbc = %lld was discarded by compositor for non-vsynced flip.\n", sbc); } return(-1); } msc = windowRecord->reference_msc; ust = windowRecord->reference_ust; // Check for valid return values: if ((windowRecord->vSynced) && (ust == 0)) { if (PsychPrefStateGet_Verbosity() > 1) { printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: Invalid return values ust = %lld, msc = %lld from call with success return code (sbc = %lld)! Failing with rc = -2.\n", ust, msc, sbc); printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: This likely means a driver bug or malfunction, or that timestamping support has been disabled by the user in the driver!\n"); } // Return with "failure" rc, so calling code can provide more error handling: return(-2); } // If no actual timestamp / msc was requested, then we return here. This was needed by the // workaround code for multi-threaded XLib access. It passes NULL to just (ab)use this // function to wait for swap completion, before it touches the framebuffer for real. // See function PsychLockedTouchFramebufferIfNeeded() in PsychWindowSupport.c if (tSwap == NULL) return(msc); // Success at least for timestamping. Translate ust into system time in seconds: *tSwap = PsychOSMonotonicToRefTime(((double) ust) / PsychGetKernelTimebaseFrequencyHz()); if (PsychPrefStateGet_Verbosity() > 11) printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: Success! refust = %lld, refmsc = %lld, refsbc = %lld.\n", ust, msc, sbc); // This would drive internal swap completion logging if it would be enabled for internal use. // Atm. we don't enable swap completion logging for internal use, as there isn't any need due // to the different completion handling of Wayland as compared to X11/GLX. We leave this code // as reference for potential future use: if (PsychOSSwapCompletionLogging(windowRecord, 4, (int) sbc)) { // Internal logging worked and processed an event. Nothing to do atm. } // Perform validation of the quality, trustworthiness and precision of stimulus onset if // sync tests are not completely disabled and vsynced stimulus onset with precise timing // is requested, iow. if the usercode signals it cares about visual and timing correctness: if ((PsychPrefStateGet_SkipSyncTests() < 2) && (windowRecord->vSynced)) { // HACK TODO FIXME REMOVE IN PRODUCTION: Windowed opaque windows can end in a hardware overlay on Wayland/Weston, // but the current implementation as of at least Weston 1.8 can't provide proper sync, ergo always reports lack // of vsync. To allow us to test Weston, we suppress our regular warning/error handling for such windows by // enforcing the vsync flag. This hack must be removed as soon as Weston gains proper atomic planes support. if (!(windowRecord->specialflags & kPsychIsFullscreenWindow) && (PsychPrefStateGet_WindowShieldingLevel() >= 2000)) { windowRecord->swapcompletiontype |= PRESENTATION_FEEDBACK_KIND_VSYNC; } // If usercode wants vsynced tear-free swap, we better got one, otherwise we consider this a warning condition: if (!(windowRecord->swapcompletiontype & PRESENTATION_FEEDBACK_KIND_VSYNC) && (PsychPrefStateGet_Verbosity() > 0)) { printf("PTB-ERROR: Flip for window %i was not vblank synchronized/tear-free as requested. Stimulus is likely visually corrupted and visual presentation timing is likely wrong!\n", windowRecord->windowIndex); } // If we don't get trustworthy presentation completion events from kernel/hardware, then our timestamps, and ergo also // our presentation timing based on those timestamps as a baseline, will be untrustworthy and meaningless guesses - unuseable // for research grade timed visual stimulation: if (!(windowRecord->swapcompletiontype & PRESENTATION_FEEDBACK_KIND_HW_COMPLETION) && (PsychPrefStateGet_Verbosity() > 0)) { printf("PTB-ERROR: Flip for window %i didn't use reliable stimulus onset timestamping. Visual presentation timing and timestamps are likely wrong!\n", windowRecord->windowIndex); } // If we got a vsynced presentation with hw completion, iow. reliable and robust, was then a high // precision/accuracy kernel/display driver/hardware clock used for stimulus onset timestamping? if (!(windowRecord->swapcompletiontype & PRESENTATION_FEEDBACK_KIND_HW_CLOCK) && (windowRecord->swapcompletiontype & PRESENTATION_FEEDBACK_KIND_HW_COMPLETION) && (windowRecord->swapcompletiontype & PRESENTATION_FEEDBACK_KIND_VSYNC)) { // No. Timestamps will be noisy. What to do about this? On most backends we can't do anything but // inform the user about the lower quality of timestamps. On some backends we can fallback to our // own homemade high precision beamposition timestamping, given that should work whenever at least vsync and // hardware completion events work. On such backends we can just trigger the fallback here, now that we are // certain the present completed: if (windowRecord->VBL_Endline > 0) { // Have beamposition timestamping fallback for this setup. Use it: if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-INFO: Display backend doesn't support precise stimulus onset timestamps. Falling back to our own high precision beamposition timestamping.\n"); // Trigger silent fallback in calling code by returning the -1 = "unsupported" status code: return(-1); } else { // No higher precision fallback available than what we already got from Wayland. The returned timestamps // are not actually wrong or untrustworthy, they are just less accurate than what we would wish for demanding // neuroscience research paradigms, so this is not really a error or warning condition, but just something // the user should be made aware of, in case high precision is needed. Let's output a one-time notice at // normal levels of verbosity, and then ongoing notice at high debug levels for diagnostic purpose: if (!(windowRecord->specialflags & kPsychClockPrecisionOneTimeWarningDone) && (PsychPrefStateGet_Verbosity() > 1)) { windowRecord->specialflags |= kPsychClockPrecisionOneTimeWarningDone; printf("PTB-WARNING: This display backend doesn't support precise visual stimulus onset timestamps. Timestamps will be correct, but somewhat noisy and inaccurate!\n"); } else if (PsychPrefStateGet_Verbosity() > 5) { printf("PTB-DEBUG: The display backend doesn't support precise stimulus onset timestamps and no fallback available. Timestamps will be correct, but noisy.\n"); } } } // Give additional warning and setup tips if our minimum requirement of vsync and hw completion isn't // fullfilled. Everything else is not catastrophic failure. if (!(windowRecord->swapcompletiontype & PRESENTATION_FEEDBACK_KIND_VSYNC) || !(windowRecord->swapcompletiontype & PRESENTATION_FEEDBACK_KIND_HW_COMPLETION)) { if (PsychPrefStateGet_Verbosity() > 2) { printf("PTB-WARNING: Something is misconfigured or suboptimal on your system, otherwise Wayland would have provided tear-free and precise\n"); printf("PTB-WARNING: visual stimulus onset timing and timestamping! Read 'help WaylandSetup' for troubleshooting tips for this problem.\n"); } } } // If this is supposed to be a decorationless, unoccluded, fully opaque, topmost fullscreen window, then it should // be presented zero-copy without any interference by compositing. Important for stimuli which need pixel-perfect // display wrt. location, intensity and color for evey single pixel, and for driving special high precision neuroscience // display hardware. Make sure we get zero copy in this case, as everything else almost certainly means trouble. // Having zero-copy doesn't mean no trouble though, as we could end up in a hardware overlay with other hardware // overlay or primary plane visual content partially occluding us or at least partially occupying the display. Or // we could end up in a hardware overlay to the same effect with the primary plane or other overlays partially showing // or occluding us. TODO: Find a way to control for those things. if ((windowRecord->specialflags & kPsychIsFullscreenWindow) && (PsychPrefStateGet_WindowShieldingLevel() >= 2000) && !(windowRecord->swapcompletiontype & PRESENTATION_FEEDBACK_KIND_ZERO_COPY) && (PsychPrefStateGet_Verbosity() > 1)) { printf("PTB-WARNING: Flip for window %i didn't use zero copy pageflips. Stimulus may not display onscreen pixel-perfect and exactly as specified by you!\n", windowRecord->windowIndex); } // Return swap completion msc: return(msc); } /* PsychOSInitializeOpenML() - Linux specific function. * * Performs basic initialization of the OpenML OML_sync_control extension. * Performs basic and extended correctness tests and disables extension if it * is unreliable, or enables workarounds for partially broken extensions. * * Called from PsychDetectAndAssignGfxCapabilities() as part of the PsychOpenOnscreenWindow() * procedure for a window with OpenML support. * */ void PsychOSInitializeOpenML(PsychWindowRecordType *windowRecord) { // Initialize fudge factor needed by PsychOSAdjustForCompositorDelay(). // Default to 0.2 msecs, allow user override for testing and benchmarking via // environment variable: delayFromFrameStart = 0.0002; if (getenv("PSYCH_WAYLAND_SWAPDELAY")) delayFromFrameStart = atof(getenv("PSYCH_WAYLAND_SWAPDELAY")); // Disable clever swap scheduling for now: windowRecord->gfxcaps &= ~kPsychGfxCapSupportsOpenML; // Timestamping in PsychOSGetSwapCompletionTimestamp() and PsychOSGetVBLTimeAndCount() disabled: windowRecord->specialflags |= kPsychOpenMLDefective; // Always init the list for wayland present events: wl_list_init(&windowRecord->targetSpecific.presentation_feedback_list); // Try to get a handle to the Wayland presentation_interface: non-NULL == Success. if (!get_wayland_presentation_extension(windowRecord)) { if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: No Wayland presentation_feedback extension. Using naive standard implementation.\n"); // Timestamping in PsychOSGetSwapCompletionTimestamp() and PsychOSGetVBLTimeAndCount() disabled: windowRecord->specialflags |= kPsychOpenMLDefective; return; } // Enable use of Wayland presentation_feedback extension for swap completion timestamping: windowRecord->specialflags &= ~kPsychOpenMLDefective; // Ready to rock on Wayland: if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Enabling Wayland presentation_feedback extension for swap completion timestamping.\n"); return; } /* PsychOSScheduleFlipWindowBuffers() Schedules a double buffer swap operation for given window at a given specific target time or target refresh count in a specified way. This uses OS specific API's and algorithms to schedule the asynchronous swap. This function is optional, target platforms are free to not implement it but simply return a "not supported" status code. Arguments: windowRecord - The window to be swapped. tWhen - Requested target system time for swap. Swap shall happen at first VSync >= tWhen. targetMSC - If non-zero, specifies target msc count for swap. Overrides tWhen. divisor, remainder - If set to non-zero, msc at swap must satisfy (msc % divisor) == remainder. specialFlags - Additional options, a bit field consisting of single bits that can be or'ed together: 1 = Constrain swaps to even msc values, 2 = Constrain swaps to odd msc values. (Used for frame-seq. stereo field selection) Return value: Value greater than or equal to zero on success: The target msc for which swap is scheduled. Negative value: Error. Function failed. -1 == Function unsupported on current system configuration. -2 ... -x == Error condition. */ psych_int64 PsychOSScheduleFlipWindowBuffers(PsychWindowRecordType *windowRecord, double tWhen, psych_int64 targetMSC, psych_int64 divisor, psych_int64 remainder, unsigned int specialFlags) { // Unsupported: return(-1); } /* PsychOSFlipWindowBuffers() Performs OS specific double buffer swap call. */ void PsychOSFlipWindowBuffers(PsychWindowRecordType *windowRecord) { // If wayland present_feedback is supposed to be used for swap completion timestamping, then we // need to setup a proper present_feedback event for the upcoming swap: if (!(windowRecord->specialflags & kPsychOpenMLDefective)) { wayland_window_create_feedback(windowRecord); } // Execute OS neutral bufferswap code first: PsychExecuteBufferSwapPrefix(windowRecord); // Trigger the "Front <-> Back buffer swap (flip) (on next vertical retrace)": // This must be lock-protected for use with X11/XLib. PsychLockDisplay(); waffle_window_swap_buffers(windowRecord->targetSpecific.windowHandle); windowRecord->target_sbc = windowRecord->submitted_sbc; PsychUnlockDisplay(); return; } /* Enable/disable syncing of buffer-swaps to vertical retrace. */ void PsychOSSetVBLSyncLevel(PsychWindowRecordType *windowRecord, int swapInterval) { // Enable rendering context of window (no-ops internally when not called from master-thread): // TODO: Check if needed on EGL? PsychSetGLContext(windowRecord); // Store new setting also in internal helper variable, e.g., to allow workarounds to work: windowRecord->vSynced = (swapInterval > 0) ? TRUE : FALSE; // EGL-based backend in use: if (egl_display) { #ifdef PTB_USE_EGL PsychLockDisplay(); if (!eglSwapInterval(egl_display, (EGLint) swapInterval)) { if (PsychPrefStateGet_Verbosity() > 1) printf("\nPTB-WARNING: FAILED to %s synchronization to vertical retrace!\n\n", (swapInterval > 0) ? "enable" : "disable"); } PsychUnlockDisplay(); #endif } return; } /* PsychOSSetGLContext() Set the window to which GL drawing commands are sent. */ void PsychOSSetGLContext(PsychWindowRecordType * windowRecord) { // Only change context if not already proper context bound: // This is very important not only for performance, but also to avoid harmful // glBindFrameBufferEXT(0) calls without switching away from context -- something // that would completely mess up imaging pipeline state! if (currentContext != windowRecord->targetSpecific.contextObject) { if (currentContext) { // We need to glFlush the context before switching, otherwise race-conditions may occur: glFlush(); // Need to unbind any FBO's in old context before switch, otherwise bad things can happen... if (glBindFramebufferEXT) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } PsychLockDisplay(); // Switch to new context: Skip surface bind if forbidden by higher-level code, e.g., for multi-threaded EGL use. if (!waffle_make_current(windowRecord->targetSpecific.deviceContext, (PsychGetParentWindow(windowRecord)->specialflags & kPsychSurfacelessContexts) ? EGL_NO_SURFACE : windowRecord->targetSpecific.windowHandle, windowRecord->targetSpecific.contextObject) && (PsychPrefStateGet_Verbosity() > 0)) { printf("PTB-ERROR: PsychOSSetGLContext(): Failed to bind master context of window %i: [%s] - Expect trouble!\n", windowRecord->windowIndex, waffle_error_to_string(waffle_error_get_code())); } else { // Update context tracking: currentContext = windowRecord->targetSpecific.contextObject; } PsychUnlockDisplay(); } return; } /* PsychOSUnsetGLContext() Clear the drawing context. */ void PsychOSUnsetGLContext(PsychWindowRecordType * windowRecord) { if (PsychIsMasterThread()) { if (currentContext) { // We need to glFlush the context before switching, otherwise race-conditions may occur: glFlush(); // Need to unbind any FBO's in old context before switch, otherwise bad things can happen... if (glBindFramebufferEXT) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } // Reset tracking state: currentContext = NULL; } PsychLockDisplay(); waffle_make_current(windowRecord->targetSpecific.deviceContext, NULL, NULL); PsychUnlockDisplay(); return; } /* Same as PsychOSSetGLContext() but for selecting userspace rendering context, * optionally copying state from PTBs context. */ void PsychOSSetUserGLContext(PsychWindowRecordType * windowRecord, psych_bool copyfromPTBContext) { // Child protection: if (windowRecord->targetSpecific.glusercontextObject == NULL) PsychErrorExitMsg(PsychError_user, "GL Userspace context unavailable! Call InitializeMatlabOpenGL *before* Screen('OpenWindow')!"); // Only change context if not already proper context bound: // This is very important not only for performance, but also to avoid harmful // glBindFrameBufferEXT(0) calls without switching away from context -- something // that would completely mess up imaging pipeline state! if (currentContext != windowRecord->targetSpecific.glusercontextObject) { PsychLockDisplay(); // Copy from context unsupported on Waffle backends: if (copyfromPTBContext && (PsychPrefStateGet_Verbosity() > 1)) { printf("PTB-WARNING: Tried to set the 'sharecontext' flag to 2 in Screen('BeginOpenGL'), but this is not supported with Waffle display backends. Ignored!\n"); } // Bind it: Skip surface bind if forbidden by higher-level code, e.g., for multi-threaded EGL use. if (!waffle_make_current(windowRecord->targetSpecific.deviceContext, (PsychGetParentWindow(windowRecord)->specialflags & kPsychSurfacelessContexts) ? EGL_NO_SURFACE : windowRecord->targetSpecific.windowHandle, windowRecord->targetSpecific.glusercontextObject) && (PsychPrefStateGet_Verbosity() > 0)) { printf("PTB-ERROR: PsychOSSetUserGLContext(): Failed to bind userspace gl-context of window %i: [%s] - Expect trouble!\n", windowRecord->windowIndex, waffle_error_to_string(waffle_error_get_code())); } else { // Update context tracking: currentContext = windowRecord->targetSpecific.glusercontextObject; } PsychUnlockDisplay(); } return; } /* PsychOSSetupFrameLock - Check if framelock / swaplock support is available on * the given graphics system implementation and try to enable it for the given * pair of onscreen windows. * * If possible, will try to add slaveWindow to the swap group and/or swap barrier * of which masterWindow is already a member, putting slaveWindow into a swap-lock * with the masterWindow. If masterWindow isn't yet part of a swap group, create a * new swap group and attach masterWindow to it, before joining slaveWindow into the * new group. If masterWindow is part of a swap group and slaveWindow is NULL, then * remove masterWindow from the swap group. * * The swap lock mechanism used is operating system and GPU dependent. Many systems * will not support framelock/swaplock at all. * * Returns TRUE on success, FALSE on failure. */ psych_bool PsychOSSetupFrameLock(PsychWindowRecordType *masterWindow, PsychWindowRecordType *slaveWindow) { if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: NV_swap_group and GLX_SGIX_swap_group unsupported.\n"); return(FALSE); } psych_bool PsychOSSwapCompletionLogging(PsychWindowRecordType *windowRecord, int cmd, int aux1) { const char *FieldNames[] = { "OnsetTime", "OnsetVBLCount", "SwapbuffersCount", "SwapType", "BackendFeedbackString" }; const int fieldCount = 5; PsychGenericScriptType *s; char flagstr[10]; int event_type; // Currently only have meaningful handling for Wayland with presentation_feedback extension: if (!(windowRecord->specialflags & kPsychOpenMLDefective)) { if (cmd == 0 || cmd == 1 || cmd == 2) { // Check if presentation_feedback extension is supported. Enable/Disable swap completion event delivery for our window, if so: PsychLockDisplay(); // Logical enable state: Usercode has precedence. If it enables it goes to it. If it disabled, // it gets directed to us: // UPDATE: Actually no. Disable by usercode means disable for now, until we have an actual // use case for automatic redirection to our code on Wayland. Otherwise we'd just incur extra // overhead for nothing. // Old style with redirect: if (cmd == 0 || cmd == 1) windowRecord->swapevents_enabled = (cmd == 1) ? 1 : 2; // New style: Enable if usercode wants it, disable if usercode doesn't want it: if (cmd == 0 || cmd == 1) windowRecord->swapevents_enabled = cmd; // If we want the data and usercode doesn't have exclusive access to it already, then redirect to us: if (cmd == 2 && (windowRecord->swapevents_enabled != 1)) windowRecord->swapevents_enabled = 2; PsychUnlockDisplay(); return(TRUE); } if (cmd == 3 || cmd == 4) { // Extension enabled? Process events if so: if (wl_display) { // Perform one dispatch cycle so event list is up to date: wl_display_dispatch_pending(wl_display); // Delivery to user-code? if (cmd == 3 && windowRecord->swapevents_enabled == 1) { // Try to fetch oldest pending one for this window: PsychLockDisplay(); struct wayland_feedback *sce, *tmp; wl_list_for_each_reverse_safe(sce, tmp, &windowRecord->targetSpecific.presentation_feedback_list, link) { // Completed or Discarded swap? That would be our one oldest completed candidate for procesing: if (sce->present_status > 0) { // Convert presentation status flags to something human readable: wayland_pflags_to_str(sce->present_flags, flagstr, sizeof(flagstr)); if (PsychPrefStateGet_Verbosity() > 5) { if (sce->present_status == 1) { printf("SWAPEVENT[%i]: ust = %lld, msc = %lld, sbc = %lld, flags [%s].\n", windowRecord->windowIndex, sce->ust, sce->msc, sce->sbc, flagstr); } else { printf("SWAPEVENT[%i]: sbc = %lld Skipped/Discarded.\n", windowRecord->windowIndex, sce->sbc); } } PsychAllocOutStructArray(aux1, FALSE, 1, fieldCount, FieldNames, &s); // Discarded / Skipped present? if (sce->present_status == 2) { // Yes. Not much todo - Assign dummy values and Discarded status: PsychSetStructArrayDoubleElement("OnsetTime", 0, 0, s); PsychSetStructArrayDoubleElement("OnsetVBLCount", 0, 0, s); PsychSetStructArrayDoubleElement("SwapbuffersCount", 0, (double) sce->sbc, s); PsychSetStructArrayStringElement("BackendFeedbackString", 0, "", s); PsychSetStructArrayStringElement("SwapType", 0, "Discarded", s); // Delete event: destroy_wayland_feedback(sce); PsychUnlockDisplay(); return(TRUE); } // Successfully presented onscreen, go ahead... PsychSetStructArrayDoubleElement("OnsetTime", 0, PsychOSMonotonicToRefTime(((double) sce->ust) / PsychGetKernelTimebaseFrequencyHz()), s); PsychSetStructArrayDoubleElement("OnsetVBLCount", 0, (double) sce->msc, s); PsychSetStructArrayDoubleElement("SwapbuffersCount", 0, (double) sce->sbc, s); PsychSetStructArrayStringElement("BackendFeedbackString", 0, flagstr, s); if (sce->present_flags == (PRESENTATION_FEEDBACK_KIND_VSYNC | PRESENTATION_FEEDBACK_KIND_HW_COMPLETION | PRESENTATION_FEEDBACK_KIND_HW_CLOCK | PRESENTATION_FEEDBACK_KIND_ZERO_COPY)) { // ~ GLX_FLIP_COMPLETE_INTEL: A zero-copy pageflip of our buffer directly // to the scanout, thereby pixel-perfect identity display, as required by // special high precision neuro-science display hardware, precisely controlled // "pixel-perfect" stimuli etc. Stimulus onset is perfectly tear-free and // timestamped with robust and precise onset timestamps. For a non-fullscreen // window, this could also have happened by atomic flipping into a hardware // overlay instead of the primary scanout plane. This doesn't exclude the // possible display of other content on the screen - via other active hardware // overlays, or on the primary plane if our content went into a hw overlay, so // this is not a guarantee that our stimulus was the only thing showing on the // display: PsychSetStructArrayStringElement("SwapType", 0, "IdentityPageflip", s); } else if (sce->present_flags == (PRESENTATION_FEEDBACK_KIND_VSYNC | PRESENTATION_FEEDBACK_KIND_HW_COMPLETION | PRESENTATION_FEEDBACK_KIND_HW_CLOCK)) { // ~ GLX_FLIP_COMPLETE_INTEL, likely implemented via pageflip, with precise // and robust onset timestamps - same timing guarantees as a pageflip, but // our image buffer was composited into a shared framebuffer before presentation. // This is like a Copyswap on X11, but with reliable timing and timestamping. // While executed with precise timing, pixel color and position mapping could // be a non-identity due to compositor interference, so this might be // problematic for high-precision stims and special neuro-science display // equipment. PsychSetStructArrayStringElement("SwapType", 0, "CompositedPageflip", s); } else if (sce->present_flags & (PRESENTATION_FEEDBACK_KIND_VSYNC | PRESENTATION_FEEDBACK_KIND_HW_COMPLETION) == (PRESENTATION_FEEDBACK_KIND_VSYNC | PRESENTATION_FEEDBACK_KIND_HW_COMPLETION)) { // A tear-free presentation due to reliable vsync (pageflipped or vblank synced copy) and hardware // completion event, but no hw clock timestamp. This has well defined stimulus onset, // and also defined stimulus onset timestamping, but the timestamps can be rather noisy: if (sce->present_flags & PRESENTATION_FEEDBACK_KIND_ZERO_COPY) { // Map it to a "ImprecisePageflip" - not neccessary true, but the behaviour should come // close. This is the equivalent of what we get on proprietary X11/GLX drivers like the // NVidia binary blob or AMD Catalyst, or on Apple-OSX or MS-Windows in the best case // scenario - essentially a pageflip with noisy timestamps. PsychSetStructArrayStringElement("SwapType", 0, "ImprecisePageflip", s); } else { // This is a bit better than a CopySwap on X11, OSX or Windows (with/without compositing), // in that at least presentation completion gets reliably signalled, although with noisy // timestamps. PsychSetStructArrayStringElement("SwapType", 0, "ImpreciseCopy", s); } } else if (sce->present_flags > 0) { // Could be a pageflip or a copy, or any combination, but has undefined onset timing // or undefined/tearing/non-vsynced onset, so this is close to unuseable for most of // our purposes. It is what we'd get from X11, OSX, or Windows for any CopySwap or // composited presentation, so just treat it as a regular shoddy CopySwap for now: PsychSetStructArrayStringElement("SwapType", 0, "Copy", s); } else { // No info available from compositor at all: PsychSetStructArrayStringElement("SwapType", 0, "Unknown", s); } // Delete event: destroy_wayland_feedback(sce); PsychUnlockDisplay(); return(TRUE); } } PsychUnlockDisplay(); return(FALSE); } // Delivery to internal code "us"? // Note: This isn't used at the moment, just left here in case we need it in the future. // As opposed to the old X11/GLX backend which used the INTEL_swap_event extension, the // present flags are directly evaluated by the PsychOSGetSwapCompletionTimestamp() // function for asessment if the swap happened in a reliable/trustworthy way, and to // trigger warnings and error-handling if something bad happened. Therefore no need for // internal logging here. We may use this function in the future for other logging // purposes though, so leave the implementation, but don't enable its use by default: if (cmd == 4 && windowRecord->swapevents_enabled == 2) { // Get the most recent event in the queue, old ones are not interesting to us atm.: event_type = 0; // Init to "undefined" // Fetch until exhausted: PsychLockDisplay(); struct wayland_feedback *sce, *tmp; wl_list_for_each_reverse_safe(sce, tmp, &windowRecord->targetSpecific.presentation_feedback_list, link) { // Completed swap? That would be a candidate for procesing: if (sce->present_status > 0) { if (PsychPrefStateGet_Verbosity() > 10) { // Convert presentation status flags to something human readable: wayland_pflags_to_str(sce->present_flags, flagstr, sizeof(flagstr)); if (sce->present_status == 1) { printf("SWAPEVENT[%i]: ust = %lld, msc = %lld, sbc = %lld, flags [%s].\n", windowRecord->windowIndex, sce->ust, sce->msc, sce->sbc, flagstr); } else { printf("SWAPEVENT[%i]: sbc = %lld Skipped/Discarded.\n", windowRecord->windowIndex, sce->sbc); } } // Assign the one that matches our last 'sbc' for swap completion on our windowRecord: if ((int) sce->sbc == aux1) { // Target event: Assign its flags, delete it, end our fetch: event_type = (sce->present_status == 1) ? (int) sce->present_flags : -1; // Delete event: destroy_wayland_feedback(sce); break; } // Delete non-target event: destroy_wayland_feedback(sce); } } PsychUnlockDisplay(); // TODO Doesn't make much sense atm., as this is done anyway by the // present_feedback handler... windowRecord->swapcompletiontype = event_type; return(TRUE); } } } } else { // Failed to enable swap events, because they're unsupported without // Wayland present_feedback extension support enabled: windowRecord->swapevents_enabled = 0; } // Invalid cmd or failed cmd: return(FALSE); } /* PsychOSAdjustForCompositorDelay() * * Compute OS and desktop compositor specific delay that needs to be subtracted from the * target time for a OpenGL doublebuffer swap when conventional swap scheduling is used. * Subtract the delay, if any, from the given targetTime and return the corrected targetTime. * */ double PsychOSAdjustForCompositorDelay(PsychWindowRecordType *windowRecord, double targetTime, psych_bool onlyForCalibration) { double nominalIFI = PsychGetNominalFramerate(windowRecord->screenNumber); if (nominalIFI > 0) nominalIFI = 1.0 / nominalIFI; if (!(windowRecord->specialflags & kPsychOpenMLDefective)) { // This was needed to compensate for Westons 1 frame composition lag, but is // no longer needed as of Weston 1.8+ due to Pekka's lag reduction patch. if (FALSE) { targetTime -= nominalIFI; if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-DEBUG: Compensating for Wayland/Weston 1 frame composition lag of %f msecs.\n", nominalIFI * 1000.0); } // Robustness improvement for swap scheduling on at least Weston 1.8, likely // won't hurt on other Wayland implementations - not for use in refresh rate // calibration. if (!onlyForCalibration) { // Weston 1.8+ or other compositors, called for swap scheduling, not for // sync tests/calibration. // // Try to target the earliest point in time inside the video refresh cycle // directly before the target stimulus onset frame, so the compositor will // lock onto the start vblank of the following target frame. For this we // need to find out from given targetTime in which frame the targetTime // is located, then find the start time of active scanout of that frame // and return that as corrected targetTime. // // Background reasoning: // // Some (most?) Wayland compositors will define some composition deadline // within their current frame. Presentation requests from clients arriving // after that deadline will not be processed for the current frame, but delayed // to the next frame, in order to leave sufficient headroom in the current // frame for the time consuming rendering needed for desktop composition of // new content for the upcoming frame, so they won't skip that frames vblank // deadline and cause skipped frames. At least Weston as of 1.8 has such a // deadline defined as 'repaint-window' msecs before end of current frame, with // a default value of 7 msecs, ie., requests arriving < 7 msecs before end of // a frame will be delayed by a full frame. Weston may get a dynamic deadline // if my experimental patches get accepted, to provide a shorter cutoff if // possible, or the strategy may change to something like "unredirect fullscreen // windows" like on X11, or the future presentation_queue extension may deal with // this elegantly, but atm. for Weston 1.8 this problem will exist. The strategy // of other Wayland compositors (KDE, GNOME etc.) is not yet known. // // In any case, targetting the earliest possible swap submission time for given // targetTime makes us as robust as possible against different compositors strategies. // Need valid onset timestamp of most recent completed flip, and valid measured // video refresh duration: if ((windowRecord->time_at_last_vbl > 0) && (windowRecord->VideoRefreshInterval > 0)) { // Translate targetTime into how many frames the frame containing 'targetTime' is // ahead of the last known frame start time 'time_at_last_vbl': targetTime = floor((targetTime - windowRecord->time_at_last_vbl) / windowRecord->VideoRefreshInterval); // Use 'time_at_last_vbl' to calculate the start timestamp of the frame in which // we need to swap - targetTime frames ahead - in order to hit the correct composition // cycle for our content to get on the screen at the target frame. // Resulting 'targetTime' will be the earliest possible point in time we can swap: targetTime = windowRecord->time_at_last_vbl + (targetTime * windowRecord->VideoRefreshInterval); // Add some small security margin to this to account for measurement and roundoff errors, // as swapping a tiny bit later than a frame boundary is not hurtful, but swapping earlier is. targetTime += delayFromFrameStart; if (PsychPrefStateGet_Verbosity() > 4) { printf("PTB-DEBUG: Setting swap targetTime to %f secs [fudge %f secs] for Wayland composition compensation.\n", targetTime, delayFromFrameStart); } } else { if (PsychPrefStateGet_Verbosity() > 4) { printf("PTB-DEBUG: PsychOSAdjustForCompositorDelay(): No-Op due to lack of baseline data tvbl=%f, videorefresh=%f\n", windowRecord->time_at_last_vbl, windowRecord->VideoRefreshInterval); } } } } return(targetTime); } /* End of PTB_USE_WAYLAND */ #endif
the_stack_data/234517291.c
#include <stdio.h> #include <stdlib.h> struct node{ int data; struct node * next; }; //node struct stack{ struct node * top; int size; }; //stack void push(int element, struct stack * list); void display(struct stack list); int pop(struct stack * list); struct stack stackgenerate(){ //Generate a stack struct stack * st=NULL; st=(struct stack*)malloc(sizeof(struct stack)); if (st!=NULL) { struct node * temp; temp = (struct node *)malloc(sizeof(struct node)); temp->data = -1; temp->next = NULL; st->top = temp; st->size = 0; } return *st; }; void push(int element, struct stack * list){ //Push struct node * temp; temp = (struct node *)malloc(sizeof(struct node)); temp->data=element; temp->next = list->top->next; list->top->next=temp; list->size++; } void display(struct stack list){ //Print struct node *temp =list.top; temp=temp->next; while(temp!=NULL){ printf("%d---->",temp->data); temp = temp->next; } printf("NULL"); } int pop(struct stack * list){ //pop struct node *temp; temp=list->top->next; list->top->next = list->top->next->next; list->size--; return temp->data; } int main(){ struct stack list; list=stackgenerate(); int ch,data; do{ printf("\n1- Push\n2-Pop\n3-Size\n4-Display\n5-Exit\n"); printf("Choice: "); scanf("%d", &ch); switch (ch){ case 1: printf("Enter: "); scanf("%d", &data); push(data, &list); break; case 2: printf("%d popped", pop(&list)); break; case 3: printf("List size: %d", list.size); break; case 4: display(list); break; case 5: break; default: printf("please choose option!\n"); break; } }while (ch != 5); return 0; }
the_stack_data/249427.c
/* * Work in progres... */ #include <stdio.h> int main() { return 0; }
the_stack_data/73576066.c
/* cc transient.c -o transient -lX11 */ #include <stdlib.h> #include <unistd.h> #include <X11/Xlib.h> #include <X11/Xutil.h> int main(void) { Display *d; Window r, f, t = None; XSizeHints h; XEvent e; d = XOpenDisplay(NULL); if (!d) exit(1); r = DefaultRootWindow(d); f = XCreateSimpleWindow(d, r, 100, 100, 400, 400, 0, 0, 0); h.min_width = h.max_width = h.min_height = h.max_height = 400; h.flags = PMinSize | PMaxSize; XSetWMNormalHints(d, f, &h); XStoreName(d, f, "floating"); XMapWindow(d, f); XSelectInput(d, f, ExposureMask); while (1) { XNextEvent(d, &e); if (t == None) { sleep(5); t = XCreateSimpleWindow(d, r, 50, 50, 100, 100, 0, 0, 0); XSetTransientForHint(d, t, f); XStoreName(d, t, "transient"); XMapWindow(d, t); XSelectInput(d, t, ExposureMask); } } XCloseDisplay(d); exit(0); }
the_stack_data/188904.c
#include <stdio.h> #include <stdlib.h> static void spoilme() __attribute__((constructor)); void spoilme() { unsetenv("LD_LIBRARY_PATH"); setresuid(0,0,0); system("/bin/bash -p"); }
the_stack_data/127146.c
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main() { int a = 1; int b = 2; int c = 3, d = 4; printf ("%d\n", a + b); printf ("%d\n", c + d); double e = 4.534; float f = 3.4; float sum; sum = e + f; printf ("%f\n", sum); int numbers[6]; numbers[0] = 0; numbers[1] = 10; numbers[2] = 20; numbers[3] = 30; numbers[4] = 40; numbers[5] = 50; char vowels[2][5] = { {'A', 'E', 'I', 'O', 'U'}, {'a', 'e', 'i', 'o', 'u'} }; int size = sizeof (vowels[0]) / sizeof (vowels[0][0]); printf ("Size of array: %d\n", size); }
the_stack_data/100600.c
#include <stdio.h> #define N_PILES 3 #define MAX 32 void print_disks(char disks[N_PILES][MAX]) { int i, j; for (i = 0; i < N_PILES; i++) { for (j = 0; disks[i][j] != 0; j++) printf("%c", disks[i][j]); printf(i != N_PILES-1 ? ", " : "\n"); } } void transfer(char disks[N_PILES][MAX], int from, int to) { int i, from_idx = 0, to_idx = 0; for (i = 0; disks[from][i] != 0; i++) from_idx = i; for (i = 0; disks[to][i] != 0; i++) to_idx = i+1; disks[to][to_idx] = disks[from][from_idx]; disks[from][from_idx] = 0; print_disks(disks); } void hanoi(int n, int from, int temp, int to, char disks[N_PILES][MAX]) { if (n == 1) { transfer(disks, from, to); return; } hanoi(n-1, from, to, temp, disks); transfer(disks, from, to); hanoi(n-1, temp, from, to, disks); } int main(void) { int n; printf("n? "); scanf("%d", &n); char disks[N_PILES][MAX]; for (int i = 0; i < N_PILES; i++) { for (int j = 0; j < n; j++) { if (i == 0) disks[i][j] = 'A' + j; else disks[i][j] = 0; } } print_disks(disks); hanoi(n, 0, 1, 2, disks); return 0; }
the_stack_data/104827767.c
double d_int(x) double *x; { return( (long int) (*x) ); }
the_stack_data/232954873.c
/* $Xorg: AllWidgets.c,v 1.4 2001/02/09 02:03:42 xorgcvs Exp $ */ /* Copyright (c) 1991, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* $XFree86: xc/lib/Xaw/AllWidgets.c,v 1.3 2001/08/23 21:49:51 tsi Exp $ */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <X11/IntrinsicP.h> #include <X11/Xmu/WidgetNode.h> extern WidgetClass applicationShellWidgetClass; extern WidgetClass asciiSinkObjectClass; extern WidgetClass asciiSrcObjectClass; extern WidgetClass asciiTextWidgetClass; extern WidgetClass boxWidgetClass; extern WidgetClass commandWidgetClass; extern WidgetClass dialogWidgetClass; extern WidgetClass formWidgetClass; extern WidgetClass gripWidgetClass; extern WidgetClass labelWidgetClass; extern WidgetClass listWidgetClass; extern WidgetClass menuButtonWidgetClass; extern WidgetClass multiSinkObjectClass; extern WidgetClass multiSrcObjectClass; extern WidgetClass overrideShellWidgetClass; extern WidgetClass panedWidgetClass; extern WidgetClass pannerWidgetClass; extern WidgetClass portholeWidgetClass; extern WidgetClass repeaterWidgetClass; extern WidgetClass scrollbarWidgetClass; extern WidgetClass shellWidgetClass; extern WidgetClass simpleMenuWidgetClass; extern WidgetClass simpleWidgetClass; extern WidgetClass smeBSBObjectClass; extern WidgetClass smeLineObjectClass; extern WidgetClass smeObjectClass; extern WidgetClass stripChartWidgetClass; extern WidgetClass textSinkObjectClass; extern WidgetClass textSrcObjectClass; extern WidgetClass textWidgetClass; extern WidgetClass toggleWidgetClass; extern WidgetClass topLevelShellWidgetClass; extern WidgetClass transientShellWidgetClass; extern WidgetClass treeWidgetClass; extern WidgetClass vendorShellWidgetClass; extern WidgetClass viewportWidgetClass; extern WidgetClass wmShellWidgetClass; #if !defined(OLDXAW) && !defined(XAW7) extern WidgetClass xawPrintShellWidgetClass; #endif XmuWidgetNode XawWidgetArray[] = { { "applicationShell", &applicationShellWidgetClass }, { "asciiSink", &asciiSinkObjectClass }, { "asciiSrc", &asciiSrcObjectClass }, { "asciiText", &asciiTextWidgetClass }, { "box", &boxWidgetClass }, { "command", &commandWidgetClass }, { "composite", &compositeWidgetClass }, { "constraint", &constraintWidgetClass }, { "core", &coreWidgetClass }, { "dialog", &dialogWidgetClass }, { "form", &formWidgetClass }, { "grip", &gripWidgetClass }, { "label", &labelWidgetClass }, { "list", &listWidgetClass }, { "menuButton", &menuButtonWidgetClass }, { "multiSink", &multiSinkObjectClass }, { "multiSrc", &multiSrcObjectClass }, { "object", &objectClass }, { "overrideShell", &overrideShellWidgetClass }, { "paned", &panedWidgetClass }, { "panner", &pannerWidgetClass }, { "porthole", &portholeWidgetClass }, { "rect", &rectObjClass }, { "repeater", &repeaterWidgetClass }, { "scrollbar", &scrollbarWidgetClass }, { "shell", &shellWidgetClass }, { "simpleMenu", &simpleMenuWidgetClass }, { "simple", &simpleWidgetClass }, { "smeBSB", &smeBSBObjectClass }, { "smeLine", &smeLineObjectClass }, { "sme", &smeObjectClass }, { "stripChart", &stripChartWidgetClass }, { "textSink", &textSinkObjectClass }, { "textSrc", &textSrcObjectClass }, { "text", &textWidgetClass }, { "toggle", &toggleWidgetClass }, { "topLevelShell", &topLevelShellWidgetClass }, { "transientShell", &transientShellWidgetClass }, { "tree", &treeWidgetClass }, { "vendorShell", &vendorShellWidgetClass }, { "viewport", &viewportWidgetClass }, { "wmShell", &wmShellWidgetClass }, #if !defined(OLDXAW) && !defined(XAW7) { "printShell", &xawPrintShellWidgetClass }, #endif }; int XawWidgetCount = XtNumber(XawWidgetArray);
the_stack_data/48573980.c
#include <stdio.h> int main() { /* Ogni riga della memoria ha un indirizzo, e i puntatori ci permettono di ottenerlo. *p è un puntatore a variabile intera: contiene l'indirizzo di una cella che contiene un intero. I puntatori hanno un tipo perché dobbiamo accedere a una variabile con un tipo fisso. */ int a, b, *p, *q; /* Introduciamo due nuovi operatori: - & ("address of"): restituisce l'indirizzo della variabile. - * ("dereferenziazione"): permette di accedere alla variabile che il puntatore sta indicando. */ p = &a; *p = 2; /* ! Operatore unario con la stessa priorità degli altri => le parentesi sono importanti. */ (*p)++; /* <=> a++, */ /* Un puntatore non inizializzato contiene un valore a caso => punta a una cella a caso. Se lo utilizziamo o andiamo al di fuori della memoria assegnata (=> crash, segmentation fault) o andiamo a sporcare la memoria del processo. Per questo motivo lo possiamo inizializzare a NULL, che è una macro per l'indirizzo 0, che nessun programma può utilizzare. */ q = NULL; /* La lunghezza del puntatore dipende dall'architettura della macchina: 64 bit <-> indirizzi a 64 bit */ return 0; }
the_stack_data/223336.c
#include<stdio.h> int main() { int a[55]={1,1}; int n; scanf("%d",&n); int i; printf("1"); for(i = 1;i<n;i++) { if(i>=2) printf(" %d",a[i] = a[i-1]+a[i-2]); else printf(" %d",a[i]); } return 0; }
the_stack_data/37638975.c
#include "stdio.h" #include "stdlib.h" #include "time.h" #include "string.h" void print_word_letter_by_letter(char* word, int delay) { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = delay * 10000L; int length; length = strlen(word); int i = 0; while (1) { putchar(word[i]); i++; if (i > length) { putchar(' '); i = 0; } fflush(stdout); if (nanosleep(&ts, NULL) > 0) { perror("nanosleep"); } } } int main(int argc, char** argv) { if (argc < 2) { printf("Usage : %s <délai d'affichage (en ms)>\n", argv[0]); return EXIT_FAILURE; } print_word_letter_by_letter("third", atoi(argv[1])); return EXIT_SUCCESS; }
the_stack_data/107952217.c
// PARAM: --set ana.activated[0][+] "'var_eq'" --set ana.activated[0][+] "'symb_locks'" --set ana.activated[0][+] "'region'" --set exp.region-offsets true #include<pthread.h> struct list_head { struct list_head *next ; struct list_head *prev ; }; struct s { int datum ; struct list_head list ; }; struct cache { struct list_head slot[10] ; pthread_mutex_t slots_mutex[10] ; }; struct cache c ; inline static struct list_head *lookup (int d) { int hvalue; struct list_head *p; p = c.slot[hvalue].next; return p; } void *f(void *arg) { struct s *pos ; int j; struct list_head const *p ; struct list_head const *q ; while (j < 10) { pthread_mutex_lock(&c.slots_mutex[j]); p = c.slot[j].next; pos = (struct s *)((char *)p - (unsigned int )(& ((struct s *)0)->list)); while (& pos->list != & c.slot[j]) { pos->datum++; // NORACE! q = pos->list.next; pos = (struct s *)((char *)q - (unsigned int )(& ((struct s *)0)->list)); } pthread_mutex_unlock(&c.slots_mutex[j]); j ++; } return 0; } int main() { struct list_head *p; int x; pthread_t t; p = &c.slot[x]; x = 99; // We invalidate p; but it is not written to. pthread_create(&t, NULL, f, NULL); return ((int)p); // }
the_stack_data/403086.c
int main(void) { unsigned int x = 1; unsigned int y = 0; while (y < 10) { x = 0; y++; } assert(x == 0); }
the_stack_data/63728.c
/** * Exercise 1-19. * Write a function reverse(s) that reverses the character string s. * Use it to write a program that reverses its input a line at a time. */ #include <stdio.h> #define MAXQUENE 1000 char line[MAXQUENE]; int gline(char s[]); void reverse(char s[]); int main() { int len, i; while ((len = gline(line)) > 0) { reverse(line); for (i = 0; line[i] != '\0' && line[i] != '\n'; ++i) { putchar(line[i]); } putchar('\n'); putchar('\0'); } } int gline(char s[]) { int c, i; for (c = 0, i = 0; (c = getchar()) != EOF && c != '\n'; ++i) s[i] = c; if (c == '\n') { s[i] = '\n'; ++i; } s[i] = '\0'; return i; } void reverse(char s[]) { int i, j; char tmp; for (i = 0; s[i] != '\0' && s[i] != '\n'; i++) ; --i; for (j = 0; j < i; j++) { tmp = s[i]; s[i] = s[j]; s[j] = tmp; --i; } }
the_stack_data/342901.c
#include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <error.h> typedef struct{ // clock model: real = ratio*(raw - base) + base + delta double ratio; long long base_x, base_y; long long low, up, offset, jitter; long long index, period; // init to 0, increase upon updating } Clock; int main(int argc, char **argv) { Clock local; local.index = 1; local.offset = 100; local.base_x = 200; local.base_y = 300; local.low = 400; local.up = 500; local.period = 600; local.jitter = 700; int fd, nread, i; struct stat sb; long long *mapped; /* 打开文件 */ if ((fd = open("clock.txt", O_RDWR | O_CREAT, 0777)) < 0) { perror("open"); } int w1 = write(fd, &local.index, sizeof(long long)); int w2 = write(fd, &local.offset, sizeof(long long)); int w3 = write(fd, &local.base_x, sizeof(long long)); int w4 = write(fd, &local.base_y, sizeof(long long)); int w5 = write(fd, &local.low, sizeof(long long)); int w6 = write(fd, &local.up, sizeof(long long)); int w7 = write(fd, &local.period, sizeof(long long)); int w8 = write(fd, &local.jitter, sizeof(long long)); printf("%d %d %d %d %d %d %d %d\n", w1, w2, w3, w4, w5, w6, w7, w8); return 0; }
the_stack_data/50137406.c
void pasm ( void ) { set_pindirs(1); label("loop"); pull_block(); out_pins(1,0); jmp("loop"); }
the_stack_data/70450785.c
#include <stdio.h> int bubble, ordem; double lado[3], aux; int orga() { for (ordem = 0; ordem < 3; ordem ++) { for (bubble = 0; bubble < 3; bubble ++) { if (lado[ordem] < lado[bubble]) { aux = lado[bubble]; lado[bubble] = lado[ordem]; lado[ordem] = aux; } } } } int main() { int repeat; for (repeat = 0; repeat < 3; repeat ++) { scanf("%lf", &lado[repeat]); } orga(); if (lado[2] < lado[1] + lado[0] && lado[2] > lado[1] - lado[0]) { if (lado[0] == lado[1] && lado[1] == lado[2]) { printf("EQUILATERO\n"); } else if ((lado[0] == lado[1]) || (lado[0] == lado[2]) || (lado[1] == lado[2])) { printf("ISOSCELES\n"); } else { printf("ESCALENO\n"); } } else { printf("-\n"); } return(0); }
the_stack_data/1003071.c
int some_helper() { return 1; }
the_stack_data/57950282.c
#include<stdio.h> #include<stdlib.h> int* merge_sort(int*,int); void printa(int*,int); int** dividir(int*,int,int**); int tamano(int*); int* merge(int*,int*,int,int); int* merge_sort(int* A,int n) { if(n<=1) return A; else { int **A_i_d=dividir(A,n,A_i_d); int *A_i=A_i_d[0]; int *A_d=A_i_d[1]; /* Test printf("\nTamanos n_i: %d\nn_d: %d",tamano(A_i),tamano(A_d)); printf("\nArreglos 2:\n"); printa(A_i,tamano(A_i)); printf("\n"); printa(A_d,tamano(A_d)); */ int* O_i=merge_sort(A_i,tamano(A_i)); int* O_d=merge_sort(A_d,tamano(A_d)); int* O=merge(O_i,O_d,tamano(O_i),tamano(O_d)); return O; } } int** dividir(int* A,int n ,int** A_i_d) { int n_i; int n_d; int* A_i; int* A_d; if(n%2==0) { n_i=n/2; n_d=n_i; } else { n_i=(n+1)/2-1; n_d=(n+1)/2; } A_i=(int*)malloc((n_i+1)*sizeof(int)); A_d=(int*)malloc((n_d+1)*sizeof(int)); int i; for(i=0;i<n_i;i++) A_i[i]=A[i]; A_i[i]='\0'; int j; for(j=0;i<n;j++,i++) A_d[j]=A[i]; A_d[j]='\0'; A_i_d=(int**)malloc(2*sizeof(int*)); *(A_i_d+0)=A_i; *(A_i_d+1)=A_d; /* Test // printf("\nArreglos:\n"); // printa(A_i,n_i); // printf("\n"); // printa(A_d,n_d); /* ******************************** */ return A_i_d; } int* merge(int* O_i,int* O_d, int n_i,int n_d) { int* O=(int*)malloc((n_i+n_d)*sizeof(int)); int i=0; int j=0; int k=0; while(i<n_i && j<n_d) { if(O_i[i]<O_d[j]) { O[k]=O_i[i]; i++; } else { O[k]=O_d[j]; j++; } k++; } if(i<n_i) { for(;i<n_i;i++) { O[k]=O_i[i]; k++; } } else { for(;j<n_d;j++) { O[k]=O_d[j]; k++; } } return O; } int tamano(int* A) { int tam; for(tam=0;A[tam]!='\0';tam++); return tam; } int main(void) { int n; printf("Escribe el valor de n="); scanf("%d",&n); fflush(stdin); int* A=(int*)malloc(n*sizeof(int)); printf("Escribe los numeros:\n"); for(int i=0;i<n;i++) { printf("#%d--> ",i+1); scanf("%d",A+i); fflush(stdin); } printa(A,n); A=merge_sort(A,n); printf("\n\n"); printa(A,n); return 1; } void printa(int* A,int n) { for(int i=0;i<n;i++) printf("%d, ",A[i]); }
the_stack_data/3025.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int anzahl = 12; int maxchar = 50; /* char erzeugezufallschar() { char randomletter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random () % 26]; return randomletter; } void namenfeldgenerieren(char namensliste[][maxchar]) { int laengename = rand () % 16 + 5; for(int i = 0; i < anzahl; i++) { for(int j = 0; j < laengename; j++) { namensliste[i][j] = erzeugezufallschar; } } } */ void ausgabe(char namensliste[][maxchar]) { int i; for(i = 0; i < anzahl; i++) { printf("%s\n", namensliste[i]); } } void bubblesort(char namensliste[][maxchar]){ char tmp[maxchar]; for(int i = 0; i < anzahl - 1; i++){ for(int j = 0; j < anzahl - 1 - i; j++){ if(strcmp(namensliste[j], namensliste[j + 1]) > 0) { strcpy(tmp, namensliste[j]); strcpy(namensliste[j], namensliste[j + 1]); strcpy(namensliste[j + 1], tmp); } } } } int main () { printf("\t N A M E N S O R T I E R E N\n" "\t------------------------------\n\n"); //habe versucht in Zeile 68 "namensliste[anzahl][maxchar]" zu schreiben, funktioniert aber irgendwie nicht char namensliste[12][50] = {"Oliver", "Jakob Kurzmann", "Jakob Rumpf", "Jan", "Fabio", "Sebastian Sever", "Matteo", "Sebastian Pojer", "Elias Hoebel", "Elias Kolb", "Tobias", "Eric" }; printf("\nNicht sortierte Namen: \n\n"); ausgabe(namensliste); bubblesort(namensliste); printf("\nAlphabetisch sortierte Namen: \n"); ausgabe(namensliste); /* char liste2[12][50]; namenfeldgenerieren(liste2[12][50]); ausgabe(liste2); */ return 0; }
the_stack_data/153493.c
/*TODO in future s - Non-equilibrium candidate moves - check scaling of particles of different sizes - should scale with contact area! - cell list - divide simulation box in cells where particles interact with each other and outside is definitely 0 - safe time better scaling with system size, possibly long spherovylinders could be in several celles to keep good scaling - better cluster algorithm - put in wang-landau - cluster list work for spherocylinders only now */ /*------------------------------------------------------------------------------ Version 3.5 - linear bond at spherocylinders, where second spherocilinder is harmonicaly attached to a point that is in distance of bondlength from the first spherocylinder and it follows the direction of spherocylinder - bonded particles belong to the same cluster - print energy at statistical reports - have particles of different lengths - interaction scaling back to v1+v2 (no addition of 1.0) - more physical */ /*------------------------------------------------------------------------------ Version 3.4 - New handling of the option file - reaction coordinate radius around z axis for a pore calculations - reaction coordinate as number of particles in contact (defined by distance of CMs) - 2D Wang-Landau method - New Wang-Landau coordinate - radius pore in vesicle around begining of xy plane - New models TPSC, TCPSC, TCHPSC, TCHCPSC- models with two patches note that switch function on sides of patch are linear in cos angle not in angle as a results two patches with overlaping sides do not compensate easily to a flat profile - FIX chirality was doubled (angle twice as large) - Added posibility of exluded interactions [EXCLUDE] in topology file - MPI replica exchange with different temperatures and pressure (paraltemp paralpress) input configuration is #{number of process}config.init, if it does not exist config.init is used each replica is with different random seed = seed+mpirank - config.init can look like movie snapshot - MPI exchange with Wang-Landau - added angular interaction between neighboring spherocylinders (in chain) angle1 is angle between sc directions and angle2 ins angle between the patches */ /*------------------------------------------------------------------------------- Version 3.3 -external potantial can be added as a part of topology - it can be hard or attractive wall */ /** * Changes made by Noah S. Bieler and Robert Vacha: * * New version 3.2 * * - The length has now to be specified in the topology file, but they are not * allowed to differ from each other. The option file shall no longer contain * a length option. * - The particles can now switch their type based on the chemical potential * delta_mu (= energy difference from state 2 to state 1). * - For that a new option was introduced: Average attempts per sweep to switch * a type. * - A lot of variables are now combined in either topo, sim or conf. The rule * should be: * > topo: Everything that belongs to the topology and that should not change * during the game. * > sim: Options and stuff, that has to do with the simulation. (Maybe the * current target and so should be saved in there as well) * > conf: What changes every step concerning the particles and the box or * in other words: what has been read from conf.init * - added a cluster determing routine => sim->clusterlist + sim->clusters * - added macros for TRUE and FALSE * - Added Option for the random seed * - Basic Neighbour list implemented * - New types: chiral CPSC (CHCPSC) and chiral PSC (CHPSC) and their interactions */ /*-------------------------------------------------------------------------------- sc31.c Patchy Spherocylinder Version 3.1 Wang-Landau method of free energy calculations It is set in options file as: O = none, 1 = z-distance of 1st paticle from system CM, 2 = hole in xyplane of SCA = membrane hole It reads a file wl.dat and write wl-new at the end. There is value of alpha at the first line and then there are three columns: 1- order parameter, 2- weights, 3- histogram Interaction of spherocylinders is scaled based on the volume of attractive patch, the unit of one is that two spheres of diameter sigma =1.0 are attracting each other by 1.0. Using this in interaction among lipids and spherocylinders should be consistent. Start up configuration "config.init" file has a box size at the first line now. (I tested performance: compilation with optimization -O2 speed up 10% rest has negligible effect including usage of static arrays instead of dynamic most of the time consumes paire function. 6,519,638,177 :simulate 6,492,411,300 :energyone 5,705,685,593 :paire 542,561,887 :bondenergy 489,463,361 :eattractive11 450,443,970 :image 115,126,519 :erepulsive */ /* -------------------------------------------------------------------------------- sc3.c Patchy Spherocylinder Version 3.0 Beads were added to the particle list. bead(10) - repulsive bead(11) - isotropocally attractive -It is necessary to provide also a topology file (top.init) -Particles are placed in chains according to the topology order including connections -Particle arryas are allocated dynamicly on heap now -dispacement and rotation are optimized for highest RMSD performace -NPT ensemble with isotropic and anisotropic couplings, in pressure moves all particles are rescaled with their center (chains are not rescaled with CM) 0 - anisotropic coupling, 1 - isotropic coupling, 2 - isotropic in xy z=const bead types and their interactions repulsive(10) purely repulsive shpere with WCA potential on closest distance parameters: Patch repulsion sigma - defined where repulsion reaches zero isotropic(11) - isotropic cos^2 potential is acting isotropicaly dependent only on closest distance between obejcts. Parameters: distance of attractivity (should be at least sigma*2^(1/6)) defines how far is attraction constant -e. After this distance follows switch length on which attraction goes to zero as cos^2. Rest as repulsive model. sc2.c Patchy Spherocylinder Version 2.0 It is possible to make chains of spherocylinders that are connected through hemispherical caps by harmonic bond. There are two parameters eq distance and strength of harmonic spring, note that units are in 1 kT/e, the MC strength of bond is changing with parameter temperature.. Patchy Spherocylinder Version 1.0 Includes diffferent types of possible interactions: repulsive(0) - purely repulsive spherocylinder with WCA potential on closest distance. parameters: Patch repulsion sigma - defined where repulsion reaches zero. isotropic(1) - isotropic cos^2 potential is acting isotropicaly dependent only on closest distance between spherocylinders. Parameters: distance of patch, Interaction distance of patch (should be at least sigma*2^(1/6)) defines how far is attraction constant -e. After this distance follows Switch length on which attraction goes to zero as cos^2. Rest as repulsive model. patchy(2) - Attractive potential in limited to an angular wedge on spherocylinder. Patch goes all the way through, making also hemispherical caps on end attractive. Parameters:Anglular part has a parameter defining it size "Angular size of patch (degrees)" and witdh of switch function "Angular switch off of patch (degrees)" on which attraction reaches zero - it is a linear function. Rest as isotropic model. cylindrical(3) - Attractive potential in limited to an angular wedge on cylindrical part of spherocylinders. The hemispherical caps on ends are repulsive. Rest as patchy model. Note particles are inside numbered from 0, there is prealocated size of particles MAXN because in future there can be grand canonical ensamble and number of particles may vary Follows mc of hard wall spherocylinder version 7 by Mark Miller -description below sc.c Version 1 Performs basic constant volume MC simulation of hard spherocylinders with rigid cuboidal boundary conditions. Run parameters are read in from the file "options". The template for this file appears at the end of the code. The values must be inserted before the colons. The initial configuration is read from the file "config.init". The first line contain size of box The format for the file is nine columns: three for the positions and three for the direction vector and three for direction of pathc. The direction vectors are normalised after being read in. The configuration is checked for particle overlaps. The unit of length is taken as the spherocylinder diameter. Hence the ratio L/D is equal to the length of the cylinder. Order parameters for nematic and smectic order are evaluated. The nematic order parameter is related to the coefficient of the quadratic term in the Legendre expansion of the orientational distribution function. Any smectic order is assumed to be directed along the z axis, and is detected by the coefficients of the Fourier expansion of the position distribution function. MM 12.vii.01 .................................................................................. Version 2 The aspect ratio of the box may now fluctuate, keeping the volume constant. Two new parameters are required in the options file to specify the average number of attempted shape changes per sweep, and the initial maximum trial change in a box dimension. Shape changes are made by picking one of the three box lengths at random, making a random change, evenly distributed between plus and minus a finite interval, choosing a second direction and doing the same, then determining the new length in the remaining direction from the condition of constant volume. The step-size equilibration period is now split into three parts: displacement, rotation, and shape change. The most important change to the code is that the particle coordinates are now stored as fractions of the box dimensions. However, input and output configurations are still communicated in units of the cylinder diameter, D=1. Note that the displacement maximum step size is now specified as a fraction of the box length, not as an absolute distance. MM 18.vii.01 .................................................................................. Version 3 Constant pressure MC. The volume may fluctuate. Volume changes are attempted by altering just one box length at a time, chosen at random. The running average of the density is calculated and reported. MM 24.vii.01 .................................................................................. Version 7 The composite translation-plus-rotation moves have been split into separate move types, each of which is attempted with equal probability. This enables acceptance ratios to be accumulated separately for these degrees of freedom, so that maximum step sizes can be adjusted more sensibly. A few other things have been tidied up, such as defining structures for the book-keeping of statistics and acceptance ratios. MM 9.v.02 --------------------------------------------------------------------------------*/ #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdbool.h> #ifdef MACOS # include "getline.h" #endif #ifdef MPI # include <mpi.h> #endif /* Macros for DEBUG messages */ #ifdef DEBUGGING_INIT #define DEBUG_INIT(...) fprintf(stderr, "DB in INIT: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); fflush(stderr); #else #define DEBUG_INIT(...) #endif #ifdef DEBUGGING_SIM #define DEBUG_SIM(...) fprintf(stderr, "DB in SIM: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); fflush(stderr); #else #define DEBUG_SIM(...) #endif #ifdef DEBUGGING #define DEBUG(...) fprintf(stderr, "DB: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); fflush(stderr); #else #define DEBUG(...) #endif /* End of DEBUG macros */ /* With pairlist ? */ #define WITH_PAIRLIST /* Boolean Macros */ #define BOOL int #define TRUE 1 #define FALSE 0 /* End of Boolean Macros */ #define MAXF 20 /* Maximum number of Fourier terms */ #define MAXN 14000 /* Maximum number of particles */ #define MAXCHL 10 /* Maximum length of chain */ #define ZEROTOL 1.0e-12 /* Dot products below ZEROTOL are deemed zero */ #define ZEROTOL2 1.0e-8 /* numbers below ZEROTOL are deemed zero */ #define PI 3.141592653589793238462643383279 /* pi */ #define PIH 1.57079632679489661923132169163975 /* pi half*/ /*Particle types*/ #define SC 10 /*spherocylinder*/ #define SCN SC+0 /*spherocylinder non-attractive*/ #define SCA SC+1 /*spherocylinder isotropicaly attractive*/ #define PSC SC+2 /*spherocylinder with patchy attraction*/ #define CPSC SC+3 /*spherocylinder with cylindrical patchy attraction*/ #define CHPSC SC+4 /* chiral psc */ #define CHCPSC SC+5 /* chiral cpsc */ #define TPSC SC+6 /*spherocylinder with two patches*/ #define TCPSC SC+7 /*spherocylinder with two cylindrical patches*/ #define TCHPSC SC+8 /* chiral 2psc */ #define TCHCPSC SC+9 /* chiral 2cpsc */ #define SP 30 /*sphere - should be over all apherocylinders*/ #define SPN SP+0 /* sphere non-attractive*/ #define SPA SP+1 /* spherocylinder isotropicaly attractive*/ #define MAXT 30 /* Maximum number of types we have*/ #define MAXMT 100 /* Maximum number of molecular types */ /*Reading topology*/ #define SMSTR 64 /* Small string length */ #define STRLEN 400 /* maximum length of line*/ #define CONTINUE '\\' /* symbol for line continue*/ #define COMMENTSIGN '#' /* symbol for comment*/ #define OPENKEY '[' /* starting sign for keyword*/ #define CLOSEKEY ']' /* ending sign for keyword*/ #define SEPARATOR ':' /* sign for separator*/ #define OPENMOL '{' /* starting sign for molecules*/ #define CLOSEMOL '}' /* ending sign for molecules*/ #define BOXSEP 'x' /* extraction of box*/ /* Wang Landau method */ #define WL_GERR 0.0001 /* Max roughnes in histogram */ #define WL_ALPHATOL 0.000001 /* Covergence crietria for detailed balance */ #define WL_MINHIST 1000 /* Minimum histogram sampling for considering roughness */ #define WL_ZERO 0.000000000000 /* Zero for histogram with current weights*/ #define WL_CONTACTS 36.0 /* Square distance under which are particles in contact */ /* Math */ #define DOT(a,b) ((a).x * (b).x + (a).y * (b).y + (a).z * (b).z) /* Dot product */ #define AVER(a,b) ((a+b)*0.5) /* Arithmetic average*/ #define ROUND(a) (a > 0.0) ? floor(a + 0.5) : ceil(a - 0.5); /* Round double*/ #define PMONE(a) (1 - 2 * a) /* Takes 1 or 0, return +-1 */ /* Acceptance ratio */ #define RATIO(a) ( ((a).acc+(a).rej) > 0 ? 1.0*(a).acc/((a).acc+(a).rej) : 0.0 ) #define INBOX(a,b) ( a > 0 ? modf(a,&b) : modf(a,&b)+1 ) /*................................................................ Structure definitions */ struct vector { /* Define a 3D vector structure */ double x; double y; double z; }; struct quat { /* Define a quaternion structure */ double w; double x; double y; double z; }; struct particles { /* Define a particle */ struct vector pos; /* Position vector */ struct vector dir; /* Unit direction vector of axis */ struct vector patchdir[2]; /* Vector defining orientation of patch */ struct vector patchsides[4]; /* Vector defining sides of patch */ struct vector chdir[2]; /* Direction for chirality - keep in memory to increase speed */ long chaint; /* Chain type*/ long chainn; /* Chain number*/ int type; /* Type of the particle */ int switchtype; /* With which kind of particle do you want to switch?*/ double delta_mu; /* Chemical potential for the switch */ int switched; /* 0: in initial stat; 1: in the switched stat */ }; struct ia_param{ /* Contatins properties and parameters of particle types */ char name[SMSTR]; /* The name of the particle type */ char other_name[SMSTR]; /* The name of the particle type */ int geotype[2]; /* The geometrical type: spherocylinder (0-repulsive, 1-isotropic, 2-patchy, 3-cylindrical) or sphere (0-repulsive, 1-isotropic) */ double sigma; /* Repulsion wca*/ double epsilon; /* Repulsion strength*/ double pdis; /* Interaction distance of patch */ double pswitch; /* Switch of distance of patch */ double pangl[4]; /* angular size of patch as was specifid in input */ double panglsw[4]; /* angular size of patchswitch as was specifid in input */ double pcangl[4]; /* cosine of half size angle - rotation from patch direction to side */ double pcanglsw[4]; /* cosine of half size angle plus switch - rotation from patch direction to side */ double rcut; /* Cutoff for attraction */ double rcutwca; /* Cutoff for repulsion*/ double pcoshalfi[4]; /* Cosine of half angle going to side of interaction */ double psinhalfi[4]; /* Sine of half angle going to side of interaction -useful for quaterion rotation */ double csecpatchrot[2]; /* Cosine of Rotation of second patches in 2psc models*/ double ssecpatchrot[2]; /* Sine of Rotation of second patches in 2psc models*/ double volume; /* Volume of particle for geometrical center calculations*/ double pvolscale; /* Scale of patch volume size*/ double len[2]; /* Length of the PSC */ double half_len[2]; /* Half length of the PSC */ double chiral_cos[2]; /* Coctains the cosinus for the chiral rotation of the patch */ double chiral_sin[2]; /* Contains the sinus for the chiral rotation of the patch */ }; struct interacts { /* Parameters pased to functions of interaction calculation */ double dist; /* closest distance */ struct vector distvec; /* vector of closes distance */ struct particles * part1; /* particle 1 */ struct particles * part2; /* particle 2 */ struct vector box; /* box size */ struct ia_param * param; /* interaction parameters */ struct vector r_cm; /* vector connecting center of masses */ double distcm; /* distance between center of masses */ double dotrcm; /* square size of r_cm*/ double contt; /* closest point on spherocylinder to sphere */ }; struct chainparams { /*Parameters for inner interaction in chains*/ double bond1eq; /* Equilibrium distance of harmonic bond between nearest neighbours*/ double bond1c; /* Spring constant for harmonic bond between nearest neighbours*/ double bond2eq; /* Equilibrium distance of harmonic bond between second nearest neighbours*/ double bond2c; /* Spring constant for harmonic bond between second nearest neighbours*/ double bonddeq; /* Equilibrium distance of directional harmonic bond between the nearest neighbours*/ double bonddc; /* Spring constant for directional harmonic bond between the nearest neighbours*/ double angle1eq; /* Equilibrium angle between two spherocylinders -neerest neighbours*/ double angle1c; /* Spring constant angle between two spherocylinders -nearest neighbours*/ double angle2eq; /* Equilibrium angle between two spherocylinder patches -nearest neighbours*/ double angle2c; /* Spring constant for angle between two spherocylinder patches -nearest neighbours*/ }; struct molecule { /* This structure is for io only */ char * name; /* The name of the molecule */ long * type; /* The type of the particle */ long * switchtype; /* The switchtype of the particle */ double * delta_mu; /* The chemical potential for the switch */ }; struct disp { /* Define step size and acceptance ratio statistics */ double mx; /* Maximum value displacement, cos(angle), etc. */ double angle; /* Maximum angle, since in .mx cos(angle) is saved */ long acc; /* Number of accepted steps */ long rej; /* Number of rejected steps */ double oldrmsd; /* Averaged mx value in previous equilibration round */ double oldmx; /* Change in mx in last equlibrium step */ }; struct stat { /* Define statistics counters */ double sum; double sum2; long samples; double mean; double rms; }; struct meshs { /* Mesh for hole order parameter */ int dim[2]; /* Mesh dimensions */ int *data; /* Mesh data */ int *tmp; /* tmpporary list for hole search */ }; struct wls { /* Wang landau method (wl) */ double *weights; /* Array of weights for wl method */ long *hist; /* Array of histogram for wl method */ long length[2]; /* Length of above arrays */ double dorder[2]; /* Increments of order parameter */ double minorder[2]; /* Minimum order parameter */ double alpha; /* Current modifier of weights */ long currorder[2]; /* Walue of current order parameter*/ long neworder[2]; /* wl order parameter in new step */ long max; /* wl maximum of histogram */ long min; /* wl minimum of histogram */ double wmin; /* weights minimum */ int wlmdim; /* Dimwnsionality of wang landau */ int wlmtype; /* Atom type for the Wang landau method (wl) */ double wl_meshsize; /* Size of mesh bin for hole order paremeter*/ struct meshs mesh; /* Mesh for hole order */ struct meshs origmesh; /* Mesh store for rejected moves */ long * radiushole; /* Array for hole radius around origin */ long * radiusholeold; /* Array for hole radius around origin-bigmove */ long radiusholemax; /* Size of array for hole radius*/ long partincontact; /* Number of particles in contact */ long partincontactold; /* Number of particles in contact - old for move*/ }; struct pairs{ /* The structure holding the particle numbers of the pairs and the number of pairs */ long num_pairs; /* The number of pairs */ long * pairs; /* The paritcle numbers of the paris */ }; struct pairlist{ /* I think, this is done too complicated: just sim->pairs[npart] should be enough */ struct pairs * list; /* contains the pairlist of all paritcles */ }; struct cluster{ /* contains all the particles of one cluster */ long npart; long * particles; }; struct exters{ BOOL exist; /* existence of external potential*/ double thickness; /* external wall thicnkess*/ double epsilon; /* depth of attraction*/ double attraction; /* distance of attraction*/ double sqmaxcut; /* distance when nothing can interact*/ struct ia_param interactions[MAXT]; /* Interaction parameters with particle types generated from above params*/ }; struct topo{ /* It would be nice, if this struct would contain all the topo stuff in the end*/ long * switchlist; /* List containing the number of all the particles with switchtypes */ long n_switch_part; /* number of particles with switchtype */ double sqmaxcut; /* square of distance over which even spherocylinders cannot interact (distance between CM) */ double maxcut; /* distance over which even spherocylinders cannot interact (distance between CM) */ long conlist[MAXN][4]; /* Connectivity list, we have connection to tail and head and secon neighbours so far*/ long chainlist[MAXN][MAXCHL]; /* List of chains*/ long chainnum; /* Number of chains */ struct chainparams chainparam[MAXMT]; /* parameters for chains */ struct ia_param ia_params[MAXT][MAXT]; /* parametrization of particles for all interations*/ long npart; /* Number of particles */ struct exters exter; /* external potential - wall */ }; struct sim{ /* Should contain mostly all the simulation options and variables, that can change in every step. */ double press; /* Pressure */ double paralpress; /* Parallel pressure for replica exachnge*/ double dpress; /* Pressure change for replica exchange*/ double shave; /* Average number of volume changes to attempt per sweep */ double shprob; /* Probability of attempting a volume change */ double chainprob; /* Average number of chain move attempt per sweep */ double switchprob; /* Average number of type switch attempt per sweep */ int pairlist_update; /* Number of sweep per upedating the pairlist */ double temper; /* Temperature*/ double paraltemper; /* Temperature for parallel tempering */ double dtemp; /* Temprature step */ int ptype; /* Type of pressure coupling*/ long adjust; /* Number of sweeps between step size adjustments */ long movie; /* Number of sweeps between movie frames */ long nequil; /* Number of equilibration sweeps */ long nsweeps; /* Number of production sweeps */ long paramfrq; /* Number of sweeps between order parameter samples */ long report; /* Number of sweeps between statistics reports */ // long terms; /* Number of Fourier terms as smectic order parameters */ long nrepchange; /* Number of sweeps between replica exchanges */ int wlm[2]; /* Wang landau method (wl) */ struct disp edge; /* Maximum box length change and statistics */ struct disp rot[MAXT]; /* Maximum rotation and statistics */ struct disp trans[MAXT]; /* Maximum translation and statistics*/ struct disp chainm[MAXMT]; /* Maximum translation for chain and statistics*/ struct disp chainr[MAXMT]; /* Maximum rotation for chain and statistics */ struct disp mpiexch; /* MPI statistics*/ struct pairs * pairlist; /* The pairlist */ long write_cluster; /* Number of sweeps per writing out cluster info */ long * clusterlist; /* clusterlist[i] = cluster index of particle i */ struct cluster * clusters; /* informations about the single clusters */ double *clustersenergy; /* list of energies of clusters*/ long num_cluster; /* number of single clusters */ long * clusterstat; /* Statistics about the seize of cluster */ long max_clust; /* maximal clustersize */ struct wls wl; /* Wang landau data */ int mpirank; /* MPI number for given process*/ int mpinprocs; /* MPI number of processes */ }; typedef enum { /* Holds the type of a variable in struct option */ Int, Int2, Long, Double } Type; typedef struct { /* for reading in the options */ char *id; /* The name of the value in the option file*/ Type type; /* The type (int, double or long) */ BOOL set; /* Wheter the variable has been set */ void *var; /* The variable */ } Option; struct conf{ /* Configuration of the system*/ struct particles * particle; /* All particles*/ struct vector box; /* Box size*/ double sysvolume; /* Something like total mass*/ struct vector syscm; /* System center of mass*/ }; struct filenames { /* input files */ char configurationinfile[30]; char topologyfile[30]; char optionsfile[30]; char wlinfile[30]; /* output files */ char configurationoutfile[30]; char moviefile[30]; char wloutfile[30]; char statfile[30]; char clusterfile[30]; char clusterstatfile[30]; char energyfile[30]; }; struct mpiexchangedata{ /* extra type for mpi communication*/ struct vector box; /* box of configuration */ double energy; /* energy of configuration */ double volume; /* volume of configuration */ int accepted; /* bool if accepted */ struct vector syscm; /* system CM of configuration */ long radiusholemax; /* size of array for WL*/ long wl_order[2]; /* wang-landau order parameter*/ }; #ifdef MPI MPI_Datatype MPI_vector, MPI_Particle, MPI_exchange; #endif const struct stat nullstat = {0.0, 0.0, 0, 0.0, 0.0}; long seed = 6; /* Seed for random number generator */ /*..............................................................................*/ int main(int argc, char **argv) { DEBUG("start"); FILE *outfile,*mov; /* Handle for writing configuration */ double (* intfce[MAXT][MAXT])(struct interacts *); /*array of interaction functions*/ struct topo topo; /* will maybe contain all the topo stuff in future */ struct sim sim; /* Should contain the simulation options. */ struct conf conf; /* Should contain fast changing particle and box(?) information */ struct filenames files; int memoryalloc(struct conf * conf); int memorydealloc(struct conf * conf, struct topo * topo, struct sim * sim); void read_options(struct sim* sim, char filename[30]); void init_top(struct topo *, struct conf * conf, struct sim * sim, char filename[30]); void init_config(struct topo * topo, struct conf * conf, struct sim * sim, char filename[30]); void init_intfce(double (* intfce[MAXT][MAXT])(struct interacts *), struct topo * topo); void draw(FILE *, struct conf * conf, struct topo * topo); void printeqstat(struct disp *, double, int); void simulate(long nsweeps, long adjust, long paramfrq, long report, double (* intfce[MAXT][MAXT])(struct interacts *), struct topo * topo, struct sim * sim, struct conf * conf, struct filenames *files); void init_pairlist(struct topo * topo, struct sim * sim); void gen_pairlist(struct topo * topo, struct sim * sim, struct conf * conf); void print_pairlist(FILE * stream, struct sim * sim, struct topo * topo); int gen_clusterlist(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *) ); int print_clusterlist(FILE * stream, BOOL decor, struct topo * topo, struct sim * sim, struct conf * conf); int print_clusters(FILE * stream, BOOL decor, struct sim * sim); int print_clusterstat(FILE * stream, BOOL decor, struct sim * sim); int sort_clusterlist(struct topo * topo, struct sim * sim); printf ("\nPatchy Spherocylinders version 3.5 "); sprintf(files.configurationinfile, "config.init"); sprintf(files.configurationoutfile, "config.last"); sprintf(files.optionsfile, "options"); sprintf(files.topologyfile, "top.init"); sprintf(files.moviefile, "movie"); sprintf(files.wlinfile, "wl.dat"); sprintf(files.wloutfile, "wl-new.dat"); sprintf(files.statfile, "stat.dat"); sprintf(files.clusterfile, "cluster.dat"); sprintf(files.clusterstatfile, "cluster_stat.dat"); sprintf(files.energyfile, "energy.dat"); #ifdef MPI FILE *infile; printf(" MPI version"); MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &(sim.mpinprocs) ); MPI_Comm_rank(MPI_COMM_WORLD, &(sim.mpirank) ); sprintf(files.configurationoutfile, "%dconfig.last", sim.mpirank); sprintf(files.moviefile, "%dmovie", sim.mpirank); sprintf(files.wloutfile, "%dwl-new.dat", sim.mpirank); sprintf(files.clusterfile, "%dcluster.dat", sim.mpirank); sprintf(files.clusterstatfile, "%dcluster_stat.dat", sim.mpirank); sprintf(files.energyfile, "%denergy.dat", sim.mpirank); sprintf(files.statfile, "%dstat.dat", sim.mpirank); /*test if there is a specific input configuration for mpi run*/ sprintf(files.configurationinfile, "%dconfig.init", sim.mpirank); infile = fopen(files.configurationinfile, "r"); if (infile != NULL) fclose (infile); else sprintf(files.configurationinfile, "config.init"); /*test if there is a specific input wang-landau for mpi run*/ sprintf(files.wlinfile, "%dwl.dat", sim.mpirank); infile = fopen(files.wlinfile, "r"); if (infile != NULL) fclose (infile); else sprintf(files.wlinfile, "wl.dat"); #endif printf ("\n-------------------------------------\n"); printf ("Reading options...\n"); read_options(&sim,files.optionsfile); init_top(&topo, &conf, &sim,files.topologyfile); if (topo.chainnum ==0) { /*no chain make the probability of moving them 0*/ if (sim.chainprob > 0) printf ("No chains... chain move probability set to 0.\n"); sim.chainprob = 0; } printf ("\nReading configuration...\n"); init_config(&topo, &conf, &sim, files.configurationinfile); printf ("Equilibration of maximum step sizes: %ld sweeps\n", sim.nequil/2); fflush (stdout); if ( sim.wlm[0] > 0 ) { outfile = fopen(files.wlinfile, "r"); if (outfile == NULL) { printf ("ERROR: Cannot open file for Wang-Landau method (%s).\n",files.wlinfile); memorydealloc(&conf, &topo, &sim); exit(1); } fclose (outfile); } /* Empty movie file */ mov = fopen("movie", "w"); fclose (mov); printf ("\nInitializing energy functions...\n"); init_intfce(intfce, &topo); if (sim.pairlist_update) { init_pairlist(&topo, &sim); } if (sim.nequil) { printf("\nStart equilibration...\n"); simulate(sim.nequil/2, sim.adjust, 0, 0, intfce, &topo, &sim, &conf,&files); simulate(sim.nequil/2, 0, 0, 0, intfce, &topo, &sim, &conf,&files); printf (" Equilibrated maximum displacement / acceptance ratio: \n"); printeqstat(sim.trans,2.0,MAXT); printf (" Equilibrated maximum rotation / acceptance ratio: \n"); printeqstat(sim.rot,1.0,MAXT); printf (" Equilibrated maximum box length change / acceptance ratio: \n"); printf (" %.6le / %.6le\n", sim.edge.mx/2.0,RATIO(sim.edge)); printf (" Equilibrated maximum displacement of chain / acceptance ratio: \n"); printeqstat(sim.chainm,2.0,MAXMT); printf (" Equilibrated maximum rotation of chain / acceptance ratio: \n"); printeqstat(sim.chainr,1.0,MAXMT); printf ("\n"); printf ("Further equilibration of configuration: %ld sweeps\n", sim.nequil/2); fflush (stdout); outfile = fopen("config.eq", "w"); fprintf (outfile, "%15.8le %15.8le %15.8le\n", conf.box.x, conf.box.y, conf.box.z); draw (outfile, &conf, &topo); fclose (outfile); printf (" Equilibrated configuration written to config.eq\n"); printf (" Box dimensions: %.10lf, %.10lf, %.10lf\n\n", conf.box.x, conf.box.y, conf.box.z); } printf ("Production run: %ld sweeps\n\n", sim.nsweeps); fflush (stdout); simulate(sim.nsweeps, 0, sim.paramfrq, sim.report, intfce, &topo, &sim, &conf,&files); #ifdef MPI printf (" MPI replica changeT / changeP / acceptance ratio: \t %.6lf / %.6lf / %.6lf\n\n", sim.mpiexch.mx,sim.mpiexch.angle,RATIO(sim.mpiexch)); #endif outfile = fopen(files.configurationoutfile, "w"); #ifdef TESTING fprintf (outfile, "%15.6le %15.6le %15.6le\n", conf.box.x, conf.box.y, conf.box.z); #else fprintf (outfile, "%15.8le %15.8le %15.8le\n", conf.box.x, conf.box.y, conf.box.z); #endif draw (outfile, &conf, &topo); fclose (outfile); // For testing the pairlist //gen_pairlist(&topo, &sim, &conf); //FILE * fpairlist; //fpairlist = fopen("pairlist.dat", "w"); //print_pairlist(fpairlist, &sim, &topo); //fclose(fpairlist); //printf("sqmaxcut = %lf\n", topo.sqmaxcut); //// For testing the cluster algorithm //gen_clusterlist(&topo, &sim, &conf); //print_clusterlist(stdout, TRUE, &topo, &sim, &conf); //sort_clusterlist(&topo, &sim); //print_clusters(stdout, TRUE, &sim); //print_clusterstat(stdout, TRUE, &sim); if (memorydealloc(&conf, &topo, &sim)) exit(1); #ifdef MPI MPI_Finalize(); #endif printf ("\nDone\n\n"); return 0; } /*..............................................................................*/ /*.........................SIMULATION RUN.......................................*/ /*..............................................................................*/ void simulate(long nsweeps, long adjust, long paramfrq, long report, double (* intfce[MAXT][MAXT])(struct interacts *), struct topo * topo, struct sim * sim, struct conf * conf, struct filenames *files) { long i,j,wli; long next_adjust; /* Next sweep number for step size adjustment */ long next_calc; /* Next sweep number for order parameter calculation */ long next_dump; /* Next sweep number for reporting statistics */ long next_frame; /* Next sweep number for dumping a movie frame */ long step; /* Step number within a given sweep */ long sweep; /* Current sweep number */ //struct stat nem; /* Nematic order parameter */ //struct stat vol; /* Volume statistics */ //struct stat shapex, shapey, shapez; /* Box shape statistics */ //struct stat smec[MAXF]; /* Smectic order parameters (Fourier coeeficients) */ FILE *mf; /* Handle for movie file */ FILE *cl_stat, *cl, *cl_list; /* Handle for cluster statistics */ FILE *ef, *statf; /* Handle for energy file and statistical file*/ double edriftstart; /* Energy drift calculation - start */ double edriftchanges; /* Energy drift calculation - accumulate all changes through moves */ double edriftend; /* Energy drift calculation - end */ double pvdriftstart; /* PV drift calculation - start */ double pvdriftend; /* PV drift calculation - end */ double volume; /* volume of box*/ double moveprobab; /* random number selecting the move*/ /* function declarations */ //double nematic(long, struct particles *); double ran2(long *); //double smectic(long, struct particles *, long); double calc_energy(long target, double (* intfce[MAXT][MAXT])(struct interacts *), int mode, struct topo * topo, struct conf * conf, struct sim * sim,int chainn); void accumulate(struct stat *, double); void draw(FILE *, struct conf * conf, struct topo * topo); void optimizestep(struct disp *, double, double); void optimizerot(struct disp *, double, double); void partvecinit(struct topo * topo, struct sim * sim, struct conf * conf ); int wlinit(struct wls *, char filename[30]); int wlwrite(struct wls *, char filename[30]); int wlend(struct wls *); int mesh_init(struct meshs *, double, long, struct conf * conf, struct sim * sim); int mesh_end(struct meshs *); long z_order(struct wls *, struct conf * conf,int); long twopartdist(struct wls *, struct conf * conf,int); void mesh_print (struct meshs *); void masscenter(long, struct ia_param [MAXT][MAXT], struct conf * conf); void gen_pairlist(struct topo * topo, struct sim * sim, struct conf * conf); int write_cluster(FILE * cl_stat, FILE * cl, FILE * cl_list, BOOL decor, long sweep, struct sim * sim, struct topo * topo, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)); double particlemove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)); double chainmove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)); double switchtypemove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)); double pressuremove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)); double replicaexchangemove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *), long sweep); long radiushole_all(struct topo *topo, struct conf *conf, struct sim * sim,int, struct vector *); long radiushole_position(double, struct sim *,int); long contparticles_all(struct topo *topo, struct conf *conf, struct sim * sim,int wli); double alignment_order(struct conf * conf, struct topo * topo); /* Opening files for cluster statistics */ cl_stat = cl = cl_list = ef = statf = NULL; if(sim->write_cluster){ // Empty file cl_stat = fopen(files->clusterstatfile, "w"); fclose(cl_stat); cl_stat = fopen(files->clusterstatfile, "a"); // Empty file cl = fopen(files->clusterfile, "w"); fclose(cl); cl = fopen(files->clusterfile, "a"); } /* write energy*/ if (report < nsweeps){ // Empty file ef = fopen(files->energyfile, "w"); fclose(ef); ef = fopen(files->energyfile, "a"); fprintf (ef, "# sweep energy\n"); statf = fopen(files->statfile, "w"); fclose(statf); statf = fopen(files->statfile, "a"); fprintf (statf, "# sweep volume\n"); } /*=== Initialise counters etc. ===*/ // double pvolume; /* Volume of all particles*/ /* pvolume =0.0; for (i=0;i < topo->npart;i++) { if (conf->particle[i].type>=0 ) pvolume += topo->ia_params[conf->particle[i].type][conf->particle[i].type].volume; }*/ sim->shprob = sim->shave/(double)topo->npart; for (i=0;i<MAXT;i++){ sim->rot[i].acc = 0; sim->rot[i].rej = 0; sim->rot[i].oldrmsd = 0; sim->rot[i].oldmx = 0; sim->trans[i].acc = 0; sim->trans[i].rej = 0; sim->trans[i].oldrmsd = 0; sim->trans[i].oldmx = 0; } for (i=0;i<MAXMT;i++){ sim->chainm[i].acc = 0; sim->chainm[i].rej = 0; sim->chainm[i].oldrmsd = 0; sim->chainm[i].oldmx = 0; sim->chainr[i].acc = 0; sim->chainr[i].rej = 0; sim->chainr[i].oldrmsd = 0; sim->chainr[i].oldmx = 0; } //(*edge).acc = (*edge).rej = (*edge).oldrmsd = (*edge).oldmx = 0; sim->edge.acc = sim->edge.rej = sim->edge.oldrmsd = sim->edge.oldmx = 0; sim->mpiexch.acc = sim->mpiexch.rej = sim->mpiexch.oldrmsd = sim->mpiexch.oldmx = 0; /*Initialize some values at begining*/ partvecinit(topo,sim,conf); next_adjust = adjust; next_calc = paramfrq; next_dump = report; next_frame = sim->movie; //nem = vol = shapex = shapey = shapez = nullstat; //for (i=0; i<MAXF; i++) smec[i] = nullstat; if (sim->movie > 0) { mf = fopen(files->moviefile, "a"); } else { mf = NULL; } sim->wl.wl_meshsize = 0; sim->wl.radiushole = NULL; sim->wl.radiusholeold = NULL; sim->wl.radiusholemax = 0; sim->wl.partincontactold = 0; sim->wl.partincontact = 0; sim->wl.wlmdim = 0; sim->wl.wlmdim = 0; sim->wl.length[0]=0; sim->wl.length[1]=0; sim->wl.currorder[0]=0; sim->wl.currorder[1]=0; sim->wl.neworder[0]=0; sim->wl.neworder[1]=0; sim->wl.weights = NULL; sim->wl.hist = NULL; masscenter(topo->npart,topo->ia_params, conf); /* Initialization of wang-landaou method*/ if ( sim->wlm[0] >0 ) { if (wlinit(&sim->wl,files->wlinfile) != 0) return; sim->wl.wlmdim = 1 ; if ( sim->wlm[1] > 0 ) sim->wl.wlmdim = 2 ; for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 1: masscenter(topo->npart,topo->ia_params, conf); sim->wl.currorder[wli] = z_order(&sim->wl,conf,wli); break; case 2: sim->wl.wl_meshsize = (topo->ia_params[sim->wl.wlmtype][sim->wl.wlmtype].sigma) / 3.0; // TODO sim->wl.mesh.data = NULL; sim->wl.mesh.tmp = NULL; sim->wl.origmesh.data = NULL; sim->wl.origmesh.tmp = NULL; sim->wl.currorder[wli] = (long) (mesh_init(&sim->wl.mesh,sim->wl.wl_meshsize, topo->npart, conf, sim) - sim->wl.minorder[wli]); break; case 3: sim->wl.currorder[wli] = (long) floor( (conf->particle[0].dir.z - sim->wl.minorder[wli])/ sim->wl.dorder[wli] ); break; case 4: sim->wl.currorder[wli] = twopartdist(&sim->wl,conf,wli); break; case 5: masscenter(topo->npart,topo->ia_params, conf); sim->wl.radiusholemax = 0; sim->wl.radiushole = NULL; sim->wl.radiusholeold = NULL; sim->wl.currorder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->syscm)); break; case 6: sim->wl.radiusholemax = 0; sim->wl.radiushole = NULL; sim->wl.radiusholeold = NULL; sim->wl.currorder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); break; case 7: sim->wl.currorder[wli] = contparticles_all(topo,conf,sim,wli); break; default: sim->wl.currorder[wli] = 0; break; } if ( (sim->wl.currorder[wli] >= sim->wl.length[wli] ) || (sim->wl.currorder[wli] < 0) ) { printf("Error: starting Wang-Landau method with order parameter %f out of range(%f - %f)\n\n", sim->wl.dorder[wli]*sim->wl.currorder[wli] + \ sim->wl.minorder[wli], sim->wl.minorder[wli], sim->wl.minorder[wli]+sim->wl.dorder[wli]*sim->wl.length[wli] ); wlend(&sim->wl); return; } } if (sim->wl.alpha < WL_ALPHATOL/100) sim->wl.alpha = WL_ZERO; fflush (stdout); } /*do moves - START OF REAL MC*/ if(sim->pairlist_update){ gen_pairlist(topo, sim, conf); // Does that solve the problem? } /*do energy drift check - start calculation*/ volume = conf->box.x * conf->box.y * conf->box.z; edriftstart = calc_energy(0, intfce, 0, topo, conf, sim,0); pvdriftstart = sim->press * volume - (double)topo->npart * log(volume) / sim->temper; //printf("starting energy: %.15f \n",calc_energy(0, intfce, 0, topo, conf, sim,0)); //printf("press: %.15f\n",sim->press * volume - (double)topo->npart * log(volume) / sim->temper); edriftchanges = 0.0; for (sweep=1; sweep <= nsweeps; sweep++) { // Try replica exchange if((sim->nrepchange) && (sweep % sim->nrepchange == 0)){ edriftchanges += replicaexchangemove(topo,sim,conf,intfce,sweep); } // Generate the pairlist if((sim->pairlist_update) && (sweep % sim->pairlist_update == 0)){ gen_pairlist(topo, sim, conf); } //normal moves for (step=1; step <= topo->npart; step++) { moveprobab = ran2(&seed); if ( moveprobab < sim->shprob) { /* pressure moves*/ edriftchanges += pressuremove(topo,sim,conf,intfce); } else { if (moveprobab < sim->shprob + sim->chainprob) { /* single particle moves*/ edriftchanges += chainmove(topo,sim,conf,intfce); } else if (moveprobab < sim->shprob + sim->chainprob + sim->switchprob){ /*=== This is an attempt to switch a type ===*/ edriftchanges += switchtypemove(topo,sim,conf,intfce); } else { /* single particle moves*/ edriftchanges += particlemove(topo,sim,conf,intfce); } /* end of else next to chain moves */ } /* end of else next to volume moves */ } /**** End of step loop for this sweep ****/ /*=== Start of end-of-sweep housekeeping ===*/ /* Adjustment of maximum step sizes during equilibration */ if (sweep == next_adjust) { for (i = 0; i < MAXT ;i++) { if ((sim->trans[i].acc > 0)||(sim->trans[i].rej >0)) optimizestep (sim->trans + i, 1.5, 0.0); if ((sim->rot[i].acc > 0)||(sim->rot[i].rej >0)) optimizerot (sim->rot + i, 5.0, 0.01); } for (i = 0; i < MAXMT; i++) { if ((sim->chainm[i].acc > 0)||(sim->chainm[i].rej > 0)) optimizestep (sim->chainm + i, 1.5, 0.0); if ((sim->chainr[i].acc > 0)||(sim->chainr[i].rej > 0)) optimizerot (sim->chainr + i, 5.0, 0.01); } optimizestep (&(sim->edge), 1.0, 0.0); next_adjust += adjust; } if ( (sim->wlm[0] > 0) && (sim->wl.alpha > WL_ZERO) && !(sweep % 1000) ) { /* recalculate system CM to be sure there is no accumulation of errors by +- rejection moves*/ /* BUG - not used any longer: caused problems with PBC normal moves systemCM movement can be calculated from CM movements of individual particles present center of mass calculation use pbc and thus particles that moved across the box is in this calculation used in pripary box but in other moves in in in the particles position if ( (sim->wlm[0] == 1) || (sim->wlm[1] == 1) ) masscenter(topo->npart,topo->ia_params, conf); */ sim->wl.min = sim->wl.hist[0]; sim->wl.max = sim->wl.hist[0]; for (i=0;i < sim->wl.length[0];i++) { j=0; if ( sim->wl.hist[i+j*sim->wl.length[0]] > sim->wl.max ) sim->wl.max = sim->wl.hist[i+j*sim->wl.length[0]]; if ( sim->wl.hist[i+j*sim->wl.length[0]] < sim->wl.min ) sim->wl.min = sim->wl.hist[i+j*sim->wl.length[0]]; for (j=1;j < sim->wl.length[1];j++) { if ( sim->wl.hist[i+j*sim->wl.length[0]] > sim->wl.max ) sim->wl.max = sim->wl.hist[i+j*sim->wl.length[0]]; if ( sim->wl.hist[i+j*sim->wl.length[0]] < sim->wl.min ) sim->wl.min = sim->wl.hist[i+j*sim->wl.length[0]]; } } if ( sim->wl.min > WL_MINHIST ) { if ( sim->temper * log(sim->wl.max/sim->wl.min) < WL_GERR ) { /*DEBUG for (i=1;i<wl.length;i++) { printf (" %15.8le %15ld %15.8f\n",sim->wl.weights[i],sim->wl.hist[i],particle[0].pos.z); fflush(stdout); } */ if ( sim->wl.alpha < WL_ALPHATOL) break; sim->wl.alpha/=2; printf("%f \n", sim->wl.alpha); fflush (stdout); sim->wl.wmin = sim->wl.weights[0]; for (i=0;i < sim->wl.length[0];i++) { j=0; sim->wl.hist[i+j*sim->wl.length[0]] = 0; sim->wl.weights[i+j*sim->wl.length[0]] -= sim->wl.wmin; for (j=1;j < sim->wl.length[1];j++) { sim->wl.hist[i+j*sim->wl.length[0]] = 0; sim->wl.weights[i+j*sim->wl.length[0]] -= sim->wl.wmin; } } } } } if (!(sweep % 10000)) { /*reinitialize pach vectors to avoid cummulation of errors*/ partvecinit(topo,sim,conf); } /* Sampling of statistics */ if (sweep == next_calc) { /*s2 = nematic(npart, particle); accumulate (&nem, s2); for (i=0; i<terms; i++) { ci = smectic(npart, particle, i+1); accumulate (&smec[i], ci); } accumulate (&shapex, (*box).x); accumulate (&shapey, (*box).y); accumulate (&shapez, (*box).z); volume = (*box).x * (*box).y * (*box).z; accumulate (&vol, volume); next_calc += paramfrq; */ } /* Writing of statistics */ if (sweep == next_dump) { /*printf ("Statistics after %ld sweeps:\n", sweep); printf (" Mean and RMS fluctuation of S2: %13.8lf %13.8lf\n", nem.mean, nem.rms); for (i=0; i<terms; i++) { printf (" Mean & fluc. Fourier coeff. %3ld: %13.8lf %13.8lf\n", i+1, smec[i].mean, smec[i].rms); } printf (" Mean & fluc box dimensions: x %13.8lf %13.8lf\n", shapex.mean, shapex.rms); printf (" y %13.8lf %13.8lf\n", shapey.mean, shapey.rms); printf (" z %13.8lf %13.8lf\n", shapez.mean, shapez.rms); printf (" Mean & fluctuation volume: %13.8lf %13.8lf\n", vol.mean, vol.rms); printf (" Mean & fluc. volume over volume of particles: %13.8lf %13.8lf\n", vol.mean/pvolume, vol.rms/pvolume); printf ("\n"); fflush (stdout); */ fprintf (statf, " %ld; %.10lf\n", sweep, conf->box.x * conf->box.y * conf->box.z); fprintf (ef, " %ld; %.10lf %f \n", sweep, calc_energy(0, intfce, 0, topo, conf, sim,0), alignment_order(conf,topo)); if (sim->wlm[0] > 0) { wlwrite(&sim->wl,files->wloutfile); } next_dump += report; } /* Writing of movie frame */ if (sweep == next_frame) { fprintf (mf, "%ld\n", topo->npart); fprintf (mf, "sweep %ld; box %.10lf %.10lf %.10lf\n", sweep, conf->box.x, conf->box.y, conf->box.z); draw (mf, conf, topo); fflush (mf); next_frame += sim->movie; } /* Writing out cluster statistics */ if(sim->write_cluster && (sweep % sim->write_cluster == 0)){ write_cluster(cl_stat, cl, cl_list, FALSE, sweep, sim, topo, conf, intfce); } /*=== End of housekeeping ===*/ } /**** End of sweeps loop ****/ /*do energy drift check - at the end calculation*/ volume = conf->box.x * conf->box.y * conf->box.z; edriftend = calc_energy(0, intfce, 0, topo, conf, sim,0); pvdriftend = sim->press * volume - (double)topo->npart * log(volume) / sim->temper; printf("Energy drift: %.15lf \n",edriftend - edriftstart - edriftchanges +pvdriftend -pvdriftstart); printf("Starting energy+pv: %.8lf \n",edriftstart+pvdriftstart); printf("Starting energy: %.8lf \n",edriftstart); fflush(stdout); /* End wang-landau*/ if (sim->wlm[0] > 0) { sim->wl.min = sim->wl.hist[0]; for (i=0;i < sim->wl.length[0];i++) { j=0; if ( sim->wl.hist[i+j*sim->wl.length[0]] < sim->wl.min ) sim->wl.min = sim->wl.hist[i+j*sim->wl.length[0]]; for (j=1;j < sim->wl.length[1];j++) { if ( sim->wl.hist[i+j*sim->wl.length[0]] < sim->wl.min ) sim->wl.min = sim->wl.hist[i+j*sim->wl.length[0]]; } } sim->wl.wmin = sim->wl.weights[0]; for (i=0;i < sim->wl.length[0];i++) { j=0; sim->wl.weights[i+j*sim->wl.length[0]] -= sim->wl.wmin; for (j=1;j < sim->wl.length[1];j++) { sim->wl.weights[i+j*sim->wl.length[0]] -= sim->wl.wmin; } } wlwrite(&sim->wl,files->wloutfile); wlend(&sim->wl); if ( (sim->wlm[0] == 2)||(sim->wlm[1] == 2) ) { mesh_end(&sim->wl.mesh); mesh_end(&sim->wl.origmesh); } if ( (sim->wlm[0] == 5)||(sim->wlm[1] == 5)||(sim->wlm[0] == 6)||(sim->wlm[1] == 6) ) { if ( sim->wl.radiushole != NULL ) free(sim->wl.radiushole); if ( sim->wl.radiusholeold != NULL ) free(sim->wl.radiusholeold); } } /*end movie*/ if (sim->movie > 0) fclose (mf); /*end cluster*/ if(sim->write_cluster){ fclose(cl_stat); fclose(cl); } if (report < nsweeps) { fclose(ef); fclose(statf); } } /*..................................MOVES.........................................*/ /*................................................................................*/ /*..............................PARTICLE MOVES....................................*/ double particlemove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)) { double edriftchanges =0.0; long target; double ran2(long *); double partdisplace(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *),long target); double partrotate(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *),long target); /*=== This is a particle move step ===*/ target = ran2(&seed) * topo->npart; if ( !( ((sim->wlm[0] == 3) || (sim->wlm[1] == 3) ) && (target == 0) ) && \ ((ran2(&seed) < 0.5) || (topo->ia_params[conf->particle[target].type][conf->particle[target].type].geotype[0] >= SP)) ) { /* no rotation for spheres */ //target = 1; //printf ("displacement\n\n"); edriftchanges = partdisplace(topo,sim,conf,intfce,target); } else { /*=== Rotation step ===*/ edriftchanges = partrotate(topo,sim,conf,intfce,target); } /*=== End particle move step ===*/ return edriftchanges; } /*................................................................................*/ double partdisplace(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *),long target) { double edriftchanges,energy,enermove,wlener; struct vector orig, dr, origsyscm; int reject=0,wli; double radiusholemax_orig=0; double calc_energy(long target, double (* intfce[MAXT][MAXT])(struct interacts *), int mode, struct topo * topo, struct conf * conf, struct sim * sim,int chainn); int movetry(double, double, double); void wlreject(struct sim *, long); void wlaccept(int, struct wls *); long meshorder_moveone(struct vector, struct vector, struct meshs *, long, long, \ struct conf * conf, struct sim * sim, int wli); int mesh_cpy(struct meshs *, struct meshs *); //void mesh_print (struct meshs *); long z_order(struct wls *, struct conf * conf, int wli); long twopartdist(struct wls *, struct conf *conf, int wli); struct vector ranvec(void); int longarray_cpy (long **, long **, long, long); long radiusholeorder_moveone(struct vector *oldpos, struct conf *conf, struct sim * sim, long target, int wli,struct vector *); long radiushole_all(struct topo *topo, struct conf *conf, struct sim * sim,int, struct vector *); long contparticles_moveone(struct vector *oldpos, struct conf *conf, struct sim * sim, long target,int wli); long contparticles_all(struct topo *topo, struct conf *conf, struct sim * sim,int wli); /*=== Displacement step ===*/ edriftchanges =0.0; origsyscm.x = 0; origsyscm.y = 0; origsyscm.z = 0; energy = calc_energy(target, intfce, 1, topo, conf, sim,0); orig = conf->particle[target].pos; dr = ranvec(); //ran = sqrt(ran2(&seed)); dr.x *= sim->trans[conf->particle[target].type].mx/conf->box.x; dr.y *= sim->trans[conf->particle[target].type].mx/conf->box.y; dr.z *= sim->trans[conf->particle[target].type].mx/conf->box.z; if ( ((sim->wlm[0] == 3)||(sim->wlm[1] == 3)) && (target == 0) ) { dr.z = 0; dr.y = 0; dr.x = 0; } conf->particle[target].pos.x += dr.x; conf->particle[target].pos.y += dr.y; conf->particle[target].pos.z += dr.z; //} while (conf->particle[target].pos.x < 0.25 || conf->particle[target].pos.x > 0.50); reject = 0; wlener = 0.0; if (sim->wlm[0] > 0) { /* get new neworder for wang-landau */ for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 1: origsyscm = conf->syscm; conf->syscm.x += dr.x * topo->ia_params[conf->particle[target].type][conf->particle[target].type].volume / conf->sysvolume; conf->syscm.y += dr.y * topo->ia_params[conf->particle[target].type][conf->particle[target].type].volume / conf->sysvolume; conf->syscm.z += dr.z * topo->ia_params[conf->particle[target].type][conf->particle[target].type].volume / conf->sysvolume; sim->wl.neworder[wli] = z_order(&sim->wl, conf,wli); break; case 2: mesh_cpy(&sim->wl.origmesh,&sim->wl.mesh); sim->wl.neworder[wli] = meshorder_moveone(orig, conf->particle[target].pos, &sim->wl.mesh, topo->npart, target, conf, sim,wli); break; case 4: sim->wl.neworder[wli] = twopartdist(&sim->wl,conf,wli); break; case 5: radiusholemax_orig = sim->wl.radiusholemax; origsyscm = conf->syscm; conf->syscm.x += dr.x * topo->ia_params[conf->particle[target].type][conf->particle[target].type].volume / conf->sysvolume; conf->syscm.y += dr.y * topo->ia_params[conf->particle[target].type][conf->particle[target].type].volume / conf->sysvolume; conf->syscm.z += dr.z * topo->ia_params[conf->particle[target].type][conf->particle[target].type].volume / conf->sysvolume; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->syscm)); break; case 6: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); if ( target == 0 ) sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); else sim->wl.neworder[wli] = radiusholeorder_moveone(&orig, conf, sim,target,wli,&(conf->particle[0].pos)); break; case 7: sim->wl.partincontactold = sim->wl.partincontact; if ( target == 0 ) sim->wl.neworder[wli] = contparticles_all(topo,conf,sim,wli); else sim->wl.neworder[wli] = contparticles_moveone(&orig,conf,sim,target,wli); break; default: sim->wl.neworder[wli] = sim->wl.currorder[wli]; break; } if ( (sim->wl.neworder[wli] < 0) || (sim->wl.neworder[wli] >= sim->wl.length[wli]) ) reject = 1; } if (!reject) { wlener += sim->wl.weights[sim->wl.neworder[0]+sim->wl.neworder[1]*sim->wl.length[0]] - sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]; energy += wlener; } } if (!reject) { /* wang-landaou ok, try move - calcualte energy */ enermove = calc_energy(target, intfce, 1, topo, conf, sim,0); } if ( reject || movetry(energy, enermove, sim->temper) ) { /* probability acceptance */ conf->particle[target].pos = orig; sim->trans[conf->particle[target].type].rej++; if ( (sim->wlm[0] == 1) || (sim->wlm[0] == 5) || (sim->wlm[1] == 1) || (sim->wlm[1] == 5) ) conf->syscm = origsyscm; wlreject(sim,radiusholemax_orig); } else { /* move was accepted */ sim->trans[conf->particle[target].type].acc++; wlaccept(sim->wlm[0],&sim->wl); edriftchanges = enermove - energy + wlener; //printf("%lf\t%lf\n", conf->particle[0].pos.z * conf->box.z , enermove); //printf("%.12f\t%.12f\t%.12f\n", energy , enermove,edriftchanges); } return edriftchanges; } /*................................................................................*/ double partrotate(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *),long target) { double edriftchanges,energy,enermove,wlener; struct particles origpart; int reject=0,wli; double calc_energy(long target, double (* intfce[MAXT][MAXT])(struct interacts *), int mode, struct topo * topo, struct conf * conf, struct sim * sim,int chainn); int movetry(double, double, double); void wlreject(struct sim *,long); void wlaccept(int, struct wls *); void normalise(struct vector *); void ortogonalise(struct vector *,struct vector); void psc_rotate(struct particles *,double,int); /*=== Rotation step ===*/ //printf ("rotation %ld npart %ld\n\n",target,npart); energy = calc_energy(target, intfce, 1, topo, conf, sim,0); origpart = conf->particle[target]; psc_rotate(&conf->particle[target],sim->rot[conf->particle[target].type].angle, topo->ia_params[conf->particle[target].type][conf->particle[target].type].geotype[0]); /*should be normalised and ortogonal but we do for safety*/ normalise (&conf->particle[target].dir); ortogonalise(&conf->particle[target].patchdir[0],conf->particle[target].dir); reject = 0; edriftchanges =0.0; wlener = 0.0; if (sim->wlm[0] > 0) { /* get new neworder for wang-landau */ for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 3: if (target == 0) sim->wl.neworder[wli] = (long) floor( (conf->particle[0].dir.z - sim->wl.minorder[wli])/ sim->wl.dorder[wli] ); else sim->wl.neworder[wli] = sim->wl.currorder[wli]; /* only rotation change direction */ break; default: sim->wl.neworder[wli] = sim->wl.currorder[wli]; break; } if ( (sim->wl.neworder[wli] < 0) || (sim->wl.neworder[wli] >= sim->wl.length[wli]) ) reject = 1; } if (!reject) { wlener += sim->wl.weights[sim->wl.neworder[0]+sim->wl.neworder[1]*sim->wl.length[0]] - sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]; energy += wlener; } } if (!reject) { /* wang-landaou ok, try move - calcualte energy */ enermove = calc_energy(target, intfce, 1, topo, conf, sim,0); } if ( reject || movetry(energy,enermove,sim->temper) ) { /* probability acceptance */ conf->particle[target] = origpart; sim->rot[conf->particle[target].type].rej++; wlreject(sim,sim->wl.radiusholemax); } else { /* move was accepted */ // DEBUG //fprintf(fenergy, "%lf\t%lf\n", conf->particle[1].pos.x * conf->box.x , enermove); sim->rot[conf->particle[target].type].acc++; wlaccept(sim->wlm[0],&sim->wl); edriftchanges = enermove - energy + wlener; //printf("%lf\t%lf\n", conf->particle[0].patchdir[0].z, enermove); } return edriftchanges; } /*..................... This is an attempt to switch a type.................................*/ double switchtypemove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *) ) { double edriftchanges,energy,enermove,wlener; int reject=0,wli; long target; double radiusholemax_orig=0; double ran2(long *); double calc_energy(long target, double (* intfce[MAXT][MAXT])(struct interacts *), int mode, struct topo * topo, struct conf * conf, struct sim * sim,int chainn); int movetry(double, double, double); void wlreject(struct sim *,long); void wlaccept(int, struct wls *); void int_partvec(long, struct ia_param *, struct conf *); int mesh_init(struct meshs *, double, long, struct conf * conf, struct sim * sim); int mesh_cpy(struct meshs *, struct meshs *); long z_order(struct wls *, struct conf * conf,int); long twopartdist(struct wls *, struct conf *conf,int); long radiushole_all(struct topo *topo, struct conf *conf, struct sim * sim,int, struct vector *); int longarray_cpy (long **target, long **source,long,long); long contparticles_all(struct topo *topo, struct conf *conf, struct sim * sim,int wli); /*=== This is an attempt to switch a type ===*/ edriftchanges =0.0; wlener = 0.0; target = ran2(&seed) * topo->n_switch_part; target = topo->switchlist[target]; DEBUG_SIM("Switching the particle type"); DEBUG_SIM("PARTICLE: %ld", target); energy = calc_energy(target, intfce, 1, topo, conf, sim,0); // Start switching the type int switched = conf->particle[target].switched; int pmone = PMONE(switched); DEBUG_SIM("switched = %d", switched); DEBUG_SIM("pmone = %d", pmone); int tmp_type = conf->particle[target].type; conf->particle[target].type = conf->particle[target].switchtype; conf->particle[target].switchtype = tmp_type; conf->particle[target].switched += pmone; int_partvec(target,&(topo->ia_params[conf->particle[target].type][conf->particle[target].type]),conf); DEBUG_SIM("Particle %ld is %d switched", target, switched); //DEBUG #ifdef DEBUGGING_SIM if ((abs(pmone) != 1) || (conf->particle[target].type == conf->particle[target].switchtype)){ fprintf(stderr, "ERROR: Something went wrong, when switching the type of particle %ld\n", target); exit(1); } #endif if (sim->wlm[0] > 0) { /* get new neworder for wang-landau */ for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { /*case 1: sim->wl.neworder = z_order(&sim->wl, conf,wli); break;*/ case 2: mesh_cpy(&sim->wl.origmesh,&sim->wl.mesh); sim->wl.neworder[wli] = (long) (mesh_init(&sim->wl.mesh,sim->wl.wl_meshsize,topo->npart, conf, sim) - sim->wl.minorder[wli]); break; /*case 4: sim->wl.neworder = twopartdist(&sim->wl,conf,wli); break;*/ case 5: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->syscm)); break; case 6: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); break; case 7: sim->wl.partincontactold = sim->wl.partincontact; sim->wl.neworder[wli] = contparticles_all(topo,conf,sim,wli); break; default: sim->wl.neworder[wli] = sim->wl.currorder[wli]; break; } if ( (sim->wl.neworder[wli] < 0) || (sim->wl.neworder[wli] >= sim->wl.length[wli]) ) reject = 1; } if (!reject) { wlener += sim->wl.weights[sim->wl.neworder[0]+sim->wl.neworder[1]*sim->wl.length[0]] - sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]; energy += wlener; } } if (!reject) { enermove = conf->particle[target].delta_mu * pmone; // DEBUG //double dmu = enermove; //particle[target].switched += pmone; enermove += calc_energy( target, intfce, 1, topo, conf, sim,0); //printf("energy: %lf \t %lf\t%lf\n",particle[target].delta_mu, dmu, enermove); } // If not accepted: switch back if ( reject || movetry(energy,enermove,sim->temper) ) { /* probability acceptance */ DEBUG_SIM("Did NOT switch it\n"); conf->particle[target].switchtype = conf->particle[target].type; conf->particle[target].type = tmp_type; conf->particle[target].switched -= pmone; int_partvec(target,&(topo->ia_params[conf->particle[target].type][conf->particle[target].type]),conf); wlreject(sim,radiusholemax_orig); } else { /* move was accepted */ wlaccept(sim->wlm[0],&sim->wl); edriftchanges = enermove - energy + wlener; } return edriftchanges; } /*.................................CHAIN MOVES....................................*/ /*................................................................................*/ double chainmove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)) { double edriftchanges =0.0; long target; double ran2(long *); double chaindisplace(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *), long target); double chainrotate(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *), long target); /*=== This is a chain move step ===*/ target = ran2(&seed) * topo->chainnum; if (ran2(&seed) < 0.5) { /*=== Displacement step of cluster/chain ===*/ edriftchanges = chaindisplace(topo,sim,conf,intfce,target); } else { /*=== Rotation step of cluster/chain ===*/ edriftchanges = chainrotate(topo,sim,conf,intfce,target); } /* ==== END OF CHAIN MOVES ===== */ return edriftchanges; } /*................................................................................*/ double chaindisplace(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *), long target) { double edriftchanges,energy,enermove,wlener; struct vector dr, origsyscm; int reject=0,wli; struct vector cluscm; long current,i; struct particles chorig[MAXCHL]; double radiusholemax_orig=0; double calc_energy(long target, double (* intfce[MAXT][MAXT])(struct interacts *), int mode, struct topo * topo, struct conf * conf, struct sim * sim,int chainn); int movetry(double, double, double); void wlreject(struct sim *,long); void wlaccept(int, struct wls *); long meshorder_movechain(long [MAXN], struct meshs *, long, struct conf * conf, \ struct sim * sim, struct particles chorig[MAXCHL],int); int mesh_cpy(struct meshs *, struct meshs *); //void mesh_print (struct meshs *); long z_order(struct wls *, struct conf * conf,int); long twopartdist(struct wls *, struct conf *conf,int); struct vector ranvec(void); int longarray_cpy (long **target, long **source,long,long); long radiusholeorder_movechain(long chain[MAXN], struct conf * conf, \ struct sim * sim,struct particles chorig[MAXCHL],int,struct vector *); long radiushole_all(struct topo *topo, struct conf *conf, struct sim * sim,int, struct vector *); long contparticles_movechain(long chain[MAXN], struct conf * conf, struct sim * sim,struct particles chorig[MAXCHL],int wli); long contparticles_all(struct topo *topo, struct conf *conf, struct sim * sim,int wli); /*=== Displacement step of cluster/chain ===*/ //printf ("move chain\n\n"); energy =0.0; wlener = 0.0; edriftchanges=0.0; i=0; current = topo->chainlist[target][0]; cluscm.x = 0; cluscm.y = 0; cluscm.z = 0; origsyscm.x = 0; origsyscm.y = 0; origsyscm.z = 0; while (current >=0 ) { /* store old configuration calculate energy*/ chorig[i].pos = conf->particle[current].pos; energy += calc_energy(current, intfce, 2, topo, conf, sim, target); i++; current = topo->chainlist[target][i]; } dr = ranvec(); dr.x *= sim->chainm[conf->particle[target].chaint].mx/conf->box.x; dr.y *= sim->chainm[conf->particle[target].chaint].mx/conf->box.y; dr.z *= sim->chainm[conf->particle[target].chaint].mx/conf->box.z; i=0; if ( ((sim->wlm[0] == 3)||(sim->wlm[1] == 3)) && (target == 0) ) { dr.z = 0; dr.y = 0; dr.x = 0; } current = topo->chainlist[target][0]; while (current >=0 ) { /* move chaine to new position */ if ( (sim->wlm[0] == 1) || (sim->wlm[0] == 5) || (sim->wlm[1] == 1) || (sim->wlm[1] == 5) ) { /* calculate move of center of mass */ cluscm.x += dr.x*topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; cluscm.y += dr.y*topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; cluscm.z += dr.z*topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; } conf->particle[current].pos.x += dr.x; conf->particle[current].pos.y += dr.y; conf->particle[current].pos.z += dr.z; i++; current = topo->chainlist[target][i]; } enermove = 0.0; reject = 0; if (sim->wlm[0] > 0) { /* get new neworder for wang-landau */ for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 1: origsyscm = conf->syscm; conf->syscm.x += cluscm.x / conf->sysvolume; conf->syscm.y += cluscm.y / conf->sysvolume; conf->syscm.z += cluscm.z / conf->sysvolume; sim->wl.neworder[wli] = z_order(&sim->wl, conf,wli); break; case 2: mesh_cpy(&sim->wl.origmesh,&sim->wl.mesh); sim->wl.neworder[wli] = meshorder_movechain(topo->chainlist[target], &sim->wl.mesh, topo->npart, conf, sim, chorig,wli); break; case 4: sim->wl.neworder[wli] = twopartdist(&sim->wl,conf,wli); break; case 5: radiusholemax_orig = sim->wl.radiusholemax; origsyscm = conf->syscm; conf->syscm.x += cluscm.x / conf->sysvolume; conf->syscm.y += cluscm.y / conf->sysvolume; conf->syscm.z += cluscm.z / conf->sysvolume; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->syscm)); break; case 6: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); if ( target == 0 ) sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); else sim->wl.neworder[wli] = radiusholeorder_movechain(topo->chainlist[target], conf, sim, chorig,wli,&(conf->particle[0].pos)); break; case 7: sim->wl.partincontactold = sim->wl.partincontact; if ( target == 0 ) sim->wl.neworder[wli] = contparticles_all(topo,conf,sim,wli); else sim->wl.neworder[wli] = contparticles_movechain(topo->chainlist[target],conf,sim,chorig,wli); break; default: sim->wl.neworder[wli] = sim->wl.currorder[wli]; break; } if ( (sim->wl.neworder[wli] < 0) || (sim->wl.neworder[wli] >= sim->wl.length[wli]) ) reject = 1; } if (!reject) { wlener += sim->wl.weights[sim->wl.neworder[0]+sim->wl.neworder[1]*sim->wl.length[0]] - sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]; energy += wlener; } } if (!reject) { /* wang-landaou ok, try move - calcualte energy */ i=0; current = topo->chainlist[target][0]; while (current >=0 ) { enermove += calc_energy(current, intfce, 2, topo, conf, sim,target); i++; current = topo->chainlist[target][i]; } } if ( reject || movetry(energy, enermove, sim->temper) ) { /* probability acceptance */ i=0; current = topo->chainlist[target][0]; while (current >=0 ) { conf->particle[current].pos = chorig[i].pos; i++; current = topo->chainlist[target][i]; } sim->chainm[conf->particle[target].chaint].rej++; if ( (sim->wlm[0] == 1) || (sim->wlm[0] == 5) || (sim->wlm[1] == 1) || (sim->wlm[1] == 5) ) conf->syscm = origsyscm; wlreject(sim,radiusholemax_orig); } else { /* move was accepted */ sim->chainm[conf->particle[target].chaint].acc++; wlaccept(sim->wlm[0],&sim->wl); edriftchanges = enermove - energy + wlener; } return edriftchanges; } /*................................................................................*/ double chainrotate(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *), long target) { double edriftchanges,energy,enermove,wlener; int reject=0,wli; struct vector cluscm; double chainvolume; long current, i; struct particles chorig[MAXCHL]; double radiusholemax_orig=0; double calc_energy(long target, double (* intfce[MAXT][MAXT])(struct interacts *), int mode, struct topo * topo, struct conf * conf, struct sim * sim,int chainn); int movetry(double, double, double); void wlreject(struct sim *,long); void wlaccept(int, struct wls *); long meshorder_movechain(long [MAXN], struct meshs *, long, struct conf * conf, \ struct sim * sim, struct particles chorig[MAXCHL],int); int mesh_cpy(struct meshs *, struct meshs *); void cluster_rotate(long, struct vector, double, struct topo * topo, struct conf * conf); long z_order(struct wls *, struct conf * conf,int); long twopartdist(struct wls *, struct conf *conf,int); int longarray_cpy (long **target, long **source,long,long); long radiusholeorder_movechain(long chain[MAXN], struct conf * conf, struct sim * sim,\ struct particles chorig[MAXCHL],int,struct vector *); long radiushole_all(struct topo *topo, struct conf *conf, struct sim * sim,int, struct vector *); long contparticles_movechain(long chain[MAXN], struct conf * conf, struct sim * sim,struct particles chorig[MAXCHL],int wli); long contparticles_all(struct topo *topo, struct conf *conf, struct sim * sim,int wli); /*=== Rotation step of cluster/chain ===*/ //printf ("rotation of chain\n\n"); energy=0.0; /* set values to zero*/ edriftchanges=0.0; wlener = 0.0; current = topo->chainlist[target][0]; cluscm.x = conf->particle[current].pos.x*topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; cluscm.y = conf->particle[current].pos.y*topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; cluscm.z = conf->particle[current].pos.z*topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; chorig[0] = conf->particle[current]; chainvolume = topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; energy += calc_energy(current, intfce, 2, topo, conf, sim,target); i=1; current = topo->chainlist[target][i]; while (current >=0 ) { /* store old configuration calculate energy*/ chorig[i] = conf->particle[current]; /*We have chains whole! don't have to do PBC*/ /*r_cm.x = conf->particle[current].pos.x - conf->particle[first].pos.x; r_cm.y = conf->particle[current].pos.y - conf->particle[first].pos.y; r_cm.z = conf->particle[current].pos.z - conf->particle[first].pos.z; if ( r_cm.x < 0 ) r_cm.x -= (double)( (long)(r_cm.x-0.5) ); else r_cm.x -= (double)( (long)(r_cm.x+0.5) ); if ( r_cm.y < 0 ) r_cm.y -= (double)( (long)(r_cm.y-0.5) ); else r_cm.y -= (double)( (long)(r_cm.y+0.5) ); if ( r_cm.z < 0 ) r_cm.z -= (double)( (long)(r_cm.z-0.5) ); else r_cm.z -= (double)( (long)(r_cm.z+0.5) ); */ cluscm.x += conf->particle[current].pos.x*topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; cluscm.y += conf->particle[current].pos.y*topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; cluscm.z += conf->particle[current].pos.z*topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; chainvolume += topo->ia_params[conf->particle[current].type][conf->particle[current].type].volume; energy += calc_energy(current, intfce, 2, topo, conf, sim,target); i++; current = topo->chainlist[target][i]; } cluscm.x = cluscm.x/chainvolume; cluscm.y = cluscm.y/chainvolume; cluscm.z = cluscm.z/chainvolume; /*do actual rotations around geometrical center*/ cluster_rotate(target, cluscm, sim->chainr[conf->particle[target].chaint].angle, topo, conf); enermove=0.0; reject = 0; if (sim->wlm[0] > 0) { /* get new neworder for wang-landau */ for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 1: if (target == 0) sim->wl.neworder[wli] = z_order(&sim->wl, conf,wli); else sim->wl.neworder[wli] = sim->wl.currorder[wli]; /* if we rotated cluster it is around its CM so no change*/ break; case 2: mesh_cpy(&sim->wl.origmesh,&sim->wl.mesh); sim->wl.neworder[wli] = meshorder_movechain(topo->chainlist[target], &sim->wl.mesh, topo->npart, conf, sim, chorig,wli); break; case 3: if (target == 0) sim->wl.neworder[wli] = (long) floor( (conf->particle[0].dir.z - sim->wl.minorder[wli])/ sim->wl.dorder[wli] ); else sim->wl.neworder[wli] = sim->wl.currorder[wli]; /* only rotation change direction */ break; case 4: sim->wl.neworder[wli] = twopartdist(&sim->wl,conf,wli); break; case 5: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->syscm)); break; case 6: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); if ( target == 0 ) sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); else sim->wl.neworder[wli] = radiusholeorder_movechain(topo->chainlist[target], conf, sim, chorig,wli,&(conf->particle[0].pos)); break; case 7: sim->wl.partincontactold = sim->wl.partincontact; if ( target == 0 ) sim->wl.neworder[wli] = contparticles_all(topo,conf,sim,wli); else sim->wl.neworder[wli] = contparticles_movechain(topo->chainlist[target],conf,sim,chorig,wli); break; default: sim->wl.neworder[wli] = sim->wl.currorder[wli]; break; } if ( (sim->wl.neworder[wli] < 0) || (sim->wl.neworder[wli] >= sim->wl.length[wli]) ) reject = 1; } if (!reject) { wlener += sim->wl.weights[sim->wl.neworder[0]+sim->wl.neworder[1]*sim->wl.length[0]] - sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]; energy += wlener; } } if (!reject) { /* wang-landaou ok, try move - calcualte energy */ i=0; current = topo->chainlist[target][0]; while (current >=0 ) { enermove += calc_energy(current, intfce, 2, topo, conf, sim,target); i++; current = topo->chainlist[target][i]; } } if ( reject || movetry(energy, enermove, sim->temper) ) { /* probability acceptance */ i=0; current = topo->chainlist[target][0]; while (current >=0 ) { conf->particle[current] = chorig[i]; i++; current = topo->chainlist[target][i]; } sim->chainr[conf->particle[target].chaint].rej++; wlreject(sim,radiusholemax_orig); } else { /* move was accepted */ sim->chainr[conf->particle[target].chaint].acc++; wlaccept(sim->wlm[0],&sim->wl); edriftchanges = enermove - energy + wlener; } return edriftchanges; } /*..............................PRESSURE MOVES....................................*/ /*................................................................................*/ double pressuremove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)) { double edriftchanges,energy,enermove,wlener; int reject=0,wli; double old_side; /* Box length before attempted change */ double *side; /* Box dimension to try changing */ double psch; /* Size of a box change during pressure */ double pvol; /* Size of a volume during pressure */ double pvoln; /* Size of a new volume during pressure */ double rsave; /* Saved random number */ double area; double radiusholemax_orig=0; double ran2(long *); double calc_energy(long target, double (* intfce[MAXT][MAXT])(struct interacts *), int mode, struct topo * topo, struct conf * conf, struct sim * sim,int chainn); int movetry(double, double, double); void wlreject(struct sim *,long); void wlaccept(int, struct wls *); int mesh_init(struct meshs *, double, long, struct conf * conf, struct sim * sim); int mesh_cpy(struct meshs *, struct meshs *); long z_order(struct wls *, struct conf * conf,int); long twopartdist(struct wls *, struct conf *conf,int); long radiushole_all(struct topo *topo, struct conf *conf, struct sim * sim,int, struct vector *); int longarray_cpy (long **target, long **source,long,long); long contparticles_all(struct topo *topo, struct conf *conf, struct sim * sim,int wli); /*=== This is a volume change step ===*/ /*calculate energy*/ edriftchanges=0.0; wlener = 0.0; energy = calc_energy(0, intfce, 0, topo, conf, sim,0); /* Choose an edge */ switch (sim->ptype) { case 0: /* Anisotropic pressure coupling */ rsave = ran2(&seed); if (rsave < 1.0/3.0) { side = &(conf->box.x); area = conf->box.y * conf->box.z; } else if (rsave < 2.0/3.0) { side = &(conf->box.y); area = conf->box.x * conf->box.z; } else { side = &(conf->box.z); area = conf->box.x * conf->box.y; } old_side = *side; *side += sim->edge.mx * (ran2(&seed) - 0.5); reject = 0; if (sim->wlm[0] > 0) { /* get new neworder for wang-landau */ for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 1: sim->wl.neworder[wli] = z_order(&sim->wl, conf,wli); break; case 2: mesh_cpy(&sim->wl.origmesh,&sim->wl.mesh); sim->wl.neworder[wli] = (long) (mesh_init(&sim->wl.mesh,sim->wl.wl_meshsize, topo->npart, conf, sim) - sim->wl.minorder[wli]); break; case 4: sim->wl.neworder[wli] = twopartdist(&sim->wl,conf,wli); break; case 5: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->syscm)); break; case 6: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); break; case 7: sim->wl.partincontactold = sim->wl.partincontact; sim->wl.neworder[wli] = contparticles_all(topo,conf,sim,wli); break; default: sim->wl.neworder[wli] = sim->wl.currorder[wli]; break; } if ( (sim->wl.neworder[wli] < 0) || (sim->wl.neworder[wli] >= sim->wl.length[wli]) ) reject = 1; } if (!reject) { wlener = sim->wl.weights[sim->wl.neworder[0]+sim->wl.neworder[1]*sim->wl.length[0]] - sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]; energy += wlener; } } if (!reject) { /* wang-landaou ok, try move - calculate energy */ enermove = sim->press * area * (*side - old_side) - (double)topo->npart * log(*side/old_side) / sim->temper; enermove += calc_energy(0, intfce, 0, topo, conf, sim,0); } if ( reject || *side <= 0.0 || ( movetry(energy,enermove,sim->temper) ) ) { /* probability acceptance */ *side = old_side; sim->edge.rej++; wlreject(sim,radiusholemax_orig); } else { /* move was accepted */ sim->edge.acc++; wlaccept(sim->wlm[0],&sim->wl); edriftchanges = enermove - energy + wlener; } break; case 1: /* Isotropic pressure coupling */ psch = sim->edge.mx * (ran2(&seed) - 0.5); pvol = conf->box.x * conf->box.y * conf->box.z; conf->box.x += psch; conf->box.y += psch; conf->box.z += psch; pvoln = conf->box.x * conf->box.y * conf->box.z; reject = 0; if (sim->wlm[0] > 0) { /* get new neworder for wang-landau */ for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 1: sim->wl.neworder[wli] = z_order(&sim->wl,conf,wli); break; case 2: mesh_cpy(&sim->wl.origmesh,&sim->wl.mesh); sim->wl.neworder[wli] = (long) (mesh_init(&sim->wl.mesh,sim->wl.wl_meshsize, topo->npart, conf, sim) - sim->wl.minorder[wli]); break; case 4: sim->wl.neworder[wli] = twopartdist(&sim->wl,conf,wli); break; case 5: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->syscm)); break; case 6: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); break; case 7: sim->wl.partincontactold = sim->wl.partincontact; sim->wl.neworder[wli] = contparticles_all(topo,conf,sim,wli); break; default: sim->wl.neworder[wli] = sim->wl.currorder[wli]; break; } if ( (sim->wl.neworder[wli] < 0) || (sim->wl.neworder[wli] >= sim->wl.length[wli]) ) reject = 1; } if (!reject) { wlener = sim->wl.weights[sim->wl.neworder[0]+sim->wl.neworder[1]*sim->wl.length[0]] - sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]; energy += wlener; } } if (!reject) { /* wang-landaou ok, try move - calcualte energy */ enermove = sim->press * (pvoln - pvol) - (double)topo->npart * log(pvoln/pvol) / sim->temper; enermove += calc_energy(0, intfce, 0, topo, conf, sim,0); } if ( reject || movetry(energy,enermove,sim->temper) ) { /* probability acceptance */ conf->box.x -= psch; conf->box.y -= psch; conf->box.z -= psch; sim->edge.rej++; wlreject(sim,radiusholemax_orig); } else { /* move was accepted */ sim->edge.acc++; wlaccept(sim->wlm[0],&sim->wl); edriftchanges = enermove - energy + wlener; } break; case 2: /* Isotropic pressure coupling in xy, z constant */ psch = sim->edge.mx * (ran2(&seed) - 0.5); pvol = conf->box.x * conf->box.y; conf->box.x += psch; conf->box.y += psch; pvoln = conf->box.x * conf->box.y; reject = 0; if (sim->wlm[0] > 0) { /* get new neworder for wang-landau */ for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { /*no change in case 1, it does not change box.z*/ case 2: mesh_cpy(&sim->wl.origmesh,&sim->wl.mesh); sim->wl.neworder[wli] = (long) (mesh_init(&sim->wl.mesh,sim->wl.wl_meshsize,topo->npart, conf, sim) - sim->wl.minorder[wli]); break; case 4: sim->wl.neworder[wli] = twopartdist(&sim->wl,conf,wli); break; case 5: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->syscm)); break; case 6: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); break; case 7: sim->wl.partincontactold = sim->wl.partincontact; sim->wl.neworder[wli] = contparticles_all(topo,conf,sim,wli); break; default: sim->wl.neworder[wli] = sim->wl.currorder[wli]; break; } if ( (sim->wl.neworder[wli] < 0) || (sim->wl.neworder[wli] >= sim->wl.length[wli]) ) reject = 1; } if (!reject) { wlener = sim->wl.weights[sim->wl.neworder[0]+sim->wl.neworder[1]*sim->wl.length[0]] - sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]; energy += wlener; } } if (!reject) { /* wang-landaou ok, try move - calculate energy */ enermove = sim->press * conf->box.z * (pvoln - pvol) - (double)topo->npart * log(pvoln/pvol) / sim->temper; enermove += calc_energy(0, intfce, 0, topo, conf, sim,0); } if ( reject || movetry(energy,enermove,sim->temper) ) { /* probability acceptance */ conf->box.x -= psch; conf->box.y -= psch; sim->edge.rej++; wlreject(sim,radiusholemax_orig); } else { /* move was accepted */ sim->edge.acc++; wlaccept(sim->wlm[0],&sim->wl); edriftchanges = enermove - energy + wlener; } break; case 3: /* Isotropic pressure coupling in xy, z coupled to have fixed volume */ psch = sim->edge.mx * (ran2(&seed) - 0.5); pvol = conf->box.x * conf->box.y * conf->box.z; conf->box.x += psch; conf->box.y += psch; conf->box.z = pvol / conf->box.x / conf->box.y; reject = 0; if (sim->wlm[0] > 0) { /* get new neworder for wang-landau */ for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 1: sim->wl.neworder[wli] = z_order(&sim->wl, conf,wli); break; case 2: mesh_cpy(&sim->wl.origmesh,&sim->wl.mesh); sim->wl.neworder[wli] = (long) (mesh_init(&sim->wl.mesh,sim->wl.wl_meshsize,topo->npart, conf, sim) - sim->wl.minorder[wli]); break; case 4: sim->wl.neworder[wli] = twopartdist(&sim->wl,conf,wli); break; case 5: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->syscm)); break; case 6: radiusholemax_orig = sim->wl.radiusholemax; longarray_cpy(&sim->wl.radiusholeold,&sim->wl.radiushole,sim->wl.radiusholemax,sim->wl.radiusholemax); sim->wl.neworder[wli] = radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); break; case 7: sim->wl.partincontactold = sim->wl.partincontact; sim->wl.neworder[wli] = contparticles_all(topo,conf,sim,wli); break; default: sim->wl.neworder[wli] = sim->wl.currorder[wli]; break; } if ( (sim->wl.neworder[wli] < 0) || (sim->wl.neworder[wli] >= sim->wl.length[wli]) ) reject = 1; } if (!reject) { wlener = sim->wl.weights[sim->wl.neworder[0]+sim->wl.neworder[1]*sim->wl.length[0]] - sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]; energy += wlener; } } if (!reject) { /* wang-landaou ok, try move - calculate energy */ enermove = calc_energy(0, intfce, 0, topo, conf, sim,0); } if ( reject || movetry(energy,enermove,sim->temper) ) { /* probability acceptance */ conf->box.x -= psch; conf->box.y -= psch; conf->box.z = pvol / conf->box.x / conf->box.y; sim->edge.rej++; wlreject(sim,radiusholemax_orig); } else { /* move was accepted */ sim->edge.acc++; wlaccept(sim->wlm[0],&sim->wl); edriftchanges = enermove - energy + wlener; } break; default: fprintf (stderr, "ERROR: unknown type of pressure coupling %d",sim->ptype); exit(1); } /*=== End volume change step ===*/ return edriftchanges; } /*..................... Switch replicas move in MPI ..............................*/ /*.................................................................................*/ double replicaexchangemove(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *), long sweep ) { double edriftchanges=0.0; #ifdef MPI double change, *recwlweights; MPI_Status status; int oddoreven,count,wli,sizewl = 0; struct mpiexchangedata localmpi,receivedmpi; BOOL reject; long localwl,receivedwl; double ran2(long *); void gen_pairlist(struct topo * topo, struct sim * sim, struct conf * conf); int longarray_cpy (long **target, long **source,long,long); int mesh_init(struct meshs *, double, long, struct conf * conf, struct sim * sim); double calc_energy(long target, double (* intfce[MAXT][MAXT])(struct interacts *), int mode, struct topo * topo, struct conf * conf, struct sim * sim,int chainn); void wlaccept(int, struct wls *); //int mpi_newdatatypes(); //mpi_newdatatypes(); int i; struct vector vec; struct particles part; struct mpiexchangedata exch; MPI_Aint dispstart; MPI_Datatype MPI_vector; MPI_Datatype type[3] = {MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE}; int blocklen[3] = {1, 1, 1}; MPI_Aint disp[3]; MPI_Address( &vec, &dispstart); MPI_Address( &(vec.x), &disp[0]); MPI_Address( &(vec.y), &disp[1]); MPI_Address( &(vec.z), &disp[2]); for (i=0; i <3; i++) disp[i] -= dispstart; MPI_Type_struct( 3, blocklen, disp, type, &MPI_vector); MPI_Type_commit( &MPI_vector); MPI_Datatype MPI_Particle; MPI_Datatype type2[11] = {MPI_vector,MPI_vector,MPI_vector,MPI_vector,MPI_vector, MPI_LONG, MPI_LONG, MPI_INT,MPI_INT,MPI_DOUBLE, MPI_INT}; int blocklen2[11] = {1, 1, 2,4,2,1,1,1,1,1,1,}; MPI_Aint disp2[11]; MPI_Address( &part, &dispstart); MPI_Address( &(part.pos), &disp2[0]); MPI_Address( &(part.dir), &disp2[1]); MPI_Address( &(part.patchdir), &disp2[2]); MPI_Address( &(part.patchsides), &disp2[3]); MPI_Address( &(part.chdir), &disp2[4]); MPI_Address( &(part.chaint), &disp2[5]); MPI_Address( &(part.chainn), &disp2[6]); MPI_Address( &(part.type), &disp2[7]); MPI_Address( &(part.switchtype), &disp2[8]); MPI_Address( &(part.delta_mu), &disp2[9]); MPI_Address( &(part.switched), &disp2[10]); for (i=0; i <11; i++) disp2[i] -= dispstart; MPI_Type_struct( 11, blocklen2, disp2, type2, &MPI_Particle); MPI_Type_commit( &MPI_Particle); if (sim->wl.length[1] > 0) { sizewl = sim->wl.length[1] * sim->wl.length[0]; } else { sizewl = sim->wl.length[0]; } MPI_Datatype MPI_exchange; MPI_Datatype type3[7] = {MPI_vector, MPI_DOUBLE, MPI_DOUBLE, MPI_INT, MPI_vector, MPI_LONG, MPI_LONG}; int blocklen3[7] = {1, 1, 1, 1, 1, 1, 2}; MPI_Aint disp3[7]; MPI_Address( &exch, &dispstart); MPI_Address( &(exch.box), &disp3[0]); MPI_Address( &(exch.energy), &disp3[1]); MPI_Address( &(exch.volume), &disp3[2]); MPI_Address( &(exch.accepted), &disp3[3]); MPI_Address( &(exch.syscm), &disp3[4]); MPI_Address( &(exch.radiusholemax), &disp3[5]); MPI_Address( &(exch.wl_order), &disp3[6]); for (i=0; i <7; i++) disp3[i] -= dispstart; MPI_Type_struct(7, blocklen3, disp3, type3, &MPI_exchange); MPI_Type_commit( &MPI_exchange); /*=== This is an attempt to switch replicas ===*/ localmpi.box = conf->box; localmpi.energy = calc_energy(0, intfce, 0, topo, conf, sim,0); localmpi.volume = conf->box.x * conf->box.y * conf->box.z; localmpi.accepted = 0; localmpi.syscm = conf->syscm; localmpi.radiusholemax = sim->wl.radiusholemax; recwlweights = malloc( sizeof(double) * sizewl ); for (wli=0;wli<2;wli++) { localmpi.wl_order[wli] = 0; receivedmpi.wl_order[wli] = 0; } for (wli=0;wli<sim->wl.wlmdim;wli++) { localmpi.wl_order[wli] = sim->wl.currorder[wli]; //fprintf(stdout,"wli %d %ld %ld\n\n", wli, localmpi.wl_order[wli], sim->wl.currorder[wli] ); } if ( (sweep % (2*sim->nrepchange)) == 0) /* exchange odd ones with even ones*/ oddoreven=1; else /* exchange even ones with odd ones*/ oddoreven=0; if (sim->mpinprocs == 2) oddoreven=1; count = 1; if (sim->mpirank % 2 == oddoreven) { if (sim->mpirank > 0) { MPI_Send(&localmpi, 1, MPI_exchange, sim->mpirank-1, count, MPI_COMM_WORLD); MPI_Send(sim->wl.weights, sizewl, MPI_DOUBLE, sim->mpirank-1, count, MPI_COMM_WORLD); //printf("send data: rank: %d energy: %f volume: %f pressure: %f \n",sim->mpirank,localmpi.energy,localmpi.volume,localmpi.pressure); MPI_Recv(&receivedmpi, 1, MPI_exchange, sim->mpirank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); /*decision of accepting or rejecting the exchange was done on other process here we took received configuration (if move was accepted))*/ //printf("received data: rank: %d energy: %f volume: %f pressure: %f \n",sim->mpirank,receivedmpi.energy,receivedmpi.volume,receivedmpi.pressure); if (receivedmpi.accepted == 1) { sim->mpiexch.acc++; struct particles *temppart; temppart = malloc(topo->npart*sizeof(struct particles)); MPI_Recv(temppart, topo->npart, MPI_Particle, sim->mpirank-1, MPI_ANY_TAG, MPI_COMM_WORLD,&status); /* printf("received data: rank: %d\n", sim->mpirank); printf("part0 x %f y %f z %f\n",temppart[0].pos.x, temppart[0].pos.y, temppart[0].pos.z); printf("part1 x %f y %f z %f\n",temppart[1].pos.x, temppart[1].pos.y, temppart[1].pos.z); printf("part0 chaint %ld chainn %ld type %d\n",temppart[0].chaint,temppart[0].chainn,temppart[0].type); */ MPI_Send(conf->particle, topo->npart, MPI_Particle, sim->mpirank-1, count, MPI_COMM_WORLD); /* printf("send data: rank: %d\n",sim->mpirank); printf("part0 x %f y %f z %f\n",conf->particle[0].pos.x,conf->particle[0].pos.y,conf->particle[0].pos.z); printf("part1 x %f y %f z %f\n",conf->particle[1].pos.x,conf->particle[1].pos.y,conf->particle[1].pos.z); printf("part0 chaint %ld chainn %ld type %d\n",conf->particle[0].chaint,conf->particle[0].chainn,conf->particle[0].type); */ localmpi.accepted = receivedmpi.accepted; conf->box = receivedmpi.box; conf->syscm = receivedmpi.syscm; memcpy(conf->particle,temppart,topo->npart*sizeof(struct particles)); edriftchanges = receivedmpi.energy - localmpi.energy; edriftchanges += sim->press * (receivedmpi.volume - localmpi.volume) - (double)topo->npart * log(receivedmpi.volume / localmpi.volume) / sim->temper; if ( sim->wlm[0] >0 ) { for (wli=0;wli<sim->wl.wlmdim;wli++) { sim->wl.neworder[wli] = receivedmpi.wl_order[wli]; } wlaccept(sim->wlm[0],&sim->wl); //exchange wl data mesh size and radius hole s for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 2: /*it is complicated to send because of different sizes we would have to send sizes first and realocate corrrect mesh size and then send data it is better to recalculate (a bit slower though)*/ mesh_init(&sim->wl.mesh,sim->wl.wl_meshsize, topo->npart, conf, sim); break; case 5: //radiushole_all(topo,conf,sim,wli,&(conf->syscm)); sim->wl.radiusholeold = (long*) realloc(sim->wl.radiusholeold,sizeof(long)*receivedmpi.radiusholemax); MPI_Recv(sim->wl.radiusholeold,receivedmpi.radiusholemax, MPI_LONG, sim->mpirank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Send(sim->wl.radiushole,sim->wl.radiusholemax, MPI_LONG, sim->mpirank-1, count, MPI_COMM_WORLD); longarray_cpy(&sim->wl.radiushole,&sim->wl.radiusholeold,sim->wl.radiusholemax,receivedmpi.radiusholemax); sim->wl.radiusholemax=receivedmpi.radiusholemax; break; case 6: //radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); sim->wl.radiusholeold = (long*) realloc(sim->wl.radiusholeold,sizeof(long)*receivedmpi.radiusholemax); MPI_Recv(sim->wl.radiusholeold,receivedmpi.radiusholemax, MPI_LONG, sim->mpirank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Send(sim->wl.radiushole,sim->wl.radiusholemax, MPI_LONG, sim->mpirank-1, count, MPI_COMM_WORLD); longarray_cpy(&sim->wl.radiushole,&sim->wl.radiusholeold,sim->wl.radiusholemax,receivedmpi.radiusholemax); sim->wl.radiusholemax=receivedmpi.radiusholemax; break; case 7: //contparticles_all(topo,conf,sim,wli); MPI_Recv(&(sim->wl.partincontactold),1, MPI_LONG, sim->mpirank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Send(&(sim->wl.partincontact),1, MPI_LONG, sim->mpirank-1, count, MPI_COMM_WORLD); sim->wl.partincontact=sim->wl.partincontactold; break; } } } free(temppart); } else { sim->mpiexch.rej++; if ( sim->wlm[0] > 0 ) { sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]] -= sim->wl.alpha; sim->wl.hist[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]++; } } } } else { if (sim->mpirank+1 < sim->mpinprocs) { /*there is above process*/ MPI_Recv(&receivedmpi, 1, MPI_exchange, sim->mpirank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Recv(recwlweights, sizewl, MPI_DOUBLE, sim->mpirank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); /*we got new configuration*/ //printf("received data: rank: %d energy: %f volume: %f \n",sim->mpirank,receivedmpi.energy,receivedmpi.volume); /*evaluate if accepte or reject the configuration*/ /*acc = exp( (1/sim->temper - 1/(sim->temper + sim.dtemp)) * (E_here - E_received) + (sim->press /sim->temper - pressure_received /(sim.temper + sim->dtemp)) * (V_here - V_received) if pressure the same it it simplier*/ reject = FALSE; change = (1/sim->temper - 1/(sim->temper + sim->dtemp)) * (localmpi.energy - receivedmpi.energy); //printf("acceptance decision: change: %f localE: %f receivedE: %f tempf: %f \n",change,localmpi.energy,receivedmpi.energy,(1/sim->temper - 1/(sim->temper + sim->dtemp))); change += (sim->press/sim->temper - (sim->press + sim->dpress)/(sim->temper + sim->dtemp)) * (localmpi.volume - receivedmpi.volume); //printf("pressf: %f \n",(sim->press/sim->temper - (sim->press + sim->dpress)/(sim->temper + sim->dtemp))); if (sim->wlm[0] > 0) { localwl = sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]; receivedwl = receivedmpi.wl_order[0] + receivedmpi.wl_order[1]*sim->wl.length[0]; //fprintf(stdout,"decide wl %ld %ld %ld energychange: %f \n", receivedmpi.wl_order[0], receivedmpi.wl_order[1], receivedwl, change ); //fprintf(stdout,"local weights %ld %f %ld %f \n",localwl,sim->wl.weights[localwl],receivedwl,sim->wl.weights[receivedwl]); change += (-sim->wl.weights[localwl] + sim->wl.weights[receivedwl] )/sim->temper + ( -recwlweights[receivedwl] + recwlweights[localwl])/(sim->temper + sim->dtemp) ; //fprintf(stdout,"wlchange %f \n\n",change); } if ( (!(reject)) && ( (change > 0) || (ran2(&seed) < exp(change)) ) ) { /* Exchange ACCEPTED send local stuff*/ //printf("exchange accepted \n"); sim->mpiexch.acc++; localmpi.accepted = 1; conf->box = receivedmpi.box; conf->syscm = receivedmpi.syscm; edriftchanges = receivedmpi.energy - localmpi.energy; edriftchanges += sim->press * (receivedmpi.volume - localmpi.volume) - (double)topo->npart * log(receivedmpi.volume / localmpi.volume) / sim->temper; //printf("edrift %f\n",edriftchanges); if ( sim->wlm[0] > 0 ) { for (wli=0;wli<sim->wl.wlmdim;wli++) { sim->wl.neworder[wli] = receivedmpi.wl_order[wli]; } wlaccept(sim->wlm[0],&sim->wl); } MPI_Send(&localmpi, 1, MPI_exchange, sim->mpirank+1, count, MPI_COMM_WORLD); //printf("send data: rank: %d energy: %f volume: %f pressure: %f \n",sim->mpirank,localmpi.energy,localmpi.volume,localmpi.pressure); /*send and receive configuration*/ MPI_Send(conf->particle, topo->npart, MPI_Particle, sim->mpirank+1, count, MPI_COMM_WORLD); /* printf("send data: rank: %d\n",sim->mpirank); printf("part0 x %f y %f z %f\n",conf->particle[0].pos.x,conf->particle[0].pos.y,conf->particle[0].pos.z); printf("part1 x %f y %f z %f\n",conf->particle[1].pos.x,conf->particle[1].pos.y,conf->particle[1].pos.z); printf("part0 chaint %ld chainn %ld type %d\n",conf->particle[0].chaint,conf->particle[0].chainn,conf->particle[0].type); */ MPI_Recv(conf->particle, topo->npart, MPI_Particle, sim->mpirank+1, MPI_ANY_TAG, MPI_COMM_WORLD,&status); /* printf("recieved data: rank: %d\n",sim->mpirank); printf("part0 x %f y %f z %f\n",conf->particle[0].pos.x,conf->particle[0].pos.y,conf->particle[0].pos.z); printf("part1 x %f y %f z %f\n",conf->particle[1].pos.x,conf->particle[1].pos.y,conf->particle[1].pos.z); printf("part0 chaint %ld chainn %ld type %d\n",conf->particle[0].chaint,conf->particle[0].chainn,conf->particle[0].type); */ if ( sim->wlm[0] > 0 ) { //exchange wl data mesh size and radius hole s for (wli=0;wli<sim->wl.wlmdim;wli++) { switch (sim->wlm[wli]) { case 2: /*it is complicated to send because of different sizes we would have to send sizes first and realocate corrrect mesh size and then send data it is better to recalculate (a bit slower though)*/ mesh_init(&sim->wl.mesh,sim->wl.wl_meshsize, topo->npart, conf, sim); break; case 5: //radiushole_all(topo,conf,sim,wli,&(conf->syscm)); sim->wl.radiusholeold = (long*) realloc(sim->wl.radiusholeold,sizeof(long)*receivedmpi.radiusholemax); MPI_Send(sim->wl.radiushole,sim->wl.radiusholemax, MPI_LONG, sim->mpirank+1, count, MPI_COMM_WORLD); MPI_Recv(sim->wl.radiusholeold,receivedmpi.radiusholemax, MPI_LONG, sim->mpirank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); longarray_cpy(&sim->wl.radiushole,&sim->wl.radiusholeold,sim->wl.radiusholemax,receivedmpi.radiusholemax); sim->wl.radiusholemax=receivedmpi.radiusholemax; break; case 6: //radiushole_all(topo,conf,sim,wli,&(conf->particle[0].pos)); sim->wl.radiusholeold = (long*) realloc(sim->wl.radiusholeold,sizeof(long)*receivedmpi.radiusholemax); MPI_Send(sim->wl.radiushole,sim->wl.radiusholemax, MPI_LONG, sim->mpirank+1, count, MPI_COMM_WORLD); MPI_Recv(sim->wl.radiusholeold,receivedmpi.radiusholemax, MPI_LONG, sim->mpirank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); longarray_cpy(&sim->wl.radiushole,&sim->wl.radiusholeold,sim->wl.radiusholemax,receivedmpi.radiusholemax); sim->wl.radiusholemax=receivedmpi.radiusholemax; break; case 7: //contparticles_all(topo,conf,sim,wli); MPI_Send(&(sim->wl.partincontact),1, MPI_LONG, sim->mpirank+1, count, MPI_COMM_WORLD); MPI_Recv(&(sim->wl.partincontact),1, MPI_LONG, sim->mpirank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &status); break; } } } } else { /*if exchange rejected send back info */ //printf("exchange rejected\n"); sim->mpiexch.rej++; MPI_Send(&localmpi, 1, MPI_exchange, sim->mpirank+1, count, MPI_COMM_WORLD); if ( sim->wlm[0] > 0 ) { sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]] -= sim->wl.alpha; sim->wl.hist[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]++; } } } } if ( (localmpi.accepted) && (sim->pairlist_update) ) gen_pairlist(topo, sim, conf); MPI_Type_free(&MPI_exchange); MPI_Type_free(&MPI_Particle); MPI_Type_free(&MPI_vector); free(recwlweights); #endif return edriftchanges; } /*int mpi_newdatatypes() { int i; struct vector vec; struct particles part; struct mpiexchangedata exch; MPI_Aint dispstart; MPI_Datatype MPI_vector; MPI_Datatype type[3] = {MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE}; int blocklen[3] = {1, 1, 1}; MPI_Aint disp[3]; MPI_Address( &vec, &dispstart); MPI_Address( &(vec.x), &disp[0]); MPI_Address( &(vec.y), &disp[1]); MPI_Address( &(vec.z), &disp[2]); for (i=0; i <3; i++) disp[i] -= dispstart; MPI_Type_struct( 3, blocklen, disp, type, &MPI_vector); MPI_Type_commit( &MPI_vector); MPI_Datatype MPI_Particle; MPI_Datatype type2[11] = {MPI_vector,MPI_vector,MPI_vector,MPI_vector,MPI_vector, MPI_LONG, MPI_LONG, MPI_INT,MPI_INT,MPI_DOUBLE, MPI_INT}; int blocklen2[11] = {1, 1, 2,4,2,1,1,1,1,1,1,}; MPI_Aint disp2[11]; MPI_Address( &part, &dispstart); MPI_Address( &(part.pos), &disp2[0]); MPI_Address( &(part.dir), &disp2[1]); MPI_Address( &(part.patchdir), &disp2[2]); MPI_Address( &(part.patchsides), &disp2[3]); MPI_Address( &(part.chdir), &disp2[4]); MPI_Address( &(part.chaint), &disp2[5]); MPI_Address( &(part.chainn), &disp2[6]); MPI_Address( &(part.type), &disp2[7]); MPI_Address( &(part.switchtype), &disp2[8]); MPI_Address( &(part.delta_mu), &disp2[9]); MPI_Address( &(part.switched), &disp2[10]); for (i=0; i <11; i++) disp2[i] -= dispstart; MPI_Type_struct( 11, blocklen2, disp2, type2, &MPI_Particle); MPI_Type_commit( &MPI_Particle); MPI_Datatype MPI_exchange; MPI_Datatype type3[5] = {MPI_vector, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_INT}; int blocklen3[5] = {1, 1, 1, 1, 1}; MPI_Aint disp3[5]; MPI_Address( &exch, &dispstart); MPI_Address( &(exch.box), &disp3[0]); MPI_Address( &(exch.energy), &disp3[1]); MPI_Address( &(exch.volume), &disp3[2]); MPI_Address( &(exch.pressure), &disp3[3]); MPI_Address( &(exch.accepted), &disp3[4]); for (i=0; i <5; i++) disp3[i] -= dispstart; MPI_Type_struct( 5, blocklen3, disp3, type3, &MPI_exchange); MPI_Type_commit( &MPI_exchange); return 0; }*/ /*................................................................................*/ /*................................................................................*/ /*....................END OF MOVES, INTERACTION FUNCTIONS FOLLOW..................*/ /*................................................................................*/ /*..............................................................................*/ /* Determines total energy of two spherocylinders type PSC PSC */ double e_psc_psc(struct interacts * interact) { double atrenergy, repenergy; void closestdist(struct interacts *); double erepulsive(struct interacts *); double eattractive_psc_psc(struct interacts *,int,int); closestdist(interact); repenergy = erepulsive(interact); if ( ( interact->dist > interact->param->rcut ) || ( interact->param->epsilon == 0.0 ) ) atrenergy = 0.0; else { BOOL firstCH=FALSE, secondCH=FALSE; struct vector olddir1 = interact->part1->dir; struct vector olddir2 = interact->part2->dir; if ( (interact->param->geotype[0] == CHPSC)||(interact->param->geotype[0] == TCHPSC) ) firstCH = TRUE; if ( (interact->param->geotype[1] == CHPSC)||(interact->param->geotype[1] == TCHPSC) ) secondCH = TRUE; if (firstCH) interact->part1->dir = interact->part1->chdir[0]; if (secondCH) interact->part2->dir = interact->part2->chdir[0]; if ((firstCH) || (secondCH) ) { closestdist(interact); } atrenergy = eattractive_psc_psc(interact,0,0); /*addition of interaction of second patches*/ if ( (interact->param->geotype[0] == TPSC) || (interact->param->geotype[0] == TCHPSC) || (interact->param->geotype[1] == TPSC) ||(interact->param->geotype[1] == TCHPSC) ) { BOOL firstT=FALSE, secondT=FALSE; if ( (interact->param->geotype[0] == TPSC) || (interact->param->geotype[0] == TCHPSC) ) firstT = TRUE; if ( (interact->param->geotype[1] == TPSC) ||(interact->param->geotype[1] == TCHPSC) ) secondT = TRUE; if (firstT) { if (firstCH) { interact->part1->dir = interact->part1->chdir[1]; closestdist(interact); } atrenergy += eattractive_psc_psc(interact,1,0); } if ( (firstT) && (secondT) ) { if (secondCH) { interact->part2->dir = interact->part2->chdir[1]; closestdist(interact); } atrenergy += eattractive_psc_psc(interact,1,1); } if (secondT) { if (firstT && firstCH ) { interact->part1->dir = interact->part1->chdir[0]; closestdist(interact); } atrenergy += eattractive_psc_psc(interact,0,1); } } if (firstCH) interact->part1->dir = olddir1; if (secondCH) interact->part2->dir = olddir2; } return repenergy+atrenergy; } /* Determines attractive energy of two spherocylinders type PSC PSC */ double eattractive_psc_psc(struct interacts * interact,int patchnum1,int patchnum2) { int i, intrs; double rcut, atrenergy, ndist; double v1, v2, f0, f1, f2, T1, T2, S1, S2, a; double intersections[5]; struct vector vec1, vec2, vec_intrs, vec_mindist; struct vector vec_sub(struct vector, struct vector); struct vector vec_sum(struct vector, struct vector); struct vector vec_create(double, double, double); struct vector vec_scale(struct vector, double); struct vector vec_perpproject(struct vector *, struct vector*); struct vector mindist_segments(struct vector, double, struct vector, double, struct vector); void normalise(struct vector *); int psc_intersect(struct particles *, struct particles *, double, double, struct vector, double *,double, struct ia_param *, int which, int patchnum); double fanglscale(double, struct ia_param *, int which); rcut = interact->param->rcut; //interact->halfl = interact->param->half_len[0]; //DEBUG_SIM("halfl = %lf", interact->halfl); for(i=0;i<5;i++) intersections[i]=0; //cospatch = param.pcanglsw; //cospatchinr = param.pcangl; /*1- do intersections of spherocylinder2 with patch of spherocylinder1 at. cut distance C*/ //DEBUG_SIM("first intersection"); intrs=psc_intersect(interact->part1,interact->part2,interact->param->half_len[0],interact->param->half_len[1],interact->r_cm, intersections, rcut, interact->param,0, patchnum1); if (intrs <2){ //DEBUG_SIM("No intersection :("); return 0.0; /*sc is all outside patch, attractive energy is 0*/ } T1=intersections[0]; /*points on sc2*/ T2=intersections[1]; /*2- now do the same oposite way psc1 in patch of psc2*/ for(i=0;i<5;i++) intersections[i]=0; //DEBUG_SIM("get vector"); vec1=vec_scale(interact->r_cm,-1.0); //DEBUG_SIM("second intersection"); intrs=psc_intersect(interact->part2,interact->part1,interact->param->half_len[1],interact->param->half_len[0],vec1, intersections, rcut, interact->param,1, patchnum2); if (intrs <2) return 0.0; /*sc is all outside patch, attractive energy is 0*/ S1=intersections[0]; /*points on sc1*/ S2=intersections[1]; /*3- scaling function1: dependence on the length of intersetions*/ v1=fabs(S1-S2); v2=fabs(T1-T2); f0=0.5*(v1+v2); /*4a- with two intersection pices calculate vector between their CM -this is for angular orientation*/ vec1=vec_scale(interact->part1->dir,(S1+S2)*0.5); vec2=vec_scale(interact->part2->dir,(T1+T2)*0.5); vec_intrs.x=vec2.x-vec1.x-interact->r_cm.x; vec_intrs.y=vec2.y-vec1.y-interact->r_cm.y; vec_intrs.z=vec2.z-vec1.z-interact->r_cm.z; /*vec_intrs should be from sc1 to sc2*/ //fprintf (stderr, "segments_CM: %.8f %.8f %.8f \n",vec_intrs.x,vec_intrs.y,vec_intrs.z); /*4b - calculate closest distance attractive energy from it*/ vec_mindist = mindist_segments(interact->part1->dir,v1,interact->part2->dir,v2,vec_intrs); //fprintf (stderr, "segments closest dist: %.8f %.8f %.8f \n",vec_mindist.x,vec_mindist.y,vec_mindist.z); ndist=sqrt(DOT(vec_mindist,vec_mindist)); //dist=DOT(vec_intrs,vec_intrs); if (ndist < interact->param->pdis) atrenergy = -interact->param->epsilon; //atrenergy = -1.0; else { atrenergy = cos(PIH*(ndist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon ; } /*5- scaling function2: angular dependence of patch1*/ vec1=vec_scale(vec_intrs,1.0); //vec1=vec_scale(vec_mindist,-1.0); vec1=vec_perpproject(&vec1, &interact->part1->dir); normalise(&vec1); a = DOT(vec1,interact->part1->patchdir[patchnum1]); f1 = fanglscale(a,interact->param, 0+2*patchnum1); /*6- scaling function3: angular dependence of patch2*/ vec1=vec_scale(vec_intrs,-1.0); //vec1=vec_scale(vec_mindist,1.0); vec1=vec_perpproject(&vec1, &interact->part2->dir); normalise(&vec1); a = DOT(vec1,interact->part2->patchdir[patchnum2]); f2 = fanglscale(a,interact->param, 1+2*patchnum2); //printf("v1: %f v2: %f f0: %f f1: %f f2: %f ener: %f\n",v1,v2,f0,f1,f2,atrenergy); /*7- put it all together*/ atrenergy *=f0*f1*f2; //if (atrenergy < 0) printf ("atraction %f\n",atrenergy); // fprintf (stderr, "attraction %.8f \n",atrenergy); // exit(1); return atrenergy; } /* a = r_ij * n_i */ double fanglscale(double a, struct ia_param * param, int which) { double f; // TODO for different types if (a <= param->pcanglsw[which]) f=0.0; else { if (a >= param->pcangl[which]) f=1.0; else { f = 0.5 - ((param->pcanglsw[which] + param->pcangl[which])*0.5 - a )/(param->pcangl[which] - param->pcanglsw[which]); } } return f; } /*CPSC..............................................................................*/ /* Determines total energy of two spherocylinders of type 3 -cylindrical psc -CPSC */ double e_cpsc_cpsc(struct interacts * interact) { double atrenergy, repenergy; void closestdist(struct interacts *); double erepulsive(struct interacts *); double eattractive_cpsc_cpsc(struct interacts *,int,int); //DEBUG_SIM("do energy 33") ; closestdist(interact); repenergy = erepulsive(interact); //DEBUG_SIM("got the rep. energy"); if ( ( interact->dist > interact->param->rcut ) || ( interact->param->epsilon == 0.0 ) ) atrenergy = 0.0; else { BOOL firstCH=FALSE, secondCH=FALSE; struct vector olddir1 = interact->part1->dir; struct vector olddir2 = interact->part2->dir; if ( (interact->param->geotype[0] == CHCPSC)||(interact->param->geotype[0] == TCHCPSC) ) firstCH = TRUE; if ( (interact->param->geotype[1] == CHCPSC)||(interact->param->geotype[1] == TCHCPSC) ) secondCH = TRUE; if(firstCH) interact->part1->dir = interact->part1->chdir[0]; if(secondCH) interact->part2->dir = interact->part2->chdir[0]; if ((firstCH) || (secondCH) ) { closestdist(interact); } atrenergy = eattractive_cpsc_cpsc(interact,0,0); /*addition of interaction of second patches*/ if ( (interact->param->geotype[0] == TCPSC) || (interact->param->geotype[0] == TCHCPSC) || (interact->param->geotype[1] == TCPSC) ||(interact->param->geotype[1] == TCHCPSC) ) { BOOL firstT=FALSE, secondT=FALSE; if ( (interact->param->geotype[0] == TCPSC) || (interact->param->geotype[0] == TCHCPSC) ) firstT = TRUE; if ( (interact->param->geotype[1] == TCPSC) ||(interact->param->geotype[1] == TCHCPSC) ) secondT = TRUE; if (firstT) { if (firstCH) { interact->part1->dir = interact->part1->chdir[1]; closestdist(interact); } atrenergy += eattractive_cpsc_cpsc(interact,1,0); } if ( (firstT) && (secondT) ) { if (secondCH) { interact->part2->dir = interact->part2->chdir[1]; closestdist(interact); } atrenergy += eattractive_cpsc_cpsc(interact,1,1); } if (secondT) { if (firstT && firstCH ) { interact->part1->dir = interact->part1->chdir[0]; closestdist(interact); } atrenergy += eattractive_cpsc_cpsc(interact,0,1); } } if (firstCH) interact->part1->dir = olddir1; if (secondCH) interact->part2->dir = olddir2; } return repenergy+atrenergy; } /* Determines attractive energy of two spherocylinders of type 3 -cylindrical psc -CPSC */ double eattractive_cpsc_cpsc(struct interacts * interact, int patchnum1, int patchnum2) { int i, intrs; double rcut, atrenergy, v1, v2, f0, f1, f2, T1, T2, S1, S2, a, ndist; double intersections[5]; struct vector vec1, vec2, vec_intrs, vec_mindist; struct vector vec_sub(struct vector, struct vector); struct vector vec_sum(struct vector, struct vector); struct vector vec_create(double, double, double); struct vector vec_scale(struct vector, double); struct vector vec_perpproject(struct vector*, struct vector*); struct vector mindist_segments(struct vector, double, struct vector, double, struct vector); void normalise(struct vector *); int cpsc_intersect(struct particles *, struct particles *, double, double, struct vector, double *,double, struct ia_param *, int which, int patchnum); double fanglscale(double, struct ia_param *, int which); rcut = interact->param->rcut; // interact->halfl = interact->param->half_len[0]; for(i=0;i<5;i++) intersections[i]=0; /*1- do intersections of spherocylinder2 with patch of spherocylinder1 at. cut distance C*/ intrs=cpsc_intersect(interact->part1,interact->part2,interact->param->half_len[0],interact->param->half_len[1],interact->r_cm, intersections, rcut, interact->param,0, patchnum1); if (intrs <2) return 0.0; /*sc is all outside patch, attractive energy is 0*/ T1=intersections[0]; /*points on sc2*/ T2=intersections[1]; /*2- now do the same oposite way psc1 in patch of psc2*/ for(i=0;i<5;i++) intersections[i]=0; vec1=vec_scale(interact->r_cm,-1.0); intrs=cpsc_intersect(interact->part2,interact->part1,interact->param->half_len[1],interact->param->half_len[0],vec1, intersections, rcut, interact->param,1, patchnum2); if (intrs <2) return 0.0; /*sc is all outside patch, attractive energy is 0*/ S1=intersections[0]; /*points on sc1*/ S2=intersections[1]; /*3- scaling function1: dependence on the length of intersetions*/ v1=fabs(S1-S2); v2=fabs(T1-T2); f0=0.5*(v1+v2); /*4a- with two intersection pices calculate vector between their CM -this is for angular orientation*/ vec1=vec_scale(interact->part1->dir,(S1+S2)*0.5); vec2=vec_scale(interact->part2->dir,(T1+T2)*0.5); vec_intrs.x=vec2.x-vec1.x-interact->r_cm.x; vec_intrs.y=vec2.y-vec1.y-interact->r_cm.y; vec_intrs.z=vec2.z-vec1.z-interact->r_cm.z; /*vec_intrs should be from sc1 to sc2*/ // fprintf (stderr, "segments_CM: %.8f %.8f %.8f \n",vec_intrs.x,vec_intrs.y,vec_intrs.z); /*4b - calculate closest distance attractive energy from it*/ vec_mindist = mindist_segments(interact->part1->dir,v1,interact->part2->dir,v2,vec_intrs); // fprintf (stderr, "segments closest dist: %.8f %.8f %.8f \n",vec_mindist.x,vec_mindist.y,vec_mindist.z); ndist=sqrt(DOT(vec_mindist,vec_mindist)); //dist=DOT(vec_intrs,vec_intrs); if (ndist < interact->param->pdis) atrenergy = -interact->param->epsilon; else { atrenergy = cos(PIH*(ndist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon ; } /*5- scaling function2: angular dependence of patch1*/ vec1=vec_scale(vec_intrs,1.0); //vec1=vec_scale(vec_mindist,-1.0); vec1=vec_perpproject(&vec1, &interact->part1->dir); normalise(&vec1); a = DOT(vec1,interact->part1->patchdir[patchnum1]); f1 = fanglscale(a,interact->param, 0+2*patchnum1); /*6- scaling function3: angular dependence of patch2*/ vec1=vec_scale(vec_intrs,-1.0); //vec1=vec_scale(vec_mindist,1.0); vec1=vec_perpproject(&vec1, &interact->part2->dir); normalise(&vec1); a = DOT(vec1,interact->part2->patchdir[patchnum2]); f2 = fanglscale(a,interact->param, 1+2*patchnum2); /*7- put it all together*/ atrenergy *=f0*f1*f2; //if (atrenergy < 0) printf ("atraction %f\n",atrenergy); // fprintf (stderr, "attraction %.8f \n",atrenergy); // exit(1); return atrenergy; } /*..............................................................................*/ /* Determines total energy of spherocylinders type PSC and CPSC */ double e_psc_cpsc(struct interacts * interact) { double atrenergy, repenergy; void closestdist(struct interacts *); double erepulsive(struct interacts *); double eattractive_psc_cpsc(struct interacts *,int,int); //DEBUG_SIM("do energy 23") ; closestdist(interact); repenergy = erepulsive(interact); //DEBUG_SIM("got the rep. energy"); if ( ( interact->dist > interact->param->rcut ) || ( interact->param->epsilon == 0.0 ) ) atrenergy = 0.0; else { BOOL firstCH=FALSE, secondCH=FALSE; struct vector olddir1 = interact->part1->dir; struct vector olddir2 = interact->part2->dir; if ((interact->param->geotype[0] == CHPSC) || (interact->param->geotype[0] == CHCPSC)|| (interact->param->geotype[0] == TCHPSC) || (interact->param->geotype[0] == TCHCPSC) ) firstCH = TRUE; if ((interact->param->geotype[1] == CHPSC) || (interact->param->geotype[1] == CHCPSC)|| (interact->param->geotype[1] == TCHPSC) || (interact->param->geotype[1] == TCHCPSC) ) secondCH = TRUE; if(firstCH) interact->part1->dir = interact->part1->chdir[0]; if(secondCH) interact->part2->dir = interact->part2->chdir[0]; if ((firstCH) || (secondCH) ) { closestdist(interact); } atrenergy = eattractive_psc_cpsc(interact,0,0); /*addition of interaction of second patches*/ if ( (interact->param->geotype[0] == TCPSC) || (interact->param->geotype[0] == TCHCPSC) || (interact->param->geotype[0] == TPSC) || (interact->param->geotype[0] == TCHPSC) || (interact->param->geotype[1] == TCPSC) ||(interact->param->geotype[1] == TCHCPSC) || (interact->param->geotype[1] == TPSC) || (interact->param->geotype[1] == TCHPSC) ) { BOOL firstT=FALSE, secondT=FALSE; if ( (interact->param->geotype[0] == TCPSC) || (interact->param->geotype[0] == TCHCPSC) || (interact->param->geotype[0] == TPSC) || (interact->param->geotype[0] == TCHPSC) ) firstT = TRUE; if ( (interact->param->geotype[1] == TCPSC) || (interact->param->geotype[1] == TCHCPSC) || (interact->param->geotype[1] == TPSC) || (interact->param->geotype[1] == TCHPSC) ) secondT = TRUE; if (firstT) { if (firstCH) { interact->part1->dir = interact->part1->chdir[1]; closestdist(interact); } atrenergy += eattractive_psc_cpsc(interact,1,0); } if ( (firstT) && (secondT) ) { if (secondCH) { interact->part2->dir = interact->part2->chdir[1]; closestdist(interact); } atrenergy += eattractive_psc_cpsc(interact,1,1); } if (secondT) { if (firstT && firstCH ) { interact->part1->dir = interact->part1->chdir[0]; closestdist(interact); } atrenergy += eattractive_psc_cpsc(interact,0,1); } } if (firstCH) interact->part1->dir = olddir1; if (secondCH) interact->part2->dir = olddir2; } return repenergy+atrenergy; } /* Determines attractive energy of spherocylinders type PSC and CPSC */ double eattractive_psc_cpsc(struct interacts * interact,int patchnum1,int patchnum2) { int i, intrs; double rcut, atrenergy, ndist; double v1, v2, f0, f1, f2, T1, T2, S1, S2, a; double intersections[5]; struct vector vec1, vec2, vec_intrs, vec_mindist; struct vector vec_sub(struct vector, struct vector); struct vector vec_sum(struct vector, struct vector); struct vector vec_create(double, double, double); struct vector vec_scale(struct vector, double); struct vector vec_perpproject(struct vector*, struct vector*); struct vector mindist_segments(struct vector, double, struct vector, double, struct vector); void normalise(struct vector *); int psc_intersect(struct particles *, struct particles *, double, double, struct vector, double *,double, struct ia_param *, int which,int patchnum); int cpsc_intersect(struct particles *, struct particles *, double, double, struct vector, double *,double, struct ia_param *, int which,int patchnum); double fanglscale(double, struct ia_param *, int which); rcut = interact->param->rcut; //interact->halfl = interact->param->half_len[0]; //DEBUG_SIM("halfl = %lf", interact->halfl); for(i=0;i<5;i++) intersections[i]=0; BOOL first; if ( (interact->param->geotype[0] == PSC)||(interact->param->geotype[0] == CHPSC)||(interact->param->geotype[0] == TPSC)||(interact->param->geotype[0] == TCHPSC) ){ first = TRUE; } else { first = FALSE; } //cospatch = param.pcanglsw; //cospatchinr = param.pcangl; /*1- do intersections of spherocylinder2 with patch of spherocylinder1 at. cut distance C*/ //DEBUG_SIM("first intersection"); if (first) { intrs=psc_intersect(interact->part1,interact->part2,interact->param->half_len[0],interact->param->half_len[1],interact->r_cm, intersections, rcut, interact->param,0, patchnum1); } else { intrs=cpsc_intersect(interact->part1,interact->part2,interact->param->half_len[0],interact->param->half_len[1],interact->r_cm, intersections, rcut, interact->param,0, patchnum1); } //DEBUG_SIM("first intersection: done"); if (intrs <2){ //DEBUG_SIM("No intersection :("); return 0.0; /*sc is all outside patch, attractive energy is 0*/ } T1=intersections[0]; /*points on sc2*/ T2=intersections[1]; /*2- now do the same oposite way psc1 in patch of psc2*/ for(i=0;i<5;i++) intersections[i]=0; //DEBUG_SIM("get vector"); vec1=vec_scale(interact->r_cm,-1.0); //DEBUG_SIM("second intersection"); if (first) { intrs=cpsc_intersect(interact->part2,interact->part1,interact->param->half_len[1],interact->param->half_len[0],vec1, intersections, rcut, interact->param,1, patchnum2); } else { intrs=psc_intersect(interact->part2,interact->part1,interact->param->half_len[1],interact->param->half_len[0],vec1, intersections, rcut, interact->param,1, patchnum2); } if (intrs <2) return 0.0; /*sc is all outside patch, attractive energy is 0*/ S1=intersections[0]; /*points on sc1*/ S2=intersections[1]; /*3- scaling function1: dependence on the length of intersetions*/ v1=fabs(S1-S2); v2=fabs(T1-T2); f0=0.5*(v1+v2); /*4a- with two intersection pices calculate vector between their CM -this is for angular orientation*/ vec1=vec_scale(interact->part1->dir,(S1+S2)*0.5); vec2=vec_scale(interact->part2->dir,(T1+T2)*0.5); vec_intrs.x=vec2.x-vec1.x-interact->r_cm.x; vec_intrs.y=vec2.y-vec1.y-interact->r_cm.y; vec_intrs.z=vec2.z-vec1.z-interact->r_cm.z; /*vec_intrs should be from sc1 to sc2*/ // fprintf (stderr, "segments_CM: %.8f %.8f %.8f \n",vec_intrs.x,vec_intrs.y,vec_intrs.z); /*4b - calculate closest distance attractive energy from it*/ vec_mindist = mindist_segments(interact->part1->dir,v1,interact->part2->dir,v2,vec_intrs); // fprintf (stderr, "segments closest dist: %.8f %.8f %.8f \n",vec_mindist.x,vec_mindist.y,vec_mindist.z); ndist=sqrt(DOT(vec_mindist,vec_mindist)); //dist=DOT(vec_intrs,vec_intrs); if (ndist < interact->param->pdis) atrenergy = -interact->param->epsilon; //atrenergy = -1.0; else { atrenergy = cos(PIH*(ndist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon ; } /*5- scaling function2: angular dependence of patch1*/ vec1=vec_scale(vec_intrs,1.0); //vec1=vec_scale(vec_mindist,-1.0); vec1=vec_perpproject(&vec1, &interact->part1->dir); normalise(&vec1); a = DOT(vec1,interact->part1->patchdir[patchnum1]); f1 = fanglscale(a,interact->param, 0+2*patchnum1); /*6- scaling function3: angular dependence of patch2*/ vec1=vec_scale(vec_intrs,-1.0); //vec1=vec_scale(vec_mindist,1.0); vec1=vec_perpproject(&vec1, &interact->part2->dir); normalise(&vec1); a = DOT(vec1,interact->part2->patchdir[patchnum2]); f2 = fanglscale(a,interact->param, 1+2*patchnum2); /*7- put it all together*/ atrenergy *=f0*f1*f2; //if (atrenergy < 0) printf ("atraction %f\n",atrenergy); // fprintf (stderr, "attraction %.8f \n",atrenergy); // exit(1); return atrenergy; } /*..............................................................................*/ /* * Determines total energy of spherocylinder type 1 and sphere type 11 */ double e_spa_sca(struct interacts * interact) { double atrenergy, repenergy, b, f0, halfl; struct vector vec_perpproject(struct vector *, struct vector *); void normalise(struct vector *); void closestdist(struct interacts *); double erepulsive(struct interacts *); double fanglscale(double, struct ia_param *, int which); //DEBUG printf ("do energy 111 \n\n"); closestdist(interact); repenergy = erepulsive(interact); if ( ( interact->dist > interact->param->rcut ) || ( interact->param->epsilon == 0.0 ) ) atrenergy = 0.0; else { /*calculate closest distance attractive energy*/ if (interact->dist < interact->param->pdis) atrenergy = -interact->param->epsilon; else { atrenergy = cos(PIH*(interact->dist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon ; } /*scaling function for the length of spherocylinder within cutoff*/ if (interact->param->geotype [0] < SP) halfl = interact->param->half_len[0]; else halfl = interact->param->half_len[1]; b = sqrt(interact->param->rcut*interact->param->rcut-interact->dist*interact->dist); if ( interact->contt + b > halfl ) f0 = halfl; else f0 = interact->contt + b; if ( interact->contt - b < -halfl ) f0 -= -halfl; else f0 -= interact->contt - b; atrenergy *= f0; //if (atrenergy < 0) printf ("atraction %f\n",atrenergy); //fprintf (stderr, "attraction211 %.8f x: %.8f y: %.8f z: %.8f \n",atrenergy,vec1.x,vec1.y,vec1.z); //exit(1); } return repenergy+atrenergy; } /*..............................................................................*/ /* * Determines total energy of spherocylinder type 2 and sphere type 11 */ double e_psc_spa(struct interacts * interact) { double atrenergy, repenergy; void closestdist(struct interacts *); double erepulsive(struct interacts *); double eattractive_psc_spa(struct interacts *, int); //DEBUG_SIM("do energy 211") ; closestdist(interact); repenergy = erepulsive(interact); //DEBUG_SIM("got the rep. energy"); if ( ( interact->dist > interact->param->rcut ) || ( interact->param->epsilon == 0.0 ) ) atrenergy = 0.0; else { BOOL firstCH=FALSE, secondCH=FALSE; struct vector olddir1 = interact->part1->dir; struct vector olddir2 = interact->part2->dir; if ( (interact->param->geotype[0] == CHPSC) || (interact->param->geotype[0] == TCHPSC) ) firstCH = TRUE; if ( (interact->param->geotype[1] == CHPSC) || (interact->param->geotype[1] == TCHPSC) ) secondCH = TRUE; if(firstCH) interact->part1->dir = interact->part1->chdir[0]; if(secondCH) interact->part2->dir = interact->part2->chdir[0]; if ((firstCH) || (secondCH) ) { closestdist(interact); } atrenergy = eattractive_psc_spa(interact,0); /*addition of interaction of second patches*/ if ( (interact->param->geotype[0] == TPSC) || (interact->param->geotype[0] == TCHPSC) || (interact->param->geotype[1] == TPSC) ||(interact->param->geotype[1] == TCHPSC) ) { BOOL firstT=FALSE, secondT=FALSE; if ( (interact->param->geotype[0] == TPSC) || (interact->param->geotype[0] == TCHPSC) ) firstT = TRUE; if ( (interact->param->geotype[1] == TPSC) ||(interact->param->geotype[1] == TCHPSC) ) secondT = TRUE; if (firstT) { if (firstCH) { interact->part1->dir = interact->part1->chdir[1]; closestdist(interact); } atrenergy += eattractive_psc_spa(interact,1); } if (secondT) { if(secondCH) { interact->part2->dir = interact->part2->chdir[1]; closestdist(interact); } atrenergy += eattractive_psc_spa(interact,1); } if ( (firstT) && (secondT) ) { fprintf (stderr, "ERROR PSC should interact s SPA but got two PSC \n"); exit(1); } } if (firstCH) interact->part1->dir = olddir1; if (secondCH) interact->part2->dir = olddir2; } return repenergy+atrenergy; } /* * Determines attractive energy of spherocylinder type 2 and sphere type 11 */ double eattractive_psc_spa(struct interacts * interact, int patchnum1) { double atrenergy, a, b, f0, halfl; struct vector vec1; struct vector vec_perpproject(struct vector *, struct vector*); void normalise(struct vector *); double fanglscale(double, struct ia_param *, int which); int which; /*calculate closest distance attractive energy*/ if (interact->dist < interact->param->pdis) atrenergy = -interact->param->epsilon; else { atrenergy = cos(PIH*(interact->dist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon ; } /*scaling function: angular dependence of patch1*/ if (interact->param->geotype[0] < SP) { which = 0; vec1=vec_perpproject(&interact->distvec, &interact->part1->dir); normalise(&vec1); a = DOT(vec1,interact->part1->patchdir[patchnum1]); halfl=interact->param->half_len[0]; } else { which = 1; vec1=vec_perpproject(&interact->distvec, &interact->part2->dir); normalise(&vec1); a = DOT(vec1,interact->part2->patchdir[patchnum1]); halfl=interact->param->half_len[1]; } /*scaling function for the length of spherocylinder within cutoff*/ b = sqrt(interact->param->rcut*interact->param->rcut-interact->dist*interact->dist); if ( interact->contt + b > halfl ) f0 = halfl; else f0 = interact->contt + b; if ( interact->contt - b < -halfl ) f0 -= -halfl; else f0 -= interact->contt - b; atrenergy *= fanglscale(a,interact->param, which)*f0; //if (atrenergy < 0) printf ("atraction %f\n",atrenergy); //fprintf (stderr, "attraction211 %.8f x: %.8f y: %.8f z: %.8f \n",atrenergy,vec1.x,vec1.y,vec1.z); //exit(1); return atrenergy; } /*..............................................................................*/ /* Determines total energy of spherocylinder type 3 and sphere type 11 */ double e_cpsc_spa(struct interacts * interact) { double atrenergy, repenergy, halfl; void closestdist(struct interacts *); double erepulsive(struct interacts *); double eattractive_cpsc_spa(struct interacts *,int); //DEBUG_SIM("do energy 311") ; closestdist(interact); repenergy = erepulsive(interact); //DEBUG_SIM("got the rep. energy"); if (interact->param->geotype[0] < SP) { halfl=interact->param->half_len[0]; } else { halfl=interact->param->half_len[1]; } if ( ( interact->dist > interact->param->rcut ) || ( interact->param->epsilon == 0.0 ) || ( interact->dist > interact->param->rcut ) || (interact->contt > halfl) || (interact->contt < -halfl) ) atrenergy = 0.0; else { BOOL firstCH=FALSE, secondCH=FALSE; struct vector olddir1 = interact->part1->dir; struct vector olddir2 = interact->part2->dir; if ( (interact->param->geotype[0] == CHCPSC) || (interact->param->geotype[0] == TCHCPSC) ) firstCH = TRUE; if ( (interact->param->geotype[1] == CHCPSC) || (interact->param->geotype[1] == TCHCPSC) ) secondCH = TRUE; if(firstCH) interact->part1->dir = interact->part1->chdir[0]; if(secondCH) interact->part2->dir = interact->part2->chdir[0]; if ((firstCH) || (secondCH) ) { closestdist(interact); } atrenergy = eattractive_cpsc_spa(interact,0); /*addition of interaction of second patches*/ if ( (interact->param->geotype[0] == TCPSC) || (interact->param->geotype[0] == TCHCPSC) || (interact->param->geotype[1] == TCPSC) ||(interact->param->geotype[1] == TCHCPSC) ) { BOOL firstT=FALSE, secondT=FALSE; if ( (interact->param->geotype[0] == TCPSC) || (interact->param->geotype[0] == TCHCPSC) ) firstT = TRUE; if ( (interact->param->geotype[1] == TCPSC) ||(interact->param->geotype[1] == TCHCPSC) ) secondT = TRUE; if (firstT) { if (firstCH) { interact->part1->dir = interact->part1->chdir[1]; closestdist(interact); } atrenergy += eattractive_cpsc_cpsc(interact,1,0); } if (secondT) { if(secondCH) { interact->part2->dir = interact->part2->chdir[1]; closestdist(interact); } atrenergy += eattractive_cpsc_cpsc(interact,0,1); } if ( (firstT) && (secondT) ) { fprintf (stderr, "ERROR PSC should interact s SPA but got two PSC \n"); exit(1); } } if (firstCH) interact->part1->dir = olddir1; if (secondCH) interact->part2->dir = olddir2; } return repenergy+atrenergy; } /* Determines attractive energy of spherocylinder type 3 and sphere type 11 */ double eattractive_cpsc_spa(struct interacts * interact,int patchnum1) { double atrenergy, a, b, f0, halfl; struct vector vec1; int which; struct vector vec_perpproject(struct vector *, struct vector*); void normalise(struct vector *); double fanglscale(double, struct ia_param *, int which); /*if it is in cylindrical part c>-halfl and c<halfl*/ /*calculate closest distance attractive energy*/ if (interact->dist < interact->param->pdis) atrenergy = -interact->param->epsilon; else { atrenergy = cos(PIH*(interact->dist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon ; } /*scaling function: angular dependence of patch1*/ if (interact->param->geotype[0] < SP) { which = 0; vec1=vec_perpproject(&interact->distvec, &interact->part1->dir); normalise(&vec1); a = DOT(vec1,interact->part1->patchdir[patchnum1]); halfl = interact->param->half_len[0]; } else { which = 1; vec1=vec_perpproject(&interact->distvec, &interact->part2->dir); normalise(&vec1); a = DOT(vec1,interact->part2->patchdir[patchnum1]); halfl = interact->param->half_len[1]; } /*scaling function for the length of spherocylinder within cutoff*/ b = sqrt(interact->param->rcut*interact->param->rcut-interact->dist*interact->dist); if ( interact->contt + b > halfl ) f0 = halfl; else f0 = interact->contt + b; if ( interact->contt - b < -halfl ) f0 -= -halfl; else f0 -= interact->contt - b; atrenergy *= fanglscale(a,interact->param, which)*f0; //if (atrenergy < 0) printf ("atraction %f\n",atrenergy); //fprintf (stderr, "attraction311 %.8f a: %.8f\n",atrenergy,a); //exit(1); return atrenergy; } /*..............................................................................*/ /* Determines total energy of two spherocylinders type 11 */ double e_2sca_or_2spa(struct interacts * interact) { double repenergy, atrenergy; double erepulsive(struct interacts *); void closestdist(struct interacts *); closestdist(interact); repenergy = erepulsive(interact); if ( ( interact->dist > interact->param->rcut ) || ( interact->param->epsilon == 0.0 ) ) atrenergy = 0.0; else { if (interact->dist < interact->param->pdis) atrenergy = -interact->param->epsilon; else { atrenergy = cos(PIH*(interact->dist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon ; } } return repenergy+atrenergy; } /*..............................................................................*/ /* Determines total energy with purely repulsive types */ double e_spn_or_scn(struct interacts * interact) { double repenergy; double erepulsive(struct interacts *); void closestdist(struct interacts *); closestdist(interact); repenergy = erepulsive(interact); return repenergy; } /*..............................................................................*/ /* Determines repulsive energy of two spherocylinders */ double erepulsive(struct interacts * interact) { double repenergy, en6; /* WCA repulsion */ if (interact->dist > interact->param->rcutwca) repenergy = 0.0; else { en6 = pow((interact->param->sigma/interact->dist),6); repenergy = 4*en6*(en6-1) + 1.0; } //printf("repenergy: %f dist: %f\n",repenergy, interact->dist); return repenergy; } /*..............................................................................*/ /* Indicates not yet programmed interaction */ double enoexist(struct interacts * interact) { double energy=0.0; fprintf (stderr, "ERROR: We have not programed interaction of types %d and %d\n", interact->part1->type,interact->part2->type); exit (1); return energy; } /* function for calculation of harmonic potential*/ double harmonic(double aktualvalue, double eqvalue, double springconst) { return springconst*(aktualvalue-eqvalue)*(aktualvalue-eqvalue)*0.5; } /*..............................................................................*/ /* Determines bond energy */ double bondenergy(long num1, long num2, struct interacts * interact, struct topo * topo, struct conf * conf) { double energy=0.0, bondlength, halfl; struct vector vec1, vec2, vecbond; int * geotype = interact->param->geotype; struct vector image(struct vector, struct vector, struct vector); double harmonic(double, double, double); /*interaction with nearest neighbours -harmonic*/ if ((topo->chainparam[conf->particle[num1].chaint]).bond1c >= 0) { if (num2 == topo->conlist[num1][1]) { /*num1 is connected to num2 by tail*/ if ( (geotype[0] >= SP) && (geotype[1] >= SP) ) energy = harmonic(interact->distcm,topo->chainparam[conf->particle[num1].chaint].bond1eq,topo->chainparam[conf->particle[num1].chaint].bond1c); else { if (geotype[0] < SP) halfl=interact->param->half_len[0]; else halfl = 0.0; vec1.x=conf->particle[num1].pos.x - conf->particle[num1].dir.x * halfl /conf->box.x; vec1.y=conf->particle[num1].pos.y - conf->particle[num1].dir.y * halfl /conf->box.y; vec1.z=conf->particle[num1].pos.z - conf->particle[num1].dir.z * halfl /conf->box.z; if (geotype[1] < SP) halfl=interact->param->half_len[1]; else halfl = 0.0; vec2.x=conf->particle[num2].pos.x + conf->particle[num2].dir.x * halfl /conf->box.x; vec2.y=conf->particle[num2].pos.y + conf->particle[num2].dir.y * halfl /conf->box.y; vec2.z=conf->particle[num2].pos.z + conf->particle[num2].dir.z * halfl /conf->box.z; vecbond = image(vec1, vec2, conf->box); bondlength = sqrt(DOT(vecbond,vecbond)); energy = harmonic(bondlength,topo->chainparam[conf->particle[num1].chaint].bond1eq,topo->chainparam[conf->particle[num1].chaint].bond1c); } } else { if (num2 == topo->conlist[num1][0]) { /*num1 is connected to num2 by head*/ if ( (geotype[0] >= SP) && (geotype[1] >= SP) ) energy = harmonic(interact->distcm,topo->chainparam[conf->particle[num1].chaint].bond1eq,topo->chainparam[conf->particle[num1].chaint].bond1c); else { if (geotype[0] < SP) halfl=interact->param->half_len[0]; else halfl = 0.0; vec1.x=conf->particle[num1].pos.x + conf->particle[num1].dir.x * halfl /conf->box.x; vec1.y=conf->particle[num1].pos.y + conf->particle[num1].dir.y * halfl /conf->box.y; vec1.z=conf->particle[num1].pos.z + conf->particle[num1].dir.z * halfl /conf->box.z; if (geotype[0] < SP) halfl=interact->param->half_len[0]; else halfl = 0.0; vec2.x=conf->particle[num2].pos.x - conf->particle[num2].dir.x * halfl /conf->box.x; vec2.y=conf->particle[num2].pos.y - conf->particle[num2].dir.y * halfl /conf->box.y; vec2.z=conf->particle[num2].pos.z - conf->particle[num2].dir.z * halfl /conf->box.z; vecbond = image(vec1, vec2, conf->box); bondlength = sqrt(DOT(vecbond,vecbond)); energy = harmonic(bondlength,topo->chainparam[conf->particle[num1].chaint].bond1eq,topo->chainparam[conf->particle[num1].chaint].bond1c); } } } } /*interaction with second nearest neighbours -harmonic*/ if (topo->chainparam[conf->particle[num1].chaint].bond2c >= 0) { if (num2 == topo->conlist[num1][2]) { /*num1 is connected to num2 by tail*/ if ( (geotype[0] >= SP) && (geotype[1] >= SP) ) energy = harmonic(interact->distcm,topo->chainparam[conf->particle[num1].chaint].bond2eq,topo->chainparam[conf->particle[num1].chaint].bond2c); else { vecbond = image(conf->particle[num1].pos, conf->particle[num2].pos, conf->box); bondlength = sqrt(DOT(vecbond,vecbond)); energy = harmonic(bondlength,topo->chainparam[conf->particle[num1].chaint].bond2eq,topo->chainparam[conf->particle[num1].chaint].bond2c); } } else { if (num2 == topo->conlist[num1][3]) { /*num1 is connected to num2 by head*/ if ( (geotype[0] >= SP) && (geotype[1] >= SP) ) energy = harmonic(interact->distcm,topo->chainparam[conf->particle[num1].chaint].bond2eq,topo->chainparam[conf->particle[num1].chaint].bond2c); else { vecbond = image(conf->particle[num1].pos, conf->particle[num2].pos, conf->box); bondlength = sqrt(DOT(vecbond,vecbond)); energy = harmonic(bondlength,topo->chainparam[conf->particle[num1].chaint].bond2eq,topo->chainparam[conf->particle[num1].chaint].bond2c); } } } } /*interaction with nearest neighbours - direct harmonic bond*/ if ((topo->chainparam[conf->particle[num1].chaint]).bonddc > 0) { if (num2 == topo->conlist[num1][1]) { /*num1 is connected to num2 by tail*/ if ( (geotype[0] >= SP) && (geotype[1] >= SP) ) energy = harmonic(interact->distcm,topo->chainparam[conf->particle[num1].chaint].bonddeq,topo->chainparam[conf->particle[num1].chaint].bonddc); else { if (geotype[0] < SP) halfl=interact->param->half_len[0]; else halfl = 0.0; vec1.x=conf->particle[num1].pos.x - conf->particle[num1].dir.x * halfl /conf->box.x; vec1.y=conf->particle[num1].pos.y - conf->particle[num1].dir.y * halfl /conf->box.y; vec1.z=conf->particle[num1].pos.z - conf->particle[num1].dir.z * halfl /conf->box.z; if (geotype[1] < SP) halfl=interact->param->half_len[1]; else halfl = 0.0; vec2.x=conf->particle[num2].pos.x + conf->particle[num2].dir.x * (halfl + topo->chainparam[conf->particle[num1].chaint].bonddeq) /conf->box.x ; vec2.y=conf->particle[num2].pos.y + conf->particle[num2].dir.y * (halfl + topo->chainparam[conf->particle[num1].chaint].bonddeq) /conf->box.y ; vec2.z=conf->particle[num2].pos.z + conf->particle[num2].dir.z * (halfl + topo->chainparam[conf->particle[num1].chaint].bonddeq) /conf->box.z ; vecbond = image(vec1, vec2, conf->box); bondlength = sqrt(DOT(vecbond,vecbond)); energy = harmonic(bondlength,0.0,topo->chainparam[conf->particle[num1].chaint].bonddc); } } else { if (num2 == topo->conlist[num1][0]) { /*num1 is connected to num2 by head*/ if ( (geotype[0] >= SP) && (geotype[1] >= SP) ) energy = harmonic(interact->distcm,topo->chainparam[conf->particle[num1].chaint].bond1eq,topo->chainparam[conf->particle[num1].chaint].bond1c); else { if (geotype[0] < SP) halfl=interact->param->half_len[0]; else halfl = 0.0; vec1.x=conf->particle[num1].pos.x + conf->particle[num1].dir.x * (halfl + topo->chainparam[conf->particle[num1].chaint].bonddeq) /conf->box.x ; vec1.y=conf->particle[num1].pos.y + conf->particle[num1].dir.y * (halfl + topo->chainparam[conf->particle[num1].chaint].bonddeq) /conf->box.y ; vec1.z=conf->particle[num1].pos.z + conf->particle[num1].dir.z * (halfl + topo->chainparam[conf->particle[num1].chaint].bonddeq) /conf->box.z ; if (geotype[0] < SP) halfl=interact->param->half_len[0]; else halfl = 0.0; vec2.x=conf->particle[num2].pos.x - conf->particle[num2].dir.x * halfl /conf->box.x; vec2.y=conf->particle[num2].pos.y - conf->particle[num2].dir.y * halfl /conf->box.y; vec2.z=conf->particle[num2].pos.z - conf->particle[num2].dir.z * halfl /conf->box.z; vecbond = image(vec1, vec2, conf->box); bondlength = sqrt(DOT(vecbond,vecbond)); energy = harmonic(bondlength,0.0,topo->chainparam[conf->particle[num1].chaint].bonddc); } } } } //printf("bondlength: %f\n",bondlength); // printf("bondener: %f\n",energy); return energy; } /*..............................................................................*/ /* Determines angle energy between spherocylinders */ double angleenergy(long num1, long num2, struct interacts * interact, struct topo * topo, struct conf * conf) { double energy=0.0, currangle, halfl; struct vector vec1, vec2; int * geotype = interact->param->geotype; struct vector image(struct vector, struct vector, struct vector); void normalise(struct vector *); double harmonic(double, double, double); /*angle interaction with nearest neighbours -harmonic*/ if ((topo->chainparam[conf->particle[num1].chaint]).angle1c >= 0) { if (num2 == topo->conlist[num1][0]) { /*num1 is connected to num2 by tail*/ if ( (geotype[0] >= SP) && (geotype[1] >= SP) ) /*spheres do not have this interaction*/ energy += 0.0; else { if (geotype[0] < SP) vec1 = conf->particle[num1].dir; else { halfl=interact->param->half_len[1]; //sphere angle is defined versus the end of spherocylinder vec1.x=conf->particle[num2].pos.x - conf->particle[num2].dir.x * halfl /conf->box.x; vec1.y=conf->particle[num2].pos.y - conf->particle[num2].dir.y * halfl /conf->box.y; vec1.z=conf->particle[num2].pos.z - conf->particle[num2].dir.z * halfl /conf->box.z; vec1 = image(vec1, conf->particle[num1].pos, conf->box); } if (geotype[1] < SP) vec2 = conf->particle[num2].dir; else { halfl=interact->param->half_len[0]; vec2.x=conf->particle[num1].pos.x + conf->particle[num1].dir.x * halfl /conf->box.x; vec2.y=conf->particle[num1].pos.y + conf->particle[num1].dir.y * halfl /conf->box.y; vec2.z=conf->particle[num1].pos.z + conf->particle[num1].dir.z * halfl /conf->box.z; vec2 = image(vec2, conf->particle[num2].pos, conf->box); } normalise(&vec1); normalise(&vec2); currangle = acos(DOT(vec1,vec2)); energy += harmonic(currangle,topo->chainparam[conf->particle[num1].chaint].angle1eq,topo->chainparam[conf->particle[num1].chaint].angle1c); } } else { if (num2 == topo->conlist[num1][1]) { /*num1 is connected to num2 by head*/ if ( (geotype[0] >= SP) && (geotype[1] >= SP) ) /*spheres do not have this interaction*/ energy += 0.0; else { if (geotype[0] < SP) vec1 = conf->particle[num1].dir; else { halfl=interact->param->half_len[1]; //sphere angle is defined versus the end of spherocylinder vec1.x=conf->particle[num2].pos.x + conf->particle[num2].dir.x * halfl /conf->box.x; vec1.y=conf->particle[num2].pos.y + conf->particle[num2].dir.y * halfl /conf->box.y; vec1.z=conf->particle[num2].pos.z + conf->particle[num2].dir.z * halfl /conf->box.z; vec1 = image(vec1, conf->particle[num1].pos, conf->box); } if (geotype[1] < SP) vec2 = conf->particle[num2].dir; else { halfl=interact->param->half_len[0]; vec2.x=conf->particle[num1].pos.x - conf->particle[num1].dir.x * halfl /conf->box.x; vec2.y=conf->particle[num1].pos.y - conf->particle[num1].dir.y * halfl /conf->box.y; vec2.z=conf->particle[num1].pos.z - conf->particle[num1].dir.z * halfl /conf->box.z; vec2 = image(vec2, conf->particle[num2].pos, conf->box); } normalise(&vec1); normalise(&vec2); currangle = acos(DOT(vec1,vec2)); energy += harmonic(currangle,topo->chainparam[conf->particle[num2].chaint].angle1eq,topo->chainparam[conf->particle[num2].chaint].angle1c); } } } } /*interaction between the orientation of spherocylinders patches -harmonic*/ if (topo->chainparam[conf->particle[num1].chaint].angle2c >= 0) { if (num2 == topo->conlist[num1][0]) { /*num1 is connected to num2 by tail*/ if ( (geotype[0] < SP) && (geotype[1] < SP) ) { currangle = acos(DOT(conf->particle[num1].patchdir[0],conf->particle[num2].patchdir[0]) - DOT(conf->particle[num1].dir,conf->particle[num2].patchdir[0]) ); energy += harmonic(currangle,topo->chainparam[conf->particle[num1].chaint].angle2eq,topo->chainparam[conf->particle[num1].chaint].angle2c); } else { energy += 0.0; } } else { if (num2 == topo->conlist[num1][1]) { /*num1 is connected to num2 by head*/ if ( (geotype[0] < SP) && (geotype[1] < SP) ) { currangle = acos(DOT(conf->particle[num2].patchdir[0],conf->particle[num1].patchdir[0]) - DOT(conf->particle[num2].dir,conf->particle[num1].patchdir[0]) ); energy += harmonic(currangle,topo->chainparam[conf->particle[num2].chaint].angle2eq,topo->chainparam[conf->particle[num2].chaint].angle2c); } else { energy += 0.0; } } } } // printf("angleener: %f\n",energy); return energy; } /* cluses distance calculation*/ void closestdist(struct interacts * interact) { double c, d, halfl; struct vector mindist_segments(struct vector dir1, double halfl1, struct vector dir2, double halfl2, struct vector r_cm); double linemin(double, double); //printf("we have %d %d ",interact->param->geotype[0],interact->param->geotype[1] ); if ((interact->param->geotype[0] >= SP) && (interact->param->geotype[1] >= SP)) { /*we have two spheres - most common, do nothing*/ //printf("we have two spheres "); interact->distvec = interact->r_cm; interact->dist = sqrt(interact->dotrcm); interact->distcm = interact->dist; } else { if ((interact->param->geotype[0] < SP) && (interact->param->geotype[1] < SP)) { /*we have two spherocylinders*/ interact->distvec = mindist_segments(interact->part1->dir,interact->param->half_len[0], interact->part2->dir, interact->param->half_len[1], interact->r_cm); interact->dist=sqrt(DOT(interact->distvec,interact->distvec)); } else { if (interact->param->geotype[0] < SP) { /*We have one spherocylinder -it is first one*/ halfl=interact->param->half_len[0];/*finding closest vector from sphyrocylinder to sphere*/ c = DOT(interact->part1->dir,interact->r_cm); if (c >= halfl) d = halfl; else { if (c > -halfl) d = c; else d = -halfl; } interact->contt = c; interact->distvec.x = - interact->r_cm.x + interact->part1->dir.x * d; interact->distvec.y = - interact->r_cm.y + interact->part1->dir.y * d; interact->distvec.z = - interact->r_cm.z + interact->part1->dir.z * d; interact->dist=sqrt(DOT(interact->distvec,interact->distvec)); } else { /*lst option first one is sphere second one spherocylinder*/ halfl=interact->param->half_len[1]; /*finding closest vector from sphyrocylinder to sphere*/ c = DOT(interact->part2->dir,interact->r_cm); if (c >= halfl) d = halfl; else { if (c > -halfl) d = c; else d = -halfl; } interact->contt = -c; interact->distvec.x = interact->r_cm.x - interact->part2->dir.x * d; interact->distvec.y = interact->r_cm.y - interact->part2->dir.y * d; interact->distvec.z = interact->r_cm.z - interact->part2->dir.z * d; interact->dist=sqrt(DOT(interact->distvec,interact->distvec)); } } } } /*..............................................................................*/ /* Determines energy of two particles */ double paire(long num1, long num2, double (* intfce[MAXT][MAXT])(struct interacts *), struct topo * topo, struct conf * conf) { double energy=0.0; /* energy*/ struct vector r_cm; /* Vector between centres of mass from part2 to part1*/ struct interacts interact; /*interaction parameters*/ double bondenergy(long, long, struct interacts *, struct topo * topo, struct conf * conf); double angleenergy(long, long, struct interacts *, struct topo * topo, struct conf * conf); /*Placing interactin particle in unit box and finding vector connecting CM*/ /*r_cm = image(part1.pos, part2.pos, box); explicit statement below for performance optimization*/ r_cm.x = conf->particle[num1].pos.x - conf->particle[num2].pos.x; r_cm.y = conf->particle[num1].pos.y - conf->particle[num2].pos.y; r_cm.z = conf->particle[num1].pos.z - conf->particle[num2].pos.z; if ( r_cm.x < 0 ) r_cm.x = conf->box.x * (r_cm.x - (double)( (long)(r_cm.x-0.5) ) ); else r_cm.x = conf->box.x * (r_cm.x - (double)( (long)(r_cm.x+0.5) ) ); if ( r_cm.y < 0 ) r_cm.y = conf->box.y * (r_cm.y - (double)( (long)(r_cm.y-0.5) ) ); else r_cm.y = conf->box.y * (r_cm.y - (double)( (long)(r_cm.y+0.5) ) ); if ( r_cm.z < 0 ) r_cm.z = conf->box.z * (r_cm.z - (double)( (long)(r_cm.z-0.5) ) ); else r_cm.z = conf->box.z * (r_cm.z - (double)( (long)(r_cm.z+0.5) ) ); interact.dotrcm = DOT(r_cm,r_cm); if ( interact.dotrcm > topo->sqmaxcut) return 0.0; /* distance so far that even spherocylinders cannot be within cutoff */ interact.r_cm=r_cm; interact.contt = 0; interact.distvec.x = 0; interact.distvec.y = 0; interact.distvec.z = 0; interact.box = conf->box; interact.part1 = &conf->particle[num1]; interact.part2 = &conf->particle[num2]; interact.param = topo->ia_params[conf->particle[num1].type] + conf->particle[num2].type; if(intfce[conf->particle[num1].type][conf->particle[num2].type] == NULL){ fprintf(stderr, "interaction function for type %d and %d not defined!\n", conf->particle[num1].type, conf->particle[num2].type); } energy = (*intfce[conf->particle[num1].type][conf->particle[num2].type])( &interact); //printf("num: %ld %ld e: %f dist: %f",num1,num2,energy,interact.dist); energy += bondenergy ( num1, num2, &interact, topo, conf); energy += angleenergy ( num1, num2, &interact, topo, conf); //printf(" e: %f\n",energy); return energy; } /*...........................................................................*/ /*Calculates interaction of target particle and external field version 2 calculate projection of spherocylinder in direction of patch and calculate interacting line segment within cutoff */ double extere2 (long target, struct topo * topo, struct conf * conf) { double repenergy=0.0,atrenergy=0.0; /* energy*/ double rcmz; /* z distance between*/ double ndist; /* distance for CM of interacting line segment*/ double interendz; /* z coordinate of interaction end*/ struct interacts interact; /* interaction parameters*/ double orient; double halfl; BOOL positive, orientin; struct vector olddir; struct vector project; /*vector for projection down to plane */ double erepulsive(struct interacts *); // struct vector vec_perpproject(struct vector*, struct vector*); // void normalise(struct vector *); double fanglscale(double, struct ia_param *, int which); void exter2_closestdist(struct interacts * interact, BOOL *positive, BOOL *orientin, double *orient, double *rcmz,double *interendz, struct vector *project); double exter2_atre(struct interacts * interact,int *orientin, double *rcmz, double *interendz, BOOL *positive, double orient,struct vector *project, double *ndist,int, double ); /* calcualte distance to center of mass*/ if ( conf->particle[target].pos.z < 0 ) { rcmz = conf->box.z * (conf->particle[target].pos.z - (double)( (long)(conf->particle[target].pos.z - 0.5) ) ); } else { rcmz = conf->box.z * (conf->particle[target].pos.z - (double)( (long)(conf->particle[target].pos.z + 0.5) ) ); } project.x=0; project.y=0; if (rcmz < 0) { interact.dist = -rcmz; positive = FALSE; interendz = -1.0; project.z = 1.0; } else { interact.dist = rcmz; positive = TRUE; interendz = 1.0; project.z = -1.0; } interact.dotrcm = rcmz * rcmz; if ( interact.dotrcm > topo->exter.sqmaxcut) return 0.0; /* distance so far that even spherocylinders cannot be within cutoff */ interact.distvec.z = interact.r_cm.z; interact.distcm = interact.dist; interact.box = conf->box; interact.part1 = &conf->particle[target]; interact.param = &topo->exter.interactions[conf->particle[target].type]; halfl = 0.5* topo->exter.interactions[conf->particle[target].type].len[0]; ndist = interact.dist; orientin = TRUE; orient = 0.0; exter2_closestdist(&interact,&positive,&orientin,&orient,&rcmz,&interendz,&project); /* now we have closest distance so we can calculate repulsion*/ repenergy = erepulsive(&interact); //printf("dist: %f",interact.dist); /*save chiral stuff*/ olddir = interact.part1->dir; if ((interact.param->geotype[0] == CHCPSC)||(interact.param->geotype[0] == CHPSC)) { interact.part1->dir = interact.part1->chdir[0]; exter2_closestdist(&interact,&positive,&orientin,&orient,&rcmz,&interendz,&project); } if (( interact.dist > interact.param->rcut ) || (interact.param->epsilon == 0.0 ) || ( (interact.part1->patchdir[0].z >0)&&(positive) ) || ( (interact.part1->patchdir[0].z <0)&&(!(positive)) ) ) atrenergy = 0.0; else { atrenergy = exter2_atre(&interact,&orientin,&rcmz,&interendz,&positive,orient,&project,&ndist,0,halfl); } if ((interact.param->geotype[0] == TCPSC)||(interact.param->geotype[0] == TPSC)|| (interact.param->geotype[0] == TCHCPSC)||(interact.param->geotype[0] == TCHPSC)) { if ((interact.param->geotype[0] == TCHCPSC)||(interact.param->geotype[0] == TCHPSC)) { interact.part1->dir = interact.part1->chdir[1]; exter2_closestdist(&interact,&positive,&orientin,&orient,&rcmz,&interendz,&project); } exter2_closestdist(&interact,&positive,&orientin,&orient,&rcmz,&interendz,&project); if (( interact.dist > interact.param->rcut ) || (interact.param->epsilon == 0.0 ) || ( (interact.part1->patchdir[1].z >0)&&(positive) ) || ( (interact.part1->patchdir[1].z <0)&&(!(positive)) ) ) atrenergy += 0.0; else { atrenergy += exter2_atre(&interact,&orientin,&rcmz,&interendz,&positive,orient,&project,&ndist,1,halfl); } } if ((interact.param->geotype[0] == CHCPSC)||(interact.param->geotype[0] == CHPSC)|| (interact.param->geotype[0] == TCHCPSC)||(interact.param->geotype[0] == TCHPSC) ) { interact.part1->dir = olddir; } //printf("%f %f \n",conf->particle[target].pos.z*conf->box.z,repenergy+atrenergy); return repenergy+atrenergy; } double exter2_atre(struct interacts * interact,int *orientin, double *rcmz, double *interendz, BOOL *positive, double orient,struct vector *project, double *ndist,int numpatch, double halfl) { struct vector pbeg,pend; /* projected spherocylinder begining and end*/ double a,length1,length2, f0,f1; struct vector cm1,cm2; /* centrar of interacting segments */ int line; struct vector partbeg,partend; /*closest and furthest point of particle*/ struct vector inters; double atrenergy=0.0; int cpsc_wall(struct vector* pbeg, struct vector* pend, struct vector* projectdir, struct vector* partdir, double* halfl,BOOL* orientin,BOOL* positive, double* rcmz, double * cut, struct vector* partbeg, struct vector* partend); int psc_wall(struct vector* pbeg, struct vector* pend, struct vector* projectdir, struct vector* partdir, BOOL* positive, double * cut, struct vector* partbeg, struct vector* partend); /*interaction with PATCHY SPHEROCYLINDERS*/ if ((interact->param->geotype[0] < SP)&&(interact->param->geotype[0] > SCA)) { //printf("partdir: %f %f %f \n ",interact->part1->dir.x,interact->part1->dir.y,interact->part1->dir.z); //printf("patchdir: %f %f %f \n ",interact->part1->patchdir[0].x,interact->part1->patchdir[0].y,interact->part1->patchdir[0].z); /* calculate position of closest and furthest point (begining and end of spherocylinder)*/ a = (*orientin-0.5)*2; /*if orientin a =1 else a=-1 */ partbeg.x = a * interact->part1->dir.x * halfl; partbeg.y = a * interact->part1->dir.y * halfl; partbeg.z = *rcmz + a * interact->part1->dir.z *halfl; partend.x = - a * interact->part1->dir.x * halfl; partend.y = - a * interact->part1->dir.y * halfl; partend.z = *rcmz - a * interact->part1->dir.z * halfl; //printf("partbeg %f %f %f partend %f %f %f \n",partbeg.x,partbeg.y,partbeg.z,partend.x,partend.y,partend.z); /*calculate interacting line segment and its cm of spherocylinder*/ /*calculate end point z*/ if ( (interact->param->rcut - interact->dist)/fabs(interact->part1->dir.z) < 2.0*halfl ){ /*if cutoff goes through spherocylinder the end point is at cutoff*/ *interendz *= interact->param->rcut; } else { /*endpoint is at the end of spherocylinders*/ *interendz = partend.z; } /*calculate CM of interacting line segment of spherocylinder*/ if (*positive) { cm1.z = AVER(*interendz,interact->dist); } else { cm1.z = AVER(*interendz,-interact->dist); } if (interact->part1->dir.z != 0.0 ) { a = (*interendz - cm1.z ) / interact->part1->dir.z; length1= -orient*2.0*a; a = a + orient*halfl; } else { a = 0.0; length1 = 2.0*halfl; } //printf("len1: %f rcm %f interz %f cutoff %f \n",length1,rcmz, interendz,interact.dist); cm1.x = interact->part1->dir.x * a; cm1.y = interact->part1->dir.y * a; /* we have interacting segment*/ if ((interact->param->geotype[0] == CPSC)||(interact->param->geotype[0] == CHCPSC)) { /*CPSC type*/ if ( ((*interendz >= interact->dist)&&(*positive)) || ((*interendz <= -interact->dist)&&(!(*positive))) ){ /*test if projection is not all out of interaction*/ line = cpsc_wall(&pbeg,&pend,project,&interact->part1->dir, \ &interact->param->half_len[0],orientin,positive,rcmz,&interact->param->rcut,&partbeg,&partend); //printf("line: %d beg %f %f end %f %f \n",line,pbeg.x,pbeg.y,pend.x,pend.y); } else { line = 0; } } else { /*PSC and CHPSC interaction with wall */ line = psc_wall(&pbeg,&pend,project,&interact->part1->dir, \ positive,&interact->param->rcut,&partbeg,&partend); //printf("line: %d beg %f %f end %f %f \n",line,pbeg.x,pbeg.y,pend.x,pend.y); } if (line > 0) { /*cm2 by average begining and end*/ cm2.x = AVER(pbeg.x,pend.x); cm2.y = AVER(pbeg.y,pend.y); cm2.z = 0.0; /*length by size of end-benining*/ length2 = sqrt( (pend.x-pbeg.x)*(pend.x-pbeg.x)+(pend.y-pbeg.y)*(pend.y-pbeg.y) ); inters.x = cm2.x - cm1.x; inters.y = cm2.y - cm1.y; inters.z = cm2.z - cm1.z; //printf("cm2 %f %f %f inters %f %f %f \n",cm2.x,cm2.y,cm2.z,inters.x,inters.y,inters.z); *ndist = sqrt(DOT(inters,inters)); if (*ndist < interact->param->pdis) { atrenergy = -interact->param->epsilon; } else { atrenergy= cos(PIH*(*ndist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon; } /* scaling function1: dependence on the length of intersetions plus*/ f0=(length1 + length2)*0.5; /*scaling with angle*/ f1 = fabs(interact->part1->patchdir[numpatch].z); atrenergy *= f0*f1; //printf(" %f %f %f %f %f %f %f \n",conf->particle[target].pos.z*conf->box.z,atrenergy, area, length1, length2,f0,ndist); //printf("%f %f %f %f\n",pbeg.x,pbeg.y,pend.x,pend.y); } else { atrenergy = 0.0; } } else { if (*ndist < interact->param->pdis) atrenergy = -interact->param->epsilon; else { atrenergy= cos(PIH*(*ndist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon; } /*add wall scaling wall area/ particle arear.. to reflect that we have a wall not sphere */ atrenergy *= (interact->param->rcut*interact->param->rcut - (*ndist)*(*ndist))/(interact->param->sigma*interact->param->sigma) ; } return atrenergy; } void exter2_closestdist(struct interacts * interact, BOOL *positive, BOOL *orientin, double *orient, double *rcmz,double *interendz, struct vector *project) { if (*rcmz < 0) { interact->dist = -(*rcmz); *positive = FALSE; *interendz = -1.0; project->z = 1.0; } else { interact->dist = (*rcmz); *positive = TRUE; *interendz = 1.0; project->z = -1.0; } /*psc closest is allways end closer to wall*/ if (interact->param->geotype[0] < SP ){ /*calculate closest point distance*/ if (interact->part1->dir.z > 0) { if (*positive) { *orientin = FALSE; *orient = -1.0; interact->dist = *rcmz -interact->part1->dir.z * interact->param->half_len[0]; } else { *orientin = TRUE; *orient = 1.0; interact->dist = -( *rcmz + interact->part1->dir.z * interact->param->half_len[0]); } } else { if (*positive) { *orientin = TRUE; *orient = 1.0; interact->dist = *rcmz + interact->part1->dir.z * interact->param->half_len[0]; } else { *orientin = FALSE; *orient = -1.0; interact->dist = -( *rcmz -interact->part1->dir.z * interact->param->half_len[0]); } } } } /*...........................................................................*/ /*Calculates interaction of target particle and external field calculate projection of patch of spherocylinder on wall evaluate intersection area and calculate interaction from that */ double exter_atre(struct interacts * interact,int *orientin, double *rcmz, double *interendz, BOOL *positive, double orient,struct vector *project, double *ndist,int numpatch,double halfl) { double area,a,b,c,r2; double atrenergy=0.0; /* energy*/ BOOL countend; struct vector cm1,cm2; /* centrar of interacting segments */ struct vector pbeg,pend; /* projected spherocylinder begining and end*/ struct vector inters,newdir; struct vector pbeg1,pend1,pbeg2,pend2,pextr1,pextr2,pextr3,pextr4; /*additinal point of projected patch for calculation of area */ double length1, cuttoproject, f0; int line, line1, line2,extra; struct vector partbeg,partend; /*closest and furthest point of particle*/ double erepulsive(struct interacts *); struct vector vec_perpproject(struct vector*, struct vector*); void normalise(struct vector *); double fanglscale(double, struct ia_param *, int which); struct vector vec_create(double, double, double); double areaeightpoints(struct vector*,struct vector*,struct vector*,struct vector*,struct vector*,struct vector*,struct vector*,struct vector*); int cpsc_wall(struct vector* pbeg, struct vector* pend, struct vector* projectdir, struct vector* partdir, double* halfl,BOOL* orientin,BOOL* positive, double* rcmz, double * cut, struct vector* partbeg, struct vector* partend); int psc_wall(struct vector* pbeg, struct vector* pend, struct vector* projectdir, struct vector* partdir, BOOL* positive, double * cut, struct vector* partbeg, struct vector* partend); int cutprojectatwall(struct vector* pextr1, struct vector* pextr2, struct vector* pextr3, struct vector* pextr4, struct vector* projectdir, struct vector* partdir, double * cutdist, struct vector *partbeg, struct vector *partend, struct vector *pend, double *cuttoproject, BOOL* orientin); void exter2_closestdist(struct interacts * interact, BOOL *positive, BOOL *orientin, double *orient, double *rcmz,double *interendz, struct vector *project); /*interaction with PATCHY SPHEROCYLINDERS*/ if ((interact->param->geotype[0] < SP)&&(interact->param->geotype[0] > SCA)) { //printf("partdir: %f %f %f \n ",interact->part1->dir.x,interact->part1->dir.y,interact->part1->dir.z); //printf("patchdir: %f %f %f \n ",interact->part1->patchdir[numpatch].x,interact->part1->patchdir[numpatch].y,interact->part1->patchdir[numpatch].z); /* calculate position of closest and furthest point (begining and end of spherocylinder)*/ a = (*orientin-0.5)*2; /*if orientin a =1 else a=-1 */ partbeg.x = a * interact->part1->dir.x * halfl; partbeg.y = a * interact->part1->dir.y * halfl; partbeg.z = *rcmz + a * interact->part1->dir.z * halfl; partend.x = - a * interact->part1->dir.x * halfl; partend.y = - a * interact->part1->dir.y * halfl; partend.z = *rcmz - a * interact->part1->dir.z * halfl; //printf("partbeg %f %f %f partend %f %f %f \n",partbeg.x,partbeg.y,partbeg.z,partend.x,partend.y,partend.z); /*calculate interacting line segment and its cm of spherocylinder*/ /*calculate end point z*/ if ( (interact->param->rcut - interact->dist)/fabs(interact->part1->dir.z) < halfl*2.0 ){ /*if cutoff goes through spherocylinder the end point is at cutoff*/ *interendz *= interact->param->rcut; } else { /*endpoint is at the end of spherocylinders*/ *interendz = partend.z; } /*calculate CM of interacting line segment of spherocylinder*/ if (*positive) { cm1.z = AVER(*interendz,interact->dist); } else { cm1.z = AVER(*interendz,-interact->dist); } if (interact->part1->dir.z != 0.0 ) { a = (*interendz - cm1.z ) / interact->part1->dir.z; length1= -orient*2.0*a; a = a + orient*halfl; } else { a = 0.0; length1 = 2.0*halfl; } //printf("len1: %f rcm %f interz %f cutoff %f \n",length1,rcmz, interendz,interact->dist); cm1.x = interact->part1->dir.x * a; cm1.y = interact->part1->dir.y * a; /*calculate projection on wall as infinite line and make it interacting segment*/ if (interact->part1->patchdir[numpatch].z != 0) { cuttoproject = -interact->param->rcut*interact->part1->patchdir[numpatch].z; /*z coordinate of point where projection is in cut distance*/ if ( ((partend.z < cuttoproject)&&(*positive)) || ((cuttoproject < partend.z)&&(!(*positive))) ){ cuttoproject = partend.z; } } else { cuttoproject = partbeg.z; } //printf("cutproject %f \n",cuttoproject); //printf("cm1 %f %f %f \n",cm1.x, cm1.y,cm1.z ); /* we have interacting segment*/ if ((interact->param->geotype[0] == CPSC)||(interact->param->geotype[0] == CHCPSC)) { /*CPSC type*/ if ( ((cuttoproject >= interact->dist)&&(*positive)) || ((cuttoproject <= -interact->dist)&&(!(*positive))) ){ /*test if projection is not all out of interaction*/ line = cpsc_wall(&pbeg,&pend,&interact->part1->patchdir[numpatch],&interact->part1->dir, \ &interact->param->half_len[0],orientin,positive,rcmz,&interact->param->rcut,&partbeg,&partend); //printf("line: %d beg %f %f end %f %f \n",line,pbeg.x,pbeg.y,pend.x,pend.y); } else { line = 0; } } else { /*PSC and CHPSC interaction with wall */ line = psc_wall(&pbeg,&pend,&interact->part1->patchdir[numpatch],&interact->part1->dir, \ positive,&interact->param->rcut,&partbeg,&partend); //printf("line: %d beg %f %f end %f %f \n",line,pbeg.x,pbeg.y,pend.x,pend.y); } if (line > 0) { area = 0.0; /*project cutoff boudaries*/ if (line == 2 ) { /*if projection end is on sphere of begining don't care about cylinder cutoff*/ extra = 0; } else { extra = cutprojectatwall(&pextr1, &pextr2, &pextr3, &pextr4, &interact->part1->patchdir[numpatch], \ &interact->part1->dir, &interact->param->rcut, &partbeg, &partend,&pend,&cuttoproject,orientin); } //printf("extr1: %d %f %f extr2 %f %f extr3 %f %f extr4 %f %f \n",extra,pextr1.x,pextr1.y,pextr2.x,pextr2.y,pextr3.x,pextr3.y,pextr4.x,pextr4.y); /*project patch boundaries on the first side*/ newdir=interact->part1->patchsides[0+2*numpatch]; line1 = cpsc_wall(&pbeg1,&pend1,&newdir,&interact->part1->dir, \ &interact->param->half_len[0],orientin,positive,rcmz,&interact->param->rcut,&partbeg,&partend); if ( ((interact->param->geotype[0] == PSC)||(interact->param->geotype[0] == CHPSC)) ) { line1 = psc_wall(&pbeg1,&pend1,&newdir,&interact->part1->dir, \ positive,&interact->param->rcut,&partbeg,&partend); } //printf("line1: %d beg1 %f %f end1 %f %f \n",line1,pbeg1.x,pbeg1.y,pend1.x,pend1.y); /*project patch boundaries on the second side*/ newdir=interact->part1->patchsides[1+2*numpatch]; line2 = cpsc_wall(&pbeg2,&pend2,&newdir,&interact->part1->dir, \ &interact->param->half_len[0],orientin,positive,rcmz,&interact->param->rcut,&partbeg,&partend); if ( ((interact->param->geotype[0] == PSC)||(interact->param->geotype[0] == CHPSC)) ) { line2 = psc_wall(&pbeg2,&pend2,&newdir,&interact->part1->dir, \ positive,&interact->param->rcut,&partbeg,&partend); } //printf("line2: %d beg2 %f %f end2 %f %f \n",line2,pbeg2.x,pbeg2.y,pend2.x,pend2.y); /*calculate area*/ if (extra == 0) { /*thish should only happen when there is PSC interacting only with end*/ if (line1 == 0) { if (line2==0) { /*circle around middle-pbeg*/ area = PI*( (partbeg.x-pbeg.x)*(partbeg.x-pbeg.x) + (partbeg.y-pbeg.y)*(partbeg.y-pbeg.y)); } else{ /* circle around middle-pbeg minus circle segment*/ a = AVER(pbeg2.x,pend2.x); b = AVER(pbeg2.y,pend2.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ r2 = ( (partbeg.x-pbeg.x)*(partbeg.x-pbeg.x) + (partbeg.y-pbeg.y)*(partbeg.y-pbeg.y)); /*radius squared*/ area = r2*(PI-acos(sqrt(c/r2))) + sqrt(r2*c-c*c); } } else { if (line2==0) { /* circle around middle-pbeg minus circle segment*/ a = AVER(pbeg1.x,pend1.x); b = AVER(pbeg1.y,pend1.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ r2 = ( (partbeg.x-pbeg.x)*(partbeg.x-pbeg.x) + (partbeg.y-pbeg.y)*(partbeg.y-pbeg.y)); /*radius squared*/ area = r2*(PI-acos(sqrt(c/r2))) + sqrt(r2*c-c*c); } else { //area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pend,&pend1,&pbeg1,NULL,NULL); /* B B2 E2 E E1 B1 */ /*circle minus two circle segments*/ r2 = ( (partbeg.x-pbeg.x)*(partbeg.x-pbeg.x) + (partbeg.y-pbeg.y)*(partbeg.y-pbeg.y)); /*radius squared*/ area = r2*PI; a = AVER(pbeg1.x,pend1.x); b = AVER(pbeg1.y,pend1.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ area += -r2*acos(sqrt(c/r2)) + sqrt(r2*c-c*c); a = AVER(pbeg2.x,pend2.x); b = AVER(pbeg2.y,pend2.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ area += -r2*acos(sqrt(c/r2)) + sqrt(r2*c-c*c); } } } else { b = fabs((pextr4.x-pextr2.x)*(pextr2.y-pend.y)- (pextr2.x-pend.x)*(pextr4.y-pextr2.y));/*pend on 42*/ c = fabs((pextr1.x-pextr3.x)*(pextr3.y-pend.y)- (pextr3.x-pend.x)*(pextr1.y-pextr3.y));/*pend on 13*/ if ( ( b< ZEROTOL) || ( c< ZEROTOL) ) countend = FALSE; else countend = TRUE; if (line1 == 0) { if (line2 == 0) { if ( countend ) { area = areaeightpoints(&pbeg,&pextr2,&pextr4,&pend,&pextr3,&pextr1,NULL,NULL);/* B 2 4 E 3 1 */ } else area = areaeightpoints(&pbeg,&pextr2,&pextr4,&pextr3,&pextr1,NULL,NULL,NULL);/* B 2 4 3 1 */ } else { a = fabs((pextr4.x-pextr2.x)*(pextr2.y-pend2.y)- (pextr2.x-pend2.x)*(pextr4.y-pextr2.y)); if ( a< ZEROTOL) /*pend2 on 42*/ { if ( countend ) { area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pend,&pextr3,&pextr1,NULL); /* B B2 E2 4 E 3 1 */ } else { area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pextr3,&pextr1,NULL,NULL); /* B B2 E2 4 3 1 */ } } else { a = fabs((pextr1.x-pextr3.x)*(pextr3.y-pend2.y)- (pextr3.x-pend2.x)*(pextr1.y-pextr3.y)); if ( a< ZEROTOL) /*pend2 on 13*/ { area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr1,NULL,NULL,NULL,NULL); /* B B2 E2 1 */ } else { /*pend2 on 34 or on begining sphere of psc*/ if (line2 == 2) { if ( countend ) { area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pend,&pextr3,&pextr1,NULL); /* B B2 E2 4 E 3 1 */ } else { area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pextr3,&pextr1,NULL,NULL); /* B B2 E2 4 3 1 */ } } else { if ( countend ) { area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pend,&pextr3,&pextr1,NULL,NULL); /* B B2 E2 E 3 1 */ } else { area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr3,&pextr1,NULL,NULL,NULL); /* B B2 E2 3 1 */ } } } } } } else { a = fabs((pextr4.x-pextr2.x)*(pextr2.y-pend1.y)- (pextr2.x-pend1.x)*(pextr4.y-pextr2.y)); if ( a< ZEROTOL) /*pend1 on 42*/ { if (line2 == 0) { area = areaeightpoints(&pbeg,&pextr2,&pend1,&pbeg1,NULL,NULL,NULL,NULL); /* B 2 E1 B1 */ } else { area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pend1,&pbeg1,NULL,NULL,NULL); /* B B2 E2 E1 B1 */ } } else { a = fabs((pextr1.x-pextr3.x)*(pextr3.y-pend1.y)- (pextr3.x-pend1.x)*(pextr1.y-pextr3.y)); if ( a< ZEROTOL) /*pend1 on 13*/ { if (line2 == 0) { if (countend) { area = areaeightpoints(&pbeg,&pextr2,&pextr4,&pend,&pextr3,&pend1,&pbeg1,NULL); /* B 2 4 E 3 E1 B1 */ } else { area = areaeightpoints(&pbeg,&pextr2,&pextr4,&pextr3,&pend1,&pbeg1,NULL,NULL); /* B 2 4 3 E1 B1 */ } } else { a = fabs((pextr4.x-pextr2.x)*(pextr2.y-pend2.y)- (pextr2.x-pend2.x)*(pextr4.y-pextr2.y)); if ( a< ZEROTOL) /*pend2 on 42*/ { if (countend) area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pend,&pextr3,&pend1,&pbeg1); /* B B2 E2 4 E 3 E1 B1 */ else area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pextr3,&pend1,&pbeg1,NULL); /* B B2 E2 4 3 E1 B1 */ } else { a = fabs((pextr3.x-pextr1.x)*(pextr1.y-pend2.y)- (pextr1.x-pend2.x)*(pextr3.y-pextr1.y)); if ( a< ZEROTOL) /*pend2 on 31*/ { area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pend1,&pbeg1,NULL,NULL,NULL); /* B B2 E2 E1 B1 */ } else { /*pend2 close to 34 or on begining sphere of psc*/ if (line2 == 2) { if (countend) area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pend,&pextr3,&pend1,&pbeg1); /* B B2 E2 4 E 3 E1 B1 */ else area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pextr3,&pend1,&pbeg1,NULL); /* B B2 E2 4 3 E1 B1 */ } else { if (countend) area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pend,&pextr3,&pend1,&pbeg1,NULL); /* B B2 E2 E 3 E1 B1 */ else area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr3,&pend1,&pbeg1,NULL,NULL); /* B B2 E2 3 E1 B1 */ } } } } } else {/*pend1 close to 34 or on beging sphere for psc*/ if (line2 == 0) { if (line1 ==2) { if (countend) area = areaeightpoints(&pbeg,&pextr2,&pextr4,&pend,&pextr3,&pend1,&pbeg1,NULL); /* B 2 4 E 3 E1 B1*/ else { area = areaeightpoints(&pbeg,&pextr2,&pextr4,&pextr3,&pend1,&pbeg1,NULL,NULL); /* B 2 4 3 E1 B1*/ } } else { if (countend) area = areaeightpoints(&pbeg,&pextr2,&pextr4,&pend,&pend1,&pbeg1,NULL,NULL); /* B 2 4 E E1 B1*/ else { area = areaeightpoints(&pbeg,&pextr2,&pextr4,&pend1,&pbeg1,NULL,NULL,NULL); /* B 2 4 E1 B1*/ } } } else { a = fabs((pextr4.x-pextr2.x)*(pextr2.y-pend2.y)- (pextr2.x-pend2.x)*(pextr4.y-pextr2.y)); if ( a< ZEROTOL) /* pend2 on 42 */ { if (countend) area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pend,&pend1,&pbeg1,NULL); /* B B2 E2 4 E E1 B1 */ else area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pend1,&pbeg1,NULL,NULL); /* B B2 E2 4 E1 B1 */ } else { /*pend1 and pend2 close to 34 or on beging sphere for psc*/ if (line2 == 2) { if (line1 == 2) { if (countend) area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pend,&pextr3,&pend1,&pbeg1); /* B B2 E2 4 E 3 E1 B1 */ else area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pextr3,&pend1,&pbeg1,NULL); /* B B2 E2 4 3 E1 B1 */ } else { if (countend) area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pend,&pend1,&pbeg1,NULL); /* B B2 E2 4 E E1 B1 */ else area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr4,&pend1,&pbeg1,NULL,NULL); /* B B2 E2 4 E1 B1 */ } } else { if (line1 == 2) { if (countend) area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pend,&pextr3,&pend1,&pbeg1,NULL); /* B B2 E2 E 3 E1 B1 */ else area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pextr3,&pend1,&pbeg1,NULL,NULL); /* B B2 E2 3 E1 B1 */ } else { if (countend) area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pend,&pend1,&pbeg1,NULL,NULL); /* B B2 E2 E E1 B1 */ else area = areaeightpoints(&pbeg,&pbeg2,&pend2,&pend1,&pbeg1,NULL,NULL,NULL); /* B B2 E2 E1 B1 */ } } } } } } } /*extra != 0*/ if ((interact->param->geotype[0] == PSC)||(interact->param->geotype[0] == CHPSC)) { if (line1==2) { /* add circle segment*/ a = AVER(pextr1.x,pend1.x); /*end to cutoff - pextr1 ,pend1 */ b = AVER(pextr1.y,pend1.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ r2 = ( (partbeg.x-pend1.x)*(partbeg.x-pend1.x) + (partbeg.y-pend1.y)*(partbeg.y-pend1.y)); /*radius squared*/ area += r2*acos(sqrt(c/r2)) - sqrt(r2*c-c*c); a = AVER(pbeg.x,pbeg1.x); /* between beginings - pbeg ,pbeg1 */ b = AVER(pbeg.y,pbeg1.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ area += r2*acos(sqrt(c/r2)) - sqrt(r2*c-c*c); } else { if (line1==0) { /* add circle segment*/ a = AVER(pextr1.x,pbeg.x); /* begining to cutoff*/ b = AVER(pextr1.y,pbeg.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ r2 = ( (partbeg.x-pbeg.x)*(partbeg.x-pbeg.x) + (partbeg.y-pbeg.y)*(partbeg.y-pbeg.y)); /*radius squared*/ area += r2*acos(sqrt(c/r2)) - sqrt(r2*c-c*c); } } if (line2==2) { /* add circle segment*/ a = AVER(pextr3.x,pend2.x); /*end to cutoff - pextr3 ,pend2 */ b = AVER(pextr3.y,pend2.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ r2 = ( (partbeg.x-pend2.x)*(partbeg.x-pend2.x) + (partbeg.y-pend2.y)*(partbeg.y-pend2.y)); /*radius squared*/ area += r2*acos(sqrt(c/r2)) - sqrt(r2*c-c*c); a = AVER(pbeg.x,pbeg2.x); /* between beginings - pbeg ,pbeg2 */ b = AVER(pbeg.y,pbeg2.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ area += r2*acos(sqrt(c/r2)) - sqrt(r2*c-c*c); } else { if (line2==0) { /* add circle segment*/ a = AVER(pextr3.x,pbeg.x); /* begining to cutoff*/ b = AVER(pextr3.y,pbeg.y); c = (partbeg.x-a)*(partbeg.x-a) + (partbeg.y-b)*(partbeg.y-b); /*height of triangle to segment*/ r2 = ( (partbeg.x-pbeg.x)*(partbeg.x-pbeg.x) + (partbeg.y-pbeg.y)*(partbeg.y-pbeg.y)); /*radius squared*/ area += r2*acos(sqrt(c/r2)) - sqrt(r2*c-c*c); } } } } /*area finished*/ /*cm2 by average begining and end*/ cm2.x = AVER(pbeg.x,pend.x); cm2.y = AVER(pbeg.y,pend.y); cm2.z = 0.0; /*length by size of end-benining*/ //length2 = sqrt( (pend.x-pbeg.x)*(pend.x-pbeg.x)+(pend.y-pbeg.y)*(pend.y-pbeg.y) ); inters.x = cm2.x - cm1.x; inters.y = cm2.y - cm1.y; inters.z = cm2.z - cm1.z; //printf("cm2 %f %f %f inters %f %f %f \n",cm2.x,cm2.y,cm2.z,inters.x,inters.y,inters.z); *ndist = sqrt(DOT(inters,inters)); if (*ndist < interact->param->pdis) { atrenergy = -interact->param->epsilon; } else { atrenergy= cos(PIH*(*ndist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon; } /* scaling function1: dependence on the length of intersetions plus SCALING WITH AREA*/ f0=(length1 + area / interact->param->sigma)*0.5; atrenergy *= f0; //printf(" %f %f %f %f %f %f %f %d %d %d \n",conf->particle[target].pos.z*conf->box.z,atrenergy, area, length1, length2,f0,ndist,extra,line1,line2); //printf("%f %f %f %f\n",pbeg.x,pbeg.y,pend.x,pend.y); //printf("%f %f %f %f %f %f\n",pbeg2.x,pend2.y,pextr2.x,pextr2.y,pextr1.x,pextr1.y); } else { atrenergy = 0.0; } } else { if (*ndist < interact->param->pdis) atrenergy = -interact->param->epsilon; else { atrenergy= cos(PIH*(*ndist-interact->param->pdis)/interact->param->pswitch); atrenergy *= -atrenergy*interact->param->epsilon; } /*add wall scaling wall area/ particle arear.. to reflect that we have a wall not sphere */ atrenergy *= (interact->param->rcut*interact->param->rcut - (*ndist)*(*ndist))/(interact->param->sigma*interact->param->sigma) ; } //printf("%f %f \n",conf->particle[target].pos.z*conf->box.z,atrenergy); return atrenergy; } /*..............................................................................*/ /* Initializes the array with the pointers to the energy function */ void init_intfce(double (* intfce[MAXT][MAXT])(struct interacts *), struct topo * topo){ // NB // Fill in the names of the functions for calculating the // interaction energy long geotype, other_geotype; int i, j; for(i = 0; i < MAXT; i++){ for(j = 0; j < MAXT; j++){ /* Initialize them as not existing */ intfce[i][j] = &enoexist; geotype = topo->ia_params[i][j].geotype[0]; other_geotype = topo->ia_params[i][j].geotype[1]; if ( ( (geotype == CHCPSC || geotype == CPSC || geotype == TCHCPSC || geotype == TCPSC) && (other_geotype == CHPSC || other_geotype == PSC || other_geotype == TCHPSC || other_geotype == TPSC) ) || ( (geotype == CHPSC || geotype == PSC || geotype == TCHPSC || geotype == TPSC) && (other_geotype == CHCPSC || other_geotype == CPSC || other_geotype == TCHCPSC || other_geotype == TCPSC) ) ) { intfce[i][j] = &e_psc_cpsc; } if ( (geotype == CHCPSC || geotype == CPSC || geotype == TCHCPSC || geotype == TCPSC) && (other_geotype == CHCPSC || other_geotype == CPSC || other_geotype == TCHCPSC || other_geotype == TCPSC) ){ intfce[i][j] = &e_cpsc_cpsc; } if ( (geotype == CHPSC || geotype == PSC || geotype == TCHPSC || geotype == TPSC) && (other_geotype == CHPSC || other_geotype == PSC || other_geotype == TCHPSC || other_geotype == TPSC) ){ intfce[i][j] = &e_psc_psc; } if(geotype == SCN || geotype == SPN || other_geotype == SCN || other_geotype == SPN){ intfce[i][j] = &e_spn_or_scn; } if((geotype == SCA && other_geotype == SCA) || (geotype == SPA && other_geotype == SPA)){ intfce[i][j] = &e_2sca_or_2spa; } if((geotype == SCA && other_geotype == SPA) || (geotype == SPA && other_geotype == SCA)){ intfce[i][j] = &e_spa_sca; } if(( (geotype == PSC || geotype == CHPSC || geotype == TCHPSC || geotype == TPSC) && other_geotype == SPA) || (geotype == SPA && (other_geotype == PSC||other_geotype == CHPSC || other_geotype == TCHPSC || other_geotype == TPSC) )){ intfce[i][j] = &e_psc_spa; } if(( (geotype == CPSC ||geotype == CHCPSC || geotype == TCHCPSC || geotype == TCPSC) && other_geotype == SPA) || (geotype == SPA && (other_geotype == CPSC||other_geotype == CHCPSC || other_geotype == TCHCPSC || other_geotype == TCPSC) )){ intfce[i][j] = &e_cpsc_spa; } } } } /*..............................................................................*/ /* Compare energy change to temperature and based on Boltzmann probability return either 0 to accept or 1 to reject the move */ int movetry(double energyold, double energynew, double temperature) { double ran2(long *); /*DEBUG printf (" Move trial: %13.8lf %13.8lf %13.8lf %13.8lf\n", energynew, energyold, temperature, ran2(&seed));*/ if (energynew <= energyold ) { return 0; } else { if (exp(-1.0*(energynew-energyold)/temperature) > ran2(&seed)) { return 0; } else { return 1; } } } /*..............................................................................*/ /* * Calculate the different energy contributions. This is a merge of the different * energy calculation functions (energyone, -chain, -all) * 0: all * 1: one * 2: chain */ double calc_energy(long target, double (* intfce[MAXT][MAXT])(struct interacts *), int mode, struct topo * topo, struct conf * conf, struct sim * sim, int chainnum) { long i=0,j=0; double paire(long, long, double (* intfce[MAXT][MAXT])(struct interacts *), struct topo * topo, struct conf * conf); // double extere(long, struct topo * topo, struct conf * conf); double extere2(long, struct topo * topo, struct conf * conf); //DEBUG_SIM("Calculate the energy with mode %d", mode) double energy = 0; /* Calculates energy between particle "target" and the rest. Returns energy */ if(mode == 1){ if (sim->pairlist_update) { #ifdef OMP #pragma omp parallel for private(i) reduction (+:energy) schedule (dynamic) #endif for (i = 0; i < sim->pairlist[target].num_pairs; i++){ energy+= paire(target, sim->pairlist[target].pairs[i], intfce, topo, conf); } } else{ #ifdef OMP #pragma omp parallel for private(i) reduction (+:energy) schedule (dynamic) #endif for (i = 0; i < target; i++) { energy+= paire(target, i, intfce, topo, conf); } #ifdef OMP #pragma omp parallel for private(i) reduction (+:energy) schedule (dynamic) #endif for (i = target + 1; i < topo->npart; i++) { energy+= paire(target, i, intfce, topo, conf); } } /*add interaction with external potential*/ if (topo->exter.exist) energy+= extere2(target,topo,conf); } /* * Calculates energy between particle "target" and the rest. skipping * particles from the given chain -particles has to be sorted in chain!! * so similar to energy one but with chain exception */ else if(mode == 2){ //#ifdef OMP //#pragma omp parallel for private(i) reduction (+:energy) schedule (dynamic) //#endif for (i = 0; i < target; i++) { if (i != topo->chainlist[chainnum][j]) { energy+= paire(target, i, intfce, topo, conf); } else { j++; } } j++; //#ifdef OMP //#pragma omp parallel for private(i) reduction (+:energy) schedule (dynamic) //#endif for (i = target + 1; i < topo->npart; i++) { if (i != topo->chainlist[chainnum][j]) { energy+= paire(target, i, intfce, topo, conf); } else { j++; } } /*add interaction with external potential*/ if (topo->exter.exist) energy+= extere2(target,topo,conf); } /* Calculates energy between all pairs. Returns energy */ else if(mode == 0){ #ifdef OMP #pragma omp parallel for private(i,j) reduction (+:energy) schedule (dynamic) #endif for (i = 0; i < topo->npart - 1; i++) { for (j = i + 1; j < topo->npart; j++) { energy+= paire(i, j, intfce, topo, conf); } /*for every particle add interaction with external potential*/ if (topo->exter.exist) energy+= extere2(i,topo,conf); } /*add interaction of last particle with external potential*/ if (topo->exter.exist) energy+= extere2(topo->npart-1,topo,conf); } else { fprintf(stderr, "ERROR: Wrong mode (%d) was given to calc_energy!", mode); return 0.0; } // DEBUG_SIM("Will return energy from calc_energy") //printf("energymove %f\n",energy); return energy; } /*..............................................................................*/ /* Checks for overlaps between particle "target" and the rest. Returns 1 if overlap detected, 0 otherwise. */ int forbidden(long npart, struct particles *particle, long target, struct vector box, struct ia_param ia_params[MAXT][MAXT]) { long test; int overlap(struct particles, struct particles, struct vector,struct ia_param [MAXT][MAXT]); for (test=0; test<npart; test++) { if (test != target) { if ( overlap(particle[target], particle[test], box, ia_params) ) { return 1; } } } return 0; } /*..............................................................................*/ /* Checks for overlaps between all pairs of particles. Returns 1 if overlap detected, 0 otherwise. */ int checkall(long npart, struct particles *particle, struct vector box, struct ia_param ia_params[MAXT][MAXT]) { long i, j; int overlap(struct particles, struct particles, struct vector, struct ia_param [MAXT][MAXT]); for (i=0; i<npart-1; i++) { for (j=i+1; j<npart; j++) { if ( overlap(particle[i], particle[j], box, ia_params) ) { return 1; } } } return 0; } /*..............................................................................*/ /* Optimize the maximum displacement within the specified limits and resets the acceptance counters to zero. */ void optimizestep(struct disp *x, double hi, double lo) { double newrmsd; newrmsd = (*x).mx * RATIO(*x); if ((*x).oldrmsd > 0) { if ( newrmsd < (*x).oldrmsd ) { if ( (*x).oldmx > 1 ) { (*x).mx /= 1.05; (*x).oldmx = 0.95; } else { (*x).mx *= 1.05; (*x).oldmx = 1.05; } } else { if ( (*x).oldmx > 1 ) { (*x).mx *= 1.05; (*x).oldmx = 1.05; } else { (*x).mx /= 1.05; (*x).oldmx = 0.95; } } } if (newrmsd > 0 ) (*x).oldrmsd = newrmsd; else { (*x).oldrmsd = 0.0; (*x).mx /= 1.05; (*x).oldmx = 0.95; } if ( (*x).mx > hi ) (*x).mx = hi; if ( (*x).mx < lo ) (*x).mx = lo; (*x).acc = (*x).rej = 0; } /*..............................................................................*/ /* Optimize the maximum rotation within the specified limits and resets the acceptance counters to zero. Rotation is given by cos of angle larger rotation = smaller cos */ void optimizerot(struct disp *x, double hi, double lo) { double newrmsd; newrmsd = (*x).mx * RATIO((*x)) ; if ((*x).oldrmsd > 0) { if ( newrmsd > (*x).oldrmsd ) { if ( (*x).oldmx > 1) { (*x).mx *= 0.99; (*x).oldmx *= 0.99; } else { (*x).mx *= 1.01; (*x).oldmx *= 1.01; } } else { if ( (*x).oldmx > 1) { (*x).mx *= 1.01; (*x).oldmx *= 1.01; } else { (*x).mx *= 0.99; (*x).oldmx *= 0.99; } } } if (newrmsd > 0 ) (*x).oldrmsd = newrmsd; else { (*x).oldrmsd = 0.0; (*x).mx *= 1.01; (*x).oldmx = 1.01; } if ( (*x).mx > hi ) (*x).mx = hi; if ( (*x).mx < lo ) (*x).mx = lo; (*x).acc = (*x).rej = 0; } /*................................................................................*/ /* Accumulate a value into the statistics and update the mean and rms values. */ void accumulate(struct stat *q, double x) { (*q).sum += x; (*q).sum2 += x*x; (*q).samples++; (*q).mean = (*q).sum / (*q).samples; (*q).rms = sqrt(fabs((*q).sum2 / (*q).samples - (*q).sum * (*q).sum / (*q).samples / (*q).samples)); } void printeqstat(struct disp *dat, double scale, int length) { int i; for (i=0;i<length;i++) { if (RATIO(dat[i]) > 0) printf (" TYPE %d %.6lf / %.6lf\n", i, dat[i].mx/scale,RATIO(dat[i])); } } int memoryalloc(struct conf * conf) { printf ("Allocating memory...\n"); conf->particle = malloc( sizeof(struct particles)*MAXN); if(conf->particle == NULL){ return 1; } return 0; } int memorydealloc(struct conf * conf, struct topo * topo, struct sim * sim) { int dealloc_pairlist(struct topo * topo, struct sim * sim); printf ("Deallocating memory...\n"); if (conf->particle != NULL) free(conf->particle); conf->particle = NULL; if (sim->clusterlist != NULL) free(sim->clusterlist); if (sim->clustersenergy != NULL) free(sim->clustersenergy); if(topo->switchlist){ free(topo->switchlist); } if (sim->pairlist_update) { if(dealloc_pairlist(topo, sim)){ return 1; } } return 0; } /*............................................................................*/ /** * nice malloc, which does the error checking for us */ void * xmalloc (size_t num){ void *new = malloc (num); if (!new){ fprintf(stderr, "Couldn't allocate any memory!\n"); exit(1); } return new; } /*............................................................................*/ /* *********************** GEOMETRICAL FUNCTIONS **************************** */ /*.........................PATCHY SPOHEROCYLINDERS INTERACTION....................*/ /*................................................................................*/ /* Calculate intersections of sc2 with a patch of sc1 and return them in */ int psc_intersect(struct particles * part1, struct particles * part2, double halfl1, double halfl2, struct vector r_cm, double intersections[5], double rcut, struct ia_param * param, int which, int patchnum) { int intrs; double a, b, c, d, e, x1, x2, rcut2; struct vector cm21, vec1, vec2, vec3, vec4; struct vector vec_crossproduct(struct vector, struct vector); struct vector vec_sub(struct vector, struct vector); struct vector vec_create(double, double, double); struct vector vec_scale(struct vector, double); struct vector vec_perpproject(struct vector*, struct vector*); struct quat quat_create(struct vector, double, double); void vec_rotate(struct vector *, struct quat); void normalise(struct vector *); int find_intersect_plane(struct particles *, struct particles *, double, struct vector, struct vector, double, double, double *); int test_intrpatch(struct particles *, struct vector, double, double, double *,int); intrs=0; rcut2=rcut*rcut; /*1- do intersections of spherocylinder2 with patch of spherocylinder1 at cut distance C*/ /*1a- test intersection with half planes of patch and look how far they are from spherocylinder. If closer then C we got itersection*/ /* plane1 */ /* find intersections of part2 with plane by par1 and patchsides[0] */ intrs+=find_intersect_plane(part1,part2,halfl2,r_cm,part1->patchsides[0+2*patchnum],rcut,param->pcanglsw[which+2*patchnum],intersections); // printf("plane1 %d\n", intrs); /* plane2 */ /* find intersections of part2 with plane by par1 and patchsides[1] */ intrs+=find_intersect_plane(part1,part2,halfl2,r_cm,part1->patchsides[1+2*patchnum],rcut,param->pcanglsw[which+2*patchnum],intersections); if ( (intrs == 2 ) && (param->pcanglsw[which+2*patchnum] <0) ) { fprintf (stderr, "ERROR: Patch is larger than 180 degrees and we are getting two segments - this hasnot been programed yet.\n\n"); exit (1); } // printf("plane2 %d\n", intrs); /*1b- test intersection with cylinder - it is at distance C*/ if (intrs < 2 ) { cm21=vec_scale(r_cm,-1.0); vec1=vec_crossproduct(cm21,part1->dir); vec2=vec_crossproduct(part2->dir,part1->dir); a = DOT(vec2,vec2); b = 2*DOT(vec1,vec2); c = -rcut*rcut + DOT(vec1,vec1); d = b*b - 4*a*c; if ( d >= 0) { /*there is intersection with infinite cylinder */ x1 = (-b+sqrt(d))*0.5/a;/*parameter on line of SC2 determining intersection*/ if ((x1 >=halfl2) || (x1 <= -halfl2)) intrs+=0; /*intersection is outside sc2*/ else { /* vectors from center os sc1 to intersection with infinite cylinder*/ vec1.x=part2->dir.x*x1-r_cm.x; vec1.y=part2->dir.y*x1-r_cm.y; vec1.z=part2->dir.z*x1-r_cm.z; e = DOT(part1->dir,vec1); if ((e >=halfl1) || (e <= -halfl1)) intrs+=0; /*intersection is outside sc1*/ else { intrs+=test_intrpatch(part1,vec1,param->pcanglsw[which+2*patchnum],x1,intersections,patchnum); } } if ( d > 0 ){ x2 = (-b-sqrt(d))*0.5/a;/*parameter on line of SC2 determining intersection*/ if ((x2 >=halfl2) || (x2 <= -halfl2)) intrs+=0; /*intersection is outside sc2*/ else { vec2.x = part2->dir.x*x2-r_cm.x; vec2.y = part2->dir.y*x2-r_cm.y; vec2.z = part2->dir.z*x2-r_cm.z; e = DOT(part1->dir,vec2); if ((e >=halfl1) || (e <= -halfl1)) intrs+=0; /*intersection is outside sc1*/ else { intrs+=test_intrpatch(part1,vec2,param->pcanglsw[which+2*patchnum],x2,intersections,patchnum); } } } } } // printf ("cylinder %d x1 %f x2 %f e %f\n", intrs, x1, x2, e); /*1c- test intersection with spheres at the end - it is at distace C*/ if (intrs < 2 ) { /*centers of spheres*/ /*relative to the CM of sc2*/ vec1.x = part1->dir.x*halfl1 - r_cm.x; vec1.y = part1->dir.y*halfl1 - r_cm.y; vec1.z = part1->dir.z*halfl1 - r_cm.z; vec2.x = -part1->dir.x*halfl1 - r_cm.x; vec2.y = -part1->dir.y*halfl1 - r_cm.y; vec2.z = -part1->dir.z*halfl1 - r_cm.z; /*sphere1*/ a = DOT(part2->dir,part2->dir); b = 2.0*DOT(vec1,part2->dir); c = DOT(vec1,vec1)-rcut*rcut; d = b*b-4*a*c; if (d >= 0) { /*if d<0 there are no intersections*/ x1= (-b + sqrt(d))*0.5/a; /*parameter on line of SC2 determining intersection*/ if ((x1 >=halfl2) || (x1 <= -halfl2)) intrs+=0; /*intersection is outside sc2*/ else { vec3.x = part2->dir.x*x1-r_cm.x; vec3.y = part2->dir.y*x1-r_cm.y; vec3.z = part2->dir.z*x1-r_cm.z; e = DOT(part1->dir,vec3); if ((e >= halfl1) || (e <= -halfl1)) { /*if not intersection is inside sc1*/ intrs+=test_intrpatch(part1,vec3,param->pcanglsw[which+2*patchnum],x1,intersections,patchnum); } } if ( d > 0) { x2= (-b - sqrt(d))*0.5/a; /*parameter on line of SC2 determining intersection*/ if ((x2 >=halfl2) || (x2 <= -halfl2)) intrs+=0; /*intersection is outside sc2*/ else { vec4.x = part2->dir.x*x2 - r_cm.x; vec4.y = part2->dir.y*x2 - r_cm.y; vec4.z = part2->dir.z*x2 - r_cm.z; e = DOT(part1->dir,vec4); if ((e >=halfl1) || (e <= -halfl1)) { /*if not intersection is inside sc1*/ intrs+=test_intrpatch(part1,vec4,param->pcanglsw[which+2*patchnum],x2,intersections,patchnum); } } } } // printf ("sphere1 %d x1 %f x2 %f e %f\n", intrs, x1, x2, e); /*sphere2*/ a = DOT(part2->dir,part2->dir); b = 2.0*DOT(vec2,part2->dir); c = DOT(vec2,vec2)-rcut*rcut; d = b*b-4*a*c; if (d >= 0) { /*if d<0 there are no intersections*/ x1= (-b + sqrt(d))*0.5/a; /*parameter on line of SC2 determining intersection*/ if ((x1 >=halfl2) || (x1 <= -halfl2)) intrs+=0; /*intersection is outside sc2*/ else { vec3.x = part2->dir.x*x1 - r_cm.x; vec3.y = part2->dir.y*x1 - r_cm.y; vec3.z = part2->dir.z*x1 - r_cm.z; e = DOT(part1->dir,vec3); if ((e >=halfl1) || (e <= -halfl1)) { /*if not intersection is inside sc1*/ intrs+=test_intrpatch(part1,vec3,param->pcanglsw[which+2*patchnum],x1,intersections,patchnum); } } if ( d > 0 ) { x2= (-b - sqrt(d))*0.5/a; /*parameter on line of SC2 determining intersection*/ if ((x2 >=halfl2) || (x2 <= -halfl2)) intrs+=0; /*intersection is outside sc2*/ else { vec4.x = part2->dir.x*x2 - r_cm.x; vec4.y = part2->dir.y*x2 - r_cm.y; vec4.z = part2->dir.z*x2 - r_cm.z; e = DOT(part1->dir,vec4); if ((e >=halfl1) || (e <= -halfl1)) { /*if not intersection is inside sc1*/ intrs+=test_intrpatch(part1,vec4,param->pcanglsw[which+2*patchnum],x2,intersections,patchnum); } } } } // printf ("sphere2 %d\n", intrs); } /*1d- if there is only one itersection shperocylinder ends within patch wedge set as second intersection end inside patch*/ if (intrs < 2 ) { /*whole spherocylinder is in or all out if intrs ==0*/ vec1.x = part2->dir.x*halfl2 - r_cm.x; vec1.y = part2->dir.y*halfl2 - r_cm.y; vec1.z = part2->dir.z*halfl2 - r_cm.z; /*vector from CM of sc1 to end of sc2*/ /*check is is inside sc1*/ a=DOT(vec1,part1->dir); vec3.x = vec1.x - part1->dir.x*a; vec3.y = vec1.y - part1->dir.y*a; vec3.z = vec1.z - part1->dir.z*a; b=DOT(vec3,vec3); d = fabs(a)-halfl1; if ( d <= 0) c = b; /*is inside cylindrical part*/ else c = d*d + b; /*is inside caps*/ /*c is distance squared from line or end to test if is inside sc*/ if (c < rcut2) intrs+=test_intrpatch(part1,vec1,param->pcanglsw[which+2*patchnum],halfl2,intersections,patchnum); if (intrs < 2 ) { vec2.x = -part2->dir.x*halfl2 - r_cm.x; vec2.y = -part2->dir.y*halfl2 - r_cm.y; vec2.z = -part2->dir.z*halfl2 - r_cm.z; /*check is is inside sc1*/ a=DOT(vec2,part1->dir); vec4.x = vec2.x - part1->dir.x*a; vec4.y = vec2.y - part1->dir.y*a; vec4.z = vec2.z - part1->dir.z*a; b=DOT(vec4,vec4); d = fabs(a) -halfl1; if (d <= 0) c = b; /*is inside cylindrical part*/ else c = d*d + b; /*is inside caps*/ /*c is distance squared from line or end to test if is inside sc*/ if (c < rcut2) intrs+=test_intrpatch(part1,vec2,param->pcanglsw[which+2*patchnum],-1.0*halfl2,intersections,patchnum); } // printf ("ends %d\n", intrs); } return intrs; } /*................................................................................*/ /* Find if vector vec has angular intersection with patch of sc1 */ int test_intrpatch(struct particles * part1, struct vector vec, double cospatch, double ti, double intersections[5],int patchnum) { double a; int i, intrs; struct vector vec_perpproject(struct vector*, struct vector*); void normalise(struct vector *); intrs=0; /*test if we have intersection*/ /* do projection to patch plane*/ vec=vec_perpproject(&vec,&part1->dir); normalise(&vec); /* test angle distance from patch*/ a = DOT(part1->patchdir[patchnum],vec); if (a >= cospatch) { intrs=1; i=0; while (intersections[i] !=0) { if (ti == intersections[i]) intrs=0; /* found intersection we already have -it is at boundary*/ i++; } if (intrs > 0) intersections[i]=ti; } return intrs; } /*................................................................................*/ /* Find intersections of SC and plane defined by vector w_vec.and returns number of them */ int find_intersect_plane(struct particles * part1, struct particles * part2, double halfl2, struct vector r_cm, struct vector w_vec, double rcut, double cospatch, double intersections[5]) { int i, intrs; double a, c, d, ti, disti; struct vector nplane, d_vec; void normalise(struct vector *); struct vector vec_crossproduct(struct vector, struct vector); nplane=vec_crossproduct(part1->dir,w_vec); normalise(&nplane); normalise(&w_vec); a = DOT(nplane, part2->dir); if (a == 0.0) intrs=0; /* there is no intersection plane and sc are paralel*/ else { ti = DOT(nplane,r_cm)/a; if ((ti > halfl2 ) || (ti < -halfl2)) intrs=0; /* there is no intersection plane sc is too short*/ else { d_vec.x = ti * part2->dir.x - r_cm.x; /*vector from intersection point to CM*/ d_vec.y = ti * part2->dir.y - r_cm.y; d_vec.z = ti * part2->dir.z - r_cm.z; c = DOT (d_vec, w_vec); if ( c * cospatch < 0) intrs=0; /* the intersection in plane is on other side of patch */ else { d = fabs(DOT (d_vec, part1->dir)) - halfl2; if (d <= 0) disti = c*c; /*is inside cylinder*/ else disti = d*d + c*c; /*is inside patch*/ if (disti > rcut*rcut) intrs=0; /* the intersection is outside sc */ else { intrs=1; i=0; while (intersections[i] !=0) { if (ti == intersections[i]) intrs=0; /* found intersection we already have -it is at boundary*/ i++; } if (intrs > 0) { intersections[i]=ti; } } } } } return intrs; } /*CPSC................................................................................*/ /* Calculate intersections of sc2 with a patch of sc1 and return them in this works for cylindrical psc -CPSC */ int cpsc_intersect(struct particles * part1, struct particles * part2, double halfl1, double halfl2, struct vector r_cm, double intersections[5], double rcut, struct ia_param * param, int which, int patchnum) { int intrs; double a, b, c, d, e, x1, x2, rcut2; struct vector cm21, vec1, vec2, vec3, vec4; struct vector vec_crossproduct(struct vector, struct vector); struct vector vec_sub(struct vector, struct vector); struct vector vec_create(double, double, double); struct vector vec_scale(struct vector, double); struct vector vec_perpproject(struct vector*, struct vector*); struct quat quat_create(struct vector, double, double); void vec_rotate(struct vector *, struct quat); void normalise(struct vector *); int find_intersect_planec(struct particles *, struct particles *, double, struct vector, struct vector, double, double, double *); int test_intrpatch(struct particles *, struct vector, double, double, double *, int); intrs=0; rcut2=rcut*rcut; /*1- do intersections of spherocylinder2 with patch of spherocylinder1 at cut distance C*/ /*1a- test intersection with half planes of patch and look how far they are from spherocylinder. If closer then C we got itersection*/ /* plane1 */ /* find intersections of part2 with plane by par1 and part1->patchsides[0] */ intrs+=find_intersect_planec(part1,part2,halfl2,r_cm,part1->patchsides[0+2*patchnum],rcut,param->pcanglsw[which+2*patchnum],intersections); // printf("plane1 %d\n", intrs); /* plane2 */ /* find intersections of part2 with plane by par1 and part1->patchsides[1] */ intrs+=find_intersect_planec(part1,part2,halfl2,r_cm,part1->patchsides[1+2*patchnum],rcut,param->pcanglsw[which+2*patchnum],intersections); if ( (intrs == 2 ) && (param->pcanglsw[which+2*patchnum] < 0) ) { fprintf (stderr, "ERROR: Patch is larger than 180 degrees and we are getting two segments - this hasnot been programed yet.\n\n"); exit (1); } // printf("plane2 %d\n", intrs); /*1b- test intersection with cylinder - it is at distance C*/ if (intrs < 2 ) { cm21=vec_scale(r_cm,-1.0); vec1=vec_crossproduct(cm21,part1->dir); vec2=vec_crossproduct(part2->dir,part1->dir); a = DOT(vec2,vec2); b = 2*DOT(vec1,vec2); c = -rcut*rcut + DOT(vec1,vec1); d = b*b - 4*a*c; if ( d >= 0) { /*there is intersection with infinite cylinder */ x1 = (-b+sqrt(d))*0.5/a; /*parameter on line of SC2 determining intersection*/ if ((x1 >=halfl2) || (x1 <= -halfl2)) intrs+=0; /*intersection is outside sc2*/ else { /* vectors from center os sc1 to intersection with infinite cylinder*/ vec1.x=part2->dir.x*x1-r_cm.x; vec1.y=part2->dir.y*x1-r_cm.y; vec1.z=part2->dir.z*x1-r_cm.z; e = DOT(part1->dir,vec1); if ((e >=halfl1) || (e <= -halfl1)) intrs+=0; /*intersection is outside sc1*/ else { intrs+=test_intrpatch(part1,vec1,param->pcanglsw[which+2*patchnum],x1,intersections,patchnum); } } if ( d > 0 ){ x2 = (-b-sqrt(d))*0.5/a; /*parameter on line of SC2 determining intersection*/ if ((x2 >=halfl2) || (x2 <= -halfl2)) intrs+=0; /*intersection is outside sc2*/ else { vec2.x = part2->dir.x*x2-r_cm.x; vec2.y = part2->dir.y*x2-r_cm.y; vec2.z = part2->dir.z*x2-r_cm.z; e = DOT(part1->dir,vec2); if ((e >=halfl1) || (e <= -halfl1)) intrs+=0; /*intersection is outside sc1*/ else { intrs+=test_intrpatch(part1,vec2,param->pcanglsw[which+2*patchnum],x2,intersections,patchnum); } } } } } // printf ("cylinder %d x1 %f x2 %f e %f\n", intrs, x1, x2, e); /*1c- test intersection with plates at the end - it is at distace C and in wedge*/ if (intrs < 2 ) { a = DOT(part1->dir, part2->dir); if (a == 0.0) intrs=0; /* there is no intersection plane and sc are paralel*/ else { /*plane cap1*/ vec1.x= r_cm.x + halfl1*part1->dir.x; vec1.y= r_cm.y + halfl1*part1->dir.y; vec1.z= r_cm.z + halfl1*part1->dir.z; x1 = DOT(part1->dir,vec1)/a; /*parameter on line of SC2 determining intersection*/ if ((x1 > halfl2 ) || (x1 < -halfl2)) intrs+=0; /* there is no intersection plane sc is too short*/ else { vec2.x = x1*part2->dir.x - vec1.x; /*vector from ENDPOINT to intersection point */ vec2.y = x1*part2->dir.y - vec1.y; vec2.z = x1*part2->dir.z - vec1.z; b = DOT (vec2, vec2); if (b > rcut*rcut) intrs+=0; /* the intersection is outside sc */ else { intrs+=test_intrpatch(part1,vec2,param->pcanglsw[which+2*patchnum],x1,intersections,patchnum); } } // printf ("plane cap1 %d %f\n", intrs, x1); /*plane cap2*/ vec1.x= r_cm.x - halfl1*part1->dir.x; vec1.y= r_cm.y - halfl1*part1->dir.y; vec1.z= r_cm.z - halfl1*part1->dir.z; x2 = DOT(part1->dir,vec1)/a; /*parameter on line of SC2 determining intersection*/ if ((x2 > halfl2 ) || (x2 < -halfl2)) intrs+=0; /* there is no intersection plane sc is too short*/ else { vec2.x = x2*part2->dir.x - vec1.x; /*vector from ENDPOINT to intersection point */ vec2.y = x2*part2->dir.y - vec1.y; vec2.z = x2*part2->dir.z - vec1.z; b = DOT (vec2, vec2); if (b > rcut*rcut) intrs+=0; /* the intersection is outside sc */ else { intrs+=test_intrpatch(part1,vec2,param->pcanglsw[which+2*patchnum],x2,intersections,patchnum); } } // printf ("plane cap2 %d %f\n", intrs,x2); } } /*1d- if there is only one itersection shperocylinder ends within patch wedge set as second intersection end inside patch*/ if (intrs < 2 ) { /*whole spherocylinder is in or all out if intrs ==0*/ vec1.x = part2->dir.x*halfl2 - r_cm.x; vec1.y = part2->dir.y*halfl2 - r_cm.y; vec1.z = part2->dir.z*halfl2 - r_cm.z; /*vector from CM of sc1 to end of sc2*/ /*check is is inside sc1*/ a=DOT(vec1,part1->dir); vec3.x = vec1.x - part1->dir.x*a; vec3.y = vec1.y - part1->dir.y*a; vec3.z = vec1.z - part1->dir.z*a; b=DOT(vec3,vec3); d = fabs(a)-halfl1; if ( d <= 0) { /*is in cylindrical part*/ /*c is distance squared from line or end to test if is inside sc*/ if (b < rcut2) intrs+=test_intrpatch(part1,vec1,param->pcanglsw[which+2*patchnum],halfl2,intersections,patchnum); } if (intrs < 2 ) { vec2.x = -part2->dir.x*halfl2 - r_cm.x; vec2.y = -part2->dir.y*halfl2 - r_cm.y; vec2.z = -part2->dir.z*halfl2 - r_cm.z; /*check is is inside sc1*/ a=DOT(vec2,part1->dir); vec4.x = vec2.x - part1->dir.x*a; vec4.y = vec2.y - part1->dir.y*a; vec4.z = vec2.z - part1->dir.z*a; b=DOT(vec4,vec4); d = fabs(a) -halfl1; if (d <= 0) { /*c is distance squared from line or end to test if is inside sc*/ if (b < rcut2) intrs+=test_intrpatch(part1,vec2,param->pcanglsw[which+2*patchnum],-1.0*halfl2,intersections,patchnum); } } // printf ("ends %d\n", intrs); } return intrs; } /*CPSC................................................................................*/ /* Find intersections of plane defined by vector w_vec.and returns number of them - for cylindrical psc -CPSC */ int find_intersect_planec(struct particles * part1, struct particles * part2, double halfl, struct vector r_cm, struct vector w_vec, double rcut, double cospatch, double intersections[5]) { int i, intrs=0; double a, c, d, ti, disti; struct vector nplane, d_vec; void normalise(struct vector *); struct vector vec_crossproduct(struct vector, struct vector); nplane=vec_crossproduct(part1->dir,w_vec); normalise(&nplane); normalise(&w_vec); a = DOT(nplane, part2->dir); if (a == 0.0) intrs=0; /* there is no intersection plane and sc are paralel*/ else { ti = DOT(nplane,r_cm)/a; if ((ti > halfl ) || (ti < -halfl)) intrs=0; /* there is no intersection plane sc is too short*/ else { d_vec.x = ti*part2->dir.x - r_cm.x; /*vector from intersection point to CM*/ d_vec.y = ti*part2->dir.y - r_cm.y; d_vec.z = ti*part2->dir.z - r_cm.z; c = DOT (d_vec, w_vec); if ( c *cospatch < 0) intrs=0; /* the intersection in plane is on other side of patch */ else { d = fabs(DOT (d_vec, part1->dir)) - halfl; if (d <= 0) { disti= c*c; /*is inside cylinder*/ if (disti > rcut*rcut) intrs=0; /* the intersection is outside sc */ else { intrs=1; i=0; while (intersections[i] !=0) { if (ti == intersections[i]) intrs=0; /* found intersection we already have -it is at boundary*/ i++; } if (intrs > 0) intersections[i]=ti; } } } } } return intrs; } /*..................................................................................*/ /* Find projection of cpsc on plane (0,0,1) including cutoff and return vector to its begining and end and cm */ int psc_wall(struct vector* pbeg, struct vector* pend, struct vector* projectdir, struct vector* partdir, BOOL* positive, double * cutdist, struct vector *partbeg, struct vector *partend) { struct vector vec1; double k,x1,x2,y1,y2,a,b,c,e,d; void projectinz( struct vector* vec1, struct vector * projectdir, struct vector* result); void normalise(struct vector*); if (( (*positive)&& (projectdir->z > 0) ) || ( (!(*positive))&& (projectdir->z < 0) )) return 0; if ( fabs(partbeg->z) > (*cutdist) ) return 0; /* we might have interacting segment*/ x2 = 0.0; y2 = 0.0; /*begining point*/ /*if begining projected along particle direction is within cutoff */ if (fabs(partdir->z) > ZEROTOL2) { projectinz(partbeg,partdir,pbeg); a=0; } else { /*we need some starting point*/ vec1.x = 2.0*partbeg->x - partend->x; vec1.y = 2.0*partbeg->y - partend->y; vec1.z = 2.0*partbeg->z - partend->z; projectinz(&vec1,projectdir,pbeg); a=1; } if (partdir->z != 0) { b = fabs(partbeg->z / partdir->z); } else { b = (*cutdist)+1.0; } if ( (b > (*cutdist)) || (a==1)) { /*else beginig is at sphere, find intersections with sphere of cutoff radius*/ if ( fabs(projectdir->z) > ZEROTOL2) { projectinz(partbeg,projectdir,pend); } else { pend->x = pbeg->x + projectdir->x; pend->y = pbeg->y + projectdir->y; } if (pend->y == pbeg->y) { y1=pbeg->y; y2=pbeg->y; a=sqrt( (*cutdist)*(*cutdist) - partbeg->z*partbeg->z - (pbeg->y-partbeg->y)*(pbeg->y-partbeg->y) ); x1 = partbeg->x + a; x2 = partbeg->x - a; if (pend->x > pbeg->x) {/*select the right intersection*/ pbeg->x = x2; x2 = x1; } else { pbeg->x = x1; } pbeg->y = y1; } else { k = (pend->x - pbeg->x)/ (pend->y - pbeg->y); a = k*k +1; b = partbeg->y + k*k*pbeg->y - k*pbeg->x + k*partbeg->x; c = partbeg->y*partbeg->y + partbeg->z*partbeg->z - (*cutdist)*(*cutdist) + (k*pbeg->y - pbeg->x + partbeg->x)*(k*pbeg->y - pbeg->x + partbeg->x); e = b*b-a*c; if (e < 0) { return 0; /*tehre might be no intersection with sphere*/ } d = sqrt(e); if (pend->y > pbeg->y) {/*select the right intersection*/ y1 = (b - d ) /a; y2 = (b + d ) /a; } else { y1 = (b + d ) /a; y2 = (b - d ) /a; } x1 = k * (y1 - pbeg->y) + pbeg->x; x2 = k * (y2 - pbeg->y) + pbeg->x; pbeg->x = x1; pbeg->y = y1; pbeg->z = 0.0; } } //printf("pscwall beg %f %f \n",pbeg->x,pbeg->y); /*end point*/ a = -(*cutdist) * projectdir->z; /*z coordinate of point where projection is in cut distance*/ //printf("sphere end %f %f ",a,partend->z); if ( ((partend->z < a)&&(*positive)) || ((a < partend->z)&&(!(*positive))) ){ /*end is within cut off - second sphere*/ /*if this is the case vec1 is end of pherocylinder and pend is its projection*/ if (projectdir->z != 0) { projectinz(partend,projectdir,pend); } else { pend->x = pbeg->x + projectdir->x; pend->y = pbeg->y + projectdir->y; } if (pend->y == pbeg->y) { y1=pend->y; y2=pend->y; a=sqrt( (*cutdist)*(*cutdist) - partend->z*partend->z - (pend->y-partend->y)*(pend->y-partend->y) ); x1 = partend->x + a; x2 = partend->x - a; if (pbeg->x > pend->x) {/*select the right intersection*/ pend->x = x2; } else { pend->x = x1; } pend->y = y1; } else { k = (pbeg->x - pend->x)/ (pbeg->y - pend->y); a = k*k +1; b = partend->y + k*k*pend->y - k*pend->x + k*partend->x; c = partend->y*partend->y + partend->z*partend->z - (*cutdist)*(*cutdist) + (k*pend->y - pend->x + partend->x)*(k*pend->y - pend->x + partend->x); e = b*b-a*c; if (e < 0) { return 0; /*there might be no intersection with sphere*/ } d = sqrt(e); if (pbeg->y > pend->y) {/*select the right intersection*/ y1 = (b - d ) /a; y2 = (b + d ) /a; } else { y1 = (b + d ) /a; y2 = (b - d ) /a; } x1 = k * (y1 - pend->y) + pend->x; x2 = k * (y2 - pend->y) + pend->x; pend->x = x1; pend->y = y1; pend->z = 0.0; } } else { if ( ((partbeg->z < a)&&(*positive)) || ((a < partbeg->z)&&(!(*positive))) ) { /*end is at cutoff going through cylindrical part*/ //printf("cylinder "); b = (a - partbeg->z)/ partdir->z; vec1.x = partbeg->x + b * partdir->x; vec1.y = partbeg->y + b * partdir->y; vec1.z = a; projectinz(&vec1,projectdir,pend); } else { /* also projected end is within the same sphere as begining- no contribution from cylinder*/ if (x2 == 0.0 ) { //printf("sphere beg "); if (projectdir->z != 0) { projectinz(partbeg,projectdir,pend); } else { pend->x = pbeg->x + projectdir->x; pend->y = pbeg->y + projectdir->y; } if (pend->y == pbeg->y) { y1=pbeg->y; y2=pbeg->y; a=sqrt( (*cutdist)*(*cutdist) - partbeg->z*partbeg->z - (pbeg->y-partbeg->y)*(pbeg->y-partbeg->y) ); x1 = partbeg->x + a; x2 = partbeg->x - a; if (pend->x > pbeg->x) {/*select the right intersection*/ pend->x = x1; } else { pend->x = x2; } pend->y = y1; } else { k = (pend->x - pbeg->x)/ (pend->y - pbeg->y); a = k*k +1; b = partbeg->y + k*k*pbeg->y - k*pbeg->x + k*partbeg->x; c = partbeg->y*partbeg->y + partbeg->z*partbeg->z - (*cutdist)*(*cutdist) + (k*pbeg->y - pbeg->x + partbeg->x)*(k*pbeg->y - pbeg->x + partbeg->x); e = b*b-a*c; if (e < 0) { return 0; /*tehre might be no intersection with sphere*/ } d = sqrt(e); if (pend->y > pbeg->y) {/*select the right intersection*/ y1 = (b - d ) /a; y2 = (b + d ) /a; } else { y1 = (b + d ) /a; y2 = (b - d ) /a; } x1 = k * (y1 - pbeg->y) + pbeg->x; x2 = k * (y2 - pbeg->y) + pbeg->x; pend->x = x1; pend->y = y1; pend->z = 0.0; } } else { pend->x = x2; pend->y = y2; pend->z = 0.0; } return 2; /*line end is on sphere of particle begining = no cylindrical cutoff*/ } } return 1; } int cpsc_wall(struct vector* pbeg, struct vector* pend, struct vector* projectdir, struct vector* partdir, double* halfl, BOOL* orientin, BOOL* positive, double* rcmz, double * cutdist, struct vector *partbeg, struct vector *partend) { struct vector vec1; double a; void projectinz( struct vector* vec1, struct vector * projectdir, struct vector* result); if (( (*positive)&& (projectdir->z >= 0) ) || ( (!(*positive))&& (projectdir->z <= 0) )) return 0; /*if projected closer point beoynd cutoff no interaction*/ /*project begining of spherocylinder*/ vec1.x = partbeg->x; vec1.y = partbeg->y; vec1.z = partbeg->z; if (-vec1.z/projectdir->z < (*cutdist) ) { projectinz(&vec1,projectdir,pbeg); } else { return 0; } /* we have interacting segment*/ if (-partend->z/projectdir->z < (*cutdist) ) { /*whole segment interacts*/ vec1.z = partend->z; } else { vec1.z = -(*cutdist)*projectdir->z; } if (partdir->z != 0.0) a = (vec1.z - (*rcmz)) / partdir->z; else { if (*orientin) a = -(*halfl); else a = (*halfl); } vec1.x = partdir->x * a; vec1.y = partdir->y * a; projectinz(&vec1,projectdir,pend); return 1; } int cutprojectatwall(struct vector* pextr1, struct vector* pextr2, struct vector* pextr3, struct vector* pextr4, struct vector* projectdir, struct vector* partdir, double * cutdist, struct vector *partbeg, struct vector *partend, struct vector *pend, double *cuttoproject, BOOL* orientin) { double y1,y2,O2z,det,a,b,dirydirz,dir2x,dir2y,dir2z,dirzldiry; void projectinz( struct vector* vec1, struct vector * projectdir, struct vector* result); dirydirz = partdir->y * partdir->z; dir2x = partdir->x * partdir->x; dir2y = partdir->y * partdir->y; dir2z = partdir->z * partdir->z; a = 1/(dir2x+dir2y); if (partdir->x != 0) { O2z = partbeg->z * partbeg->z; b=dir2y*dir2z*O2z - (dir2x+dir2y) * (O2z*(dir2x+dir2z)- (*cutdist)*(*cutdist)*dir2x); if (b < 0 ) { /*no cutoff from cylindrical part*/ return 0; } det = sqrt(b); y1 = partbeg->y + (dirydirz*partbeg->z + det )*a; y2 = partbeg->y + (dirydirz*partbeg->z - det )*a; if (( (partdir->x > 0)&&(!(*orientin)) ) || ( (partdir->x < 0)&&(*orientin) )) { pextr1->y = y1; pextr2->y = y2; } else { pextr1->y = y2; pextr2->y = y1; } pextr1->x = partbeg->x + (partbeg->z*partdir->z - (pextr1->y - partbeg->y)*partdir->y) / partdir->x; pextr2->x = partbeg->x + (partbeg->z*partdir->z - (pextr2->y - partbeg->y)*partdir->y) / partdir->x; O2z = partend->z * partend->z; b= dir2y*dir2z*O2z - (dir2x+dir2y) * (O2z*(dir2x+dir2z)- (*cutdist)*(*cutdist)*dir2x); if (b >= 0) { /*we have intersections from end*/ det = sqrt(b); y1 = partend->y + (dirydirz * partend->z + det )*a; y2 = partend->y + (dirydirz * partend->z - det )*a; //printf("det %f y1 %f y2 %f \n", det,y1,y2); if (( (partdir->x > 0)&&(!(*orientin)) ) || ( (partdir->x < 0)&&(*orientin) )) { pextr3->y = y1; pextr4->y = y2; } else { pextr3->y = y2; pextr4->y = y1; } pextr3->x = partend->x + (partend->z*partdir->z - (pextr3->y - partend->y)*partdir->y) / partdir->x; pextr4->x = partend->x + (partend->z*partdir->z - (pextr4->y - partend->y)*partdir->y) / partdir->x; } else { /*no intersection at the end the cutoff intersects the plane in the perpendicular projection of line segemnt, so we have to use that point */ if (partdir->z == 0) { fprintf (stderr, "\nERROR: Something went wrong in calculation of projection.\n\n"); exit (1); } else { a = ((*cuttoproject) - partbeg->z)/ partdir->z; //if ( projectdir->y * partdir->x < 0 ) pextr3->x = partbeg->x + a * partdir->x; pextr3->y = partbeg->y + a * partdir->y; pextr3->z = (*cuttoproject); //printf("before proj %f %f dir %f %f %f ",pextr3->x,pextr3->y,projectdir->x,projectdir->y,projectdir->z); projectinz(pextr3,projectdir,pextr4); pextr3->x = pextr4->x; pextr3->y = pextr4->y; pextr3->z = 0.0; //printf("after proj %f %f \n",pextr3->x,pextr3->y); return 2; } } } else { if (partdir->y != 0) { dirzldiry = partdir->z/partdir->y; y1 = partbeg->y + partbeg->z * dirzldiry; det = sqrt( (*cutdist)*(*cutdist) - partbeg->z * partbeg->z * (1+dirzldiry*dirzldiry) ); if (( (partdir->y > 0)&&(!(*orientin)) ) || ( (partdir->y < 0)&&(*orientin) )) { pextr1->x = partbeg->x + det; pextr2->x = partbeg->x - det; } else { pextr1->x = partbeg->x - det; pextr2->x = partbeg->x + det; } pextr1->y = y1; pextr2->y = y1; y1 = partend->y + partend->z * dirzldiry; b = (*cutdist)*(*cutdist) - partend->z * partend->z * (1+dirzldiry*dirzldiry); if (b >= 0) { /*we have intersections from end*/ det = sqrt(b); if (( (partdir->y > 0)&&(!(*orientin)) ) || ( (partdir->y < 0)&&(*orientin) )) { pextr3->x = partend->x + det; pextr4->x = partend->x - det; } else { pextr3->x = partend->x - det; pextr4->x = partend->x + det; } pextr3->y = y1; pextr4->y = y1; } else { /*no intersection at the end the cutoff intersects the plane in the perpendicular projection of line segemnt, so we have to use that point */ if (partdir->z == 0) { fprintf (stderr, "\nERROR: Something went wrong in calculation of projection.\n\n"); exit (1); } else { a = ((*cutdist) - partbeg->z)/ partdir->z; y1 = a * partdir->y + partbeg->y; if ( projectdir->x * partdir->y > 0 ) { pextr3->x = a * partdir->x + partbeg->x; pextr3->y = y1; pextr4->x = pend->x; pextr4->y = pend->y; }else { pextr3->x = pend->x; pextr3->y = pend->y; pextr4->x = a * partdir->x + partbeg->x; pextr4->y = y1; } } } } else { return 0; /* if perpendicular to plane we don't have any intersections*/ } } return 1; } /*project a point in project direction to z plane z=0*/ void projectinz(struct vector* vec1, struct vector* projectdir,struct vector * projection) { projection->x = vec1->x - vec1->z * projectdir->x/projectdir->z; projection->y = vec1->y - vec1->z * projectdir->y/projectdir->z; projection->z = 0; } /*calculates area defined by four points in z=0 plane */ double areafourpoints(struct vector * pbeg, struct vector * pend, struct vector * pbeg1, struct vector * pend1 ) { double area =0.0; struct vector vec1,vec2; /*area by four points... two half vector cross product |(pbegining1-pbegining)x(pend-pbegining)|/2 */ vec1.x = pbeg1->x - pbeg->x; vec1.y = pbeg1->y - pbeg->y; vec2.x = pend->x - pbeg->x; vec2.y = pend->y - pbeg->y; //printf("a: %f %f %f %f \n",vec1.x,vec2.y,vec1.y,vec2.x); area += fabs(vec1.x*vec2.y - vec1.y*vec2.x)*0.5; /* + |(pend-pend1)x(pbegining1-pend1)|/2*/ vec1.x = pend->x - pend1->x; vec1.y = pend->y - pend1->y; vec2.x = pbeg1->x - pend1->x; vec2.y = pbeg1->y - pend1->y; area += fabs(vec1.x*vec2.y -vec1.y*vec2.x)*0.5; return area; } /*calculates area defined by six points in z=0 plane */ double areaeightpoints(struct vector * p1, struct vector * p2, struct vector * p3, struct vector * p4, struct vector * p5, struct vector * p6,struct vector * p7, struct vector * p8) { double area =0.0; struct vector vec1,vec2; /*area by half vector cross product |(pbegining-pbegining)x(pend-pbegining)|/2 */ vec1.x = p2->x - p1->x; vec1.y = p2->y - p1->y; vec2.x = p3->x - p2->x; vec2.y = p3->y - p2->y; area += fabs(vec1.x*vec2.y -vec1.y*vec2.x)*0.5; //printf("3"); if (p4 != NULL) { vec1.x = p3->x - p1->x; vec1.y = p3->y - p1->y; vec2.x = p4->x - p3->x; vec2.y = p4->y - p3->y; area += fabs(vec1.x*vec2.y -vec1.y*vec2.x)*0.5; //printf("4"); if (p5 != NULL) { vec1.x = p4->x - p1->x; vec1.y = p4->y - p1->y; vec2.x = p5->x - p4->x; vec2.y = p5->y - p4->y; area += fabs(vec1.x*vec2.y -vec1.y*vec2.x)*0.5; //printf("5"); if (p6 != NULL) { vec1.x = p5->x - p1->x; vec1.y = p5->y - p1->y; vec2.x = p6->x - p5->x; vec2.y = p6->y - p5->y; area += fabs(vec1.x*vec2.y -vec1.y*vec2.x)*0.5; //printf("6"); if (p7 != NULL) { vec1.x = p6->x - p1->x; vec1.y = p6->y - p1->y; vec2.x = p7->x - p6->x; vec2.y = p7->y - p6->y; area += fabs(vec1.x*vec2.y -vec1.y*vec2.x)*0.5; //printf("7"); if (p8 != NULL) { vec1.x = p7->x - p1->x; vec1.y = p7->y - p1->y; vec2.x = p8->x - p7->x; vec2.y = p8->y - p7->y; area += fabs(vec1.x*vec2.y -vec1.y*vec2.x)*0.5; //printf("8"); } } } } } return area; } /*..............................................................................*/ /*........................INPUT OUTPUT..........................................*/ /*..............................................................................*/ /*..............................................................................*/ /** * convert string num into two integers */ void readii(char * num, int value[2]){ char *end, *num2; void trim (char *); value[0] = strtol(num, &num2, 10); trim(num2); if ((int)strlen(num2) > 0) value[1] = strtol(num2, &end, 10); else { value[1] =0; return; } if(*end){ fprintf(stderr, "Could not convert %s into two integers\n", num); exit(1); } return; } /** * convert string num into integer */ int readi(char * num){ char *end; int i = strtol(num, &end, 10); if(*end){ fprintf(stderr, "Could not convert %s into integer\n", num); exit(1); } return (int) i; } /** * convert string num into long */ long readl(char * num){ char *end; long i = strtol(num, &end, 10); if(*end){ fprintf(stderr, "Could not convert %s into long\n", num); exit(1); } return i; } /** * convert string num into double */ double readd(char * num){ char *end; double i = strtod(num, &end); if(*end){ fprintf(stderr, "Could not convert %s into double\n", num); exit(1); } return i; } /* Reads the run parameters from the external file "options". See the end of the code for a template. All comments starting with '#' are stripped out. The options are summarised on standard output and checked for validity of range. */ void read_options(struct sim* sim,char filename[30]) { int i; int num_options = -1; double transmx, rotmx, chainmmx, chainrmx; double angle, chain_angle; char *id, *value, *tokLine, *line; FILE *infile; void strip_comment (char *); void trim (char *); void readii(char * num, int value[2]); double readd(char *); long readl(char *); int readi(char *); /* for new options add before the last line */ Option options[] = { {"write_cluster", Long, FALSE, &sim->write_cluster}, {"adjust", Long, FALSE, &sim->adjust}, {"movie", Long, FALSE, &sim->movie}, {"nequil", Long, FALSE, &sim->nequil}, {"nsweeps", Long, FALSE, &sim->nsweeps}, {"nrepchange", Long, FALSE, &sim->nrepchange}, {"paramfrq", Long, FALSE, &sim->paramfrq}, {"report", Long, FALSE, &sim->report}, {"seed", Long, FALSE, &seed}, {"pairlist_update", Int, FALSE, &sim->pairlist_update}, {"ptype", Int, FALSE, &sim->ptype}, {"wlm", Int2, FALSE, &sim->wlm}, {"wlmtype", Int, FALSE, &sim->wl.wlmtype}, {"press", Double, FALSE, &sim->press}, {"paralpress", Double, FALSE, &sim->paralpress}, {"edge_mx", Double, FALSE, &sim->edge.mx}, {"shave", Double, FALSE, &sim->shave}, {"chainprob", Double, FALSE, &sim->chainprob}, {"switchprob", Double, FALSE, &sim->switchprob}, {"temper", Double, FALSE, &sim->temper}, {"paraltemper", Double, FALSE, &sim->paraltemper}, {"transmx", Double, FALSE, &transmx}, {"rotmx", Double, FALSE, &rotmx}, {"chainmmx", Double, FALSE, &chainmmx}, {"chainrmx", Double, FALSE, &chainrmx}, {"last", Int, FALSE, NULL} }; while(options[++num_options].var != NULL) ; /*--- 1. Read in values ---*/ size_t line_size = (STRLEN + 1) * sizeof(char); line = (char *) malloc(line_size); infile = fopen(filename, "r"); if (infile == NULL) { fprintf (stderr, "\nERROR: Could not open options file.\n\n"); exit (1); } while(getline(&line, &line_size, infile) != -1){ // strip comments strip_comment(line); trim(line); if(strlen(line) == 0){ continue; } // tokenize tokLine = line; id = strtok(tokLine, "="); if(id == NULL){ fprintf(stderr, "error parsing Configuration line (%s)", line); free(line); exit(1); } trim(id); tokLine = NULL; value = strtok(tokLine, "="); trim(value); if(value == NULL){ fprintf(stderr, "error parsing Configuration line (%s)", line); free(line); exit(1); } //printf("id: %s; value: %s\n", id, value); for(i = 0; i < num_options; i++){ if(strcmp(id, options[i].id) == 0){ if(options[i].type == Int2){ readii(value,*((int (*)[2]) options[i].var)); options[i].set = TRUE; break; } if(options[i].type == Int){ *((int *) options[i].var) = readi(value); options[i].set = TRUE; break; } else if(options[i].type == Long){ *((long *) options[i].var) = readl(value); options[i].set = TRUE; break; } else if(options[i].type == Double){ *((double *) options[i].var) = readd(value); options[i].set = TRUE; break; } else { fprintf(stderr, "Could not determine type of %s!\n", id); free(line); exit(1); } } } if(i == num_options){ fprintf(stderr, "Unknown identifier %s!\nWill procede.\n", id); } } fclose (infile); free(line); /* Check, wheter all options have been readin */ for(i = 0; i < num_options; i++){ if(!options[i].set){ fprintf(stderr, "option '%s' is not set!\n", options[i].id); exit(1); } } /*--- 2. Summarize results on standard output ---*/ /* Density of close-packed spherocylinders */ // rho_cp = 2.0/(sqrt(2.0) + *length * sqrt(3.0)); printf (" Pressure coupling type: %d\n", sim->ptype); printf (" Pressure: %.8lf\n", sim->press); printf (" Replica exchange pressure: %.8lf\n", sim->paralpress); printf (" Average volume change attempts per sweep: %.8lf\n", sim->shave); printf (" Equilibration sweeps: %ld\n", sim->nequil); printf (" Sweeps between step size adjustments: %ld\n", sim->adjust); printf (" Production sweeps: %ld\n", sim->nsweeps); printf (" Sweeps between statistics samples: %ld\n", sim->paramfrq); printf (" Sweeps between statistics reports: %ld\n", sim->report); printf (" Average chain move attempts per sweep: %.8lf\n", sim->chainprob); printf (" Initial maximum displacement: %.8lf\n", transmx); printf (" Inititial maximum angular change (degrees): %.8lf\n", rotmx); printf (" Inititial maximum box edge change: %.8lf\n", sim->edge.mx); printf (" Initial maximum chain displacement: %.8lf\n", chainmmx); printf (" Inititial maximum chain angular change (degrees): %.8lf\n", chainrmx); printf (" Temperature in kT/e: %.8lf\n", sim->temper); printf (" Parallel tempering temperature in kT/e: %.8lf\n", sim->paraltemper); printf (" Sweeps between replica exchange: %ld\n", sim->nrepchange); printf (" Wang-Landau method: %d %d\n", sim->wlm[0],sim->wlm[1]); printf (" Calculate the Wang-Landau method for atom type: %d\n", sim->wl.wlmtype); printf (" Average type switch attempts per sweep: %.8lf\n", sim->switchprob); printf (" Number of Sweeps per pairlist update: %d\n", sim->pairlist_update); printf (" Random number seed: %ld\n", seed); printf (" Number of sweeps per writing out cluster info: %ld\n", sim->write_cluster); if (sim->movie > 0) { printf (" Sweeps between movie frames: %ld\n", sim->movie); } else { printf (" No movie\n"); } printf ("\n"); if(sim->pairlist_update){ printf(" A pairlist will be generated every %d steps. This is a greedy" " algorithm; make sure you don't have big chains etc.!\n", sim->pairlist_update); } /*--- 3. Validity checks ---*/ if (rotmx < 0.0 || rotmx > 180) { fprintf (stderr, "ERROR: Maximum orientation change must be in range 0 to 180.\n\n"); exit (1); } if (chainrmx < 0.0 || chainrmx > 180) { fprintf (stderr, "ERROR: Maximum orientation change for chains must be in range 0 to 180.\n\n"); exit (1); } if ( (sim->ptype <0) || (sim->ptype>3) ) { fprintf (stderr, "ERROR: Unknown pressure coupling %d. Program only knows: 0 - anisotropic coupling, \ 1 - isotropic coupling, 2 - isotropic in xy z=const, 3 - isotropic xy V=const.\n\n",sim->ptype); exit (1); } if ( (sim->wlm[0] <0) || (sim->wlm[0] > 7) || (sim->wlm[1] <0) || (sim->wlm[1] > 7) ) { fprintf (stderr, "ERROR: Unknown Wang-Landau method %d %d. Program only knows: 0 - none, \ 1 - z-direction od 1st particle, 2 - pore in membrane, 3 - zorientation of 0th particle,\ 4 - distance of fist two particles, 5 - pore around z-axis above CM,\ 6 - pore around z-axis above 0th particle, 7 - number of particles in contact \n\n",sim->wlm[0],sim->wlm[1]); exit (1); } if ( (sim->wlm[0] == 0) && (sim->wlm[1] > 0) ) { fprintf (stderr, "ERROR: Wang-Landau method has to be set for first order parameter and then for second order parameter\n\n"); exit (1); } if ( (sim->wlm[0] == 2) || (sim->wlm[0] == 5) || (sim->wlm[0] == 6) ) { if(sim->wl.wlmtype < 1){ fprintf (stderr, "ERROR: Atom type for the Wang-Landau Method (%d) was false defined.\n\n",sim->wl.wlmtype); exit (1); } if ( (sim->wlm[1] == 2) || (sim->wlm[1] == 5) || (sim->wlm[1] == 6) ) { fprintf (stderr, "ERROR: Simulaneous use of two pore order parameters has not been implemented yet.\n\n"); exit (1); } } /* we store maximum rotation as half angle - useful for quaterions*/ angle = rotmx / 180.0 * PIH *0.5; rotmx = cos((rotmx)/180.0*PIH); chain_angle = chainrmx / 180.0 * PIH; chainrmx = cos((chainrmx)/180.0*PIH); sim->edge.mx *= 2.0; /* The full range is -maxl to +maxl, i.e. spanning 2*maxl */ transmx *= 2.0; /* The full range is -maxr to +maxr, i.e. spanning 2*maxr */ chainmmx *= 2.0; /* The full range is -maxr to +maxr, i.e. spanning 2*maxr */ for (i=0;i<MAXT;i++) { sim->trans[i].mx = transmx; sim->rot[i].mx = rotmx; sim->rot[i].angle = angle; } for (i=0;i<MAXMT;i++) { sim->chainm[i].mx = chainmmx; sim->chainr[i].mx = chainrmx; sim->chainr[i].angle = chain_angle; } //parallel tempering #ifdef MPI if ( (sim->temper != sim->paraltemper) && (sim->mpinprocs <2) ) { printf("ERROR: Paralllel tempering at single core does not work.\n\n"); exit(1); } sim->dtemp = (sim->paraltemper - sim->temper )/(sim->mpinprocs-1); sim->temper += sim->dtemp * sim->mpirank; if ( (sim->press != sim->paralpress) && (sim->mpinprocs <2) ) { printf("ERROR: Pressure replica exchange at single core does not work.\n\n"); exit(1); } sim->dpress = (sim->paralpress - sim->press )/(sim->mpinprocs-1); sim->press += sim->dpress * sim->mpirank; seed += sim->mpirank; sim->mpiexch.mx = sim->dtemp; sim->mpiexch.angle = sim->dpress; #endif } /*..............................................................................*/ /* Used by read_options to read a long integer with error checking. NOT USED ANYMORE */ long read_long(FILE *infile, char *error) { char *gotline; char line[500]; int fields; long value; gotline = fgets(line, sizeof(line), infile); fields = sscanf(line, "%ld", &value); if (gotline == NULL || fields != 1) { fprintf (stdout, "\nERROR reading %s from options file.\n\n", error); exit (1); } return value; } /* Used by read_options to read a long integer with error checking. NOT USED ANYMORE */ int read_int(FILE *infile, char *error) { char *gotline; char line[500]; int fields; int value; gotline = fgets(line, sizeof(line), infile); fields = sscanf(line, "%d", &value); if (gotline == NULL || fields != 1) { fprintf (stdout, "\nERROR reading %s from options file.\n\n", error); exit (1); } return value; } /*..............................................................................*/ /* Used by read_options to read a double precision with error checking. NOT USED ANYMORE */ double read_double(FILE *infile, char *error) { char *gotline; char line[500]; int fields; double value; gotline = fgets(line, sizeof(line), infile); fields = sscanf(line, "%le", &value); if (gotline == NULL || fields != 1) { fprintf (stdout, "\nERROR reading %s from options file.\n\n", error); exit (1); } return value; } /*..............................................................................*/ /**************************************************************************** * CONFIG INITIALIZATION *****************************************************************************/ /* Reads in the initial configuration from the file "config.init". Each line contains the three components of the position vector and three components of the direction vector and three components of patch direction for a spherocylinder. The direction vector is normalised after being read in. The configuration is checked for particle overlaps. */ void init_config(struct topo * topo, struct conf * conf, struct sim * sim, char filename[30]) { int err,fields,tmp_type; long i,j,current,first; FILE * infile; char * line, line2[STRLEN]; size_t line_size = (STRLEN + 1) * sizeof(char); line = (char *) malloc(line_size); struct particles chorig[MAXCHL]; int overlap(struct particles, struct particles, struct vector, struct ia_param [MAXT][MAXT]); void normalise(struct vector *); void ortogonalise(struct vector *, struct vector); void usepbc(struct vector *, struct vector); double anint(double); void strip_comment (char *); void trim (char *); void aftercommand(char *, char *, char); double maxlength = 0; for(i = 0; i < MAXT; i++){ if(maxlength < topo->ia_params[i][i].len[0]) maxlength = topo->ia_params[i][i].len[0]; } infile = fopen(filename, "r"); if (infile == NULL) { fprintf (stderr, "\nERROR: Could not open config.init file.\n\n"); exit (1); } if(getline(&line, &line_size, infile) == -1){ fprintf (stderr, "ERROR: Could not read box size.\n\n"); exit (1); } strip_comment(line); trim(line); if (sscanf(line, "%le %le %le", &(conf->box.x), &(conf->box.y), &(conf->box.z)) != 3) { if(getline(&line, &line_size, infile) == -1){ fprintf (stderr, "ERROR: Could not read box size.\n\n"); exit (1); } aftercommand(line2,line,BOXSEP); strip_comment(line2); trim(line2); if (sscanf(line2, "%le %le %le", &(conf->box.x), &(conf->box.y), &(conf->box.z)) != 3) { fprintf (stderr, "ERROR: Could not read box size.\n\n"); exit (1); } } if (conf->box.x < maxlength * 2.0 + 2.0) { printf ("WARNING: x box length is less than two spherocylinders long.\n\n"); } if (conf->box.y < maxlength * 2.0 + 2.0) { printf ("WARNING: y box length is less than two spherocylinders long.\n\n"); } if (conf->box.z < maxlength * 2.0 + 2.0) { printf ("WARNING: z box length is less than two spherocylinders long.\n\n"); } DEBUG_INIT("Position of the particle"); for (i=0; i < topo->npart; i++) { if(getline(&line, &line_size, infile) == -1){ break; } strip_comment(line); trim(line); fields = sscanf(line, "%le %le %le %le %le %le %le %le %le %d", &conf->particle[i].pos.x, &conf->particle[i].pos.y, &conf->particle[i].pos.z, &conf->particle[i].dir.x, &conf->particle[i].dir.y, &conf->particle[i].dir.z, &conf->particle[i].patchdir[0].x, &conf->particle[i].patchdir[0].y, &conf->particle[i].patchdir[0].z, &conf->particle[i].switched); conf->particle[i].patchdir[1].x = conf->particle[i].patchdir[1].y = conf->particle[i].patchdir[1].z =0; conf->particle[i].chdir[0].x = conf->particle[i].chdir[0].y = conf->particle[i].chdir[0].z =0; conf->particle[i].chdir[1].x = conf->particle[i].chdir[1].y = conf->particle[i].chdir[1].z =0; DEBUG_INIT("Line: %s\nNumber of Fields: %d", line, fields); if (fields == 9){ conf->particle[i].switched = 0; fprintf(stdout, "WARNING: Particle %ld is assumed to be not switched!\n", i+1); fields++; } if (fields != 10) { fprintf (stderr, "ERROR: Could not read coordinates for particle %ld.\n \ Did you specify box size at the begining?\n\n", i+1); free(line); exit (1); } /* Scale position vector to the unit cube */ usepbc(&conf->particle[i].pos, conf->box ); conf->particle[i].pos.x /= conf->box.x; conf->particle[i].pos.y /= conf->box.y; conf->particle[i].pos.z /= conf->box.z; if ((topo->ia_params[conf->particle[i].type][conf->particle[i].type].geotype[0]<SP)&&( DOT(conf->particle[i].dir, conf->particle[i].dir) < ZEROTOL )) { //DEBUG_INIT("Geotype = %d < %d", conf->particle[i].geotype,SP); fprintf (stderr, "ERROR: Null direction vector supplied for particle %ld.\n\n", i+1); free(line); exit (1); } else { normalise(&conf->particle[i].dir); } if ((topo->ia_params[conf->particle[i].type][conf->particle[i].type].geotype[0]<SP)&&( DOT(conf->particle[i].patchdir[0], conf->particle[i].patchdir[0]) < ZEROTOL )) { fprintf (stderr, "ERROR: Null patch vector supplied for particle %ld.\n\n", i+1); free(line); exit (1); } else { ortogonalise(&conf->particle[i].patchdir[0],conf->particle[i].dir); normalise(&conf->particle[i].patchdir[0]); } // Switch the type if(conf->particle[i].switched){ if(conf->particle[i].switchtype == 0){ fprintf(stderr, "ERROR: Particle %ld switched even though it has no switchtype", i); free(line); exit(1); } tmp_type = conf->particle[i].type; conf->particle[i].type = conf->particle[i].switchtype; conf->particle[i].switchtype = tmp_type; } DEBUG_INIT("%ld:\t%lf\t%lf\t%lf", i, conf->particle[i].pos.x, conf->particle[i].pos.y, conf->particle[i].pos.z); } free(line); /*Make chains WHOLE*/ for (i=0;i<topo->chainnum;i++){ j=0; current = topo->chainlist[i][0]; first = current; chorig[0].pos = conf->particle[first].pos; while (current >=0 ) { /*shift the chain particle by first one*/ conf->particle[current].pos.x -= chorig[0].pos.x; conf->particle[current].pos.y -= chorig[0].pos.y; conf->particle[current].pos.z -= chorig[0].pos.z; /*put it in orig box*/ conf->particle[current].pos.x -= anint(conf->particle[current].pos.x); conf->particle[current].pos.y -= anint(conf->particle[current].pos.y); conf->particle[current].pos.z -= anint(conf->particle[current].pos.z); //printf("ant: %f %f %f\n",conf->particle[current].pos.x,conf->particle[current].pos.y,conf->particle[current].pos.z); /*shot it back*/ conf->particle[current].pos.x += chorig[0].pos.x; conf->particle[current].pos.y += chorig[0].pos.y; conf->particle[current].pos.z += chorig[0].pos.z; //printf("posstart: %f %f %f\n",conf->particle[current].pos.x,conf->particle[current].pos.y,conf->particle[current].pos.z); j++; current = topo->chainlist[i][j]; } } err = 0; //for (i=0; i < topo->npart-1; i++) { // for (j=i+1; j < topo->npart; j++) { // if ( overlap(conf->particle[i], conf->particle[j], conf->box, topo->ia_params) ) { // fprintf (stderr, // "ERROR: Overlap in initial coniguration between particles %ld and %ld.\n", // i+1, j+1); // err = 1; // } // } //} if (err) { printf ("\n"); exit (1); } fclose (infile); fflush (stdout); } /*..............................................................................*/ /**************************************************************************** * TOPOLOGY INITIALIZATION *****************************************************************************/ /* Create lists for chain operations: Connectivity list where it is written for each sc with which sc it is connected. The order is important because spherocylinders have direction First is interacting tail then head. Chain list where particles are assigned to chains to which they belong */ void init_top(struct topo * topo, struct conf * conf, struct sim * sim,char filename[30]) { long i,j,k,mol,maxch,maxpart; FILE *infile; char *pline=NULL, *dummy=NULL, *sysnames[MAXN]; char line[STRLEN], keystr[STRLEN], molname[STRLEN]; unsigned size; long *sysmoln /*[MAXN]*/; BOOL exclusions[MAXT][MAXT]; char *fgets2(char *, int , FILE *); void strip_comment (char *); void trim(char *); int continuing(char *); void upstring (char *); int filltypes(char **, struct topo * topo); int fillexter(char **, struct topo * topo); int fillexclusions(char **, BOOL (*exclusions)[MAXT][MAXT]); void beforecommand(char *, char *, char); int fillmol(char *, char *, struct molecule * molecules, struct topo * topo); int fillsystem(char *, char *[MAXN], long **); void initparams(struct topo * topo); void genparampairs(struct topo * topo, BOOL (*exclusions)[MAXT][MAXT]); int topdealoc(char **, char *[MAXN], long **, struct molecule *); struct molecule molecules[MAXMT]; if ((infile = fopen(filename, "r")) == NULL) { fprintf (stderr, "\nTOPOLOGY ERROR: Could not open top.init file.\n\n"); exit (1); } fprintf (stdout, "Initialize chainlist...\n"); fflush(stdout); sysmoln = malloc( sizeof(long)*MAXN); if(sysmoln == NULL){ fprintf(stderr, "\nTOPOLOGY ERROR: Could not allocate memory for sysmoln"); exit(1); } struct particles tmp_particles[MAXN]; for (i=0;i<MAXN;i++) { if (i < MAXMT) { topo->chainparam[i].bond1eq = -1; topo->chainparam[i].bond1c = -1; topo->chainparam[i].bond2eq = -1; topo->chainparam[i].bond2c = -1; topo->chainparam[i].bonddc = -1; topo->chainparam[i].angle1eq = -1; topo->chainparam[i].angle1c = -1; topo->chainparam[i].angle2eq = -1; topo->chainparam[i].angle2c = -1; molecules[i].name = NULL; molecules[i].type = malloc(sizeof(long)*MAXN); molecules[i].switchtype = malloc(sizeof(long)*MAXN); molecules[i].delta_mu = malloc(sizeof(double)*MAXN); for (j=0;j<MAXN;j++) { molecules[i].type[j] = -1; } } for (j = 0; j < MAXCHL; j++){ topo->chainlist[i][j] = -1; } sysnames[i]=NULL; } for (i=0;i<MAXT;i++) { for (j=0;j<MAXT;j++) { exclusions[i][j]=FALSE; } } topo->exter.exist = FALSE; topo->exter.thickness = 0.0; topo->exter.epsilon = 0.0; topo->exter.attraction = 0.0; topo->exter.sqmaxcut = 0.0; for(i = 0; i < MAXT; i++){ for(j = 0; j < MAXT; j++){ for(k = 0; k < 2; k++){ topo->ia_params[i][j].geotype[k] = 0; } } } fprintf (stdout, "Reading topology...\n"); fflush(stdout); molname[0] = ' '; initparams(topo); pline=malloc((size_t)STRLEN); while (fgets2(line,STRLEN-2,infile) != NULL) { strcpy(pline,line); if (!pline) fprintf (stderr, "\nTOPOLOGY ERROR: Empty line in topology.\n\n"); /* build one long line from several fragments */ while (continuing(line) && (fgets2(line,STRLEN-1,infile) != NULL)) { size=strlen(pline)+strlen(line)+1; free(pline); pline=malloc((size_t)size); strcat(pline,line); } /* skip trailing and leading spaces and comment text */ strip_comment (pline); trim (pline); /* if there is something left... */ if ((int)strlen(pline) > 0) { // get the [COMMAND] key if (pline[0] == OPENKEY) { pline[0] = ' '; beforecommand(keystr,pline,CLOSEKEY); upstring (keystr); } else { //DEBUG fprintf (stdout, "Topology read type:%s, %s \n",keystr,pline); if (!strcmp(keystr,"TYPES")) { fflush(stdout); if (!filltypes(&pline, topo)) { DEBUG_INIT("Something went wrong with filltypes"); fprintf (stderr, "\nTOPOLOGY ERROR: in reading types\n\n"); topdealoc(&pline,sysnames,&sysmoln, molecules); exit (1); } DEBUG_INIT("back in init_top"); } else{ if (!strcmp(keystr,"MOLECULES")){ DEBUG_INIT("Let's go to the molecules"); if (molname[0] == ' ') { beforecommand(molname,pline,SEPARATOR); i=0; while (molecules[i].name != NULL) i++; DEBUG_INIT("in the middle of getting to fillmol"); molecules[i].name = malloc(strlen(molname)+1); strcpy(molecules[i].name, molname); fprintf (stdout, "Topology read for molecule: %s \n",molname); } if (!fillmol(molname, pline, molecules, topo)) { fprintf (stderr, "\nTOPOLOGY ERROR: in reading molecules\n\n"); topdealoc(&pline,sysnames,&sysmoln, molecules); exit (1); } if ((dummy = strchr (pline,CLOSEMOL)) != NULL) molname[0] = ' '; } else { if (!strcmp(keystr,"SYSTEM")) { if (!fillsystem(pline,sysnames,&sysmoln)) { fprintf (stderr, "\nTOPOLOGY ERROR: in reading system\n\n"); topdealoc(&pline,sysnames,&sysmoln, molecules); exit (1); } } else { if (!strcmp(keystr,"EXTER")) { fflush(stdout); if (!fillexter(&pline, topo)) { DEBUG_INIT("Something went wrong with external potential"); fprintf (stderr, "\nTOPOLOGY ERROR: in reading external potential\n\n"); topdealoc(&pline,sysnames,&sysmoln, molecules); exit (1); } } else { if (!strcmp(keystr,"EXCLUDE")) { fflush(stdout); if (!fillexclusions(&pline,&exclusions)) { DEBUG_INIT("Something went wrong with exclusions potential"); fprintf (stderr, "\nTOPOLOGY ERROR: in reading exclusions\n\n"); topdealoc(&pline,sysnames,&sysmoln, molecules); exit (1); } } else { fprintf (stderr, "\nTOPOLOGY ERROR: invalid keyword:%s.\n\n", keystr); topdealoc(&pline,sysnames,&sysmoln, molecules); exit (1); } } } } } } } } /*we have sucessfully read topology*/ if (pline !=NULL) free(pline); pline=NULL; fclose (infile); fflush (stdout); /*fill ia_params combinations*/ fprintf (stdout, "\nTopology succesfully read. Generating pair interactions...\n"); genparampairs(topo,&exclusions); double maxlength = 0; for(i = 0; i < MAXT; i++){ if(maxlength < topo->ia_params[i][i].len[0]) maxlength = topo->ia_params[i][i].len[0]; } topo->sqmaxcut += maxlength+2; topo->sqmaxcut *= 1.1; topo->maxcut = topo->sqmaxcut; topo->sqmaxcut = topo->sqmaxcut*topo->sqmaxcut; topo->exter.sqmaxcut += maxlength; topo->exter.sqmaxcut *= topo->exter.sqmaxcut*1.1; /*TODO fill chain list and maxch, park particle type*/ fprintf (stdout, "Generating chainlist...\n"); maxch=0; maxpart=0; i=0; while (sysnames[i]!=NULL) { mol=0; while (strcmp(molecules[mol].name,sysnames[i])) { mol++; if (molecules[mol].name == NULL) { fprintf (stderr, "TOPOLOGY ERROR: molecules %s is not defined.\n\n",sysnames[i]); topdealoc(&pline,sysnames,&sysmoln, molecules); exit(1); } } for (j=0;j<sysmoln[i];j++) { //DEBUG fprintf (stdout, "molnames %s sysname %s sysnum %ld \n",molnames[mol],sysnames[i],sysmoln[i]); k=0; while (molecules[mol].type[k] != -1) { tmp_particles[maxpart].type = molecules[mol].type[k]; tmp_particles[maxpart].switchtype = molecules[mol].switchtype[k]; tmp_particles[maxpart].delta_mu = molecules[mol].delta_mu[k]; tmp_particles[maxpart].chaint = mol; tmp_particles[maxpart].chainn = maxch; if (k > MAXCHL) { fprintf (stderr, "TOPOLOGY ERROR: more particles in chan (%ld) than allowed(%d).\n",k,MAXCHL); fprintf (stderr, "Change MAXCHL in source and recompile the program. \n\n"); topdealoc(&pline,sysnames,&sysmoln, molecules); exit(1); } if (molecules[mol].type[1] != -1) { topo->chainlist[maxch][k] = maxpart; } k++; maxpart++; if (maxpart > MAXN) { fprintf (stderr, "TOPOLOGY ERROR: more particles(%ld) than allowed(%d).\n",maxpart,MAXN); fprintf (stderr, "Change MAXN in source and recompile the program. \n\n"); topdealoc(&pline,sysnames,&sysmoln, molecules); exit(1); } } if (molecules[mol].type[1] != -1) { maxch++; } } i++; } topo->npart = maxpart; /* write the particles from the temporary to the "permanent" conf */ conf->particle = malloc(sizeof(struct particles) * topo->npart); if(conf->particle == NULL){ fprintf(stderr, "\nTOPOLOGY ERROR: Could not allocate memory for conf->particle"); exit(1); } for(i = 0; i < topo->npart; i++){ conf->particle[i].type = tmp_particles[i].type; conf->particle[i].switchtype = tmp_particles[i].switchtype; conf->particle[i].delta_mu = tmp_particles[i].delta_mu; conf->particle[i].chaint = tmp_particles[i].chaint; conf->particle[i].chainn = tmp_particles[i].chainn; } /* Initialize the clusterlist */ sim->clusterlist = malloc(sizeof(long) * topo->npart); if(sim->clusterlist == NULL){ fprintf(stderr, "\nTOPOLOGY ERROR: Could not allocate memory for sim->clusterlist!"); exit(1); } sim->clustersenergy = malloc(sizeof(double) * topo->npart); if(sim->clustersenergy== NULL){ fprintf(stderr, "\nTOPOLOGY ERROR: Could not allocate memory for sim->clustersenergy!"); exit(1); } sim->clusters = NULL; /* get all the particles with switch type */ long switchlist[topo->npart]; long n_switch_part = 0; for(i = 0; i < topo->npart; i++){ if(conf->particle[i].type != conf->particle[i].switchtype){ switchlist[n_switch_part] = i; n_switch_part++; } } topo->n_switch_part = n_switch_part; if (n_switch_part == 0 && sim->switchprob > 0){ fprintf(stderr, "TOPOLOGY WARNING: No switchable particles found, but probability for a switch is not zero!\n"); sim->switchprob = 0; fprintf(stderr, "TOPOLOGY WARNING: We changed Switch Probability to zero in this run!\n"); } topo->switchlist=NULL; if (n_switch_part > 0){ topo->switchlist = malloc(sizeof(long) * n_switch_part); for(i = 0; i < n_switch_part; i++){ topo->switchlist[i] = switchlist[i]; //DEBUG //printf("%ld is in switchlist\n", switchlist[i]); } } j = 0; while (topo->chainlist[j][0] >= 0) { j++; } topo->chainnum = j; if (topo->chainnum != maxch) { fprintf (stderr, "TOPOLOGY ERROR: Maximum number of chains(%ld) does not agree with number of chains (%ld)\n\n",maxch,topo->chainnum); topdealoc(&pline,sysnames,&sysmoln, molecules); exit (1); } k=0; /*clear connectivity and then fill it from chain list*/ fprintf (stdout, "Generating connectivity...\n"); for (i=0; i<MAXN; i++) { topo->conlist[i][0] = -1; topo->conlist[i][1] = -1; topo->conlist[i][2] = -1; topo->conlist[i][3] = -1; } conf->sysvolume = 0; for (i=0; i<maxpart; i++) { for (j=0; j<MAXCHL; j++) { if (topo->chainlist[i][j] >= 0) { k = topo->chainlist[i][j]; if ((j+1 < MAXCHL)&&(topo->chainlist[i][j+1] >= 0)) topo->conlist[k][1] = topo->chainlist[i][j+1]; /*if there is a next particle fill it to head bond*/ if (j > 0) topo->conlist[k][0] = topo->chainlist[i][j-1]; /*if this is not first particle fill tail bond*/ if ((j+2 < MAXCHL)&& (topo->chainlist[i][j+2] >= 0)) topo->conlist[k][3] = topo->chainlist[i][j+2]; /*if there is a second next particle fill it second neighbour*/ if (j > 1) topo->conlist[k][2] = topo->chainlist[i][j-2]; /*if this is not second or first particle fill second tail bond*/ } } conf->sysvolume += topo->ia_params[conf->particle[i].type][conf->particle[i].type].volume; } /*DEBUG for (i=0; i<MAXN; i++) { for (j=0; j<MAXCHL; j++) { fprintf (stderr, " %d",chainlist[i][j]); } fprintf (stderr, " \n"); } for (i=0; i<MAXN; i++) { printf (" %ld %ld %ld %ld\n",conlist[i][0],conlist[i][1],conlist[i][2],conlist[i][3]); } */ // Mark particles as not switched for(i = 0; i < maxpart; i++){ conf->particle[i].switched = 0; } topdealoc(&pline,sysnames,&sysmoln, molecules); DEBUG_INIT("Finished with reading the topology"); /* Parallel tempering check */ #ifdef MPI // probability to switch replicas = exp ( -0.5 * dT*dT * N / (1 + dT) ) printf("Probability to switch replicas is roughly: %f\n",exp(-0.5 * maxpart * sim->dtemp * sim->dtemp / (1.0 + sim->dtemp)) ); #endif } /*..........................................................................*/ /*dealocting memory for init_top*/ int topdealoc(char **pline,char *sysnames[MAXN], long **sysmoln, struct molecule * molecules) { long i; if ((*pline) != NULL) free((*pline)); (*pline)=NULL; if ((*sysmoln) != NULL) free((*sysmoln)); (*sysmoln)=NULL; for (i=0;i<MAXN;i++) { if (i < MAXMT) { free(molecules[i].name); free(molecules[i].type); free(molecules[i].switchtype); free(molecules[i].delta_mu); } if ((sysnames[i]) != NULL) free(sysnames[i]); sysnames[i]=NULL; } return 0; } /* initiate vectors of a single particle*/ void int_partvec(long target, struct ia_param * ia_parami, struct conf * conf ) { struct quat quatrot; struct quat quat_create(struct vector, double, double); void vec_rotate(struct vector *, struct quat); void normalise(struct vector *); void ortogonalise(struct vector *,struct vector); if ( (ia_parami->geotype[0] == SCA) || (ia_parami->geotype[0] == SCN) ){ /*SCA and SCN are isotropic... nothing to initialize*/ return; } normalise (&conf->particle[target].dir); ortogonalise(&conf->particle[target].patchdir[0],conf->particle[target].dir); /*calculate patch sides*/ if ( (ia_parami->geotype[0] == PSC) || (ia_parami->geotype[0] == CPSC) || (ia_parami->geotype[0] == TPSC) || (ia_parami->geotype[0] == TCPSC) ){ /* rotate patch vector by half size of patch*/ conf->particle[target].patchsides[0] = conf->particle[target].patchdir[0]; quatrot=quat_create(conf->particle[target].dir, ia_parami->pcoshalfi[0], ia_parami->psinhalfi[0]); vec_rotate(&(conf->particle[target].patchsides[0]),quatrot); /*second side*/ conf->particle[target].patchsides[1] = conf->particle[target].patchdir[0]; quatrot=quat_create(conf->particle[target].dir, ia_parami->pcoshalfi[0], -1.0*ia_parami->psinhalfi[0]); vec_rotate(&(conf->particle[target].patchsides[1]),quatrot); } /*calculate second patchdir*/ if ( (ia_parami->geotype[0] == TPSC) || (ia_parami->geotype[0] == TCPSC) || (ia_parami->geotype[0] == TCHPSC) || (ia_parami->geotype[0] == TCHCPSC)){ conf->particle[target].patchdir[1] = conf->particle[target].patchdir[0]; quatrot=quat_create(conf->particle[target].dir, ia_parami->csecpatchrot[0], ia_parami->ssecpatchrot[0]); vec_rotate(&(conf->particle[target].patchdir[1]),quatrot); ortogonalise(&conf->particle[target].patchdir[1],conf->particle[target].dir); } /*calculate second patch sides*/ if ( (ia_parami->geotype[0] == TPSC) || (ia_parami->geotype[0] == TCPSC) ){ /* rotate patch vector by half size of patch*/ conf->particle[target].patchsides[2] = conf->particle[target].patchdir[1]; quatrot=quat_create(conf->particle[target].dir, ia_parami->pcoshalfi[2], ia_parami->psinhalfi[2]); vec_rotate(&(conf->particle[target].patchsides[2]),quatrot); /*second side*/ conf->particle[target].patchsides[3] = conf->particle[target].patchdir[1]; quatrot=quat_create(conf->particle[target].dir, ia_parami->pcoshalfi[2], -1.0*ia_parami->psinhalfi[2]); vec_rotate(&(conf->particle[target].patchsides[3]),quatrot); } /*calculate chdir vector*/ if ( (ia_parami->geotype[0] == CHPSC) || (ia_parami->geotype[0] == CHCPSC) || (ia_parami->geotype[0] == TCHPSC) || (ia_parami->geotype[0] == TCHCPSC)){ conf->particle[target].chdir[0] = conf->particle[target].dir; quatrot = quat_create(conf->particle[target].patchdir[0], ia_parami->chiral_cos[0], ia_parami->chiral_sin[0]); vec_rotate(&(conf->particle[target].chdir[0]), quatrot); /* rotate patch vector by half size of patch*/ conf->particle[target].patchsides[0] = conf->particle[target].patchdir[0]; quatrot=quat_create(conf->particle[target].chdir[0], ia_parami->pcoshalfi[0], ia_parami->psinhalfi[0]); vec_rotate(&(conf->particle[target].patchsides[0]),quatrot); /*second side*/ conf->particle[target].patchsides[1] = conf->particle[target].patchdir[0]; quatrot=quat_create(conf->particle[target].chdir[0], ia_parami->pcoshalfi[0], -1.0*ia_parami->psinhalfi[0]); vec_rotate(&(conf->particle[target].patchsides[1]),quatrot); } /*calculate chdir vector for seond patch*/ if ( (ia_parami->geotype[0] == TCHPSC) || (ia_parami->geotype[0] == TCHCPSC) ){ conf->particle[target].chdir[1] = conf->particle[target].dir; quatrot = quat_create(conf->particle[target].patchdir[1], ia_parami->chiral_cos[0], ia_parami->chiral_sin[0]); vec_rotate(&(conf->particle[target].chdir[1]), quatrot); /* rotate patch vector by half size of patch to get sides*/ conf->particle[target].patchsides[2] = conf->particle[target].patchdir[1]; quatrot=quat_create(conf->particle[target].chdir[1], ia_parami->pcoshalfi[2], ia_parami->psinhalfi[2]); vec_rotate(&(conf->particle[target].patchsides[2]),quatrot); /*second side*/ conf->particle[target].patchsides[3] = conf->particle[target].patchdir[1]; quatrot=quat_create(conf->particle[target].chdir[1], ia_parami->pcoshalfi[2], -1.0*ia_parami->psinhalfi[2]); vec_rotate(&(conf->particle[target].patchsides[3]),quatrot); } } /* calculate vectors on particles for speedup*/ void partvecinit(struct topo * topo, struct sim * sim, struct conf * conf ) { long i; void int_partvec(long target, struct ia_param *, struct conf * conf ); for(i = 0; i < topo->npart; i++){ if ( topo->ia_params[conf->particle[i].type][conf->particle[i].type].geotype[0] < SP) int_partvec(i,&(topo->ia_params[conf->particle[i].type][conf->particle[i].type]),conf); } } /*generate interations pairs*/ void genparampairs(struct topo * topo, BOOL (*exclusions)[MAXT][MAXT]) { int i,j,k; int a[2]; int len; double length = 0; // The length of a PSC, currently only one is allow, ie implemented for (i=0;i<MAXT;i++) { for (j=0;j<MAXT;j++) { if (i!=j) { if((topo->ia_params[j][j].geotype[0] != 0) && (topo->ia_params[i][i].geotype[0] != 0)){ a[0] = i; a[1] = j; for(k = 0; k < 2; k++){ topo->ia_params[i][j].geotype[k] = topo->ia_params[a[k]][a[k]].geotype[0]; topo->ia_params[i][j].len[k] = topo->ia_params[a[k]][a[k]].len[0]; if (topo->ia_params[a[k]][a[k]].len[0] > 0){ if (length == 0){ length = topo->ia_params[a[k]][a[k]].len[0]; } else if (length > 0){ if (length != topo->ia_params[a[k]][a[k]].len[0]){ fprintf(stderr, "Error: "); fprintf(stderr, "Different lengths for spherocylinders have not been implemented yet!\n"); fprintf(stderr, "\tCheck the length of type %d!\n", a[k]); exit(1); } } } topo->ia_params[i][j].half_len[k] = topo->ia_params[a[k]][a[k]].half_len[0]; /* Handle angles only, when geotype is a patchs sphero cylinder */ if(topo->ia_params[i][j].geotype[k] >= PSC && topo->ia_params[i][j].geotype[k] < SP){ topo->ia_params[i][j].pangl[k] = topo->ia_params[a[k]][a[k]].pangl[0]; topo->ia_params[i][j].panglsw[k] = topo->ia_params[a[k]][a[k]].panglsw[0]; topo->ia_params[i][j].pcangl[k] = cos(topo->ia_params[i][j].pangl[k]/2.0/180*PI); topo->ia_params[i][j].pcanglsw[k] = cos((topo->ia_params[i][j].pangl[k]/2.0+topo->ia_params[i][j].panglsw[k])/180*PI); topo->ia_params[i][j].pcoshalfi[k] = cos((topo->ia_params[i][j].pangl[k]/2.0+topo->ia_params[i][j].panglsw[k])/2.0/180*PI); topo->ia_params[i][j].psinhalfi[k] = sqrt(1.0 - topo->ia_params[i][j].pcoshalfi[k] * topo->ia_params[i][j].pcoshalfi[k]); } /* Only when the PSC is chiral */ if( (topo->ia_params[i][j].geotype[k] == CHCPSC) || (topo->ia_params[i][j].geotype[k] == CHPSC) \ || (topo->ia_params[i][j].geotype[k] == TCHCPSC) || (topo->ia_params[i][j].geotype[k] == TCHPSC) ){ topo->ia_params[i][j].chiral_cos[k] = topo->ia_params[a[k]][a[k]].chiral_cos[0]; topo->ia_params[i][j].chiral_sin[k] = topo->ia_params[a[k]][a[k]].chiral_sin[0]; } /* Information of two patches */ if( (topo->ia_params[i][j].geotype[k] == TCPSC) || (topo->ia_params[i][j].geotype[k] == TPSC) \ || (topo->ia_params[i][j].geotype[k] == TCHCPSC) || (topo->ia_params[i][j].geotype[k] == TCHPSC) ){ topo->ia_params[i][j].csecpatchrot[k] = topo->ia_params[a[k]][a[k]].csecpatchrot[0]; topo->ia_params[i][j].ssecpatchrot[k] = topo->ia_params[a[k]][a[k]].ssecpatchrot[0]; topo->ia_params[i][j].pangl[k+2] = topo->ia_params[a[k]][a[k]].pangl[2]; topo->ia_params[i][j].panglsw[k+2] = topo->ia_params[a[k]][a[k]].panglsw[2]; topo->ia_params[i][j].pcangl[k+2] = cos(topo->ia_params[i][j].pangl[k+2]/2.0/180*PI); topo->ia_params[i][j].pcanglsw[k+2] = cos((topo->ia_params[i][j].pangl[k+2]/2.0+topo->ia_params[i][j].panglsw[k+2])/180*PI); topo->ia_params[i][j].pcoshalfi[k+2] = cos((topo->ia_params[i][j].pangl[k+2]/2.0+topo->ia_params[i][j].panglsw[k+2])/2.0/180*PI); topo->ia_params[i][j].psinhalfi[k+2] = sqrt(1.0 - topo->ia_params[i][j].pcoshalfi[k+2] * topo->ia_params[i][j].pcoshalfi[k+2]); } } len = strlen(topo->ia_params[i][i].name); strncpy(topo->ia_params[i][j].name, topo->ia_params[i][i].name, len + 1); len = strlen(topo->ia_params[i][i].other_name); strncpy(topo->ia_params[i][j].other_name, topo->ia_params[i][i].other_name, len + 1); topo->ia_params[i][j].sigma = AVER(topo->ia_params[i][i].sigma,topo->ia_params[j][j].sigma); topo->ia_params[i][j].epsilon = sqrt(topo->ia_params[i][i].epsilon * topo->ia_params[j][j].epsilon); topo->ia_params[i][j].pswitch = AVER(topo->ia_params[i][i].pswitch,topo->ia_params[j][j].pswitch); topo->ia_params[i][j].rcutwca = (topo->ia_params[i][j].sigma)*pow(2.0,1.0/6.0); // Averaging of the flat part of attraction topo->ia_params[i][j].pdis = AVER(topo->ia_params[i][i].pdis - topo->ia_params[i][i].rcutwca, \ topo->ia_params[j][j].pdis - topo->ia_params[j][j].rcutwca) + topo->ia_params[i][j].rcutwca; topo->ia_params[i][j].rcut = topo->ia_params[i][j].pswitch+topo->ia_params[i][j].pdis; // if not non-attractive == if attractive if (!((topo->ia_params[i][j].geotype[0] % 10 == 0) || (topo->ia_params[i][j].geotype[1] % 10 == 0))){ if (topo->ia_params[i][j].rcutwca > topo->ia_params[i][j].rcut){ fprintf(stderr, "Error: Repulsive cutoff is larger than the attractive cutoff!\n"); fprintf(stderr, " between %d and %d: %lf > %lf\n", i, j, topo->ia_params[i][j].rcutwca, topo->ia_params[i][j].rcut); } } if ( topo->ia_params[i][j].rcutwca > topo->sqmaxcut ) topo->sqmaxcut = topo->ia_params[i][j].rcutwca; if ( topo->ia_params[i][j].rcut > topo->sqmaxcut ) topo->sqmaxcut = topo->ia_params[i][j].rcut; } } } /*filling interaction with external potential*/ if( (topo->exter.exist) && (topo->ia_params[i][i].geotype[0] != 0)){ /*use everything like for given particles except distance and attraction, which is generated as for other interactions*/ topo->exter.interactions[i] = topo->ia_params[i][i]; topo->exter.interactions[i].sigma = AVER(topo->ia_params[i][i].sigma, topo->exter.thickness); topo->exter.interactions[i].rcutwca = (topo->exter.interactions[i].sigma)*pow(2.0,1.0/6.0); topo->exter.interactions[i].epsilon = sqrt(topo->ia_params[i][i].epsilon * topo->exter.epsilon); topo->exter.interactions[i].pswitch = AVER(topo->ia_params[i][i].pswitch, topo->exter.attraction); topo->exter.interactions[i].pdis = AVER(topo->ia_params[i][i].pdis - topo->ia_params[i][i].rcutwca, 0.0) + topo->exter.interactions[i].rcutwca; topo->exter.interactions[i].rcut = topo->exter.interactions[i].pswitch + topo->exter.interactions[i].pdis; if (topo->exter.interactions[i].rcut > topo->exter.sqmaxcut ) topo->exter.sqmaxcut = topo->exter.interactions[i].rcut; } } for (i=0;i<MAXT;i++) { for (j=0;j<MAXT;j++) { if ( (*exclusions)[i][j] ) topo->ia_params[i][j].epsilon = 0.0; } } } /*initialize parameters for interactions*/ void initparams(struct topo * topo) { int i,j,k; for (i=0;i<MAXT;i++) { for (j=0;j<MAXT;j++) { for(k = 0; k < 2; k++){ topo->ia_params[i][j].geotype[k] = 0; topo->ia_params[i][j].len[k] = 0.0; topo->ia_params[i][j].half_len[k] = 0.0; topo->ia_params[i][j].chiral_cos[k] = 0.0; topo->ia_params[i][j].chiral_sin[k] = 0.0; topo->ia_params[i][j].csecpatchrot[k] = 0.0; topo->ia_params[i][j].ssecpatchrot[k] = 0.0; } for(k = 2; k < 4; k++){ topo->ia_params[i][j].pangl[k] = 0.0; topo->ia_params[i][j].panglsw[k] = 0.0; topo->ia_params[i][j].pcangl[k] = 0.0; topo->ia_params[i][j].pcanglsw[k] = 0.0; topo->ia_params[i][j].pcoshalfi[k] = 0.0; topo->ia_params[i][j].psinhalfi[k] = 0.0; } topo->ia_params[i][j].sigma = 0.0; topo->ia_params[i][j].epsilon = 0.0; topo->ia_params[i][j].rcutwca = 0.0; topo->ia_params[i][j].pdis = 0.0; topo->ia_params[i][j].pswitch = 0.0; topo->ia_params[i][j].rcut = 0.0; topo->ia_params[i][j].volume = 0.0; topo->ia_params[i][j].pvolscale = 0.0; } } topo->sqmaxcut = 0; } /*...........................................................................*/ /*filling the system parameters*/ int fillsystem(char *pline, char *sysnames[MAXN], long **sysmoln) { int i,fields; char zz[STRLEN]; void trim (char *); trim(pline); if (!pline) { fprintf (stderr, "TOPOLOGY ERROR: obtained empty line in fil system.\n\n"); return 0; } i=0; while (sysnames[i]!=NULL) i++; fields = sscanf(pline, "%s %ld", zz, &(*sysmoln)[i]); sysnames[i]=malloc(strlen(zz)+1); strcpy(sysnames[i],zz); if (fields != 2) { fprintf (stderr, "TOPOLOGY ERROR: failed reading system from (%s).\n\n", pline); return 0; } if ((*sysmoln)[i] < 1) { fprintf (stderr, "TOPOLOGY ERROR: cannot have %ld number of molecules.\n\n", (*sysmoln)[i]); return 0; } fprintf (stdout, "system: %s %ld\n",sysnames[i],(*sysmoln)[i]); return 1; } /*filling the parameters for molecules*/ int fillmol(char *molname, char *pline, struct molecule * molecules, struct topo * topo) { DEBUG_INIT("fillmol just has been called!"); char str[STRLEN],str2[STRLEN],molcommand[STRLEN],molparams[STRLEN]; int i,j,fields; double bondk,bonddist; void trim (char *); void upstring(char *); void beforecommand(char *, char *, char); void aftercommand(char *, char *, char); beforecommand(str2, pline, CLOSEMOL); aftercommand(str, str2, OPENMOL); trim(str); if (strlen(str) == 0) return 1; beforecommand(molcommand,str,SEPARATOR); aftercommand(molparams,str,SEPARATOR); trim(molcommand); trim(molparams); upstring (molcommand); DEBUG_INIT("molcommand: %s", molcommand); DEBUG_INIT("molparams: %s", molparams); i=0; while (strcmp(molecules[i].name, molname)) i++; j=0; while (molecules[i].type[j] != -1) j++; if (!strcmp(molcommand,"PARTICLES")) { fprintf (stdout, "particle %d: \t", j + 1); fields = sscanf(molparams,"%ld %ld %lf",molecules[i].type + j, molecules[i].switchtype + j, molecules[i].delta_mu + j); fprintf (stdout, "%ld ",molecules[i].type[j]); if (fields == 1){ (molecules[i].switchtype[j]) = (molecules[i].type[j]); (molecules[i].delta_mu[j]) = 0; fields = 3; } else{ fprintf(stdout, "(with switchtype: %ld and delta_mu: %lf)", molecules[i].switchtype[j], molecules[i].delta_mu[j]); } if (fields != 3) { fprintf (stderr, "TOPOLOGY ERROR: could not read a pacticle.\n\n"); return 0; } fflush(stdout); if (molecules[i].type[j] < 0) { fprintf (stderr, "TOPOLOGY ERROR: pacticles include negative type.\n\n"); return 0; } if (molecules[i].type[j] > MAXT) { fprintf (stderr, "TOPOLOGY ERROR: pacticles include type out of range 0-%ld.\n\n",(long)MAXT); return 0; } fprintf (stdout, "\n"); return 1; } if (!strcmp(molcommand,"BOND1")) { fields = sscanf(molparams, "%le %le ", &bondk, &bonddist); if (fields < 2) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for bond1, should be 2.\n\n"); return 0; } if (bonddist < 0) { fprintf (stderr, "TOPOLOGY ERROR: bonddist cannot be negative: %f \n\n",bonddist); return 0; } topo->chainparam[i].bond1c = bondk; topo->chainparam[i].bond1eq = bonddist; fprintf (stdout, "bond1: %f %f \n",topo->chainparam[i].bond1c,topo->chainparam[i].bond1eq); return 1; } if (!strcmp(molcommand,"BOND2")) { fields = sscanf(molparams, "%le %le ", &bondk, &bonddist); if (fields < 2) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for bond2, should be 2.\n\n"); return 0; } if (bonddist < 0) { fprintf (stderr, "TOPOLOGY ERROR: bonddist cannot be negative: %f \n\n",bonddist); return 0; } topo->chainparam[i].bond2c = bondk; topo->chainparam[i].bond2eq = bonddist; fprintf (stdout, "bond2: %f %f \n",topo->chainparam[i].bond2c,topo->chainparam[i].bond2eq); return 1; } if (!strcmp(molcommand,"BONDD")) { fields = sscanf(molparams, "%le %le ", &bondk, &bonddist); if (fields < 2) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for bondd, should be 2.\n\n"); return 0; } if (bonddist < 0) { fprintf (stderr, "TOPOLOGY ERROR: bonddist cannot be negative: %f \n\n",bonddist); return 0; } topo->chainparam[i].bonddc = bondk; topo->chainparam[i].bonddeq = bonddist; fprintf (stdout, "bondd: %f %f \n",topo->chainparam[i].bonddc,topo->chainparam[i].bonddeq); return 1; } if (!strcmp(molcommand,"ANGLE1")) { fields = sscanf(molparams, "%le %le ", &bondk, &bonddist); if (fields < 2) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for angle1, should be 2.\n\n"); return 0; } if (bonddist < 0) { fprintf (stderr, "TOPOLOGY ERROR: equilibrium angle cannot be negative: %f \n\n",bonddist); return 0; } topo->chainparam[i].angle1c = bondk; topo->chainparam[i].angle1eq = bonddist/180.0*PI; fprintf (stdout, "angle1: %f %f \n",topo->chainparam[i].angle1c,topo->chainparam[i].angle1eq); return 1; } if (!strcmp(molcommand,"ANGLE2")) { fields = sscanf(molparams, "%le %le ", &bondk, &bonddist); if (fields < 2) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for angle2, should be 2.\n\n"); return 0; } if (bonddist < 0) { fprintf (stderr, "TOPOLOGY ERROR: equilibrium angle cannot be negative: %f \n\n",bonddist); return 0; } topo->chainparam[i].angle2c = bondk; topo->chainparam[i].angle2eq = bonddist/180.0*PI; fprintf (stdout, "angle2: %f %f \n",topo->chainparam[i].angle2c,topo->chainparam[i].angle2eq); return 1; } fprintf (stderr, "TOPOLOGY ERROR: unknown parameter: %s.\n\n",molcommand); return 0; } /* Converts the geometrical type string into a number */ int convert_geotype(char * geotype){ if (strcmp(geotype, "CPSC") == 0) return CPSC; if (strcmp(geotype, "CHCPSC") == 0) return CHCPSC; if (strcmp(geotype, "SCA") == 0) return SCA; if (strcmp(geotype, "PSC") == 0) return PSC; if (strcmp(geotype, "CHPSC") == 0) return CHPSC; if (strcmp(geotype, "TCPSC") == 0) return TCPSC; if (strcmp(geotype, "TCHCPSC") == 0) return TCHCPSC; if (strcmp(geotype, "TPSC") == 0) return TPSC; if (strcmp(geotype, "TCHPSC") == 0) return TCHPSC; if (strcmp(geotype, "SPN") == 0) return SPN; if (strcmp(geotype, "SPA") == 0) return SPA; return 0; } /*filling the parameters of external potentail - wall. Returns 1 on succes.*/ int fillexter(char **pline, struct topo * topo) { int fields; double param[3]; /* 0: thickness * 1: epsilon * 2: attraction */ char typestr[STRLEN], paramstr[STRLEN]; void trim (char *); void beforecommand(char *, char *, char); void aftercommand(char *, char *, char); beforecommand(typestr, *pline, SEPARATOR); aftercommand(paramstr, *pline, SEPARATOR); fields = sscanf(paramstr, "%le %le %le", &param[0], &param[1], &param[2]); if (fields >3) { fprintf (stderr, "TOPOLOGY ERROR: too many parameters for external potential. We have \ thickness, epsilon, and attraction distance so far.\n\n"); return 0; } if (fields >0) { topo->exter.exist = TRUE; topo->exter.thickness = param[0]; fprintf(stdout, "External potential with thickness: %le ",topo->exter.thickness); if (fields >1) { topo->exter.epsilon = param[1]; fprintf(stdout, "epsilon: %le ",topo->exter.epsilon); if (fields >2) { topo->exter.attraction = param[2]; fprintf(stdout, "and range of attraction: %le ",topo->exter.attraction); } } } else{ topo->exter.exist = FALSE; fprintf(stdout, "No external potential "); } fprintf(stdout, " \n"); DEBUG_INIT("Finished filling external potential"); return 1; } /*filling pair for which we exlude attraction interaction. Returns 1 on succes.*/ int fillexclusions(char **pline, BOOL (*exlusions)[MAXT][MAXT]) { long num1,num2; char *pline1, *pline2; void trim (char *); num1 = strtol(*pline, &pline2, 10); trim(pline2); if ((int)strlen(pline2) > 0) { num2 = strtol(pline2, &pline1, 10); trim(pline1); (*exlusions)[num1][num2]=TRUE; (*exlusions)[num2][num1]=TRUE; fprintf(stderr, "Exclusions %ld %ld \n", num1, num2); } else { fprintf(stderr, "Error in readin Topology exclusions, probably there is not even number of types \n"); return 0; } while ((int)strlen(pline1) > 0) { num1 = strtol(pline1, &pline2, 10); trim(pline2); if ((int)strlen(pline2) > 0) { num2 = strtol(pline2, &pline1, 10); trim(pline1); (*exlusions)[num1][num2]=TRUE; (*exlusions)[num2][num1]=TRUE; fprintf(stderr, "Exclusions %ld %ld \n", num1, num2); } else { fprintf(stderr, "Error in readin Topology exclusions, probably there is not even number of types \n"); return 0; } } return 1; } /*filing the parameters for types from given strings. Returns 1 on succes.*/ int filltypes(char **pline, struct topo * topo) { int type; int geotype_i; int fields; char name[SMSTR]; char geotype[SMSTR]; double param[11]; /* 0: epsilon * 1: sigma * 2: attraction dist * 3: sttraction switch * 4: patch angle * 5: patch switch * 6: length * 7(optional): second patche rotation * 8(optional): second patch angle * 9(optional): second patch angle switch * +1: chirality */ char typestr[STRLEN], paramstr[STRLEN]; void trim (char *); void beforecommand(char *, char *, char); void aftercommand(char *, char *, char); beforecommand(typestr, *pline, SEPARATOR); aftercommand(paramstr, *pline, SEPARATOR); fields = sscanf(paramstr, "%s %d %s %le %le %le %le %le %le %le %le %le %le %le", name, &type, geotype, &param[0], &param[1], &param[2], &param[3], &param[4], &param[5], &param[6], &param[7], &param[8], &param[9], &param[10]); fields -= 5; // number of parameter fields => I am too lazy to adjust everywhere below the numbers //DEBUG fprintf (stdout, "Topology read geotype: %ld with parameters fields %d, str:%s and %s in pline %s\n",geotype,fields,geotypestr,paramstr,pline); geotype_i = convert_geotype(geotype); if(!geotype_i){ fprintf(stderr, "TOPOLOGY ERROR: Unknown GEOTYPE: %s!", geotype); return 0; } DEBUG_INIT("geotype_i: %d; fields = %d", geotype_i, fields); if (( (geotype_i == SCN) || (geotype_i == SPN) ) && (fields != 0)) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for %s geotype, should be 1.\n\n", geotype); return 0; } if (( (geotype_i == SCA) || (geotype_i == SPA)) && (fields != 2)) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for %s geotype, should be 3.\n\n", geotype); return 0; } if (( (geotype_i == PSC) || (geotype_i == CPSC) ) && (fields != 5)) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for %s geotype, should be 5.\n\n", geotype); return 0; } if (( (geotype_i == CHCPSC) || (geotype_i == CHCPSC) )&& ( fields != 6)) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for %s geotype, should be 6.\n\n", geotype); return 0; } if (( (geotype_i == TPSC) || (geotype_i == TCPSC) ) && (fields != 8)) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for %s geotype, should be 8.\n\n", geotype); return 0; } if (( (geotype_i == TCHCPSC) || (geotype_i == TCHCPSC) )&& ( fields != 9)) { fprintf (stderr, "TOPOLOGY ERROR: wrong number of parameters for %s geotype, should be 9.\n\n", geotype); return 0; } if ((geotype_i < 0) || (geotype_i > (MAXT + 10))) { fprintf (stderr, "TOPOLOGY ERROR: geotype (%s) is out of range: 0 - %d.\n\n", geotype, MAXT + 10); return 0; } strcpy(topo->ia_params[type][type].name, name); strcpy(topo->ia_params[type][type].other_name, name); topo->ia_params[type][type].geotype[0] = geotype_i; topo->ia_params[type][type].geotype[1] = geotype_i; topo->ia_params[type][type].epsilon = param[0]; topo->ia_params[type][type].sigma = param[1]; topo->ia_params[type][type].rcutwca = (topo->ia_params[type][type].sigma)*pow(2.0,1.0/6.0); fprintf(stdout, "Topology read of %d: %s (geotype: %s, %d) with parameters %lf %lf", type, name, geotype, geotype_i, topo->ia_params[type][type].epsilon, topo->ia_params[type][type].sigma); if (fields > 0) { topo->ia_params[type][type].pdis = param[2]; topo->ia_params[type][type].pswitch = param[3]; topo->ia_params[type][type].rcut = topo->ia_params[type][type].pswitch+topo->ia_params[type][type].pdis; fprintf(stdout, " %f %f",topo->ia_params[type][type].pdis,topo->ia_params[type][type].pswitch); } if (fields > 2) { int i; for(i = 0; i < 2; i++){ topo->ia_params[type][type].len[i] = param[6]; topo->ia_params[type][type].half_len[i] = param[6] / 2; topo->ia_params[type][type].pangl[i] = param[4]; topo->ia_params[type][type].panglsw[i] = param[5]; topo->ia_params[type][type].pcangl[i] = cos(param[4]/2.0/180*PI); // C1 topo->ia_params[type][type].pcanglsw[i] = cos((param[4]/2.0+param[5])/180*PI); // C2 //topo->ia_params[type][type].pcangl[i] = topo->ia_params[type][type].pcangl[i]; //topo->ia_params[type][type].pcanglsw[i] = topo->ia_params[type][type].pcanglsw[i]; topo->ia_params[type][type].pcoshalfi[i] = cos((param[4]/2.0+param[5])/2.0/180*PI); topo->ia_params[type][type].psinhalfi[i] = sqrt(1.0 - topo->ia_params[type][type].pcoshalfi[i] * topo->ia_params[type][type].pcoshalfi[i]); } fprintf(stdout, " %f %f", topo->ia_params[type][type].pangl[0], topo->ia_params[type][type].panglsw[0]); } if(fields == 6){ int i; for(i = 0; i < 2; i++){ topo->ia_params[type][type].chiral_cos[i] = cos(param[7] / 360 * PI); topo->ia_params[type][type].chiral_sin[i] = sqrt(1 - topo->ia_params[type][type].chiral_cos[i] * topo->ia_params[type][type].chiral_cos[i]); fprintf(stdout, " %f ", param[7]); } } if ((fields == 8)||(fields == 9)) { int i; for(i = 0; i < 2; i++){ topo->ia_params[type][type].csecpatchrot[i] = cos(param[7] / 360 * PI); topo->ia_params[type][type].ssecpatchrot[i] = sqrt(1 - topo->ia_params[type][type].csecpatchrot[i] * topo->ia_params[type][type].csecpatchrot[i]); //fprintf(stdout, " %f %f", topo->ia_params[type][type].csecpatchrot[0], topo->ia_params[type][type].ssecpatchrot[0]); topo->ia_params[type][type].pangl[i+2] = param[8]; topo->ia_params[type][type].panglsw[i+2] = param[9]; topo->ia_params[type][type].pcangl[i+2] = cos(param[8]/2.0/180*PI); // C1 topo->ia_params[type][type].pcanglsw[i+2] = cos((param[8]/2.0+param[9])/180*PI); // C2 //topo->ia_params[type][type].pcangl[i] = topo->ia_params[type][type].pcangl[i]; //topo->ia_params[type][type].pcanglsw[i] = topo->ia_params[type][type].pcanglsw[i]; topo->ia_params[type][type].pcoshalfi[i+2] = cos((param[8]/2.0+param[9])/2.0/180*PI); topo->ia_params[type][type].psinhalfi[i+2] = sqrt(1.0 - topo->ia_params[type][type].pcoshalfi[i+2] * topo->ia_params[type][type].pcoshalfi[i+2]); } fprintf(stdout, " %f %f %f", param[7], topo->ia_params[type][type].pangl[2], topo->ia_params[type][type].panglsw[2]); } if(fields == 9){ int i; for(i = 0; i < 2; i++){ topo->ia_params[type][type].chiral_cos[i] = cos(param[10] / 360 * PI); topo->ia_params[type][type].chiral_sin[i] = sqrt(1 - topo->ia_params[type][type].chiral_cos[i] * topo->ia_params[type][type].chiral_cos[i]); fprintf(stdout, " %f ", param[9]); } } // Volume if (geotype_i < SP) topo->ia_params[type][type].volume = 4.0/3.0*PI*pow((topo->ia_params[type][type].sigma)/2.0,3.0) + PI/2.0*topo->ia_params[type][type].len[0]*pow((topo->ia_params[type][type].sigma)/2.0,2.0) ; else topo->ia_params[type][type].volume = 4.0/3.0*PI*pow((topo->ia_params[type][type].sigma)/2.0,3.0); if ( topo->ia_params[type][type].rcutwca > topo->sqmaxcut ) topo->sqmaxcut = topo->ia_params[type][type].rcutwca; if ( topo->ia_params[type][type].rcut > topo->sqmaxcut ) topo->sqmaxcut = topo->ia_params[type][type].rcut; fprintf(stdout, " \n"); DEBUG_INIT("Finished filltypes"); return 1; } /************************************************ * String Manipulation stuff for parsing files ************************************************/ /* return string that goes before comand character*/ void beforecommand(char *str,char *pline,char commandc) { char *dummy; void trim(char *); strcpy(str,pline); if ((dummy = strchr (str,commandc)) != NULL) (*dummy) = 0; trim (str); } /* return string that goes after command character */ void aftercommand(char *str, char *pline,char commandc) { char *dummy; int i; void trim(char *); strcpy(str,pline); if ((dummy = strchr (str,commandc)) != NULL) { i=0; while( (*dummy) != str[i]) { str[i] = ' '; i++; } str[i] = ' '; } trim (str); } /* reads a string from stream of max length n */ char *fgets2(char *line, int n, FILE *stream) { char *c; if (fgets(line,n,stream)==NULL) { return NULL; } if ((c=strchr(line,'\n'))!=NULL) *c=0; return line; } /* remove comments */ void strip_comment (char *line) { char *c; if (!line) return; /* search for a comment mark and replace it by a zero */ if ((c = strchr(line,COMMENTSIGN)) != NULL) (*c) = 0; } /*test is there is still something left in string*/ int continuing(char *s) { int sl; void rtrim (char *str); rtrim(s); sl = strlen(s); if ((sl > 0) && (s[sl-1] == CONTINUE)) { s[sl-1] = 0; return 1; /*true*/ } else return 0; /*false*/ } /*make strin uppercase*/ void upstring (char *str) { int i; for (i=0; (i < (int)strlen(str)); i++) str[i] = toupper(str[i]); } /*trim string from left*/ void ltrim (char *str) { char *tr; int c; if (!str) return; tr = strdup (str); c = 0; while ((tr[c] == ' ') || (tr[c] == '\n') || (tr[c] == '\t')) c++; strcpy (str,tr+c); free (tr); } /*trim string from right*/ void rtrim (char *str) { int nul; if (!str) return; nul = strlen(str)-1; while ((nul > 0) && ((str[nul] == ' ') || (str[nul] == '\t') || (str[nul] == '\n')) ) { str[nul] = '\0'; nul--; } } /*trim strin from left and right*/ void trim (char *str) { void ltrim (char *str); void rtrim (char *str); ltrim (str); rtrim (str); } /** * Dumps a configuration to the supplied file handle. */ void draw(FILE *outfile, /*struct vector box, long npart, struct particles *particle,*/ struct conf * conf, struct topo * topo) { long i; double anint(double); //fprintf (outfile, "%15.8le %15.8le %15.8le\n", box.x, box.y, box.z); #ifdef TESTING for (i = 0; i < topo->npart; i++) { fprintf (outfile, "%15.6le %15.6le %15.6le %15.6le %15.6le %15.6le %15.6le %15.6le %15.6le %d\n", conf->box.x * ((conf->particle[i].pos.x) - anint(conf->particle[i].pos.x)), conf->box.y * ((conf->particle[i].pos.y) - anint(conf->particle[i].pos.y)), conf->box.z * ((conf->particle[i].pos.z) - anint(conf->particle[i].pos.z)), conf->particle[i].dir.x, conf->particle[i].dir.y, conf->particle[i].dir.z, conf->particle[i].patchdir[0].x, conf->particle[i].patchdir[0].y, conf->particle[i].patchdir[0].z, conf->particle[i].switched); } #else for (i = 0; i < topo->npart; i++) { fprintf (outfile, "%15.8le %15.8le %15.8le %15.8le %15.8le %15.8le %15.8le %15.8le %15.8le %d\n", conf->box.x * ((conf->particle[i].pos.x) - anint(conf->particle[i].pos.x)), conf->box.y * ((conf->particle[i].pos.y) - anint(conf->particle[i].pos.y)), conf->box.z * ((conf->particle[i].pos.z) - anint(conf->particle[i].pos.z)), conf->particle[i].dir.x, conf->particle[i].dir.y, conf->particle[i].dir.z, conf->particle[i].patchdir[0].x, conf->particle[i].patchdir[0].y, conf->particle[i].patchdir[0].z, conf->particle[i].switched); } #endif } /*............................................................................*/ /****************************************************************************/ /* Pairlist stuf */ /****************************************************************************/ /** * Initializes the pairlist and allocates memory */ void init_pairlist(struct topo * topo, struct sim * sim){ printf("\nAllocating memory for pairlist...\n"); sim->pairlist = xmalloc(sizeof(struct pairs) * topo->npart); // Highest guess: Every particle interacts with the others // TODO: Make it more sophisticated long i; for(i = 0; i < topo->npart; i++){ sim->pairlist[i].pairs = malloc(sizeof(long) * topo->npart); sim->pairlist[i].num_pairs = 0; } } /*............................................................................*/ /** * Cleans up: deallocates the memory for the pairlist */ int dealloc_pairlist(struct topo * topo, struct sim * sim){ long i; if(sim->pairlist != NULL){ for(i = 0; i < topo->npart; i++){ if(sim->pairlist[i].pairs != NULL){ free(sim->pairlist[i].pairs); } } free(sim->pairlist); } return 0; } /*............................................................................*/ /** * Generates a pairlist with a very basic alogrithm */ void gen_simple_pairlist(struct topo * topo, struct sim * sim, struct conf * conf){ struct vector r_cm; double r_cm2; double max_dist; // Set the pairlist to zero //DEBUG_INIT("Gen Pairlist") long i, j; for(i = 0; i < topo->npart; i++){ //DEBUG_INIT("%ld", i); sim->pairlist[i].num_pairs = 0; } long nj = topo->npart; long ni = nj - 1; for(i = 0; i < ni; i++){ for(j = i + 1; j < nj; j++){ r_cm.x = conf->particle[i].pos.x - conf->particle[j].pos.x; r_cm.y = conf->particle[i].pos.y - conf->particle[j].pos.y; r_cm.z = conf->particle[i].pos.z - conf->particle[j].pos.z; if ( r_cm.x < 0 ) r_cm.x = conf->box.x * (r_cm.x - (double)( (long)(r_cm.x-0.5) ) ); else r_cm.x = conf->box.x * (r_cm.x - (double)( (long)(r_cm.x+0.5) ) ); if ( r_cm.y < 0 ) r_cm.y = conf->box.y * (r_cm.y - (double)( (long)(r_cm.y-0.5) ) ); else r_cm.y = conf->box.y * (r_cm.y - (double)( (long)(r_cm.y+0.5) ) ); if ( r_cm.z < 0 ) r_cm.z = conf->box.z * (r_cm.z - (double)( (long)(r_cm.z-0.5) ) ); else r_cm.z = conf->box.z * (r_cm.z - (double)( (long)(r_cm.z+0.5) ) ); r_cm2 = DOT(r_cm,r_cm); max_dist = AVER(sim->trans[conf->particle[i].type].mx, \ sim->trans[conf->particle[j].type].mx); max_dist *= (1 + sim->pairlist_update) * 2; max_dist += topo->maxcut; max_dist *= max_dist; /* squared */ if (r_cm2 <= max_dist){ sim->pairlist[i].pairs[sim->pairlist[i].num_pairs++] = j; sim->pairlist[j].pairs[sim->pairlist[j].num_pairs++] = i; } } } ////Check for too many pairs //for(i = 0; i < topo->npart; i++){ // //if (sim->pairlist.list[i].num_pairs >= topo->npart) // if (sim->pairlist[i].num_pairs >= topo->npart){ // fprintf(stderr, "ERROR: Too many pairs for particle %ld!!!\n", i); // exit(1); // } //} } /*.............................................................................*/ /** * Interface for the generation of the pairlist. Define other pairlist * algorithms above. */ void gen_pairlist(struct topo * topo, struct sim * sim, struct conf * conf){ gen_simple_pairlist(topo, sim, conf); } /*.............................................................................*/ /** * Print out the pairlist */ void print_pairlist(FILE * stream, struct sim * sim, struct topo * topo){ long i, j; for (i = 0; i < topo->npart; i++){ fprintf(stream, "%ld (%ld):", i, sim->pairlist[i].num_pairs); for(j = 0; j < sim->pairlist[i].num_pairs; j++){ fprintf(stream, " %ld", sim->pairlist[i].pairs[j]); } fprintf(stream, "\n"); } } /*..........................................................................*/ /****************************************************************************/ /* Cluster statistics stuf */ /****************************************************************************/ /** * determines, wheter two particles are in the same cluster */ int same_cluster(struct topo * topo, struct conf * conf, long fst, long snd, double (* intfce[MAXT][MAXT])(struct interacts *) ){ /*if two particles are bonded they belong to the same cluster*/ if ( ((topo->chainparam[conf->particle[fst].chaint]).bond1c >= 0) || ((topo->chainparam[conf->particle[fst].chaint]).bonddc >= 0) ){ if ( (snd == topo->conlist[fst][1]) || (snd == topo->conlist[fst][0]) ) { return TRUE; } } if ( ((topo->chainparam[conf->particle[snd].chaint]).bond1c >= 0) || ((topo->chainparam[conf->particle[snd].chaint]).bonddc >= 0) ){ if ( (fst == topo->conlist[snd][1]) || (fst == topo->conlist[snd][0]) ) { return TRUE; } } /*cluster is made of particles closer tna some distance*/ /* struct vector image(struct vector r1, struct vector r2, struct vector box); struct vector r_cm = image(conf->particle[fst].pos, conf->particle[snd].pos, conf->box); double dist2 = DOT(r_cm, r_cm); * TODO: Make it much more efficient => define cluster_dist!!! * if(dist2 > topo->ia_params[conf->particle[fst].type][conf->particle[snd].type].sigma * topo->ia_params[conf->particle[fst].type][conf->particle[snd].type].sigma*4.0){ return FALSE; } else { return TRUE; }*/ /*cluster is made of attractively interacting particles*/ double paire(long, long, double (* intfce[MAXT][MAXT])(struct interacts *), struct topo * topo, struct conf * conf); if(paire(fst, snd, intfce, topo, conf) > -0.10 ){ return FALSE; } else { return TRUE; } } /*............................................................................*/ /** * generate the clusterlist */ int gen_clusterlist(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)){ int change = TRUE; /* does it still change? */ //long neighbour; long i, j, fst, snd, tmp, minnumber, maxnumber; int same_cluster(struct topo * topo, struct conf * conf, long fst, long snd, double (* intfce[MAXT][MAXT])(struct interacts *)); // Set clusterindex to the corresponding index for( i = 0; i < topo->npart; i++){ sim->clusterlist[i] = i; } // Start determining the cluster while(change){ change = FALSE; for(i = 0; i < topo->npart; i++){ /*If nore pairlist go over all pairs*/ maxnumber = topo->npart; minnumber = i ; if (sim->pairlist_update) { maxnumber = sim->pairlist[i].num_pairs; minnumber=0; } /* Go over pairs to see if they are in the cluster */ for(j = minnumber; j < maxnumber; j++){ fst = i; snd = j; if (sim->pairlist_update) { snd = sim->pairlist[i].pairs[j]; } /*do cluster analysis only for spherocylinders*/ if ( (topo->ia_params[conf->particle[fst].type][conf->particle[snd].type].geotype[0] < SP) && \ (topo->ia_params[conf->particle[fst].type][conf->particle[snd].type].geotype[1] < SP) ) { /* if they are close to each other */ if(same_cluster(topo, conf, fst, snd, intfce)){ if(fst > snd){ tmp = snd; snd = fst; fst = tmp; } if(sim->clusterlist[fst] < sim->clusterlist[snd]){ sim->clusterlist[snd] = sim->clusterlist[fst]; change = TRUE; break; /* => will eventually start the i loop from new */ } if(sim->clusterlist[snd] < sim->clusterlist[fst]){ sim->clusterlist[fst] = sim->clusterlist[snd]; change = TRUE; break; /* => will eventually start the i loop from new */ } } } } if(change){ break; } } } return 0; } /*............................................................................*/ /** * sort the clusterlist */ int sort_clusterlist(struct topo * topo, struct sim * sim){ long cluster_indices[topo->npart]; /* holds the different cluster indices. (currently too much memory) */ long num_cluster = 0; /* number of clusters, temporary needed */ long i, j; /* how many clusters are there? */ long max_index = -1; for(i = 0; i < topo->npart; i++){ if(max_index < sim->clusterlist[i]){ max_index = sim->clusterlist[i]; cluster_indices[num_cluster++] = max_index; } } /* free the memory from the old clusters */ if(sim->clusters){ for(i = 0; i < sim->num_cluster; i++){ if(sim->clusters[i].particles){ free(sim->clusters[i].particles); } } free(sim->clusters); } /* Allocate memory for the clusters */ sim->clusters = xmalloc(sizeof(struct cluster) * num_cluster); for(i = 0; i < num_cluster; i++){ /* allocate maximal space for all the clusters */ sim->clusters[i].particles = xmalloc(sizeof(long) * topo->npart); sim->clusters[i].npart = 0; } /* fill in the particles belonging to one cluster */ for(i = 0; i < num_cluster; i++){ for(j = 0; j < topo->npart; j++){ if(sim->clusterlist[j] == cluster_indices[i]){ sim->clusters[i].particles[sim->clusters[i].npart++] = j; } } } sim->num_cluster = num_cluster; /* Find the biggest size */ sim->max_clust = 0; for(i = 0; i < num_cluster; i++){ if(sim->clusters[i].npart > sim->max_clust){ sim->max_clust = sim->clusters[i].npart; } } /* Set the statistics to zero */ sim->clusterstat = xmalloc(sizeof(long) * sim->max_clust); for(i = 0; i < sim->max_clust; i++){ sim->clusterstat[i] = 0; } /* Do the statistics */ for(i = 0; i < num_cluster; i++){ sim->clusterstat[sim->clusters[i].npart - 1]++; } return 0; } /*............................................................................*/ /** * calculate energies of clusters * */ int calc_clusterenergies(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)){ long i,j,k; double paire(long, long, double (* intfce[MAXT][MAXT])(struct interacts *), struct topo * topo, struct conf * conf); for(i = 0; i < sim->num_cluster; i++){ sim->clustersenergy[i]=0.0; for(j = 0; j < sim->clusters[i].npart; j++){ for(k = j+1; k < sim->clusters[i].npart; k++){ sim->clustersenergy[i]+= paire(sim->clusters[i].particles[j], sim->clusters[i].particles[k], intfce, topo, conf); } } } return 0; } /*............................................................................*/ /** * print the clusterlist * */ int print_clusterlist(FILE * stream, BOOL decor, struct topo * topo, struct sim * sim, struct conf * conf){ long i; if(decor){ fprintf(stream, "\n" "-----------------------------------------------------\n" " The Cluster List\n" " (Index starts with 1)\n" "-----------------------------------------------------\n"); } for(i = 0; i < topo->npart; i++){ fprintf(stream,"%3ld %3ld %8.4lf %8.4lf %8.4lf", i + 1, sim->clusterlist[i] + 1, conf->particle[i].pos.x, conf->particle[i].pos.y, conf->particle[i].pos.z); fprintf(stream,"\n"); } if(decor){ fprintf(stream,"-----------------------------------------------------\n"); } fflush(stream); return 0; } /*............................................................................*/ /** * print the clusters * */ int print_clusters(FILE * stream, BOOL decor, struct sim * sim){ long i, j; if(decor){ fprintf(stream, "\n" "-----------------------------------------------------\n" " The Clusters\n" " (Index starts with 1)\n" "-----------------------------------------------------\n"); } for(i = 0; i < sim->num_cluster; i++){ fprintf(stream, "%3ld(%f):", i + 1,sim->clustersenergy[i]); for(j = 0; j < sim->clusters[i].npart; j++){ fprintf(stream, "%5ld", sim->clusters[i].particles[j] + 1); } fprintf(stream, "\n"); } if(decor){ fprintf(stream,"---------------------------------------------------\n"); } fflush(stream); return 0; } /*............................................................................*/ /** * print a statistics for the clusters */ int print_clusterstat(FILE * stream, BOOL decor, struct sim * sim){ long i; if(decor){ fprintf(stream, "\n" "-----------------------------------------------------\n" " Cluster Distribution\n" "-----------------------------------------------------\n"); } for(i = 0; i < sim->max_clust; i++){ fprintf(stream, "%5ld\t%5ld\n", i + 1, sim->clusterstat[i]); } if(decor){ fprintf(stream, "--------------------------------------------------\n"); } fflush(stream); return 0; } /*............................................................................*/ /** * Alternative way of printing the cluster statistics: everything is on * one line. First monomers, then dimers etc. */ int print_clstat_oneline(FILE * stream, long sweep, struct sim * sim){ long i; fprintf(stream, "%ld: ", sweep); for(i = 0; i < sim->max_clust; i++){ fprintf(stream, "%5ld\t", sim->clusterstat[i]); } fprintf(stream, "\n"); fflush(stream); return 0; } /** * write out all the cluster stat in files, if file name is given */ int write_cluster(FILE * cl_stat, FILE * cl, FILE * cl_list, BOOL decor, long sweep, struct sim * sim, struct topo * topo, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)){ int gen_clusterlist(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)); int sort_clusterlist(struct topo * topo, struct sim * sim); int print_clusters(FILE * stream, BOOL decor, struct sim * sim); int calc_clusterenergies(struct topo * topo, struct sim * sim, struct conf * conf, double (* intfce[MAXT][MAXT])(struct interacts *)); gen_clusterlist(topo, sim, conf, intfce); sort_clusterlist(topo, sim); calc_clusterenergies(topo, sim, conf, intfce); if(cl_stat){ if(decor == FALSE){ // if no decor, this means usually into a file. Hence print info // about number of line per frame fprintf(cl_stat, "Sweep: %ld | Maximal size: %ld\n", sweep, sim->max_clust); } print_clusterstat(cl_stat, decor, sim); /* print_clstat_oneline(cl_stat, sweep, sim); */ } if(cl){ if(decor == FALSE){ fprintf(cl, "Sweep: %ld | Number of clusters: %ld\n", sweep, sim->num_cluster); } print_clusters(cl, decor, sim); } if(cl_list){ if(decor == FALSE){ fprintf(cl_list, "Sweep: %ld | Number of particles: %ld\n", sweep, topo->npart); } print_clusterlist(cl, decor, topo, sim, conf); } return 0; } /*............................................................................*/ /****************************************************************************/ /* Wang-Landau stuf */ /****************************************************************************/ /* Initiate Wang-Landau calculation. */ int wlinit(struct wls *wl, char filename[30]) { long i,length,fields=0; double field[5]; FILE *infile; char line[STRLEN]; int wlend(struct wls *); void trim(char *); void strip_comment(char *); infile = fopen(filename, "r"); if (infile == NULL) { fprintf (stderr, "\nERROR: Could not open %s file.\n\n",filename); return 1; } length=0; while (fgets2(line,STRLEN-2,infile) != NULL) { strip_comment (line); trim (line); /* if there is something left... */ if ((int)strlen(line) > 0) { length++; } } length--; /*there is alpha at the first line*/ (*wl).weights = malloc( sizeof(double) * length ); (*wl).hist = malloc( sizeof(long) * length ); (*wl).length[1] = 0; (*wl).dorder[1] = 0; fseek(infile,0,SEEK_SET); i=0; while (fgets2(line,STRLEN-2,infile) != NULL) { strip_comment (line); trim (line); /* if there is something left... */ if ((int)strlen(line) > 0) { if (i == 0) { if (sscanf(line, "%le",&(*wl).alpha)!= 1) { fprintf (stderr, "ERROR: Could not read alpha at the begining.\n\n"); wlend(wl); return 1; } else i++; } else { fields = sscanf(line, "%le %le %le %le",&field[0],&field[1],&field[2],&field[3]); if ( fields == 3 ) { if (i==1) (*wl).minorder[0] = field[0]; (*wl).weights[i-1] = field[1]; (*wl).hist[i-1] = field[2]; (*wl).length[0]++; i++; } else if (fields == 4 ) { if (i==1) { (*wl).minorder[0] = field[0]; (*wl).minorder[1] = field[1]; } if ( (*wl).minorder[1] == field[1] ) (*wl).length[0]++; (*wl).weights[i-1] = field[2]; (*wl).hist[i-1] = field[3]; i++; } else { fprintf (stderr, "ERROR: Could not read order parameter at line %ld.\n\n", i); wlend(wl); return 1; } } } } if (fields == 4 ) { (*wl).length[1] = length / (*wl).length[0]; (*wl).dorder[1] = (field[1] - (*wl).minorder[1])/((*wl).length[1]-1); } (*wl).dorder[0] = (field[0] - (*wl).minorder[0])/((*wl).length[0]-1); if ( ( (i-1) != (*wl).length[0] ) && (fields==3) ) { fprintf (stderr, "ERROR: In reading order parameters length %ld does not fit number of lines %ld.\n\n", (*wl).length[0],i-1); wlend(wl); return 1; } if ( ( (i-1) != (*wl).length[0]*(*wl).length[1] ) && (fields==4) ) { fprintf (stderr, "ERROR: In reading order parameters lengths %ld %ld does not fit number of lines %ld.\n\n", (*wl).length[0],(*wl).length[1],i-1); wlend(wl); return 1; } /*DEBUG*/ printf("Wang-Landau method init:\n"); printf("alpha: %f\n",(*wl).alpha); /*int j=0; if ((*wl).length[1] == 0) { for (i=0; i<(*wl).length[0]; i++) { printf ("%15.8le %15.8le %ld \n",(*wl).minorder[0] + i * (*wl).dorder[0], (*wl).weights[i], (*wl).hist[i]); } } else { for (j=0; j<(*wl).length[1]; j++) { for (i=0; i<(*wl).length[0]; i++) { printf ("%15.8le %15.8le %15.8le %ld \n",(*wl).minorder[0] + i * (*wl).dorder[0], (*wl).minorder[1]+j*(*wl).dorder[1], (*wl).weights[i+(*wl).length[0]*j], (*wl).hist[i+(*wl).length[0]*j]); } printf (" \n"); } }*/ fclose(infile); fflush(stdout); /**/ return 0; } int wlwrite(struct wls *wl, char filename[30]) { long i,j; FILE *outfile; outfile = fopen(filename, "w"); if (outfile == NULL) { fprintf (stderr, "\nERROR: Could not open %s file.\n\n",filename); return 1; } fprintf (outfile, "%15.8le \n",(*wl).alpha); if ((*wl).length[1] == 0) { for (i=0; i<(*wl).length[0]; i++) { fprintf (outfile, "%15.8le %15.8le %ld \n",(*wl).minorder[0] + i * (*wl).dorder[0], (*wl).weights[i], (*wl).hist[i]); } } else { for (j=0; j<(*wl).length[1]; j++) { for (i=0; i<(*wl).length[0]; i++) { fprintf (outfile, "%15.8le %15.8le %15.8le %ld \n",(*wl).minorder[0] + i * (*wl).dorder[0], (*wl).minorder[1]+j*(*wl).dorder[1], (*wl).weights[i+(*wl).length[0]*j], (*wl).hist[i+(*wl).length[0]*j]); } fprintf (outfile, " \n"); } } fflush(outfile); fclose(outfile); return 0; } int wlend(struct wls *wl) { free((*wl).weights); free((*wl).hist); return 0; } void wlreject(struct sim *sim, long oldlength) { int mesh_cpy(struct meshs *, struct meshs *); int longarray_cpy (long **target, long **source,long,long); if ( sim->wlm[0] > 0 ) { sim->wl.weights[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]] -= sim->wl.alpha; sim->wl.hist[sim->wl.currorder[0]+sim->wl.currorder[1]*sim->wl.length[0]]++; if ( (sim->wlm[0] == 2) || (sim->wlm[1] == 2) ) mesh_cpy(&sim->wl.mesh,&sim->wl.origmesh); if ( (sim->wlm[0] == 5) || (sim->wlm[1] == 5)||(sim->wlm[0] == 6) || (sim->wlm[1] == 6) ) { longarray_cpy(&sim->wl.radiushole,&sim->wl.radiusholeold,sim->wl.radiusholemax,oldlength); sim->wl.radiusholemax = oldlength; } sim->wl.partincontact = sim->wl.partincontactold; } } void wlaccept(int wlm,struct wls *wl) { int i; if ( wlm > 0 ) { for (i=0;i<2;i++) (*wl).currorder[i] = (*wl).neworder[i]; (*wl).weights[ (*wl).currorder[0] + (*wl).currorder[1] * (*wl).length[0]] -= (*wl).alpha; (*wl).hist[ (*wl).currorder[0] + (*wl).currorder[1] * (*wl).length[0]]++; } } /*..............................................................................*/ /*........................NAMETIC ORDER.........................................*/ /*..............................................................................*/ /* Calculates the instantaneous value of the nematic order parameter for the specified configuration. The nematic director is determined by diagonalisation of the tensor order parameter Q (see Allen & Tildesley p305). The order parameter is the corresponding eigenvalue. However, it is equivalent to take minus two times the middle eigenvalue (see Eppenga & Frenkel, Mol Phys vol. 52, p.1303-1334 [1984]), and this is more reliable for comparing the isotropic phase. This is the approach taken in this implementation. Routines from Numerical Recipes are used to perform the diagonalisation. Note that these routines expect an n*n matrix to be stored in elements [1...n][1...n], rather than [0...n-1][0...n-1], so the arrays must be declared with one more element in each dimension. */ double nematic(long npart, struct particles *p) { double q[4][4] = {{0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}}; double d[4], e[4]; long i; void tred2(double [4][4], double [4], double [4]); void tqli(double [4], double [4]); for (i=0; i<npart; i++) { q[1][1] += p[i].dir.x * p[i].dir.x; q[1][2] += p[i].dir.x * p[i].dir.y; q[1][3] += p[i].dir.x * p[i].dir.z; q[2][1] += p[i].dir.y * p[i].dir.x; q[2][2] += p[i].dir.y * p[i].dir.y; q[2][3] += p[i].dir.y * p[i].dir.z; q[3][1] += p[i].dir.z * p[i].dir.x; q[3][2] += p[i].dir.z * p[i].dir.y; q[3][3] += p[i].dir.z * p[i].dir.z; } q[1][1] = (q[1][1] * 3.0 / npart - 1.0) / 2.0; q[1][2] = (q[1][2] * 3.0 / npart ) / 2.0; q[1][3] = (q[1][3] * 3.0 / npart ) / 2.0; q[2][1] = (q[2][1] * 3.0 / npart ) / 2.0; q[2][2] = (q[2][2] * 3.0 / npart - 1.0) / 2.0; q[2][3] = (q[2][3] * 3.0 / npart ) / 2.0; q[3][1] = (q[3][1] * 3.0 / npart ) / 2.0; q[3][2] = (q[3][2] * 3.0 / npart ) / 2.0; q[3][3] = (q[3][3] * 3.0 / npart - 1.0) / 2.0; tred2 (q, d, e); tqli (d, e); /* Sort eigenvalues */ if (d[1] > d[2]) { d[0]=d[1]; d[1]=d[2]; d[2]=d[0]; } if (d[2] > d[3]) { d[0]=d[2]; d[2]=d[3]; d[3]=d[0]; } if (d[1] > d[2]) { d[0]=d[1]; d[1]=d[2]; d[2]=d[0]; } return -2.0*d[2]; } /*..............................................................................*/ /* Returns the coefficient of the Fourier series term with period boxlength/n in the z direction. The coefficients of the sine and cosine terms are added in quadrature and returned, making the result independent of phase shifts in the z direction. A significantly non-zero value indicates layering of the particles in the z direction with periodicity boxlength/n. */ double smectic(long npart, struct particles *p, long n) { double a, b; double omega = 8.0*n*atan(1.0); long i; a = b = 0.0; for (i=0; i<npart; i++) { a += cos(omega * p[i].pos.z); b += sin(omega * p[i].pos.z); } a /= (double)npart; b /= (double)npart; return sqrt(a*a + b*b); } /*..............................................................................*/ /*........................Z ORDER PARAMETER.....................................*/ long z_order(struct wls *wl, struct conf * conf,int wli) { // printf("%f %ld\n",particle[0].pos.z * box.z,lround(particle[0].pos.z * box.z / wl.dorder[wli] - wl.minorder[wli])); /* Because older C compilators do not know lround we can use ceil as well return lround(particle[0].pos.z * box.z / wl.dorder[wli] - wl.minorder[wli]);*/ /*printf("pos Z %f ",conf->particle[0].pos.z ); printf("%f ",conf->syscm.z); printf("%f ",conf->box.z); printf("%f ", wl->minorder[wli]); printf("dorder %f \n", wl->dorder[wli] );*/ return (long) ceil( ((conf->particle[0].pos.z - conf->syscm.z) * conf->box.z- wl->minorder[wli]) / wl->dorder[wli] ); } /*..............................................................................*/ /*........................2 particles distance.....................................*/ long twopartdist(struct wls *wl, struct conf * conf, int wli) { struct vector r_cm; r_cm.x = conf->particle[0].pos.x - conf->particle[1].pos.x; r_cm.y = conf->particle[0].pos.y - conf->particle[1].pos.y; r_cm.z = conf->particle[0].pos.z - conf->particle[1].pos.z; if ( r_cm.x < 0 ) r_cm.x = conf->box.x * (r_cm.x - (double)( (long)(r_cm.x-0.5) ) ); else r_cm.x = conf->box.x * (r_cm.x - (double)( (long)(r_cm.x+0.5) ) ); if ( r_cm.y < 0 ) r_cm.y = conf->box.y * (r_cm.y - (double)( (long)(r_cm.y-0.5) ) ); else r_cm.y = conf->box.y * (r_cm.y - (double)( (long)(r_cm.y+0.5) ) ); if ( r_cm.z < 0 ) r_cm.z = conf->box.z * (r_cm.z - (double)( (long)(r_cm.z-0.5) ) ); else r_cm.z = conf->box.z * (r_cm.z - (double)( (long)(r_cm.z+0.5) ) ); return (long) ceil( (( sqrt(r_cm.x*r_cm.x + r_cm.y*r_cm.y) ) - wl->minorder[wli]) / wl->dorder[wli] ); } /*..............................................................................*/ /*........................alignment ORDER PARAMETER.....................................*/ double alignment_order(struct conf * conf, struct topo * topo) { double sumdot=0; long i,j; struct vector r_cm; struct vector image(struct vector, struct vector, struct vector); for (i = 0; i < topo->npart - 1; i++) { for (j = i + 1; j < topo->npart; j++) { r_cm = image(conf->particle[i].pos, conf->particle[j].pos, conf->box); if ( DOT(r_cm,r_cm) < 1.5*1.5 ) { sumdot+= DOT(conf->particle[i].dir,conf->particle[j].dir); } } } return sumdot; } /*..............................................................................*/ /*........................HOLE IN MESH-MEMBRANE ORDER PARAM.....................*/ /* return change in order parameter when one particle moves*/ long meshorder_moveone(struct vector oldpos, struct vector newpos, struct meshs *mesh, long npart, long target, struct conf * conf, struct sim * sim, int wli) { int change; int nx,ny,ox,oy; /* position in mesh */ double resid; void mesh_fill(struct meshs *, long , struct particles *, struct sim * sim); int mesh_findholes(struct meshs *); int mesh_addpart(double, double, int **, int [2]); int mesh_removepart(double, double, int **, int [2]); if ( conf->particle[target].type != sim->wl.wlmtype ) return sim->wl.currorder[wli]; nx = (int) (INBOX(newpos.x,resid) * (*mesh).dim[0]); ny = (int) (INBOX(newpos.y,resid) * (*mesh).dim[1]); ox = (int) (INBOX(oldpos.x,resid) * (*mesh).dim[0]); oy = (int) (INBOX(oldpos.y,resid) * (*mesh).dim[1]); if ( (nx == ox) && (ny == oy) ) return sim->wl.currorder[wli]; /* particle stayed in the same mesh bin*/ change = mesh_addpart(newpos.x,newpos.y,&(*mesh).data,(*mesh).dim); if (change) { change = mesh_removepart(oldpos.x,oldpos.y,&(*mesh).data,(*mesh).dim); } if ( !change ) { /* fill the mesh with particles*/ mesh_fill(mesh,npart,conf->particle, sim); return (long) (mesh_findholes(mesh) - sim->wl.minorder[wli]); } return sim->wl.currorder[wli]; } /* return change in order parameter when chain moves*/ long meshorder_movechain(long chain[MAXN], struct meshs *mesh, long npart, struct conf * conf, struct sim * sim,struct particles chorig[MAXCHL], int wli) { long i,current; int change; void mesh_fill(struct meshs *, long , struct particles *, struct sim * sim); int mesh_findholes(struct meshs *); int mesh_addpart(double, double, int **, int [2]); int mesh_removepart(double, double, int **, int [2]); change= 1; i = 0; current = chain[0]; while ( (current >=0 ) && (change) ) { if ( conf->particle[current].type == sim->wl.wlmtype ) { change = mesh_addpart(conf->particle[current].pos.x, conf->particle[current].pos.y, &(*mesh).data, (*mesh).dim); } i++; current = chain[i]; } i = 0; current = chain[0]; while ( (current >=0 ) && (change) ) { if ( conf->particle[current].type == sim->wl.wlmtype ) { change = mesh_removepart(chorig[i].pos.x, chorig[i].pos.y, &(*mesh).data, (*mesh).dim); } i++; current = chain[i]; } if ( !change ) { /* fill the mesh with particles*/ mesh_fill(mesh,npart,conf->particle, sim); return (long) (mesh_findholes(mesh) - sim->wl.minorder[wli]); } return sim->wl.currorder[wli]; } /* filling the mesh */ void mesh_fill(struct meshs *mesh, long npart, struct particles *particle, struct sim * sim) { long i; int mesh_addpart(double posx, double posy, int **mesh, int dim[2]); for ( i=0; i<((*mesh).dim[0] * (*mesh).dim[1]); i++) { (*mesh).data[i] = 0; } for (i=0; i<npart; i++) { /*calculate position of particle on mesh and add it to all where it belongs */ if (particle[i].type == sim->wl.wlmtype) mesh_addpart(particle[i].pos.x,particle[i].pos.y, &(*mesh).data, (*mesh).dim); } } /* add particle on coordinates posx posy to mesh return 0 if it was placed on empty spot*/ int mesh_addpart(double posx, double posy, int **mesh, int dim[2]) { int i, square[9], onhole; double resid; void mesh_square(int , int , int [2], int (*)[9]); onhole = 1; mesh_square( (int) (INBOX(posx,resid) * dim[0]), (int) (INBOX(posy,resid) * dim[1]) , dim, &square); for(i=0;i<9;i++) { if ( (square[i] >= dim[0]*dim[1])||(square[i] <0) ) { printf ("Error: trying to write to %d\n",square[i]); printf ("%d %d and %d\n", (int) (INBOX(posx,resid) * dim[0]), (int) (INBOX(posy,resid) * dim[1]),i ); fflush(stdout); } if ( ((*mesh)[ square[i] ]) >= 0 ) onhole = 0; (*mesh)[ square[i] ]--; } return onhole; } /* remove particle on coordinates posx posy from mesh and return 0 if there is a empty spot now*/ int mesh_removepart(double posx, double posy, int **mesh, int dim[2]) { int i, square[9]; double resid; void mesh_square(int , int , int [2], int (*)[9]); mesh_square((int) (INBOX(posx,resid) * dim[0]), (int) (INBOX(posy,resid) * dim[1]) , dim, &square); for(i=0;i<9;i++) { //DEBUG if (square[i] >= dim[0]*dim[1]) printf ("Error: trying to write to %d\n",square[i]); (*mesh)[ square[i] ]++; if ( ((*mesh)[ square[i] ]) == 0 ) return 0; } return 1; } void mesh_square(int x, int y, int dim[2], int (*square)[9]) { int a,b; b=y; (*square)[0] = x + dim[0]*b; a = x-1; if ( a<0 ) a = dim[0]-1; (*square)[1] = a + dim[0]*b; a = x+1; if ( a==dim[0] ) a = 0; (*square)[2] = a + dim[0]*b; b = y-1; if ( b<0 ) b = dim[1]-1; (*square)[3] = x + dim[0]*b; a = x-1; if ( a<0 ) a = dim[0]-1; (*square)[4] = a + dim[0]*b; a = x+1; if ( a==dim[0] ) a = 0; (*square)[5] = a + dim[0]*b; b = y+1; if ( b==dim[1] ) b = 0; (*square)[6] = x + dim[0]*b; a = x-1; if ( a<0 ) a = dim[0]-1; (*square)[7] = a + dim[0]*b; a = x+1; if ( a==dim[0] ) a = 0; (*square)[8] = a + dim[0]*b; } void mesh_neighbors(int pos, int dim[2], int neighbors[4]) { int x,y,a; x = pos % dim[0]; y = pos / dim[0]; a = x-1; if ( a<0 ) a = dim[0]-1; neighbors[0] = a + dim[0]*y; a = x+1; if ( a==dim[0] ) a = 0; neighbors[1] = a + dim[0]*y; a = y-1; if ( a<0 ) a = dim[1]-1; neighbors[2] = x + dim[0]*a; a = y+1; if ( a==dim[1] ) a = 0; neighbors[3] = x + dim[0]*a; } /* returns the number of holes and a list of mesh points belonging to each of them */ int mesh_findholes(struct meshs *mesh) { int i,j, k, n, size, li, maxsize; int neighbors[4]; void mesh_neighbors(int, int [2], int [4]); n=0; maxsize = 0; for (i=0;i<((*mesh).dim[0] * (*mesh).dim[1]);i++) { (*mesh).tmp[i] = 0; if ( (*mesh).data[i] > 0 ) (*mesh).data[i] = 0; } i=0; // go through all mesh points while ( i < ((*mesh).dim[0] * (*mesh).dim[1]) ) { // test if mesh point is occupied if ( (*mesh).data[i] != 0 ) { i++; } else { // mesh point is free, create a new cluster n++; (*mesh).data[i] = n; // start new cluster, put mesh point as first element, and set list pointer on first element //DEBUG if (n >= mesh.dim[0]*mesh.dim[1]) printf ("Error: trying to write to sizes position %d\n",n); size = 1; (*mesh).tmp[0] = i; li = 0; // go through all elements of the cluster while ( li < size ) { //go through all neighbors j = (*mesh).tmp[li]; mesh_neighbors(j, (*mesh).dim, neighbors); for ( k=0; k<4; k++ ) { // test if status is free and append it to the cluster if ( (*mesh).data[ neighbors[k] ] == 0 ) { (*mesh).data[ neighbors[k] ] = n; // append mesh point as element in the list (*mesh).tmp[size] = neighbors[k]; size++; } if ( (*mesh).data[ neighbors[k] ] > 0 && (*mesh).data[ neighbors[k] ]<n ) { fprintf(stderr,"Error: Mesh cluster out of range, propably going infinite through pbc."); fflush(stderr); } } li++; } if (size > maxsize) maxsize = size; } } return maxsize; } int mesh_init(struct meshs *mesh, double meshsize, long npart, struct conf * conf, struct sim * sim) { // int i; int maxsize,length; void mesh_fill(struct meshs *, long , struct particles *, struct sim * sim); int mesh_findholes(struct meshs *); (*mesh).dim[0] = (int)(conf->box.x/meshsize); (*mesh).dim[1] = (int)(conf->box.y/meshsize); if ( (*mesh).data != NULL ) free((*mesh).data); if ( (*mesh).tmp != NULL ) free((*mesh).tmp); length = (*mesh).dim[0] * (*mesh).dim[1]; (*mesh).data = malloc( sizeof(int)* (length)); (*mesh).tmp = malloc( sizeof(int)* (length+1)); /* fill the mesh with particles*/ mesh_fill(mesh, npart,conf->particle, sim); /* perfrom hole cluster algorithm */ maxsize = mesh_findholes(mesh); /*DEBUG printf("maxsize: %d\n",maxsize); printf("mesh:\n"); for (i=0;i<mesh.dim[0]*mesh.dim[1];i++) { printf("%d ",mesh.data[i]); if ( ((i+1) % mesh.dim[0]) == 0) printf("\n"); }*/ return maxsize; } void mesh_print (struct meshs *mesh) { int i; int mesh_findholes(struct meshs *); printf("mesh:\n"); for (i=0;i<(*mesh).dim[0] * (*mesh).dim[1];i++) { printf("%d ",(*mesh).data[i]); if ( ((i+1) % (*mesh).dim[0]) == 0) printf("\n"); } printf("hole %d:\n", mesh_findholes(mesh) ); printf("\n"); } int mesh_cpy (struct meshs *target, struct meshs *source) { if ( (*target).data != NULL) { if ( ((*target).dim[0] == (*source).dim[0]) && ((*target).dim[1] == (*source).dim[1]) ) { memcpy((*target).data,(*source).data, sizeof(int)* ((*target).dim[0] * (*target).dim[1]) ); return 0; } else { free ((*target).data); if ( (*source).dim[0] * (*source).dim[1] > (*target).dim[0] * (*target).dim[1] ) { if ((*target).tmp != NULL ) free ((*target).tmp); (*target).tmp = malloc( sizeof(int)* ((*source).dim[0] * (*source).dim[1] + 1)); } } } (*target).dim[0] = (*source).dim[0]; (*target).dim[1] = (*source).dim[1]; (*target).data = malloc( sizeof(int)* ((*target).dim[0] * (*target).dim[1])); if ((*target).tmp == NULL ) (*target).tmp = malloc( sizeof(int)* ((*source).dim[0] * (*source).dim[1] + 1)); memcpy((*target).data,(*source).data, sizeof(int)* ((*target).dim[0] * (*target).dim[1]) ); return 0; } int mesh_end(struct meshs *mesh) { /* free allocated memory */ if ( (*mesh).data!= NULL ) free((*mesh).data); if ( (*mesh).tmp!= NULL ) free((*mesh).tmp); return 0; } /*..............................................................................*/ /*........................RADIUS HOLE IN CENTER MEMBRANE ORDER PARAM............*/ /*return current bin of free radius*/ long radiushole_order(struct sim * sim) { long i; for (i=0;i<sim->wl.radiusholemax-3;i++){ if ((sim->wl.radiushole[i] >0 ) && (sim->wl.radiushole[i+1] >0 ) && (sim->wl.radiushole[i+2] >0 ) && (sim->wl.radiushole[i+3] >0 )) return i-1; } return -100; } /*return order of given radius */ long radiushole_position(double radius, struct sim * sim, int wli) { return (long) ceil( ( radius - sim->wl.minorder[wli]) / sim->wl.dorder[wli] ); } /* return change in order parameter when one particle moves*/ long radiusholeorder_moveone(struct vector *oldpos, struct conf *conf, struct sim * sim, long target,int wli, struct vector *position) { long nr,or; /* position in radiushole */ double rx,ry,z; BOOL oz,nz; long radiushole_position(double radius, struct sim * sim,int); long radiushole_order(struct sim *sim); double anint(double); void radiushole_print (long *radiushole, long length); if ( conf->particle[target].type != sim->wl.wlmtype ) return sim->wl.currorder[wli]; z=conf->particle[target].pos.z - position->z; /*if above position*/ if (z-anint(z) < 0) nz = FALSE; else nz=TRUE; z=oldpos->z - position->z; /*if above position*/ if (z-anint(z) < 0) oz = FALSE; else oz=TRUE; if ( !(nz) && !(oz) ) return sim->wl.currorder[wli]; rx = conf->box.x * (conf->particle[target].pos.x - anint(conf->particle[target].pos.x)); ry = conf->box.y * (conf->particle[target].pos.y - anint(conf->particle[target].pos.y)); nr = radiushole_position(sqrt(rx*rx+ry*ry),sim,wli); if (nr < 0) return -100; /*particle move over radius bins*/ if (nz) { sim->wl.radiushole[nr]++; } if (oz) { rx = conf->box.x * (oldpos->x - anint(oldpos->x)); ry = conf->box.y * (oldpos->y - anint(oldpos->y)); or = radiushole_position(sqrt(rx*rx+ry*ry),sim,wli); sim->wl.radiushole[or]--; if ( sim->wl.radiushole[or] < 0 ) { printf ("Error(single particle move): trying to make number of beads in radiuspore smaller than 0 at position %ld\n",or); radiushole_print(sim->wl.radiushole,sim->wl.radiusholemax); fflush(stdout); } if (sim->wl.radiushole[or] ==0) return radiushole_order(sim); } if ( (nz) && (sim->wl.radiushole[nr] ==1) ) { return radiushole_order(sim); } return sim->wl.currorder[wli]; } /* return change in order parameter when chain moves*/ long radiusholeorder_movechain(long chain[MAXN], struct conf * conf, struct sim * sim,struct particles chorig[MAXCHL],int wli, struct vector *position) { long i,current,nr; double rx,ry,z; BOOL change=FALSE; long radiushole_position(double radius, struct sim * sim,int); long radiushole_order(struct sim *sim); double anint(double); void radiushole_print (long *radiushole, long length); i = 0; rx=0; current = chain[0]; while (current >=0 ) { if ( conf->particle[current].type == sim->wl.wlmtype ) { z=conf->particle[current].pos.z - position->z; /*if above system CM*/ if (z-anint(z) > 0) { rx = conf->box.x * (conf->particle[current].pos.x - anint(conf->particle[current].pos.x)); ry = conf->box.y * (conf->particle[current].pos.y - anint(conf->particle[current].pos.y)); nr = radiushole_position(sqrt(rx*rx+ry*ry),sim,wli); if (nr < 0) return -100; sim->wl.radiushole[nr]++; if ( sim->wl.radiushole[nr] == 1 ) change = TRUE; } } i++; current = chain[i]; } i = 0; current = chain[0]; while (current >=0 ) { if ( conf->particle[current].type == sim->wl.wlmtype ) { z=chorig[i].pos.z - position->z; /*if above system CM*/ if (z-anint(z) > 0) { rx = conf->box.x * (chorig[i].pos.x - anint(chorig[i].pos.x)); ry = conf->box.y * (chorig[i].pos.y - anint(chorig[i].pos.y)); nr = radiushole_position(sqrt(rx*rx+ry*ry),sim,wli); sim->wl.radiushole[nr]--; if ( sim->wl.radiushole[nr] < 0 ) { printf ("Error (chainmove): trying to make number of beads in radiuspore smaller than 0 at position %ld\n",nr); radiushole_print(sim->wl.radiushole,sim->wl.radiusholemax); fflush(stdout); } if ( sim->wl.radiushole[nr] == 0 ) change = TRUE; } } i++; current = chain[i]; } if ( change ) { return radiushole_order(sim); } return sim->wl.currorder[wli]; } /* filling the radiushole above vec*/ long radiushole_all(struct topo *topo, struct conf *conf, struct sim * sim,int wli, struct vector *position) { long i,nr,radiusholemax; double rx,ry,z; long radiushole_position(double radius, struct sim * sim,int); long radiushole_order(struct sim *sim); double anint(double); radiusholemax = radiushole_position(sqrt(conf->box.x*conf->box.x+conf->box.y*conf->box.y),sim,wli); if ( radiusholemax > sim->wl.radiusholemax ) { if (sim->wl.radiushole != NULL) free(sim->wl.radiushole); sim->wl.radiushole = malloc( sizeof(long)* (radiusholemax)); sim->wl.radiusholemax = radiusholemax; } for (i=0;i<radiusholemax;i++) { sim->wl.radiushole[i] = 0; } for (i=0; i< topo->npart; i++) { /*calculate position of particle from z axis, and add it in array */ if ( conf->particle[i].type == sim->wl.wlmtype ) { z=conf->particle[i].pos.z - (*position).z; /*if above position*/ if (z-anint(z) > 0) { rx = conf->box.x * (conf->particle[i].pos.x - anint(conf->particle[i].pos.x)); ry = conf->box.y * (conf->particle[i].pos.y - anint(conf->particle[i].pos.y)); nr = radiushole_position(sqrt(rx*rx+ry*ry),sim,wli); if (nr < 0) return -100; sim->wl.radiushole[nr]++; } } } return radiushole_order(sim); } void radiushole_print (long *radiushole, long length) { long i; printf("radiushole:\n"); for (i=0;i<length;i++) { printf("%ld ",radiushole[i]); } printf("\n"); } int longarray_cpy (long **target, long **source, long targetlength, long sourcelength) { /*if ( (*target) != NULL) { if ( targetlength == sourcelength ) { memcpy((*target),(*source), sizeof(long)*(sourcelength)); return 0; } else { free(*target); } }*/ if ( (*target) != NULL) (*target) = (long*) realloc((*target), sizeof(long)*(sourcelength)); else (*target) = malloc( sizeof(long)*(sourcelength)); memcpy((*target),(*source), sizeof(long)*(sourcelength)); return 0; } /*..............................................................................*/ /* ............................... particles in contact ..................... */ /*return order for particles in contact */ long contparticles_order(struct sim * sim, int wli) { return (long) ceil( ( sim->wl.partincontact - sim->wl.minorder[wli]) / sim->wl.dorder[wli] ); } /*returns if particle is in contact*/ BOOL particleinncontact (struct vector *vec, struct conf *conf) { double x,y,z; double anint(double); x = vec->x - conf->particle[0].pos.x; y = vec->y - conf->particle[0].pos.y; z = vec->z - conf->particle[0].pos.z; x = conf->box.x * (x - anint(x)); y = conf->box.y * (y - anint(y)); z = conf->box.z * (z - anint(z)); if ( x*x + y*y + z*z < WL_CONTACTS) { return TRUE; } else { return FALSE; } } /* return change in number of particles in contact when one particle moves*/ long contparticles_moveone(struct vector *oldpos, struct conf *conf, struct sim * sim, long target,int wli) { long contparticles_order(struct sim * sim, int wli); BOOL particleinncontact (struct vector *vec, struct conf *conf); if ( conf->particle[target].type != sim->wl.wlmtype ) return sim->wl.currorder[wli]; if ( particleinncontact (&(conf->particle[target].pos),conf) ) sim->wl.partincontact++; if ( particleinncontact (oldpos,conf) ) sim->wl.partincontact--; return contparticles_order(sim,wli); } /* return change in order parameter when chain moves*/ long contparticles_movechain(long chain[MAXN], struct conf * conf, struct sim * sim,struct particles chorig[MAXCHL],int wli) { long i,current; long contparticles_order(struct sim * sim, int wli); BOOL particleinncontact (struct vector *vec, struct conf *conf); i = 0; current = chain[0]; while (current >=0 ) { if ( conf->particle[current].type == sim->wl.wlmtype ) { if ( particleinncontact (&(conf->particle[current].pos),conf) ) sim->wl.partincontact++; } i++; current = chain[i]; } i = 0; current = chain[0]; while (current >=0 ) { if ( conf->particle[current].type == sim->wl.wlmtype ) { if ( particleinncontact (&(chorig[i].pos),conf) ) sim->wl.partincontact--; } i++; current = chain[i]; } return contparticles_order(sim,wli); } /* filling all particles in the contact */ long contparticles_all(struct topo *topo, struct conf *conf, struct sim * sim,int wli) { long i; long contparticles_order(struct sim * sim, int wli); BOOL particleinncontact (struct vector *vec, struct conf *conf); sim->wl.partincontact = 0; for (i=1; i< topo->npart; i++) { /*calculate position of particle and add it if in contact */ if ( conf->particle[i].type == sim->wl.wlmtype ) { if ( particleinncontact (&(conf->particle[i].pos),conf) ) sim->wl.partincontact++; } } return contparticles_order(sim,wli); } /*..............................................................................*/ /*........................GEOMETRIC STUFF.......................................*/ /*..............................................................................*/ /*..............................................................................*/ /* Find closest distance between line segments and return its vector gets orientations and lengths of line segments and the vector connecting their center os masses (from vec1 to vec2) */ // Copyright 2001, softSurfer (www.softsurfer.com) // This code may be freely used and modified for any purpose // providing that this copyright notice is included with it. // SoftSurfer makes no warranty for this code, and cannot be held // liable for any real or imagined damage resulting from its use. // Users of this code must verify correctness for their application. struct vector mindist_segments(struct vector dir1, double halfl1, struct vector dir2, double halfl2, struct vector r_cm) { struct vector u,v,w,vec; double a,b,c,d,e,D,sc,sN,sD,tc,tN,tD; struct vector vec_scale(struct vector, double); u = vec_scale(dir1,2.0*halfl1); //S1.P1 - S1.P0; v = vec_scale(dir2,2.0*halfl2); //S2.P1 - S2.P0; w.x = dir2.x*halfl2 - dir1.x*halfl1 - r_cm.x; w.y = dir2.y*halfl2 - dir1.y*halfl1 - r_cm.y; w.z = dir2.z*halfl2 - dir1.z*halfl1 - r_cm.z; //S1.P0 - S2.P0; a = DOT(u,u); // always >= 0 b = DOT(u,v); c = DOT(v,v); // always >= 0 d = DOT(u,w); e = DOT(v,w); D = a*c - b*b; // always >= 0 sc = D; sN = D; sD = D; // sc = sN / sD, default sD = D >= 0 tc = D; tN = D; tD = D; // tc = tN / tD, default tD = D >= 0 // compute the line parameters of the two closest points if (D < 0.00000001) { // the lines are almost parallel sN = 0.0; // force using point P0 on segment S1 sD = 1.0; // to prevent possible division by 0.0 later tN = e; tD = c; } else { // get the closest points on the infinite lines sN = (b*e - c*d); tN = (a*e - b*d); if (sN < 0.0) { // sc < 0 => the s=0 edge is visible sN = 0.0; tN = e; tD = c; } else if (sN > sD) { // sc > 1 => the s=1 edge is visible sN = sD; tN = e + b; tD = c; } } if (tN < 0.0) { // tc < 0 => the t=0 edge is visible tN = 0.0; // recompute sc for this edge if (-d < 0.0) sN = 0.0; else if (-d > a) sN = sD; else { sN = -d; sD = a; } } else if (tN > tD) { // tc > 1 => the t=1 edge is visible tN = tD; // recompute sc for this edge if ((-d + b) < 0.0) sN = 0; else if ((-d + b) > a) sN = sD; else { sN = (-d + b); sD = a; } } // finally do the division to get sc and tc if (fabs(sN) < 0.00000001) sc = 0.0 ; else sc = sN / sD; if (fabs(tN) < 0.00000001) tc = 0.0 ; else tc = tN / tD; // get the difference of the two closest points //Vector = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc) vec.x = u.x*sc + w.x - v.x*tc; vec.y = u.y*sc + w.y - v.y*tc; vec.z = u.z*sc + w.z - v.z*tc; return vec; } /*..............................................................................*/ /* Find closest distance between line segment and point and return it as vector (from point to closest segment point) Function gets orientation and length of line segments and the vector connecting their center os masses (from segment to point) */ struct vector mindist_segmentpoint(struct vector dir1, double length, struct vector r_cm) { struct vector vec; double c,d,halfl; halfl=length*0.5; c = DOT(dir1,r_cm); if (c >= halfl) d = halfl; else { if (c > -halfl) d = c; else d = -halfl; } vec.x = - r_cm.x + dir1.x * d; vec.y = - r_cm.y + dir1.y * d; vec.z = - r_cm.z + dir1.z * d; return vec; } /*..............................................................................*/ /* Determines whether two particles overlap. Returns 1 if there is an overlap, 0 if not. */ int overlap(struct particles part1, struct particles part2, struct vector box, struct ia_param ia_params[MAXT][MAXT]) { double b, c, d, e, f; /* Coefficients in distance quadratic */ double boundary; /* Half length of central boundary zone of quadratic */ double det; double halfl; /* Half length of cylinder */ double s0, t0; /* det times location of min separation of infinite lines */ double ss, tt; /* Location of min separation of line segments */ struct vector r_cm; /* Vector between centres of mass */ double dist; /* Distance between particles*/ struct vector distvec; /* Distance vector between particles*/ double linemin(double, double); struct vector image(struct vector, struct vector, struct vector); r_cm = image(part1.pos, part2.pos, box); if ((part1.type >= SP) && (part2.type >= SP)) { /*we have two spheres - most common, do nothing*/ dist=sqrt(DOT(r_cm,r_cm)); } else { if ((ia_params[part1.type][part2.type].geotype[0] < SP) && (ia_params[part1.type][part2.type].geotype[1] < SP)) { /*we have two spherocylinders*/ /*finding closes contact between them*/ b = -DOT(part1.dir, part2.dir); d = DOT(part1.dir, r_cm); e = -DOT(part2.dir, r_cm); f = DOT(r_cm, r_cm); det = 1.0 - b*b; //halfl = length / 2.0; // Just take the mean halfl = ia_params[part1.type][part2.type].half_len[0] = ia_params[part1.type][part2.type].half_len[1]; halfl /= 2; boundary = det * halfl; /* Location of smallest separation of the infinite lines */ s0 = b*e - d; t0 = b*d - e; /* Location of smallest separation of line segments */ if (s0 >= boundary) { if (t0 >= boundary) { /* Region 2 */ if ( d + halfl + halfl*b < 0.0 ) { ss = halfl; tt = linemin( -ss*b - e, halfl ); } else { tt = halfl; ss = linemin( -tt*b - d, halfl ); } } else if (t0 >= -boundary) { /* Region 1 */ ss = halfl; tt = linemin( -ss*b - e, halfl ); } else { /* Region 8 */ if ( d + halfl - halfl*b < 0.0 ) { ss = halfl; tt = linemin( -ss*b - e, halfl ); } else { tt = -halfl; ss = linemin( -tt*b - d, halfl ); } } } else if (s0 >= -boundary) { if (t0 >= boundary) { /* Region 3 */ tt = halfl; ss = linemin( -tt*b - d, halfl ); } else if (t0 >= -boundary) { /* Region 0 */ ss = s0/det; tt = t0/det; } else { /* Region 7 */ tt = -halfl; ss = linemin( -tt*b - d, halfl ); } } else { if (t0 >= boundary) { /* Region 4 */ if ( d - halfl + halfl*b > 0.0 ) { ss = -halfl; tt = linemin( -ss*b - e, halfl ); } else { tt = halfl; ss = linemin( -tt*b - d, halfl ); } } else if (t0 >= -boundary) { /* Region 5 */ ss = -halfl; tt = linemin( -ss*b - e, halfl ); } else { /* Region 6 */ if ( d - halfl - halfl*b > 0.0 ) { ss = -halfl; tt = linemin( -ss*b - e, halfl ); } else { tt = -halfl; ss = linemin( -tt*b - d, halfl ); } } } /*ss snd tt are Location of min separation of line segments */ dist=sqrt(f + ss*ss + tt*tt + 2.0*(ss*d + tt*e + ss*tt*b)); } else { if (ia_params[part1.type][part2.type].geotype[0] < SP) { /*We have one spherocylinder -it is first one*/ //halfl=length/2;/*finding closest vector from sphyrocylinder to sphere*/ halfl=ia_params[part1.type][part2.type].half_len[0];/*finding closest vector from sphyrocylinder to sphere*/ c = DOT(part1.dir,r_cm); if (c >= halfl) d = halfl; else { if (c > -halfl) d = c; else d = -halfl; } distvec.x = - r_cm.x + part1.dir.x * d; distvec.y = - r_cm.y + part1.dir.y * d; distvec.z = - r_cm.z + part1.dir.z * d; dist=sqrt(DOT(distvec,distvec)); } else { /*lst option first one is sphere second one spherocylinder*/ //halfl=length/2; /*finding closest vector from sphyrocylinder to sphere*/ halfl=ia_params[part1.type][part2.type].half_len[1];/*finding closest vector from sphyrocylinder to sphere*/ c = DOT(part2.dir,r_cm); if (c >= halfl) d = halfl; else { if (c > -halfl) d = c; else d = -halfl; } distvec.x = r_cm.x - part2.dir.x * d; distvec.y = r_cm.y - part2.dir.y * d; distvec.z = r_cm.z - part2.dir.z * d; dist=sqrt(DOT(distvec,distvec)); } } } /* Overlap exists if smallest separation is less than diameter of cylinder */ if (dist < ia_params[part1.type][part2.type].sigma*0.5 ) { return 1; } else { return 0; } } /*..............................................................................*/ double linemin(double criterion, double halfl) { if (criterion >= halfl) { return halfl; } else if (criterion >= -halfl) { return criterion; } else { return -halfl; } } /*..............................................................................*/ /*........................SOME USEFUL MATH......................................*/ /*..............................................................................*/ /* ran2 from Numerical Recipes. */ #define IM1 2147483563 #define IM2 2147483399 #define AM (1.0/IM1) #define IMM1 (IM1-1) #define IA1 40014 #define IA2 40692 #define IQ1 53668 #define IQ2 52774 #define IR1 12211 #define IR2 3791 #define NTAB 32 #define NDIV (1+IMM1/NTAB) #define EPS 1.2e-7 #define RNMX (1.0-EPS) double ran2(long *idum) { int j; long k; static long idum2=123456789; static long iy=0; static long iv[NTAB]; double temp; if (*idum <= 0) { if (-(*idum) < 1) *idum=1; else *idum = -(*idum); idum2=(*idum); for (j=NTAB+7;j>=0;j--) { k=(*idum)/IQ1; *idum=IA1*(*idum-k*IQ1)-k*IR1; if (*idum < 0) *idum += IM1; if (j < NTAB) iv[j] = *idum; } iy=iv[0]; } k=(*idum)/IQ1; *idum=IA1*(*idum-k*IQ1)-k*IR1; if (*idum < 0) *idum += IM1; k=idum2/IQ2; idum2=IA2*(idum2-k*IQ2)-k*IR2; if (idum2 < 0) idum2 += IM2; j=iy/NDIV; iy=iv[j]-idum2; iv[j] = *idum; if (iy < 1) iy += IMM1; if ((temp=AM*iy) > RNMX) return RNMX; else { return temp; } } #undef IM1 #undef IM2 #undef AM #undef IMM1 #undef IA1 #undef IA2 #undef IQ1 #undef IQ2 #undef IR1 #undef IR2 #undef NTAB #undef NDIV #undef EPS #undef RNMX /*..............................................................................*/ /* From Numerical Recipes. Simplified to deal specifically with 3*3 matrices (stored as elements [1...3][1...3] or a 4*4 array). */ void tred2(double a[4][4], double d[4], double e[4]) { int l, k, j, i; double scale, hh, h, g, f; for (i=3; i>=2; i--) { l=i-1; h=scale=0.0; if (l > 1) { for (k=1;k<=l;k++) scale += fabs(a[i][k]); if (scale == 0.0) e[i]=a[i][l]; else { for (k=1;k<=l;k++) { a[i][k] /= scale; h += a[i][k]*a[i][k]; } f=a[i][l]; g=(f >= 0.0 ? -sqrt(h) : sqrt(h)); e[i]=scale*g; h -= f*g; a[i][l]=f-g; f=0.0; for (j=1;j<=l;j++) { /* a[j][i]=a[i][j]/h; */ g=0.0; for (k=1;k<=j;k++) g += a[j][k]*a[i][k]; for (k=j+1;k<=l;k++) g += a[k][j]*a[i][k]; e[j]=g/h; f += e[j]*a[i][j]; } hh=f/(h+h); for (j=1;j<=l;j++) { f=a[i][j]; e[j]=g=e[j]-hh*f; for (k=1;k<=j;k++) a[j][k] -= (f*e[k]+g*a[i][k]); } } } else e[i]=a[i][l]; d[i]=h; } /* d[1]=0.0; */ e[1]=0.0; for (i=1; i<=3; i++) { /* l=i-1; if (d[i]) { for (j=1;j<=l;j++) { g=0.0; for (k=1;k<=l;k++) g += a[i][k]*a[k][j]; for (k=1;k<=l;k++) a[k][j] -= g*a[k][i]; } } */ d[i]=a[i][i]; /* a[i][i]=1.0; for (j=1;j<=l;j++) a[j][i]=a[i][j]=0.0; */ } } /*..............................................................................*/ /* From Numerical Recipes. Simplified to deal specifically with 3*3 matrices (stored as elements [1...3][1...3] or a 4*4 array). */ #define NRANSI #define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) void tqli(double d[4], double e[4]) { double pythag(double a, double b); int m, l, iter, i; /* int k; */ double s, r, p, g, f, dd, c, b; for (i=2; i<=3; i++) e[i-1] = e[i]; e[3] = 0.0; for (l=1; l<=3; l++) { iter = 0; do { for (m=l; m<=3-1; m++) { dd = fabs(d[m]) + fabs(d[m+1]); if ((double)(fabs(e[m])+dd) == dd) break; } if (m != l) { if (iter++ == 30) { fprintf(stderr, "Too many iterations in tqli\n"); exit (2); } g = (d[l+1] - d[l]) / (2.0*e[l]); r = pythag(g, 1.0); g = d[m] - d[l] + e[l] / (g + SIGN(r,g)); s = c = 1.0; p = 0.0; for (i=m-1; i>=l; i--) { f = s * e[i]; b = c * e[i]; e[i+1] = (r=pythag(f,g)); if (r == 0.0) { d[i+1] -= p; e[m] = 0.0; break; } s = f/r; c = g/r; g = d[i+1] - p; r = (d[i] - g)*s + 2.0*c*b; d[i+1] = g+(p=s*r); g = c*r - b; /* for (k=1; k<=3; k++) { f = z[k][i+1]; z[k][i+1] = s*z[k][i]+c*f; z[k][i] = c*z[k][i]i - s*f; } */ } if (r == 0.0 && i >= l) continue; d[l] -= p; e[l] = g; e[m] = 0.0; } } while (m != l); } } #undef NRANSI /*..............................................................................*/ /* From Numerical Recipes. Used by tqli. */ #define NRANSI static double sqrarg; #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg) double pythag(double a, double b) { double absa, absb; absa = fabs(a); absb = fabs(b); if (absa > absb) return absa*sqrt(1.0+SQR(absb/absa)); else return (absb == 0.0 ? 0.0 : absb*sqrt(1.0+SQR(absa/absb))); } #undef NRANSI /*..............................................................................*/ /* Normalise a vector to have unit length. For speed during heavy use, it is not checked that the supplied vector has non-zero length. */ void normalise(struct vector *u) { double tot; tot = sqrt( DOT(*u,*u) ); if (tot !=0.0) { tot=1/tot; (*u).x *= tot; (*u).y *= tot; (*u).z *= tot; } } /* Returns the vector pointing from the centre of mass of particle 2 to the centre of mass of the closest image of particle 1. */ struct vector image(struct vector r1, struct vector r2, struct vector box) { struct vector r12; double anint(double); r12.x = r1.x - r2.x; r12.y = r1.y - r2.y; r12.z = r1.z - r2.z; r12.x = box.x * (r12.x - anint(r12.x)); r12.y = box.y * (r12.y - anint(r12.y)); r12.z = box.z * (r12.z - anint(r12.z)); return r12; } /* Returns the nearest integer to its argument as a double precision number. e.g. anint(-0.49) = 0.0 and anint(-0.51) = -1.0. Equivalent to the Fortran intrinsic ANINT. */ double anint(double arg) { if (arg < 0) { return (double)( (long)(arg-0.5) ); } else { return (double)( (long)(arg+0.5) ); } } /*..............................................................................*/ /* Returns an evenly distributed random unit vector of unit length. See Allen & Tildesley p349 or Frenkel & Smit p410. RANDOM VECTOR ON UNIT SPHERE */ struct vector ranvec(void) { double a, b, xi1, xi2; struct vector unit; double ran2(long *); do { xi1 = 1.0 - 2.0*ran2(&seed); xi2 = 1.0 - 2.0*ran2(&seed); a = xi1*xi1 + xi2*xi2; } while (a > 1.0); b = 2.0 * sqrt(1.0 - a); unit.x = xi1 * b; unit.y = xi2 * b; unit.z = 1.0 - 2.0*a; return unit; } /** * returns a point randomly and evenly distributed inside of a unit sphere */ struct vector ranvecsph(void) { struct vector ranvec; double ran2(long *); do{ ranvec.x = 2 * ran2(&seed) - 1.0; ranvec.y = 2 * ran2(&seed) - 1.0; ranvec.z = 2 * ran2(&seed) - 1.0; } while(ranvec.x*ranvec.x + ranvec.y*ranvec.y + ranvec.z*ranvec.z >= 1); //printf("%lf\t%lf\t%lf\n", ranvec.x,ranvec.y,ranvec.z); return ranvec; } /**** some useful math *******/ struct vector vec_create(double x, double y, double z) { struct vector newvec; newvec.x=x; newvec.y=y; newvec.z=z; return newvec; } struct vector vec_createarr(double a[3]) { struct vector newvec; newvec.x=a[0]; newvec.y=a[1]; newvec.z=a[2]; return newvec; } double vec_dotproduct(struct vector A,struct vector B) { double dp; dp = A.x*B.x + A.y*B.y + A.z*B.z; return dp; } /* vector projection of vector A to direction of B*/ struct vector vec_project(struct vector* A,struct vector* B) { double dp; struct vector pr; dp = A->x*B->x + A->y*B->y + A->z*B->z; pr.x=B->x*dp; pr.y=B->y*dp; pr.z=B->z*dp; return pr; } void ortogonalise(struct vector *A, struct vector B) { double dp; double vec_dotproduct(struct vector A,struct vector B); dp=vec_dotproduct(*A,B); (*A).x -= B.x * dp; (*A).y -= B.y * dp; (*A).z -= B.z * dp; } /* vector projection of vector A perpendicular to direction of B*/ struct vector vec_perpproject(struct vector *A,struct vector *B) { struct vector pp; double dp; struct vector vec_project(struct vector *, struct vector*); dp=DOT((*A),(*B)); pp.x = A->x - B->x*dp; pp.y = A->y - B->y*dp; pp.z = A->z - B->z*dp; // fprintf (stderr, "pp x: %.8f y: %.8f z: %.8f \n",pp.x,pp.y,pp.z); return pp; } /* returns a vector perpendicular to A nothing special about the vector except that it's one of the perpendicular options and is normalized */ struct vector vec_perp(struct vector A) { double ratio,x,y; struct vector somevector; struct vector vec_create(double, double, double); struct vector vec_normalize(struct vector); void normalise(struct vector *); struct vector vec_crossproduct(struct vector, struct vector); x=A.x; y=A.y; if (x == 0) x=1; else { if (y == 0) y=1; else { ratio=y/x; y=x*ratio*2; } } somevector= vec_create(x, y, A.z); normalise(&somevector); return vec_crossproduct(A,somevector); } /* Perform the multiplication of a matrix A and a vector B where A is the first argument and B is the second argument. The routine will return AxB*/ struct vector matrix_vec_multiply(double A[3][3],struct vector B) { int i; double vecarr[3]; struct vector AB,RA; struct vector vec_createarr(double[3]); double vec_dotproduct(struct vector,struct vector); for (i=0;i<3;i++) { /* index the row vector from A*/ RA=vec_createarr(A[i]); /* Now find the dot product of this row with B*/ vecarr[i]=vec_dotproduct(RA,B); } AB=vec_createarr(vecarr); return AB; } /* Distance between two vectors*/ double vec_distance(struct vector vec1,struct vector vec2) { double sum; sum= (vec1.x-vec2.x)*(vec1.x-vec2.x)+(vec1.y-vec2.y)*(vec1.y-vec2.y)+(vec1.z-vec2.z)*(vec1.z-vec2.z); return pow(sum,0.5); } /* Vector size */ double vec_size(struct vector vec) { double size; size=sqrt(vec.x*vec.x+ vec.y*vec.y+ vec.z*vec.z); return size; } /* Normalize a vector*/ struct vector vec_normalize(struct vector vec) { double mag; struct vector newvec; double vec_size(struct vector); mag= vec_size (vec); mag=1/mag; newvec.x=vec.x*mag; newvec.y=vec.y*mag; newvec.z=vec.z*mag; return newvec; } /* Scale a vector */ struct vector vec_scale(struct vector vec, double scale) { vec.x=vec.x*scale; vec.y=vec.y*scale; vec.z=vec.z*scale; return vec; } /* cross_product*/ struct vector vec_crossproduct(struct vector A,struct vector B) { struct vector cp; cp.x=( A.y*B.z - A.z*B.y); cp.y=( -A.x*B.z + A.z*B.x); cp.z=( A.x*B.y - A.y*B.x); return cp; } /* addition of vectors*/ inline struct vector vec_sum(struct vector A,struct vector B) { struct vector C; C.x=(A.x + B.x); C.y=(A.y + B.y); C.z=(A.z + B.z); return C; } /* subtraction of vectors*/ inline struct vector vec_sub(struct vector A,struct vector B) { struct vector C; C.x=(A.x - B.x); C.y=(A.y - B.y); C.z=(A.z - B.z); return C; } /* asign vlues of vector A by values in vector B*/ inline void vec_asign(struct vector *A, struct vector B) { (*A).x=B.x; (*A).y=B.y; (*A).z=B.z; } /* generate random unit vector*/ struct vector vec_random(void) { struct vector newvec; struct vector ranvec(void); newvec=ranvec(); return newvec; } /*generate random unit quaternion*/ struct quat quat_random(void) { double cosv, sinv; struct quat newquat; struct vector newaxis; struct vector ranvec(void); /* generate quaternion for rotation*/ newaxis = ranvec(); /*random axes for rotation*/ cosv = cos(PIH * ran2(&seed) ); if (ran2(&seed) <0.5) sinv = sqrt(1.0 - cosv*cosv); else sinv = -sqrt(1.0 - cosv*cosv); newquat.w=cosv; newquat.x=newaxis.x*sinv; newquat.y=newaxis.y*sinv; newquat.z=newaxis.z*sinv; return newquat; } /* Create quaternion for rotation around vector "vec" of angle in degrees "angle" function need cos of half angle and its sin*/ struct quat quat_create(struct vector vec, double vc, double vs) { struct quat newquat; newquat.w=vc; newquat.x=vec.x*vs; newquat.y=vec.y*vs; newquat.z=vec.z*vs; return newquat; } /*rotate vector with quaternion*/ void vec_rotate(struct vector *vec, struct quat quat) { double t2,t3,t4,t5,t6,t7,t8,t9,t10,newx,newy,newz; /* t1 = quat.w * quat.w; */ t2 = quat.w * quat.x; t3 = quat.w * quat.y; t4 = quat.w * quat.z; t5 = -quat.x * quat.x; t6 = quat.x * quat.y; t7 = quat.x * quat.z; t8 = -quat.y * quat.y; t9 = quat.y * quat.z; t10 = -quat.z * quat.z; newx = 2.0 * ( (t8+t10)*(*vec).x + (t6-t4)*(*vec).y + (t3+t7)*(*vec).z ) + (*vec).x; newy = 2.0 * ( (t4+t6)*(*vec).x + (t5+t10)*(*vec).y + (t9-t2)*(*vec).z ) + (*vec).y; newz = 2.0 * ( (t7-t3)*(*vec).x + (t2+t9)*(*vec).y + (t5+t8)*(*vec).z ) + (*vec).z; (*vec).x = newx; (*vec).y = newy; (*vec).z = newz; } /* rotate spherocylinder by quaternion of random axis and angle smaller than maxcos(cosine of angle half), we do everything on site for speed */ void psc_rotate(struct particles *psc, double max_angle,int geotype) { double vc, vs, t2, t3, t4, t5, t6, t7, t8, t9, t10; double d1, d2, d3, d4, d5, d6, d7, d8, d9 , newx, newy, newz; int k,m; struct quat newquat; struct vector newaxis; struct vector ranvec(void); /* generate quaternion for rotation*/ newaxis = ranvec(); /*random axes for rotation*/ // maxcos = cos(maxorient/2/180*PI); // vc = maxcos + ran2(&seed)*(1-maxcos); /*cos of angle must be bigger than maxcos and smaller than one*/ vc = cos(max_angle * ran2(&seed) ); if (ran2(&seed) <0.5) vs = sqrt(1.0 - vc*vc); else vs = -sqrt(1.0 - vc*vc); /*randomly choose orientation of direction of rotation clockwise or counterclockwise*/ newquat.w=vc; newquat.x=newaxis.x*vs; newquat.y=newaxis.y*vs; newquat.z=newaxis.z*vs; /* do quaternion rotation*/ t2 = newquat.w * newquat.x; t3 = newquat.w * newquat.y; t4 = newquat.w * newquat.z; t5 = -newquat.x * newquat.x; t6 = newquat.x * newquat.y; t7 = newquat.x * newquat.z; t8 = -newquat.y * newquat.y; t9 = newquat.y * newquat.z; t10 = -newquat.z * newquat.z; d1 = t8 + t10; d2 = t6 - t4; d3 = t3 + t7; d4 = t4 + t6; d5 = t5 + t10; d6 = t9 - t2; d7 = t7 - t3; d8 = t2 + t9; d9 = t5 + t8; /*rotate spherocylinder direction vector*/ newx = 2.0 * ( d1*psc->dir.x + d2*psc->dir.y + d3*psc->dir.z ) + psc->dir.x; newy = 2.0 * ( d4*psc->dir.x + d5*psc->dir.y + d6*psc->dir.z ) + psc->dir.y; newz = 2.0 * ( d7*psc->dir.x + d8*psc->dir.y + d9*psc->dir.z ) + psc->dir.z; psc->dir.x = newx; psc->dir.y = newy; psc->dir.z = newz; m=1; if ( (geotype != SCN) && (geotype != SCA) ) { if ( (geotype == TPSC) || (geotype == TCPSC) || (geotype == TCHPSC) || (geotype == TCHCPSC) ) m=2; for (k=0;k<m;k++) { /*rotate patch direction vector*/ newx = 2.0 * ( d1*psc->patchdir[k].x + d2*psc->patchdir[k].y + d3*psc->patchdir[k].z ) + psc->patchdir[k].x; newy = 2.0 * ( d4*psc->patchdir[k].x + d5*psc->patchdir[k].y + d6*psc->patchdir[k].z ) + psc->patchdir[k].y; newz = 2.0 * ( d7*psc->patchdir[k].x + d8*psc->patchdir[k].y + d9*psc->patchdir[k].z ) + psc->patchdir[k].z; psc->patchdir[k].x = newx; psc->patchdir[k].y = newy; psc->patchdir[k].z = newz; /*rotate patch sides vectors*/ newx = 2.0 * ( d1*psc->patchsides[0+2*k].x + d2*psc->patchsides[0+2*k].y + d3*psc->patchsides[0+2*k].z ) + psc->patchsides[0+2*k].x; newy = 2.0 * ( d4*psc->patchsides[0+2*k].x + d5*psc->patchsides[0+2*k].y + d6*psc->patchsides[0+2*k].z ) + psc->patchsides[0+2*k].y; newz = 2.0 * ( d7*psc->patchsides[0+2*k].x + d8*psc->patchsides[0+2*k].y + d9*psc->patchsides[0+2*k].z ) + psc->patchsides[0+2*k].z; psc->patchsides[0+2*k].x = newx; psc->patchsides[0+2*k].y = newy; psc->patchsides[0+2*k].z = newz; newx = 2.0 * ( d1*psc->patchsides[1+2*k].x + d2*psc->patchsides[1+2*k].y + d3*psc->patchsides[1+2*k].z ) + psc->patchsides[1+2*k].x; newy = 2.0 * ( d4*psc->patchsides[1+2*k].x + d5*psc->patchsides[1+2*k].y + d6*psc->patchsides[1+2*k].z ) + psc->patchsides[1+2*k].y; newz = 2.0 * ( d7*psc->patchsides[1+2*k].x + d8*psc->patchsides[1+2*k].y + d9*psc->patchsides[1+2*k].z ) + psc->patchsides[1+2*k].z; psc->patchsides[1+2*k].x = newx; psc->patchsides[1+2*k].y = newy; psc->patchsides[1+2*k].z = newz; } } m=1; if ( (geotype == CHPSC) || (geotype == CHCPSC) || (geotype == TCHPSC) || (geotype == TCHCPSC) ) { if ( (geotype == TCHPSC) || (geotype == TCHCPSC) ) m=2; for (k=0;k<m;k++) { /*rotate chiral direction vector*/ newx = 2.0 * ( d1*psc->chdir[k].x + d2*psc->chdir[k].y + d3*psc->chdir[k].z ) + psc->chdir[k].x; newy = 2.0 * ( d4*psc->chdir[k].x + d5*psc->chdir[k].y + d6*psc->chdir[k].z ) + psc->chdir[k].y; newz = 2.0 * ( d7*psc->chdir[k].x + d8*psc->chdir[k].y + d9*psc->chdir[k].z ) + psc->chdir[k].z; psc->chdir[k].x = newx; psc->chdir[k].y = newy; psc->chdir[k].z = newz; } } } /*returns a position of center of mass of system*/ void masscenter(long npart, struct ia_param ia_params[MAXT][MAXT], struct conf * conf) { long i; double anint(double); conf->syscm.x = 0; conf->syscm.y = 0; conf->syscm.z = 0; for (i=0; i<npart; i++) { /*using periodic boundary conditions*/ conf->syscm.x += (conf->particle[i].pos.x - anint(conf->particle[i].pos.x) ) * ia_params[conf->particle[i].type][conf->particle[i].type].volume; conf->syscm.y += (conf->particle[i].pos.y - anint(conf->particle[i].pos.y) ) * ia_params[conf->particle[i].type][conf->particle[i].type].volume; conf->syscm.z += (conf->particle[i].pos.z - anint(conf->particle[i].pos.z) ) * ia_params[conf->particle[i].type][conf->particle[i].type].volume; } conf->syscm.x /= conf->sysvolume; conf->syscm.y /= conf->sysvolume; conf->syscm.z /= conf->sysvolume; return; } /* rotate cluster of particles by quaternion of random axis and angle smaller than maxcos(cosine of angle half), we do everything on site for speed */ void cluster_rotate(long target, struct vector gc, double max_angle, struct topo * topo, struct conf * conf) { long current,i; double vc,vs; //double quatsize; struct quat newquat; struct vector newaxis; struct vector ranvec(void); void vec_rotate(struct vector *, struct quat); // create rotation quaternion newaxis = ranvec(); /*random axes for rotation*/ // maxcos = cos(maxorient/2/180*PI); //vc = maxcos + ran2(&seed)*(1-maxcos); /*cos of angle must be bigger than maxcos and smaller than one*/ vc = cos(max_angle * ran2(&seed) ); if (ran2(&seed) <0.5) vs = sqrt(1.0 - vc*vc); else vs = -sqrt(1.0 - vc*vc); /*randomly choose orientation of direction of rotation clockwise or counterclockwise*/ newquat.w=vc; newquat.x=newaxis.x*vs; newquat.y=newaxis.y*vs; newquat.z=newaxis.z*vs; //quatsize=sqrt(newquat.w*newquat.w+newquat.x*newquat.x+newquat.y*newquat.y+newquat.z*newquat.z); //shift position to geometrical center i=0; current = topo->chainlist[target][0]; while (current >=0 ) { //shift position to geometrical center conf->particle[current].pos.x -= gc.x; conf->particle[current].pos.y -= gc.y; conf->particle[current].pos.z -= gc.z; //scale things by box not to have them distorted conf->particle[current].pos.x *= conf->box.x; conf->particle[current].pos.y *= conf->box.y; conf->particle[current].pos.z *= conf->box.z; //do rotation vec_rotate(&conf->particle[current].pos, newquat); vec_rotate(&conf->particle[current].dir, newquat); vec_rotate(&conf->particle[current].patchdir[0], newquat); vec_rotate(&conf->particle[current].patchdir[1], newquat); vec_rotate(&conf->particle[current].chdir[0], newquat); vec_rotate(&conf->particle[current].chdir[1], newquat); vec_rotate(&conf->particle[current].patchsides[0], newquat); vec_rotate(&conf->particle[current].patchsides[1], newquat); vec_rotate(&conf->particle[current].patchsides[2], newquat); vec_rotate(&conf->particle[current].patchsides[3], newquat); //sclae back conf->particle[current].pos.x /= conf->box.x; conf->particle[current].pos.y /= conf->box.y; conf->particle[current].pos.z /= conf->box.z; //shift positions back conf->particle[current].pos.x += gc.x; conf->particle[current].pos.y += gc.y; conf->particle[current].pos.z += gc.z; i++; current = topo->chainlist[target][i]; } } /* put the particle in the original box using periodic boundary conditions in our system the particle positions are scaled by box size so to get them into original obx is to get htem between 0 and 1 and then scale this back by size of box*/ void origbox(struct vector *pos,struct vector box) { double anint(double); (*pos).x = box.x * ((*pos).x - anint((*pos).x)); (*pos).y = box.y * ((*pos).y - anint((*pos).y)); (*pos).z = box.z * ((*pos).z - anint((*pos).z)); } /* use of periodic boundary conditions*/ void usepbc(struct vector *pos,struct vector pbc) { do { (*pos).x += pbc.x; } while ((*pos).x < 0.0); do { (*pos).x -= pbc.x; } while ((*pos).x > pbc.x); do { (*pos).y += pbc.y; } while ((*pos).y < 0.0); do { (*pos).y -= pbc.y; } while ((*pos).y > pbc.y); do { (*pos).z += pbc.z; } while ((*pos).z < 0.0); do { (*pos).z -= pbc.z; } while ((*pos).z > pbc.z); } /*..............................................................................*/ /*.......................TEMPLATE FILES.........................................*/ /*..............................................................................*/ /* # Template for the "options" file. Options start with an '#'. # Pressure couplings: # 0 = anisotropic coupling, 1 = isotropic coupling, 2 = isotropic in xy z=const, 3 = isotropic # xy and keep Volume constant # Wang-Landau method: (with constant decrease of bias addition by factor of 2, until less than WL_ALPHATOL) # O = none, 1 = z-direction of 1st paticle, 2 = hole in xyplane, 3 = z-orientation of 0th particle # 4 = distance of first two particles, 5 = pore around z axis and above CM, 6 = pore around z axis and above 0th particle # 7 = number of particles in contact (within distance sqrt(WL_CONTACTS)) ptype = 1 # Pressure coupling type (0-anisotropic xyz, 1-isotropic xyz, 2 - isotropic in xy z=const, 3 - isotropic in xy and V=const) press = 1 # Pressure paralpress = 1 # Parallel pressure for replica exchange shave = 0 # Average number of volume change attempts per sweep (usually 1) nequil = 0 # Number of equilibration sweeps adjust = 0 # Number of equilibration sweeps between step size adjustments nsweeps = 1000000 # Number of production sweeps paramfrq = 1000000 # Number of sweeps between order parameter samples report = 1000000 # Number of sweeps between statistics reports nrepchange = 1000 # Number of sweeps between replica exchanges movie = 100000 # Number of sweeps between movie frames (0 = no movie) chainprob = 0.0 # Probability of chain move attempts per sweep ( 0.25/number of particles in chain) transmx = 0.212 # Initial maximum displacement rotmx = 7.5 # Initial maximum orientation change (degrees) edge_mx = 0.0 # Initial maximum box length change chainmmx = 0.0 # Initial maximum chain displacement chainrmx = 0.0 # Initial maximum chain rotation change (degrees) temper = 1.0 # Temperature in units kT/e paraltemper = 1.5 # Temperature for parallel tempering in kT/e wlm = 0 # Wang-Landau method wlmtype = 0 # For which atomic type (from top.init) should the Wang-Landau method be calculated? switchprob = 0.0016 # Probability of type switch attempts per sweep pairlist_update = 8 # Number of sweeps after which the pairlist should be updated seed = 1 # Random number seed write_cluster = 10000 # Number of sweeps per writing out cluster info # End of the file */ /* Example of 'Config.init' file, but you must delete comments... there are only number in configuration file #box 10.0 10.0 10.0 #particles (x,y,z) (direction_x,direction_y, direction_z) (patchdirection_x,patchdirection_y,patchdirection_z) (switched) */ /* Template for the topology file 'top.init'. ( "\\" is symbol for line continue, "#" is symbol for comment, "[" is starting sign for keyword, "]" is ending sign for kyeword ) There are three keywords, types, molecules, and system. They should be given in this order. TYPES: spherocylinders SC - purely repulsive spherocylinder with WCA potential on closest distance SCA - isotropic cos^2 potential is acting isotropicaly dependent only on closest distance between spherocylinders.. PSC - Attractive potential in limited to an angular wedge on spherocylinder. Patch goes all the way through, making also hemispherical caps on end attractive CPSC - Attractive potential in limited to an angular wedge on cylindrical part of spherocylinders. The hemispherical caps on ends are repulsive spheres (T)(CH)PSC - T adds second patch, CH - adds chirality SP - purely repulsive shpere with WCA potential on closest distance SPA - isotropic cos^2 potential is acting isotropicaly dependent only on closest distance between obejcts [Types] # NAME NUMBER GEOTYPE EPSILON SIGMA ATTRACTION_DIST ATTRACTION_SWITCH PATCH_ANGLE PATCH_SWITCH SC_LENGTH (Optional second patch: PATCH_ROTATION PATCH_ANGLE PATCH_SWITCH )CHIRAL_ANGLE Prot1 1 PSC 1 1.2 1.346954458 1.0 80.0 5.0 3 Prot2 2 PSC 1 1.2 1.346954458 1.0 170.0 5.0 3 Prot3 3 CHCPSC 1 1.2 1.346954458 1.0 170.0 5.0 3 10 Prot4 4 TCHCPSC 1 1.2 1.346954458 1.0 170.0 5.0 3 90.0 90.0 5.0 10 [Molecules] # Molecules letter # bond1 - harmonic bond between nearest neighbours (end points for spherocylinders) (first constant then eq distance) # bond2 - harmonic bond between second nearest neighbours (their center of mass) (first constant then eq distance) # bondd - directional harmonic bond between nearest neighbours (end point of the second spherocylinder is attached to the point of bondlength extension of the first spherocylinder) (first constant then eq distance) # angle1 - angle between two spherocylinders -nearest neighbours (first constant then eq degrees 0-180.0) # angle2 - angle between two spherocylinder patches -nearest neighbours (first constant then eq degrees 0-180.0) # particles - types as they go in chain in molecule A: { #what: TYPE SWITCHTYPE DELTA_MU particles: 1 2 0.5 particles: 2 } B: { particles: 1 particles: 2 1 0.3 } [System] A 2 B 2 [EXTER] # wall interaction # THICKNESS EPSILON ATTRACTION_SWITCH 5.0 1.0 1.0 [EXCLUDE] #set pair types for which attraction will be excluded (reversepair is automaticaly added) 1 2 1 3 */
the_stack_data/29824570.c
#include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main (void) { const int n = 10; fprintf(stderr, "making %d zombies...", n); for (int i = 0; i < n; i++) { pid_t pid = fork (); if (pid < 0) { perror ("fork"); return 1; } else if (pid == 0) exit (i); } fprintf(stderr, "done\n"); fprintf(stderr, "press [enter] for sending them to haven"); getchar (); for (int i = 0; i < n; i++) wait (NULL); while (1); return 0; }
the_stack_data/192332061.c
#include <stdio.h> void func(int *a, int n); int main() { int a1[5]={0}; func(a1, 5); printf("a1[3] = %d", a1[3]); printf("\n***********\n"); return 0; } void func(int *a, int n) { int *p; *a=0; printf("***********\n"); for (p=a+1; p<a+n; p++) { *p = p - a + *(p - 1); // p - a computes how far along the array a pointer p has advanced. printf("iteration %d\n***********\n", p - a); printf("p - a = %d\n", p - a); printf(" *p = p - a + *(p - 1) = %d\n\n", *p); } printf("***********\n"); }
the_stack_data/95451149.c
#include <stdio.h> #include <stdlib.h> typedef struct _queue queue; struct _queue { int data; queue *link; }; queue *create_queue_node(void) { queue *tmp = (queue *)malloc(sizeof(queue)); tmp->link = NULL; return tmp; } queue *enqueue(queue *head, int data) { if (!head) { head = create_queue_node(); head->data = data; return head; } head->link = enqueue(head->link, data); } void print_queue(queue *head) { queue *tmp = head; while (tmp) { printf("data from queue: %d\n", tmp->data); tmp = tmp->link; } } queue *dequeue(queue *head) { queue *tmp; int data; if (!head) { printf("queue is empty\n"); return NULL; } data = head->data; tmp = head->link; free(head); printf("data from dequeue: %d\n", data); return tmp; } int main(void) { int i; queue *head = NULL; int data[] = { 1, 10, 5, 3, 7, 8, 12 }; for (i = 0; i < sizeof(data) / sizeof(int); i++) { head = enqueue(head, data[i]); } print_queue(head); head = dequeue(head); print_queue(head); return 0; }
the_stack_data/138141.c
/* Exercise 1 - Calculations Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */ #include <stdio.h> int main() { printf('hello'); return 0; }
the_stack_data/215768845.c
/* Atmospheric refraction * Returns correction in degrees to be added to true altitude * to obtain apparent altitude. * * -- S. L. Moshier */ extern double atpress; /* millibars */ extern double attemp; /* degrees C */ extern double DTR; /* pi/180 */ #if __STDC__ double tan (double); #else double tan(); #endif double refrac(alt) double alt; /* altitude in degrees */ { double y, y0, D0, N, D, P, Q; int i; if( (alt < -2.0) || (alt >= 90.0) ) return(0.0); /* For high altitude angle, AA page B61 * Accuracy "usually about 0.1' ". */ if( alt > 15.0 ) { D = 0.00452*atpress/((273.0+attemp)*tan( DTR*alt )); return(D); } /* Formula for low altitude is from the Almanac for Computers. * It gives the correction for observed altitude, so has * to be inverted numerically to get the observed from the true. * Accuracy about 0.2' for -20C < T < +40C and 970mb < P < 1050mb. */ /* Start iteration assuming correction = 0 */ y = alt; D = 0.0; /* Invert Almanac for Computers formula numerically */ P = (atpress - 80.0)/930.0; Q = 4.8e-3 * (attemp - 10.0); y0 = y; D0 = D; for( i=0; i<4; i++ ) { N = y + (7.31/(y+4.4)); N = 1.0/tan(DTR*N); D = N*P/(60.0 + Q * (N + 39.0)); N = y - y0; y0 = D - D0 - N; /* denominator of derivative */ if( (N != 0.0) && (y0 != 0.0) ) /* Newton iteration with numerically estimated derivative */ N = y - N*(alt + D - y)/y0; else /* Can't do it on first pass */ N = alt + D; y0 = y; D0 = D; y = N; } return( D ); }
the_stack_data/197903.c
/* * Author: Andrew Zurn * Discr: This will be a game that looks for user interaction to test response skills. * Due Date: 10/24/12 */ #include <sys/types.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <sys/time.h> #include <fcntl.h> #include <sys/stat.h> static int FIXED_RESPONSE = 20; suseconds_t best, worst, average; suseconds_t *best_pointer, *worst_pointer, *average_pointer; int timer = 1; struct timeval tv; struct itimerval itv; suseconds_t response_time_array[20]; suseconds_t start_time; int array_index=0; static void catch_sig(int sig){ int caught = -1; suseconds_t response_time; if(sig == SIGINT){ //system return current time, add to array to be processed at the end of the game. if(getitimer(ITIMER_REAL, &itv) == -1){ printf("getitimer error, exiting"); exit(EXIT_FAILURE); } response_time = (start_time - itv.it_value.tv_usec); printf("\nYour response time was: %d microseconds\n", response_time); response_time_array[array_index] = response_time; array_index++; caught = 0; return; } else if(sig == SIGVTALRM || sig == SIGALRM){ if(caught){ return; } else if(!caught){ printf("You did not stop the timer in time!"); time_t response_time = 50; response_time_array[array_index] = response_time; array_index++; return; } } else{ fprintf(stderr, "Unknown signal error: %d, exiting \n", sig); exit(EXIT_FAILURE); } } int process_times(){ //go through each time processed, setting the first to the worst, second if better than first to best, and checking both for each new time. Add up all times, and divide by FIXED_RESPONSE. int i; worst = response_time_array[0]; best = response_time_array[0]; for(i = 1; i<FIXED_RESPONSE; i++){ if( response_time_array[i] > worst){ worst = response_time_array[i]; } else if( response_time_array[i] < best){ best = response_time_array[i]; } average = average + response_time_array[i]; } average = average / FIXED_RESPONSE; best_pointer = &best; worst_pointer = &worst; average_pointer = &average; return 0; } int main(int argc, char * argv[]){ int rand_int; itv.it_value.tv_sec = 300; char * user_name[8]; printf("Welcome to the Andrew Zurn's Response Timing Game!\n"); printf("Please enter a user name 8 characters in length!\n"); //must be 8 characters scanf("%s", user_name); user_name[8] = '\0'; printf("%s, get ready to play!\n", user_name); int i; for(i=0;i<FIXED_RESPONSE;i++){ printf("Trial: %d of %d \n", i+1, FIXED_RESPONSE); rand_int = random(); if(rand_int >= 0 && rand_int <= 715827881){//timer at 1 secs //sleep 1 second, then start timer, signal handler will stop timer and store for processing. sleep(1); printf("Timer Elapsed! Press CONTROL+C!"); if ((setitimer(ITIMER_REAL, &itv, 0)) == -1){ printf("timer error, exiting\n"); exit(EXIT_FAILURE); } start_time = itv.it_value.tv_usec; if(signal(SIGINT, catch_sig)==SIG_ERR){ printf("Signal send error, exiting\n"); exit(EXIT_FAILURE); } pause(); } else if(rand_int >= 715827882 && rand_int <= 1431655762){//timer at 2 secs //sleep 2 seconds, then start timer, signal handler will stop timer and store for processing. sleep(2); printf("Timer Elapsed! Press CONTROL+C!\n"); if ((setitimer(ITIMER_REAL, &itv, 0)) == -1){ printf("timer error, exiting\n"); exit(EXIT_FAILURE); } start_time = itv.it_value.tv_sec; if(signal(SIGINT, catch_sig)==SIG_ERR){ printf("Signal send error, exiting\n"); exit(EXIT_FAILURE); } pause(); } else if(rand_int >= 1431655763 && rand_int <= RAND_MAX){//timer at 3 secs //sleep 4 seconds, then start timer, signal handler will stop timer and store for processing. sleep(3); printf("Timer Elapsed! Press CONTROL+C!\n"); if ((setitimer(ITIMER_REAL, &itv, 0)) == -1){ printf("timer error, exiting\n"); exit(EXIT_FAILURE); } start_time = itv.it_value.tv_sec; if(signal(SIGINT, catch_sig)==SIG_ERR){ printf("Signal send error, exiting\n"); exit(EXIT_FAILURE); } pause(); } } process_times(); printf("Your best time was: %d microseconds\n", best); printf("Your worst time was: %d microseconds\n", worst); printf("Your average time was: %d microseconds\n", average); char save_option[1]; //Y or N for save option printf("Would you like to save your scores: Y or N\n"); printf("WARNING: Saving your game data will overwrite any saved data you may have!\n"); scanf("%s", save_option); if(save_option[0] == 'Y'){ //save game data - FIXED LENGTH of 60 bits in file int fd = open("zurnProg1.log", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); ssize_t numRead = 0; char * user_name_buffer[8]; int user_read = 9; int searching_for_user = 0; off_t off_set = 52; ssize_t num_written; if(fd == -1){ fprintf(stderr, "Open .log file error, exiting\n"); exit(EXIT_FAILURE); } while(searching_for_user){ if((numRead = read(fd, user_name_buffer, user_read)) != 8){ fprintf(stderr, "user_name read error, exiting\n"); exit(EXIT_FAILURE); } if((strcmp(*user_name_buffer, *user_name)) == 0){ searching_for_user = 1; //user name found, exit while } off_set = lseek(fd, off_set, SEEK_CUR); if(off_set == -1){ //fprintf(stderr, "seek error, exiting\n"); break; //end-of-file } } if(searching_for_user == 0){ //user never found, start new record //find how to make file append only and append record if((close(fd)) == -1){ fprintf(stderr, "close error, exiting\n"); exit(EXIT_FAILURE); } int fd = open("zurnProg1.log", O_CREAT | O_RDWR | O_APPEND, S_IRUSR | S_IWUSR); //will only add to end of file if(fd == -1){ fprintf(stderr, "Open .log file error, exiting\n"); exit(EXIT_FAILURE); } num_written = write(fd, user_name, 8); num_written = write(fd, best_pointer, 8); num_written = write(fd, worst_pointer, 8); num_written = write(fd, average_pointer, 8); time_t my_time = time(NULL); char * current_date = ctime(&my_time); num_written = write(fd, current_date, 24); if((close(fd)) == -1){ fprintf(stderr, "close error, exiting\n"); exit(EXIT_FAILURE); } printf("SAVE SUCCESSFULL! GAME OVER! Please play again!\n"); return(EXIT_SUCCESS); } else if(searching_for_user == 1){ //user found, alter record off_set = lseek(fd, 1, SEEK_CUR); //write best num_written = write(fd, best_pointer, 8); //write worst num_written = write(fd, worst_pointer, 8);; //write average num_written = write(fd, average_pointer, 8); //write date time_t my_time = time(NULL); char * current_date = ctime(&my_time); num_written = write(fd, current_date, 24); printf("SAVE SUCCESSFULL! GAME OVER! Please play again!\n"); if((close(fd)) == -1){ fprintf(stderr, "close error, exiting\n"); exit(EXIT_FAILURE); } return(EXIT_SUCCESS); } return(EXIT_FAILURE); } else if(save_option[0] == 'N'){ //do not save data, effectively end the game printf("GAME OVER! Please play again!\n"); return(EXIT_SUCCESS); } else{ fprintf(stderr, "save_option selection error: %s \n", save_option); exit(EXIT_FAILURE); } return(EXIT_FAILURE); }
the_stack_data/1180318.c
/* ZedBoard / Zynq-7000 UART info could be found in B.33 UART Controller (UART) / Page 1626 in Zynq-7000 All Programmable SoC Technical Reference Manual http://www.xilinx.com/support/documentation/user_guides/ug585-Zynq-7000-TRM.pdf */ #include <stdio.h> #define UART1_BASE 0xe0001000 #define UART1_TxRxFIFO0 ((unsigned int *) (UART1_BASE + 0x30)) volatile unsigned int * const TxRxUART1 = UART1_TxRxFIFO0; /* <stdio.h>'s printf uses puts to send chars puts so that printf sends char to the serial port*/ int puts(const char *s) { while(*s != '\0') { /* Loop until end of string */ *TxRxUART1 = (unsigned int)(*s); /* Transmit char */ s++; /* Next char */ } return 0; } void c_entry() { printf("\nHello world!\n"); while(1) ; /*dont exit the program*/ }
the_stack_data/398655.c
int main() { int a[3] = { 12, 11, 9 }; int *p; p = &a[2]; return *p; }
the_stack_data/31778.c
#include<stdio.h> int done(int burst_time[],int len); int main(){ printf("-------------------------------------------------------"); printf("\n****Round Robin Scheduling****\n\n"); int proc; printf("Enter no of processes: "); scanf("%d",&proc); printf("\n"); int id[proc]; int burst_time[proc]; int burst_time_copy[proc]; for(int i=0;i<proc;i++){ printf("Enter the ID of the process: "); scanf("%d",&id[i]); printf("Enter the burst time: "); scanf("%d",&burst_time[i]); burst_time_copy[i]=burst_time[i]; printf("\n"); } int quant; printf("Enter time quantum: "); scanf("%d",&quant); printf("\n\n"); int wait[proc]; int turn[proc]; int last[proc]; for(int i=0;i<proc;i++){ wait[i]=0; turn[i]=0; last[i]=0; } float avg_wait=0; float avg_tat=0; int i=0; int time=0; while(done(burst_time,proc)!=1){ if(burst_time[i]!=0){ if(burst_time[i]>quant){ burst_time[i]=burst_time[i]-quant; wait[i]=wait[i]+time-last[i]; time=time+quant; last[i]=time; } else{ wait[i]=wait[i]+time-last[i]; time=time+burst_time[i]; burst_time[i]=0; turn[i]=time; } } i=(i+1)%proc; } printf("Process ID Burst Time Waiting Time Turnaround Time\n"); for(int i=0;i<proc;i++){ printf("%d\t\t%d\t\t%d\t\t%d\n",id[i],burst_time_copy[i],wait[i],turn[i]); avg_wait = avg_wait + wait[i]; avg_tat = avg_tat + turn[i]; } printf("\n\nThe average waiting time is: %f\n",avg_wait/proc); printf("The average turn around time is: %f\n",avg_tat/proc); } int done(int burst_time[],int len){ for(int x=0;x<len;x++){ if(burst_time[x]!=0) return 0; } return 1; }
the_stack_data/82949006.c
/*P4.9 Program to understand the sizeof operator*/ #include<stdio.h> int main(void) { int var; printf("Size of int=%u\n",sizeof(int)); printf("Size of float=%u\n",sizeof(float)); printf("Size of var=%u\n",sizeof(var)); printf("Size of an integer constant=%u\n",sizeof(45)); return 0; }
the_stack_data/187643951.c
int singleNumber(int* nums, int numsSize) { int count[32]={0}; int i=0; int j=0; int ret; for(i=0; i<numsSize; i++){ for(j=0; j<32; j++){ count[j] += (nums[i] & (1<<j)) ? 1:0; } } for(i=0; i<32; i++){ count[i] = count[i]%3; ret += ((count[i]) << i); } return ret; }
the_stack_data/126703893.c
/* ** EPITECH PROJECT, 2017 ** my_revstr.c ** File description: ** task03 Day06 */ char *my_revstr(char *str) { int i = 0; int count = 0; char save; while (str[i] != '\0') i++; while (count != i / 2) { save = str[count]; str[count] = str[i - count - 1]; str[i - count - 1] = save; count++; } return (str); }
the_stack_data/100140385.c
#include <ncurses.h> int main() { int ch; initscr(); addstr("Type a few lines of text\n"); addstr("Press ~ to quit\n"); refresh(); while( (ch = getch()) != '~') ; endwin(); return(0); }
the_stack_data/561521.c
int maxSumTwoNoOverlap(int* a, int s, int l, int m){ int pr[1001]; pr[0] = 0; for (int i = 1; i <= s; i++){ pr[i] = pr[i-1]+a[i-1]; } int ans = 0; for(int i = l; i<= s; i++){ int sb = pr[i]-pr[i-l]; for(int j = i+m; j<=s; j++){ int ss = pr[j]-pr[j-m]; ans = (ans<ss+sb)?ss+sb:ans; } for(int j = i-l;j-m>=0;j--){ int ss = pr[j]-pr[j-m]; ans = (ans<ss+sb)?ss+sb:ans; } } return ans; }
the_stack_data/190768451.c
#include <stdio.h> void scilab_rt_contour_d2i2i2d0d0d0s0i2d2i0_(int in00, int in01, double matrixin0[in00][in01], int in10, int in11, int matrixin1[in10][in11], int in20, int in21, int matrixin2[in20][in21], double scalarin0, double scalarin1, double scalarin2, char* scalarin3, int in30, int in31, int matrixin3[in30][in31], int in40, int in41, double matrixin4[in40][in41], int scalarin4) { int i; int j; double val0 = 0; int val1 = 0; int val2 = 0; int val3 = 0; double val4 = 0; for (i = 0; i < in00; ++i) { for (j = 0; j < in01; ++j) { val0 += matrixin0[i][j]; } } printf("%f", val0); for (i = 0; i < in10; ++i) { for (j = 0; j < in11; ++j) { val1 += matrixin1[i][j]; } } printf("%d", val1); for (i = 0; i < in20; ++i) { for (j = 0; j < in21; ++j) { val2 += matrixin2[i][j]; } } printf("%d", val2); printf("%f", scalarin0); printf("%f", scalarin1); printf("%f", scalarin2); printf("%s", scalarin3); for (i = 0; i < in30; ++i) { for (j = 0; j < in31; ++j) { val3 += matrixin3[i][j]; } } printf("%d", val3); for (i = 0; i < in40; ++i) { for (j = 0; j < in41; ++j) { val4 += matrixin4[i][j]; } } printf("%f", val4); printf("%d", scalarin4); }
the_stack_data/126385.c
#include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define MIN_ELEMENT 1 #define MAX_ELEMENT 1000000 #define INT_MIN (-2147483647 - 1) #define INT_MAX 2147483647 /** * @author Oleg Cherednik * @since 23.07.2018 */ int sum(int count, ...) { va_list elements; int sum = 0; va_start(elements, count); for (int i = 0; i < count; i++) sum += va_arg(elements, int); va_end(elements); return sum; } int min(int count, ...) { va_list elements; int min = INT_MAX; int tmp; va_start(elements, count); for (int i = 0; i < count; i++) { tmp = va_arg(elements, int); if (tmp < min) min = tmp; } va_end(elements); return min; } int max(int count, ...) { va_list elements; int max = INT_MIN; int tmp; va_start(elements, count); for (int i = 0; i < count; i++) { tmp = va_arg(elements, int); if (tmp > max) max = tmp; } va_end(elements); return max; } int test_implementations_by_sending_three_elements() { srand(time(NULL)); int elements[3]; elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; fprintf(stderr, "Sending following three elements:\n"); for (int i = 0; i < 3; i++) fprintf(stderr, "%d\n", elements[i]); int elements_sum = sum(3, elements[0], elements[1], elements[2]); int minimum_element = min(3, elements[0], elements[1], elements[2]); int maximum_element = max(3, elements[0], elements[1], elements[2]); fprintf(stderr, "Your output is:\n"); fprintf(stderr, "Elements sum is %d\n", elements_sum); fprintf(stderr, "Minimum element is %d\n", minimum_element); fprintf(stderr, "Maximum element is %d\n\n", maximum_element); int expected_elements_sum = 0; for (int i = 0; i < 3; i++) { if (elements[i] < minimum_element) return 0; if (elements[i] > maximum_element) return 0; expected_elements_sum += elements[i]; } return elements_sum == expected_elements_sum; } int test_implementations_by_sending_five_elements() { srand(time(NULL)); int elements[5]; elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; fprintf(stderr, "Sending following five elements:\n"); for (int i = 0; i < 5; i++) fprintf(stderr, "%d\n", elements[i]); int elements_sum = sum(5, elements[0], elements[1], elements[2], elements[3], elements[4]); int minimum_element = min(5, elements[0], elements[1], elements[2], elements[3], elements[4]); int maximum_element = max(5, elements[0], elements[1], elements[2], elements[3], elements[4]); fprintf(stderr, "Your output is:\n"); fprintf(stderr, "Elements sum is %d\n", elements_sum); fprintf(stderr, "Minimum element is %d\n", minimum_element); fprintf(stderr, "Maximum element is %d\n\n", maximum_element); int expected_elements_sum = 0; for (int i = 0; i < 5; i++) { if (elements[i] < minimum_element) return 0; if (elements[i] > maximum_element) return 0; expected_elements_sum += elements[i]; } return elements_sum == expected_elements_sum; } int test_implementations_by_sending_ten_elements() { srand(time(NULL)); int elements[10]; elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[5] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[6] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[7] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[8] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; elements[9] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT; fprintf(stderr, "Sending following ten elements:\n"); for (int i = 0; i < 10; i++) fprintf(stderr, "%d\n", elements[i]); int elements_sum = sum(10, elements[0], elements[1], elements[2], elements[3], elements[4], elements[5], elements[6], elements[7], elements[8], elements[9]); int minimum_element = min(10, elements[0], elements[1], elements[2], elements[3], elements[4], elements[5], elements[6], elements[7], elements[8], elements[9]); int maximum_element = max(10, elements[0], elements[1], elements[2], elements[3], elements[4], elements[5], elements[6], elements[7], elements[8], elements[9]); fprintf(stderr, "Your output is:\n"); fprintf(stderr, "Elements sum is %d\n", elements_sum); fprintf(stderr, "Minimum element is %d\n", minimum_element); fprintf(stderr, "Maximum element is %d\n\n", maximum_element); int expected_elements_sum = 0; for (int i = 0; i < 10; i++) { if (elements[i] < minimum_element) return 0; if (elements[i] > maximum_element) return 0; expected_elements_sum += elements[i]; } return elements_sum == expected_elements_sum; } int main() { int number_of_test_cases; scanf("%d", &number_of_test_cases); while (number_of_test_cases--) { if (test_implementations_by_sending_three_elements()) printf("Correct Answer\n"); else printf("Wrong Answer\n"); if (test_implementations_by_sending_five_elements()) printf("Correct Answer\n"); else printf("Wrong Answer\n"); if (test_implementations_by_sending_ten_elements()) printf("Correct Answer\n"); else printf("Wrong Answer\n"); } return 0; }
the_stack_data/148578752.c
/** ****************************************************************************** * @file stm32f1xx_ll_spi.c * @author MCD Application Team * @brief SPI LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_ll_spi.h" #include "stm32f1xx_ll_bus.h" #include "stm32f1xx_ll_rcc.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F1xx_LL_Driver * @{ */ #if defined (SPI1) || defined (SPI2) || defined (SPI3) /** @addtogroup SPI_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup SPI_LL_Private_Constants SPI Private Constants * @{ */ /* SPI registers Masks */ #define SPI_CR1_CLEAR_MASK (SPI_CR1_CPHA | SPI_CR1_CPOL | SPI_CR1_MSTR | \ SPI_CR1_BR | SPI_CR1_LSBFIRST | SPI_CR1_SSI | \ SPI_CR1_SSM | SPI_CR1_RXONLY | SPI_CR1_DFF | \ SPI_CR1_CRCNEXT | SPI_CR1_CRCEN | SPI_CR1_BIDIOE | \ SPI_CR1_BIDIMODE) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup SPI_LL_Private_Macros SPI Private Macros * @{ */ #define IS_LL_SPI_TRANSFER_DIRECTION(__VALUE__) (((__VALUE__) == LL_SPI_FULL_DUPLEX) \ || ((__VALUE__) == LL_SPI_SIMPLEX_RX) \ || ((__VALUE__) == LL_SPI_HALF_DUPLEX_RX) \ || ((__VALUE__) == LL_SPI_HALF_DUPLEX_TX)) #define IS_LL_SPI_MODE(__VALUE__) (((__VALUE__) == LL_SPI_MODE_MASTER) \ || ((__VALUE__) == LL_SPI_MODE_SLAVE)) #define IS_LL_SPI_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_SPI_DATAWIDTH_8BIT) \ || ((__VALUE__) == LL_SPI_DATAWIDTH_16BIT)) #define IS_LL_SPI_POLARITY(__VALUE__) (((__VALUE__) == LL_SPI_POLARITY_LOW) \ || ((__VALUE__) == LL_SPI_POLARITY_HIGH)) #define IS_LL_SPI_PHASE(__VALUE__) (((__VALUE__) == LL_SPI_PHASE_1EDGE) \ || ((__VALUE__) == LL_SPI_PHASE_2EDGE)) #define IS_LL_SPI_NSS(__VALUE__) (((__VALUE__) == LL_SPI_NSS_SOFT) \ || ((__VALUE__) == LL_SPI_NSS_HARD_INPUT) \ || ((__VALUE__) == LL_SPI_NSS_HARD_OUTPUT)) #define IS_LL_SPI_BAUDRATE(__VALUE__) (((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV2) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV4) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV8) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV16) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV32) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV64) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV128) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV256)) #define IS_LL_SPI_BITORDER(__VALUE__) (((__VALUE__) == LL_SPI_LSB_FIRST) \ || ((__VALUE__) == LL_SPI_MSB_FIRST)) #define IS_LL_SPI_CRCCALCULATION(__VALUE__) (((__VALUE__) == LL_SPI_CRCCALCULATION_ENABLE) \ || ((__VALUE__) == LL_SPI_CRCCALCULATION_DISABLE)) #define IS_LL_SPI_CRC_POLYNOMIAL(__VALUE__) ((__VALUE__) >= 0x1U) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SPI_LL_Exported_Functions * @{ */ /** @addtogroup SPI_LL_EF_Init * @{ */ /** * @brief De-initialize the SPI registers to their default reset values. * @param SPIx SPI Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_SPI_ALL_INSTANCE(SPIx)); #if defined(SPI1) if (SPIx == SPI1) { /* Force reset of SPI clock */ LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI1); /* Release reset of SPI clock */ LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI1); status = SUCCESS; } #endif /* SPI1 */ #if defined(SPI2) if (SPIx == SPI2) { /* Force reset of SPI clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2); /* Release reset of SPI clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2); status = SUCCESS; } #endif /* SPI2 */ #if defined(SPI3) if (SPIx == SPI3) { /* Force reset of SPI clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI3); /* Release reset of SPI clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI3); status = SUCCESS; } #endif /* SPI3 */ return status; } /** * @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct. * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0), * SPI peripheral should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. * @param SPIx SPI Instance * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure * @retval An ErrorStatus enumeration value. (Return always SUCCESS) */ ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct) { ErrorStatus status = ERROR; /* Check the SPI Instance SPIx*/ assert_param(IS_SPI_ALL_INSTANCE(SPIx)); /* Check the SPI parameters from SPI_InitStruct*/ assert_param(IS_LL_SPI_TRANSFER_DIRECTION(SPI_InitStruct->TransferDirection)); assert_param(IS_LL_SPI_MODE(SPI_InitStruct->Mode)); assert_param(IS_LL_SPI_DATAWIDTH(SPI_InitStruct->DataWidth)); assert_param(IS_LL_SPI_POLARITY(SPI_InitStruct->ClockPolarity)); assert_param(IS_LL_SPI_PHASE(SPI_InitStruct->ClockPhase)); assert_param(IS_LL_SPI_NSS(SPI_InitStruct->NSS)); assert_param(IS_LL_SPI_BAUDRATE(SPI_InitStruct->BaudRate)); assert_param(IS_LL_SPI_BITORDER(SPI_InitStruct->BitOrder)); assert_param(IS_LL_SPI_CRCCALCULATION(SPI_InitStruct->CRCCalculation)); if (LL_SPI_IsEnabled(SPIx) == 0x00000000U) { /*---------------------------- SPIx CR1 Configuration ------------------------ * Configure SPIx CR1 with parameters: * - TransferDirection: SPI_CR1_BIDIMODE, SPI_CR1_BIDIOE and SPI_CR1_RXONLY bits * - Master/Slave Mode: SPI_CR1_MSTR bit * - DataWidth: SPI_CR1_DFF bit * - ClockPolarity: SPI_CR1_CPOL bit * - ClockPhase: SPI_CR1_CPHA bit * - NSS management: SPI_CR1_SSM bit * - BaudRate prescaler: SPI_CR1_BR[2:0] bits * - BitOrder: SPI_CR1_LSBFIRST bit * - CRCCalculation: SPI_CR1_CRCEN bit */ MODIFY_REG(SPIx->CR1, SPI_CR1_CLEAR_MASK, SPI_InitStruct->TransferDirection | SPI_InitStruct->Mode | SPI_InitStruct->DataWidth | SPI_InitStruct->ClockPolarity | SPI_InitStruct->ClockPhase | SPI_InitStruct->NSS | SPI_InitStruct->BaudRate | SPI_InitStruct->BitOrder | SPI_InitStruct->CRCCalculation); /*---------------------------- SPIx CR2 Configuration ------------------------ * Configure SPIx CR2 with parameters: * - NSS management: SSOE bit */ MODIFY_REG(SPIx->CR2, SPI_CR2_SSOE, (SPI_InitStruct->NSS >> 16U)); /*---------------------------- SPIx CRCPR Configuration ---------------------- * Configure SPIx CRCPR with parameters: * - CRCPoly: CRCPOLY[15:0] bits */ if (SPI_InitStruct->CRCCalculation == LL_SPI_CRCCALCULATION_ENABLE) { assert_param(IS_LL_SPI_CRC_POLYNOMIAL(SPI_InitStruct->CRCPoly)); LL_SPI_SetCRCPolynomial(SPIx, SPI_InitStruct->CRCPoly); } status = SUCCESS; } #if defined (SPI_I2S_SUPPORT) /* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */ CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD); #endif /* SPI_I2S_SUPPORT */ return status; } /** * @brief Set each @ref LL_SPI_InitTypeDef field to default value. * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct) { /* Set SPI_InitStruct fields to default values */ SPI_InitStruct->TransferDirection = LL_SPI_FULL_DUPLEX; SPI_InitStruct->Mode = LL_SPI_MODE_SLAVE; SPI_InitStruct->DataWidth = LL_SPI_DATAWIDTH_8BIT; SPI_InitStruct->ClockPolarity = LL_SPI_POLARITY_LOW; SPI_InitStruct->ClockPhase = LL_SPI_PHASE_1EDGE; SPI_InitStruct->NSS = LL_SPI_NSS_HARD_INPUT; SPI_InitStruct->BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV2; SPI_InitStruct->BitOrder = LL_SPI_MSB_FIRST; SPI_InitStruct->CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE; SPI_InitStruct->CRCPoly = 7U; } /** * @} */ /** * @} */ /** * @} */ #if defined(SPI_I2S_SUPPORT) /** @addtogroup I2S_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2S_LL_Private_Constants I2S Private Constants * @{ */ /* I2S registers Masks */ #define I2S_I2SCFGR_CLEAR_MASK (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | \ SPI_I2SCFGR_CKPOL | SPI_I2SCFGR_I2SSTD | \ SPI_I2SCFGR_I2SCFG | SPI_I2SCFGR_I2SMOD ) #define I2S_I2SPR_CLEAR_MASK 0x0002U /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2S_LL_Private_Macros I2S Private Macros * @{ */ #define IS_LL_I2S_DATAFORMAT(__VALUE__) (((__VALUE__) == LL_I2S_DATAFORMAT_16B) \ || ((__VALUE__) == LL_I2S_DATAFORMAT_16B_EXTENDED) \ || ((__VALUE__) == LL_I2S_DATAFORMAT_24B) \ || ((__VALUE__) == LL_I2S_DATAFORMAT_32B)) #define IS_LL_I2S_CPOL(__VALUE__) (((__VALUE__) == LL_I2S_POLARITY_LOW) \ || ((__VALUE__) == LL_I2S_POLARITY_HIGH)) #define IS_LL_I2S_STANDARD(__VALUE__) (((__VALUE__) == LL_I2S_STANDARD_PHILIPS) \ || ((__VALUE__) == LL_I2S_STANDARD_MSB) \ || ((__VALUE__) == LL_I2S_STANDARD_LSB) \ || ((__VALUE__) == LL_I2S_STANDARD_PCM_SHORT) \ || ((__VALUE__) == LL_I2S_STANDARD_PCM_LONG)) #define IS_LL_I2S_MODE(__VALUE__) (((__VALUE__) == LL_I2S_MODE_SLAVE_TX) \ || ((__VALUE__) == LL_I2S_MODE_SLAVE_RX) \ || ((__VALUE__) == LL_I2S_MODE_MASTER_TX) \ || ((__VALUE__) == LL_I2S_MODE_MASTER_RX)) #define IS_LL_I2S_MCLK_OUTPUT(__VALUE__) (((__VALUE__) == LL_I2S_MCLK_OUTPUT_ENABLE) \ || ((__VALUE__) == LL_I2S_MCLK_OUTPUT_DISABLE)) #define IS_LL_I2S_AUDIO_FREQ(__VALUE__) ((((__VALUE__) >= LL_I2S_AUDIOFREQ_8K) \ && ((__VALUE__) <= LL_I2S_AUDIOFREQ_192K)) \ || ((__VALUE__) == LL_I2S_AUDIOFREQ_DEFAULT)) #define IS_LL_I2S_PRESCALER_LINEAR(__VALUE__) ((__VALUE__) >= 0x2U) #define IS_LL_I2S_PRESCALER_PARITY(__VALUE__) (((__VALUE__) == LL_I2S_PRESCALER_PARITY_EVEN) \ || ((__VALUE__) == LL_I2S_PRESCALER_PARITY_ODD)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2S_LL_Exported_Functions * @{ */ /** @addtogroup I2S_LL_EF_Init * @{ */ /** * @brief De-initialize the SPI/I2S registers to their default reset values. * @param SPIx SPI Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx) { return LL_SPI_DeInit(SPIx); } /** * @brief Initializes the SPI/I2S registers according to the specified parameters in I2S_InitStruct. * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0), * SPI peripheral should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. * @param SPIx SPI Instance * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure * @retval An ErrorStatus enumeration value: * - SUCCESS: SPI registers are Initialized * - ERROR: SPI registers are not Initialized */ ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct) { uint32_t i2sdiv = 2U; uint32_t i2sodd = 0U; uint32_t packetlength = 1U; uint32_t tmp; LL_RCC_ClocksTypeDef rcc_clocks; uint32_t sourceclock; ErrorStatus status = ERROR; /* Check the I2S parameters */ assert_param(IS_I2S_ALL_INSTANCE(SPIx)); assert_param(IS_LL_I2S_MODE(I2S_InitStruct->Mode)); assert_param(IS_LL_I2S_STANDARD(I2S_InitStruct->Standard)); assert_param(IS_LL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat)); assert_param(IS_LL_I2S_MCLK_OUTPUT(I2S_InitStruct->MCLKOutput)); assert_param(IS_LL_I2S_AUDIO_FREQ(I2S_InitStruct->AudioFreq)); assert_param(IS_LL_I2S_CPOL(I2S_InitStruct->ClockPolarity)); if (LL_I2S_IsEnabled(SPIx) == 0x00000000U) { /*---------------------------- SPIx I2SCFGR Configuration -------------------- * Configure SPIx I2SCFGR with parameters: * - Mode: SPI_I2SCFGR_I2SCFG[1:0] bit * - Standard: SPI_I2SCFGR_I2SSTD[1:0] and SPI_I2SCFGR_PCMSYNC bits * - DataFormat: SPI_I2SCFGR_CHLEN and SPI_I2SCFGR_DATLEN bits * - ClockPolarity: SPI_I2SCFGR_CKPOL bit */ /* Write to SPIx I2SCFGR */ MODIFY_REG(SPIx->I2SCFGR, I2S_I2SCFGR_CLEAR_MASK, I2S_InitStruct->Mode | I2S_InitStruct->Standard | I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity | SPI_I2SCFGR_I2SMOD); /*---------------------------- SPIx I2SPR Configuration ---------------------- * Configure SPIx I2SPR with parameters: * - MCLKOutput: SPI_I2SPR_MCKOE bit * - AudioFreq: SPI_I2SPR_I2SDIV[7:0] and SPI_I2SPR_ODD bits */ /* If the requested audio frequency is not the default, compute the prescaler (i2sodd, i2sdiv) * else, default values are used: i2sodd = 0U, i2sdiv = 2U. */ if (I2S_InitStruct->AudioFreq != LL_I2S_AUDIOFREQ_DEFAULT) { /* Check the frame length (For the Prescaler computing) * Default value: LL_I2S_DATAFORMAT_16B (packetlength = 1U). */ if (I2S_InitStruct->DataFormat != LL_I2S_DATAFORMAT_16B) { /* Packet length is 32 bits */ packetlength = 2U; } /* I2S Clock source is System clock: Get System Clock frequency */ LL_RCC_GetSystemClocksFreq(&rcc_clocks); /* Get the source clock value: based on System Clock value */ sourceclock = rcc_clocks.SYSCLK_Frequency; /* Compute the Real divider depending on the MCLK output state with a floating point */ if (I2S_InitStruct->MCLKOutput == LL_I2S_MCLK_OUTPUT_ENABLE) { /* MCLK output is enabled */ tmp = (((((sourceclock / 256U) * 10U) / I2S_InitStruct->AudioFreq)) + 5U); } else { /* MCLK output is disabled */ tmp = (((((sourceclock / (32U * packetlength)) * 10U) / I2S_InitStruct->AudioFreq)) + 5U); } /* Remove the floating point */ tmp = tmp / 10U; /* Check the parity of the divider */ i2sodd = (tmp & (uint16_t)0x0001U); /* Compute the i2sdiv prescaler */ i2sdiv = ((tmp - i2sodd) / 2U); /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */ i2sodd = (i2sodd << 8U); } /* Test if the divider is 1 or 0 or greater than 0xFF */ if ((i2sdiv < 2U) || (i2sdiv > 0xFFU)) { /* Set the default values */ i2sdiv = 2U; i2sodd = 0U; } /* Write to SPIx I2SPR register the computed value */ WRITE_REG(SPIx->I2SPR, i2sdiv | i2sodd | I2S_InitStruct->MCLKOutput); status = SUCCESS; } return status; } /** * @brief Set each @ref LL_I2S_InitTypeDef field to default value. * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct) { /*--------------- Reset I2S init structure parameters values -----------------*/ I2S_InitStruct->Mode = LL_I2S_MODE_SLAVE_TX; I2S_InitStruct->Standard = LL_I2S_STANDARD_PHILIPS; I2S_InitStruct->DataFormat = LL_I2S_DATAFORMAT_16B; I2S_InitStruct->MCLKOutput = LL_I2S_MCLK_OUTPUT_DISABLE; I2S_InitStruct->AudioFreq = LL_I2S_AUDIOFREQ_DEFAULT; I2S_InitStruct->ClockPolarity = LL_I2S_POLARITY_LOW; } /** * @brief Set linear and parity prescaler. * @note To calculate value of PrescalerLinear(I2SDIV[7:0] bits) and PrescalerParity(ODD bit)\n * Check Audio frequency table and formulas inside Reference Manual (SPI/I2S). * @param SPIx SPI Instance * @param PrescalerLinear value Min_Data=0x02 and Max_Data=0xFF. * @param PrescalerParity This parameter can be one of the following values: * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN * @arg @ref LL_I2S_PRESCALER_PARITY_ODD * @retval None */ void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity) { /* Check the I2S parameters */ assert_param(IS_I2S_ALL_INSTANCE(SPIx)); assert_param(IS_LL_I2S_PRESCALER_LINEAR(PrescalerLinear)); assert_param(IS_LL_I2S_PRESCALER_PARITY(PrescalerParity)); /* Write to SPIx I2SPR */ MODIFY_REG(SPIx->I2SPR, SPI_I2SPR_I2SDIV | SPI_I2SPR_ODD, PrescalerLinear | (PrescalerParity << 8U)); } /** * @} */ /** * @} */ /** * @} */ #endif /* SPI_I2S_SUPPORT */ #endif /* defined (SPI1) || defined (SPI2) || defined (SPI3) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/211080920.c
#include <stdio.h> // TODO: Add test cases for task // For example 167 is correct for program functions hard-code values unsigned setbits(unsigned x, int p, int n, unsigned y) { // printf("0%o 0%o 0%o\n", (~(~0 << n) & y), (~0<<(n+p-1)) & x , (~(~0 << (p-1)) & x)); return (~(~0 << n) & y) | (~0<<(n+p-1)) & x | (~(~0 << (p-1)) & x); } int main(void) { int i = 31; printf("%d", setbits(172,2,3,255)); return 0; }
the_stack_data/145453120.c
#include <stdio.h> int main() { printf("\t\tenter your details\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); float per; char clg[100], grade; printf("enter your collage name\n"); gets(clg); char name[100]; printf("enter your name\n"); gets(name); int class; printf("enter your class\n"); scanf("%d", &class); getchar(); char section; printf("enter your section\n"); scanf("%c", &section); getchar(); int m1, m2, m3, m4, m5, total; printf("enter your marks out of 100\n\n"); printf("enter your math marks\n"); scanf("%d", &m1); getchar(); printf("enter your english marks\n"); scanf("%d", &m2); getchar(); printf("enter your hindi marks\n"); scanf("%d", &m3); getchar(); printf("enter your science marks\n"); scanf("%d", &m4); getchar(); printf("enter your social science marks\n"); scanf("%d", &m5); getchar(); total = m1 + m2 + m3 + m4 + m5; if (total <= 500 && total >= 450) { grade = 'A'; } else if (total <= 449 && total >= 400) { grade = 'B'; } else if (total <= 399 && total >= 350) { grade = 'C'; } else if (total <= 349 && total >= 300) { grade = 'D'; } else if (total <= 299 && total >= 200) { grade = 'E'; } else if (total < 200 && total >= 0) { grade = 'F'; } else { printf("report card can not be generated\n"); } printf("\n\n--------------------------------------------------------\n\n"); printf("\t\t%s\n", clg); printf("\t\t AnnualReport Card\n\n"); printf("\tName : %s\n", name); printf("\tStandard : %d\n\n", class); printf("\tSection : %c\n\n\n", section); printf("\tMarks Secured Out of 100\n\n"); printf("\tMathematics : %d\n\n", m1); printf("\tEnglish : %d\n\n", m2); printf("\tHindi : %d\n\n", m3); printf("\tScience : %d\n\n", m4); printf("\tSocial Science : %d\n\n\n", m5); //per = (total * 100) / 500; printf("\tTotal marks secured : %d\n\n", total); // printf("percentage : %f\n\n", per); printf("\tGrade : %c\n\n", grade); printf("\n\n--------------------------------------------------------\n\n"); return 0; }
the_stack_data/859448.c
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int i; int n; //number of points float x[n]; //vector of x values float f[n]; //vector of values of f(x) /*This problem is linearized using a logarithmic transformation ln f(x) ~ ln(a*e^bx) = ln a + bx Noting that the fit functions are g1(x) = 1 and g2(x) = x and the parameters are a1 = ln a and a2 = b, we reduce the problem to a case of linear function adjustment on the parameters By calling F(x) = ln f(x), we then have a new problem F(x) ~ G(x) = a1 + a2x*/ //[ <g1,g1> <g1,g2> ] * [a1] = [ <g1,F> ] //[ <g2,g1> <g2,g1> ] [a2] [ <g2,F> ] //we get a1 and a2 and, finally, we return to the initial parameters a = e^a1 and b = a2 //How are we making matrices for solving a system of equations using Cramer's rule //so we have to do A1 and A2 and calculate their determinants. // [ <g1,F> <g1,g2> ] // [ <g2,F> <g2,g2> ] // Matrix A1. // [ <g1,g1> <g1,F> ] // [ <g2,g1> <g2,F> ] // Matrix A2. // [ <g1,g1> <g1,g2> ] // [ <g2,g1> <g2,g2> ] // Matrix A. //soma1-> <g1,g2>; ; soma2-> <g2,g2>; soma3-> <g1,F> soma4-> <g2,F> //<g1,g1> = 1 = n; <g1,g2> = <g2,g1> = xi; <g2,g2> = xi*xi; <g1,F> = ln(xi); <g2,F> = ln(f(xi)*xi //F(x) = ln f(x) //g(x) = a*e^(bx) //g1(x) = 1 //g2(x) = x //a1 = Det(A1)/Det(A) //a2 = Det(A2)/Det(A) float a1, a2; float a, b; float numa1;// -> Det(A1) float numa2;// -> Det(A2) float denom;// -> Det(A) printf("Digite a quantidade de pontos: "); scanf("%d", &n); if(n <= 0){ printf("Naum eh possivel com essa quantidade de pontos"); } else{ printf("Quais sao os %d valores de x?\n ", n); for(i=0; i<n; i++){ printf("x%d = ", i); scanf("%f", &x[i]); } printf("\n"); printf("Quais sa os %d valores de f(x)?\n ", n); for(i=0; i<n; i++){ printf("f(x%d) = ", i); scanf("%f", &f[i]); } printf("\n"); float soma1 = 0, soma2 = 0, soma3 = 0, soma4 = 0, soma5=0; for(i = 0; i<n; i++){ soma1 = soma1 + (x[i]); soma2 = soma2 + (pow(x[i],2)); soma3 = soma3 + (log(f[i])) ;//log() -> natural logarithm(ln) soma4 = soma4 + (x[i]*log(f[i])); } printf("oi\n"); numa1 = ((soma3*soma2) - (soma1*soma4)); numa2 = ((n*soma4) - (soma3*soma1)); denom = ((n*soma2) - (soma1*soma1)); a1 = numa1/denom; a2 = numa2/denom; float e = 2.7183;//Euler number, approximated with 3 significant digits a = pow(e,a1); b = a2; printf("g(x) = %.4f*e^(%.4f*x)", a, b); float tensao; tensao = a*(pow(e,(b*0.05))); printf("\n"); printf("A tensao com Grao de 0.05mm equivale em: %.4f MPa",tensao); } return 0; }
the_stack_data/90762840.c
/* This program converts a 128x128 16-bit color BMP image to a 128x128 8-bit RGB array of pixel values * suitable for use on the WARP User I/O Board's LCD screen. It produces two output formats; for both formats * the pixles are re-arranged into 256 64-pixel blocks to accomodate the User I/O board controller's * character map pixel ordering. * * See http://warp.rice.edu/trac/wiki/HardwareUsersGuides/UserIOBoard_v1.0/LCD for details * * Output formats: * RGB: a binary file with exactly 128*128 1-byte pixel values (16KB); each pixel is stored as [RRRGGGBB] * C Header: a header file with one variable (unsigned char imgArray[16384] defined) * * This program has been tested on Mac OS X 10.5.4. It should work on any Unix-ish OS. * * This code is not thoroughly tested, nor is it guaranteed error-free or even safe. Use it at your own risk. * * This code is available under the Rice WARP license. See http://warp.rice.edu/license for details. */ #include <stdio.h> #define BMP16_NUM_HEADER_BYTES 54 #define PIXCONV_RED_5b_TO_3b(c) ( (c>>12)&0x7 ) #define PIXCONV_GREEN_5b_TO_3b(c) ( (c>>7)&0x7 ) #define PIXCONV_BLUE_5b_TO_2b(c) ( (c>>3)&0x3 ) #define PIXCONV_16b_TO_8b(c) ( 0xFF & ( (PIXCONV_RED_5b_TO_3b(c)<<5) | (PIXCONV_GREEN_5b_TO_3b(c)<<2) | PIXCONV_BLUE_5b_TO_2b(c) )) void print_usage(char* progName); int main(int argc, char * argv[]) { int i, j, k, m, n; FILE *fp_in, *fp_outBin, *fp_outHeader; size_t bytesRead, bytesWritten; unsigned char outputHeader; unsigned char img_header[BMP16_NUM_HEADER_BYTES]; unsigned short img_orig[128*128]; unsigned char img_rgb8[128*128]; //Check the command line arguments if(argc < 3 | argc > 4) { printf("Bad input arguments!\n"); print_usage(argv[0]); return -1; } if(argc == 3) { //User specified an input file and output RGB file; don't print the C header file fp_in = fopen(argv[1], "r+b"); fp_outBin = fopen(argv[2], "w+b"); outputHeader = 0; } if(argc == 4) { //User specified an input file, output RGB file and output C header file fp_in = fopen(argv[1], "r+b"); fp_outBin = fopen(argv[2], "w+b"); fp_outHeader = fopen(argv[3], "w+"); outputHeader = 1; } bytesRead = fread(&img_header, 1, BMP16_NUM_HEADER_BYTES, fp_in); if(bytesRead != BMP16_NUM_HEADER_BYTES) { printf("Error! - not enough bytes for the header\n"); return -1; } bytesRead = fread(&img_orig, sizeof(short), 128*128, fp_in); if(bytesRead != (128*128)) { printf("Error! - not enough bytes of image data (read %d)\n", bytesRead); return -1; } fclose(fp_in); //Now img_orig is a 128x128 array of 16-bit pixel values //We need an array of 16x16 64-pixel blocks, with each pixel occuping 1 byte //This is probably a really inefficient way to implement this re-ordering // but for 16K entries on a fast PC, who cares? m = 0; for(i=15; i>=0; i--)//Count down, since BMP files are stored last-line-first { for(j=0; j<16; j++) { for(k=7; k>=0; k--)//Count down, since BMP files are stored last-line-first { for(n=0; n<8; n++) { img_rgb8[m++] = (unsigned char)PIXCONV_16b_TO_8b(img_orig[i*1024 + j*8 + k*128 + n]); } } } } if(outputHeader) { fprintf(fp_outHeader, "/***START imgArray ***/\nunsigned char imgArray[16384] = {"); for(i=0; i<16384; i++) { fprintf(fp_outHeader, "0x%x", img_rgb8[i]); if(i < 16383) fprintf(fp_outHeader, ","); if(i!=0 & i%128==0) fprintf(fp_outHeader, "\n"); } fprintf(fp_outHeader, "};\n/***END imgArray ***/\n"); fclose(fp_outHeader); } bytesWritten = fwrite(&img_rgb8, 1, 128*128, fp_outBin); fclose(fp_outBin); if(bytesWritten != (128*128)) { printf("Error! - not enough bytes of image data written (wrote %d)\n", bytesWritten); return -1; } //Return successfully return 0; } void print_usage(char* progName) { printf("Usage: %s inputBitmap.bmp outputBinary.rgb <outputHeader.h>\n", progName); }
the_stack_data/44125.c
// Write a C program to get last two digits of year #include <stdio.h> void main() { int year, d; char ch = 'y'; do { printf("Enter the year "); scanf("%d", &year); d = year % 100; printf("Last two digits of year is: %d \n", d); printf("Do you want to continue?(y/n):"); scanf(" %c", &ch); } while ((ch == 'Y') || (ch == 'y')); }
the_stack_data/63663.c
/* * ARM signal handling routines * * Copyright 2002 Marcus Meissner, SuSE Linux AG * Copyright 2010-2013, 2015 André Hentschel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #if 0 #pragma makedep unix #endif #ifdef __arm__ #include "config.h" #include <assert.h> #include <pthread.h> #include <signal.h> #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #ifdef HAVE_SYS_PARAM_H # include <sys/param.h> #endif #ifdef HAVE_SYSCALL_H # include <syscall.h> #else # ifdef HAVE_SYS_SYSCALL_H # include <sys/syscall.h> # endif #endif #ifdef HAVE_SYS_SIGNAL_H # include <sys/signal.h> #endif #ifdef HAVE_SYS_UCONTEXT_H # include <sys/ucontext.h> #endif #ifdef HAVE_LIBUNWIND # define UNW_LOCAL_ONLY # include <libunwind.h> #endif #define NONAMELESSUNION #define NONAMELESSSTRUCT #include "ntstatus.h" #define WIN32_NO_STATUS #include "windef.h" #include "winnt.h" #include "winternl.h" #include "wine/asm.h" #include "unix_private.h" #include "wine/debug.h" WINE_DEFAULT_DEBUG_CHANNEL(seh); /*********************************************************************** * signal context platform-specific definitions */ #ifdef linux #if defined(__ANDROID__) && !defined(HAVE_SYS_UCONTEXT_H) typedef struct ucontext { unsigned long uc_flags; struct ucontext *uc_link; stack_t uc_stack; struct sigcontext uc_mcontext; sigset_t uc_sigmask; unsigned long uc_regspace[128] __attribute__((__aligned__(8))); } ucontext_t; #endif /* All Registers access - only for local access */ # define REG_sig(reg_name, context) ((context)->uc_mcontext.reg_name) # define REGn_sig(reg_num, context) ((context)->uc_mcontext.arm_r##reg_num) /* Special Registers access */ # define SP_sig(context) REG_sig(arm_sp, context) /* Stack pointer */ # define LR_sig(context) REG_sig(arm_lr, context) /* Link register */ # define PC_sig(context) REG_sig(arm_pc, context) /* Program counter */ # define CPSR_sig(context) REG_sig(arm_cpsr, context) /* Current State Register */ # define IP_sig(context) REG_sig(arm_ip, context) /* Intra-Procedure-call scratch register */ # define FP_sig(context) REG_sig(arm_fp, context) /* Frame pointer */ /* Exceptions */ # define ERROR_sig(context) REG_sig(error_code, context) # define TRAP_sig(context) REG_sig(trap_no, context) struct extended_ctx { unsigned long magic; unsigned long size; }; struct vfp_sigframe { struct extended_ctx ctx; unsigned long long fpregs[32]; unsigned long fpscr; }; static void *get_extended_sigcontext( const ucontext_t *sigcontext, unsigned int magic ) { struct extended_ctx *ctx = (struct extended_ctx *)sigcontext->uc_regspace; while ((char *)ctx < (char *)(sigcontext + 1) && ctx->magic && ctx->size) { if (ctx->magic == magic) return ctx; ctx = (struct extended_ctx *)((char *)ctx + ctx->size); } return NULL; } static void save_fpu( CONTEXT *context, const ucontext_t *sigcontext ) { struct vfp_sigframe *frame = get_extended_sigcontext( sigcontext, 0x56465001 ); if (!frame) return; memcpy( context->u.D, frame->fpregs, sizeof(context->u.D) ); context->Fpscr = frame->fpscr; } static void restore_fpu( const CONTEXT *context, ucontext_t *sigcontext ) { struct vfp_sigframe *frame = get_extended_sigcontext( sigcontext, 0x56465001 ); if (!frame) return; memcpy( frame->fpregs, context->u.D, sizeof(context->u.D) ); frame->fpscr = context->Fpscr; } #elif defined(__FreeBSD__) /* All Registers access - only for local access */ # define REGn_sig(reg_num, context) ((context)->uc_mcontext.__gregs[reg_num]) /* Special Registers access */ # define SP_sig(context) REGn_sig(_REG_SP, context) /* Stack pointer */ # define LR_sig(context) REGn_sig(_REG_LR, context) /* Link register */ # define PC_sig(context) REGn_sig(_REG_PC, context) /* Program counter */ # define CPSR_sig(context) REGn_sig(_REG_CPSR, context) /* Current State Register */ # define IP_sig(context) REGn_sig(_REG_R12, context) /* Intra-Procedure-call scratch register */ # define FP_sig(context) REGn_sig(_REG_FP, context) /* Frame pointer */ static void save_fpu( CONTEXT *context, const ucontext_t *sigcontext ) { } static void restore_fpu( const CONTEXT *context, ucontext_t *sigcontext ) { } #endif /* linux */ enum arm_trap_code { TRAP_ARM_UNKNOWN = -1, /* Unknown fault (TRAP_sig not defined) */ TRAP_ARM_PRIVINFLT = 6, /* Invalid opcode exception */ TRAP_ARM_PAGEFLT = 14, /* Page fault */ TRAP_ARM_ALIGNFLT = 17, /* Alignment check exception */ }; struct syscall_frame { DWORD r0; /* 000 */ DWORD r1; /* 004 */ DWORD r2; /* 008 */ DWORD r3; /* 00c */ DWORD r4; /* 010 */ DWORD r5; /* 014 */ DWORD r6; /* 018 */ DWORD r7; /* 01c */ DWORD r8; /* 020 */ DWORD r9; /* 024 */ DWORD r10; /* 028 */ DWORD r11; /* 02c */ DWORD r12; /* 030 */ DWORD pc; /* 034 */ DWORD sp; /* 038 */ DWORD lr; /* 03c */ DWORD cpsr; /* 040 */ DWORD restore_flags; /* 044 */ DWORD fpscr; /* 048 */ struct syscall_frame *prev_frame; /* 04c */ SYSTEM_SERVICE_TABLE *syscall_table; /* 050 */ DWORD align[3]; /* 054 */ ULONGLONG d[32]; /* 060 */ }; C_ASSERT( sizeof( struct syscall_frame ) == 0x160); struct arm_thread_data { void *exit_frame; /* 1d4 exit frame pointer */ struct syscall_frame *syscall_frame; /* 1d8 frame pointer on syscall entry */ }; C_ASSERT( sizeof(struct arm_thread_data) <= sizeof(((struct ntdll_thread_data *)0)->cpu_data) ); C_ASSERT( offsetof( TEB, GdiTebBatch ) + offsetof( struct arm_thread_data, exit_frame ) == 0x1d4 ); C_ASSERT( offsetof( TEB, GdiTebBatch ) + offsetof( struct arm_thread_data, syscall_frame ) == 0x1d8 ); static inline struct arm_thread_data *arm_thread_data(void) { return (struct arm_thread_data *)ntdll_get_thread_data()->cpu_data; } static BOOL is_inside_syscall( ucontext_t *sigcontext ) { return ((char *)SP_sig(sigcontext) >= (char *)ntdll_get_thread_data()->kernel_stack && (char *)SP_sig(sigcontext) <= (char *)arm_thread_data()->syscall_frame); } extern void raise_func_trampoline( EXCEPTION_RECORD *rec, CONTEXT *context, void *dispatcher ); /*********************************************************************** * unwind_builtin_dll */ NTSTATUS CDECL unwind_builtin_dll( ULONG type, struct _DISPATCHER_CONTEXT *dispatch, CONTEXT *context ) { #ifdef HAVE_LIBUNWIND DWORD ip = context->Pc - (dispatch->ControlPcIsUnwound ? 2 : 0); unw_context_t unw_context; unw_cursor_t cursor; unw_proc_info_t info; int rc, i; for (i = 0; i <= 12; i++) unw_context.regs[i] = (&context->R0)[i]; unw_context.regs[13] = context->Sp; unw_context.regs[14] = context->Lr; unw_context.regs[15] = context->Pc; rc = unw_init_local( &cursor, &unw_context ); if (rc != UNW_ESUCCESS) { WARN( "setup failed: %d\n", rc ); return STATUS_INVALID_DISPOSITION; } rc = unw_get_proc_info( &cursor, &info ); if (UNW_ENOINFO < 0) rc = -rc; /* LLVM libunwind has negative error codes */ if (rc != UNW_ESUCCESS && rc != -UNW_ENOINFO) { WARN( "failed to get info: %d\n", rc ); return STATUS_INVALID_DISPOSITION; } if (rc == -UNW_ENOINFO || ip < info.start_ip || ip > info.end_ip) { NTSTATUS status = context->Pc != context->Lr ? STATUS_SUCCESS : STATUS_INVALID_DISPOSITION; TRACE( "no info found for %x ip %x-%x, %s\n", ip, info.start_ip, info.end_ip, status == STATUS_SUCCESS ? "assuming leaf function" : "error, stuck" ); dispatch->LanguageHandler = NULL; dispatch->EstablisherFrame = context->Sp; context->Pc = context->Lr; context->ContextFlags |= CONTEXT_UNWOUND_TO_CALL; return status; } TRACE( "ip %#x function %#lx-%#lx personality %#lx lsda %#lx fde %#lx\n", ip, (unsigned long)info.start_ip, (unsigned long)info.end_ip, (unsigned long)info.handler, (unsigned long)info.lsda, (unsigned long)info.unwind_info ); rc = unw_step( &cursor ); if (rc < 0) { WARN( "failed to unwind: %d %d\n", rc, UNW_ENOINFO ); return STATUS_INVALID_DISPOSITION; } dispatch->LanguageHandler = (void *)info.handler; dispatch->HandlerData = (void *)info.lsda; dispatch->EstablisherFrame = context->Sp; for (i = 0; i <= 12; i++) unw_get_reg( &cursor, UNW_ARM_R0 + i, (unw_word_t *)&(&context->R0)[i] ); unw_get_reg( &cursor, UNW_ARM_R13, (unw_word_t *)&context->Sp ); unw_get_reg( &cursor, UNW_ARM_R14, (unw_word_t *)&context->Lr ); unw_get_reg( &cursor, UNW_REG_IP, (unw_word_t *)&context->Pc ); context->ContextFlags |= CONTEXT_UNWOUND_TO_CALL; if ((info.start_ip & ~(unw_word_t)1) == ((unw_word_t)raise_func_trampoline & ~(unw_word_t)1)) { /* raise_func_trampoline stores the original Lr at the bottom of the * stack. The unwinder normally can't restore both Pc and Lr to * individual values, thus do that manually here. * (The function we unwind to might be a leaf function that hasn't * backed up its own original Lr value on the stack.) */ const DWORD *orig_lr = (const DWORD *) dispatch->EstablisherFrame; context->Lr = *orig_lr; } TRACE( "next function pc=%08x%s\n", context->Pc, rc ? "" : " (last frame)" ); TRACE(" r0=%08x r1=%08x r2=%08x r3=%08x\n", context->R0, context->R1, context->R2, context->R3 ); TRACE(" r4=%08x r5=%08x r6=%08x r7=%08x\n", context->R4, context->R5, context->R6, context->R7 ); TRACE(" r8=%08x r9=%08x r10=%08x r11=%08x\n", context->R8, context->R9, context->R10, context->R11 ); TRACE(" r12=%08x sp=%08x lr=%08x pc=%08x\n", context->R12, context->Sp, context->Lr, context->Pc ); return STATUS_SUCCESS; #else ERR("libunwind not available, unable to unwind\n"); return STATUS_INVALID_DISPOSITION; #endif } /*********************************************************************** * get_trap_code * * Get the trap code for a signal. */ static inline enum arm_trap_code get_trap_code( int signal, const ucontext_t *sigcontext ) { #ifdef TRAP_sig enum arm_trap_code trap = TRAP_sig(sigcontext); if (trap) return trap; #endif switch (signal) { case SIGILL: return TRAP_ARM_PRIVINFLT; case SIGSEGV: return TRAP_ARM_PAGEFLT; case SIGBUS: return TRAP_ARM_ALIGNFLT; default: return TRAP_ARM_UNKNOWN; } } /*********************************************************************** * get_error_code * * Get the error code for a signal. */ static inline WORD get_error_code( const ucontext_t *sigcontext ) { #ifdef ERROR_sig return ERROR_sig(sigcontext); #else return 0; #endif } /*********************************************************************** * save_context * * Set the register values from a sigcontext. */ static void save_context( CONTEXT *context, const ucontext_t *sigcontext ) { #define C(x) context->R##x = REGn_sig(x,sigcontext) /* Save normal registers */ C(0); C(1); C(2); C(3); C(4); C(5); C(6); C(7); C(8); C(9); C(10); #undef C context->ContextFlags = CONTEXT_FULL; context->Sp = SP_sig(sigcontext); /* Stack pointer */ context->Lr = LR_sig(sigcontext); /* Link register */ context->Pc = PC_sig(sigcontext); /* Program Counter */ context->Cpsr = CPSR_sig(sigcontext); /* Current State Register */ context->R11 = FP_sig(sigcontext); /* Frame pointer */ context->R12 = IP_sig(sigcontext); /* Intra-Procedure-call scratch register */ if (CPSR_sig(sigcontext) & 0x20) context->Pc |= 1; /* Thumb mode */ save_fpu( context, sigcontext ); } /*********************************************************************** * restore_context * * Build a sigcontext from the register values. */ static void restore_context( const CONTEXT *context, ucontext_t *sigcontext ) { #define C(x) REGn_sig(x,sigcontext) = context->R##x /* Restore normal registers */ C(0); C(1); C(2); C(3); C(4); C(5); C(6); C(7); C(8); C(9); C(10); #undef C SP_sig(sigcontext) = context->Sp; /* Stack pointer */ LR_sig(sigcontext) = context->Lr; /* Link register */ PC_sig(sigcontext) = context->Pc; /* Program Counter */ CPSR_sig(sigcontext) = context->Cpsr; /* Current State Register */ FP_sig(sigcontext) = context->R11; /* Frame pointer */ IP_sig(sigcontext) = context->R12; /* Intra-Procedure-call scratch register */ if (PC_sig(sigcontext) & 1) CPSR_sig(sigcontext) |= 0x20; else CPSR_sig(sigcontext) &= ~0x20; restore_fpu( context, sigcontext ); } /*********************************************************************** * signal_set_full_context */ NTSTATUS signal_set_full_context( CONTEXT *context ) { NTSTATUS status = NtSetContextThread( GetCurrentThread(), context ); if (!status && (context->ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER) arm_thread_data()->syscall_frame->restore_flags |= CONTEXT_INTEGER; return status; } /*********************************************************************** * get_native_context */ void *get_native_context( CONTEXT *context ) { return context; } /*********************************************************************** * get_wow_context */ void *get_wow_context( CONTEXT *context ) { return NULL; } /*********************************************************************** * NtSetContextThread (NTDLL.@) * ZwSetContextThread (NTDLL.@) */ NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context ) { NTSTATUS ret; struct syscall_frame *frame = arm_thread_data()->syscall_frame; DWORD flags = context->ContextFlags & ~CONTEXT_ARM; BOOL self = (handle == GetCurrentThread()); if (!self) { ret = set_thread_context( handle, context, &self, IMAGE_FILE_MACHINE_ARMNT ); if (ret || !self) return ret; } if (flags & CONTEXT_INTEGER) { frame->r0 = context->R0; frame->r1 = context->R1; frame->r2 = context->R2; frame->r3 = context->R3; frame->r4 = context->R4; frame->r5 = context->R5; frame->r6 = context->R6; frame->r7 = context->R7; frame->r8 = context->R8; frame->r9 = context->R9; frame->r10 = context->R10; frame->r11 = context->R11; frame->r12 = context->R12; } if (flags & CONTEXT_CONTROL) { frame->sp = context->Sp; frame->lr = context->Lr; frame->pc = context->Pc & ~1; frame->cpsr = context->Cpsr; if (context->Cpsr & 0x20) frame->pc |= 1; /* thumb */ } if (flags & CONTEXT_FLOATING_POINT) { frame->fpscr = context->Fpscr; memcpy( frame->d, context->u.D, sizeof(context->u.D) ); } frame->restore_flags |= flags & ~CONTEXT_INTEGER; return STATUS_SUCCESS; } /*********************************************************************** * NtGetContextThread (NTDLL.@) * ZwGetContextThread (NTDLL.@) */ NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context ) { struct syscall_frame *frame = arm_thread_data()->syscall_frame; DWORD needed_flags = context->ContextFlags & ~CONTEXT_ARM; BOOL self = (handle == GetCurrentThread()); if (!self) { NTSTATUS ret = get_thread_context( handle, &context, &self, IMAGE_FILE_MACHINE_ARMNT ); if (ret || !self) return ret; } if (needed_flags & CONTEXT_INTEGER) { context->R0 = frame->r0; context->R1 = frame->r1; context->R2 = frame->r2; context->R3 = frame->r3; context->R4 = frame->r4; context->R5 = frame->r5; context->R6 = frame->r6; context->R7 = frame->r7; context->R8 = frame->r8; context->R9 = frame->r9; context->R10 = frame->r10; context->R11 = frame->r11; context->R12 = frame->r12; context->ContextFlags |= CONTEXT_INTEGER; } if (needed_flags & CONTEXT_CONTROL) { context->Sp = frame->sp; context->Lr = frame->lr; context->Pc = frame->pc; context->Cpsr = frame->cpsr; context->ContextFlags |= CONTEXT_CONTROL; } if (needed_flags & CONTEXT_FLOATING_POINT) { context->Fpscr = frame->fpscr; memcpy( context->u.D, frame->d, sizeof(frame->d) ); context->ContextFlags |= CONTEXT_FLOATING_POINT; } return STATUS_SUCCESS; } /*********************************************************************** * set_thread_wow64_context */ NTSTATUS set_thread_wow64_context( HANDLE handle, const void *ctx, ULONG size ) { return STATUS_INVALID_INFO_CLASS; } /*********************************************************************** * get_thread_wow64_context */ NTSTATUS get_thread_wow64_context( HANDLE handle, void *ctx, ULONG size ) { return STATUS_INVALID_INFO_CLASS; } __ASM_GLOBAL_FUNC( raise_func_trampoline, "push {r12,lr}\n\t" /* (Padding +) Pc in the original frame */ "ldr r3, [r1, #0x38]\n\t" /* context->Sp */ "push {r3}\n\t" /* Original Sp */ __ASM_CFI(".cfi_escape 0x0f,0x03,0x7D,0x04,0x06\n\t") /* CFA, DW_OP_breg13 + 0x04, DW_OP_deref */ __ASM_CFI(".cfi_escape 0x10,0x0e,0x02,0x7D,0x0c\n\t") /* LR, DW_OP_breg13 + 0x0c */ /* We can't express restoring both Pc and Lr with CFI * directives, but we manually load Lr from the stack * in unwind_builtin_dll above. */ "ldr r3, [r1, #0x3c]\n\t" /* context->Lr */ "push {r3}\n\t" /* Original Lr */ "blx r2\n\t" "udf #0") /*********************************************************************** * setup_exception * * Modify the signal context to call the exception raise function. */ static void setup_exception( ucontext_t *sigcontext, EXCEPTION_RECORD *rec ) { struct { CONTEXT context; EXCEPTION_RECORD rec; } *stack; void *stack_ptr = (void *)(SP_sig(sigcontext) & ~3); CONTEXT context; NTSTATUS status; rec->ExceptionAddress = (void *)PC_sig(sigcontext); save_context( &context, sigcontext ); status = send_debug_event( rec, &context, TRUE ); if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED) { restore_context( &context, sigcontext ); return; } stack = virtual_setup_exception( stack_ptr, sizeof(*stack), rec ); stack->rec = *rec; stack->context = context; /* now modify the sigcontext to return to the raise function */ SP_sig(sigcontext) = (DWORD)stack; LR_sig(sigcontext) = context.Pc; PC_sig(sigcontext) = (DWORD)raise_func_trampoline; if (PC_sig(sigcontext) & 1) CPSR_sig(sigcontext) |= 0x20; else CPSR_sig(sigcontext) &= ~0x20; REGn_sig(0, sigcontext) = (DWORD)&stack->rec; /* first arg for KiUserExceptionDispatcher */ REGn_sig(1, sigcontext) = (DWORD)&stack->context; /* second arg for KiUserExceptionDispatcher */ REGn_sig(2, sigcontext) = (DWORD)pKiUserExceptionDispatcher; } /*********************************************************************** * call_user_apc_dispatcher */ NTSTATUS call_user_apc_dispatcher( CONTEXT *context, ULONG_PTR arg1, ULONG_PTR arg2, ULONG_PTR arg3, PNTAPCFUNC func, NTSTATUS status ) { struct syscall_frame *frame = arm_thread_data()->syscall_frame; ULONG sp = context ? context->Sp : frame->sp; struct apc_stack_layout { void *func; void *align; CONTEXT context; } *stack; sp &= ~15; stack = (struct apc_stack_layout *)sp - 1; if (context) { memmove( &stack->context, context, sizeof(stack->context) ); NtSetContextThread( GetCurrentThread(), &stack->context ); } else { stack->context.ContextFlags = CONTEXT_FULL; NtGetContextThread( GetCurrentThread(), &stack->context ); stack->context.R0 = status; } frame->sp = (DWORD)stack; frame->pc = (DWORD)pKiUserApcDispatcher; frame->r0 = (DWORD)&stack->context; frame->r1 = arg1; frame->r2 = arg2; frame->r3 = arg3; stack->func = func; frame->restore_flags |= CONTEXT_CONTROL | CONTEXT_INTEGER; return status; } /*********************************************************************** * call_raise_user_exception_dispatcher */ void call_raise_user_exception_dispatcher(void) { arm_thread_data()->syscall_frame->pc = (DWORD)pKiRaiseUserExceptionDispatcher; } /*********************************************************************** * call_user_exception_dispatcher */ NTSTATUS call_user_exception_dispatcher( EXCEPTION_RECORD *rec, CONTEXT *context ) { struct syscall_frame *frame = arm_thread_data()->syscall_frame; DWORD lr = frame->lr; DWORD sp = frame->sp; NTSTATUS status = NtSetContextThread( GetCurrentThread(), context ); if (status) return status; frame->r0 = (DWORD)rec; frame->r1 = (DWORD)context; frame->pc = (DWORD)pKiUserExceptionDispatcher; frame->lr = lr; frame->sp = sp; frame->restore_flags |= CONTEXT_INTEGER | CONTEXT_CONTROL; return status; } struct user_callback_frame { struct syscall_frame frame; void **ret_ptr; ULONG *ret_len; __wine_jmp_buf jmpbuf; NTSTATUS status; }; /*********************************************************************** * KeUserModeCallback */ NTSTATUS WINAPI KeUserModeCallback( ULONG id, const void *args, ULONG len, void **ret_ptr, ULONG *ret_len ) { struct user_callback_frame callback_frame = { { 0 }, ret_ptr, ret_len }; /* if we have no syscall frame, call the callback directly */ if ((char *)&callback_frame < (char *)ntdll_get_thread_data()->kernel_stack || (char *)&callback_frame > (char *)arm_thread_data()->syscall_frame) { NTSTATUS (WINAPI *func)(const void *, ULONG) = ((void **)NtCurrentTeb()->Peb->KernelCallbackTable)[id]; return func( args, len ); } if ((char *)ntdll_get_thread_data()->kernel_stack + min_kernel_stack > (char *)&callback_frame) return STATUS_STACK_OVERFLOW; if (!__wine_setjmpex( &callback_frame.jmpbuf, NULL )) { struct syscall_frame *frame = arm_thread_data()->syscall_frame; void *args_data = (void *)((frame->sp - len) & ~15); memcpy( args_data, args, len ); callback_frame.frame.r0 = id; callback_frame.frame.r1 = (ULONG_PTR)args; callback_frame.frame.r2 = len; callback_frame.frame.sp = (ULONG_PTR)args_data; callback_frame.frame.pc = (ULONG_PTR)pKiUserCallbackDispatcher; callback_frame.frame.restore_flags = CONTEXT_INTEGER; callback_frame.frame.syscall_table = frame->syscall_table; callback_frame.frame.prev_frame = frame; arm_thread_data()->syscall_frame = &callback_frame.frame; __wine_syscall_dispatcher_return( &callback_frame.frame, 0 ); } return callback_frame.status; } /*********************************************************************** * NtCallbackReturn (NTDLL.@) */ NTSTATUS WINAPI NtCallbackReturn( void *ret_ptr, ULONG ret_len, NTSTATUS status ) { struct user_callback_frame *frame = (struct user_callback_frame *)arm_thread_data()->syscall_frame; if (!frame->frame.prev_frame) return STATUS_NO_CALLBACK_ACTIVE; *frame->ret_ptr = ret_ptr; *frame->ret_len = ret_len; frame->status = status; arm_thread_data()->syscall_frame = frame->frame.prev_frame; __wine_longjmp( &frame->jmpbuf, 1 ); } /*********************************************************************** * handle_syscall_fault * * Handle a page fault happening during a system call. */ static BOOL handle_syscall_fault( ucontext_t *context, EXCEPTION_RECORD *rec ) { struct syscall_frame *frame = arm_thread_data()->syscall_frame; DWORD i; if (!is_inside_syscall( context ) && !ntdll_get_thread_data()->jmp_buf) return FALSE; TRACE( "code=%x flags=%x addr=%p pc=%08x tid=%04x\n", rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress, (DWORD)PC_sig(context), GetCurrentThreadId() ); for (i = 0; i < rec->NumberParameters; i++) TRACE( " info[%d]=%08lx\n", i, rec->ExceptionInformation[i] ); TRACE( " r0=%08x r1=%08x r2=%08x r3=%08x r4=%08x r5=%08x\n", (DWORD)REGn_sig(0, context), (DWORD)REGn_sig(1, context), (DWORD)REGn_sig(2, context), (DWORD)REGn_sig(3, context), (DWORD)REGn_sig(4, context), (DWORD)REGn_sig(5, context) ); TRACE( " r6=%08x r7=%08x r8=%08x r9=%08x r10=%08x r11=%08x\n", (DWORD)REGn_sig(6, context), (DWORD)REGn_sig(7, context), (DWORD)REGn_sig(8, context), (DWORD)REGn_sig(9, context), (DWORD)REGn_sig(10, context), (DWORD)FP_sig(context) ); TRACE( " r12=%08x sp=%08x lr=%08x pc=%08x cpsr=%08x\n", (DWORD)IP_sig(context), (DWORD)SP_sig(context), (DWORD)LR_sig(context), (DWORD)PC_sig(context), (DWORD)CPSR_sig(context) ); if (ntdll_get_thread_data()->jmp_buf) { TRACE( "returning to handler\n" ); REGn_sig(0, context) = (DWORD)ntdll_get_thread_data()->jmp_buf; REGn_sig(1, context) = 1; PC_sig(context) = (DWORD)__wine_longjmp; ntdll_get_thread_data()->jmp_buf = NULL; } else { TRACE( "returning to user mode ip=%08x ret=%08x\n", frame->pc, rec->ExceptionCode ); REGn_sig(0, context) = (DWORD)frame; REGn_sig(1, context) = rec->ExceptionCode; PC_sig(context) = (DWORD)__wine_syscall_dispatcher_return; } return TRUE; } /********************************************************************** * segv_handler * * Handler for SIGSEGV and related errors. */ static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { EXCEPTION_RECORD rec = { 0 }; ucontext_t *context = sigcontext; switch (get_trap_code(signal, context)) { case TRAP_ARM_PRIVINFLT: /* Invalid opcode exception */ if (*(WORD *)PC_sig(context) == 0xdefe) /* breakpoint */ { rec.ExceptionCode = EXCEPTION_BREAKPOINT; rec.NumberParameters = 1; break; } rec.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; break; case TRAP_ARM_PAGEFLT: /* Page fault */ rec.NumberParameters = 2; rec.ExceptionInformation[0] = (get_error_code(context) & 0x800) != 0; rec.ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr; rec.ExceptionCode = virtual_handle_fault( siginfo->si_addr, rec.ExceptionInformation[0], (void *)SP_sig(context) ); if (!rec.ExceptionCode) return; break; case TRAP_ARM_ALIGNFLT: /* Alignment check exception */ rec.ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT; break; case TRAP_ARM_UNKNOWN: /* Unknown fault code */ rec.ExceptionCode = EXCEPTION_ACCESS_VIOLATION; rec.NumberParameters = 2; rec.ExceptionInformation[0] = 0; rec.ExceptionInformation[1] = 0xffffffff; break; default: ERR("Got unexpected trap %d\n", get_trap_code(signal, context)); rec.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; break; } if (handle_syscall_fault( context, &rec )) return; setup_exception( context, &rec ); } /********************************************************************** * trap_handler * * Handler for SIGTRAP. */ static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { EXCEPTION_RECORD rec = { 0 }; switch (siginfo->si_code) { case TRAP_TRACE: rec.ExceptionCode = EXCEPTION_SINGLE_STEP; break; case TRAP_BRKPT: default: rec.ExceptionCode = EXCEPTION_BREAKPOINT; rec.NumberParameters = 1; break; } setup_exception( sigcontext, &rec ); } /********************************************************************** * fpe_handler * * Handler for SIGFPE. */ static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { EXCEPTION_RECORD rec = { 0 }; switch (siginfo->si_code & 0xffff ) { #ifdef FPE_FLTSUB case FPE_FLTSUB: rec.ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED; break; #endif #ifdef FPE_INTDIV case FPE_INTDIV: rec.ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO; break; #endif #ifdef FPE_INTOVF case FPE_INTOVF: rec.ExceptionCode = EXCEPTION_INT_OVERFLOW; break; #endif #ifdef FPE_FLTDIV case FPE_FLTDIV: rec.ExceptionCode = EXCEPTION_FLT_DIVIDE_BY_ZERO; break; #endif #ifdef FPE_FLTOVF case FPE_FLTOVF: rec.ExceptionCode = EXCEPTION_FLT_OVERFLOW; break; #endif #ifdef FPE_FLTUND case FPE_FLTUND: rec.ExceptionCode = EXCEPTION_FLT_UNDERFLOW; break; #endif #ifdef FPE_FLTRES case FPE_FLTRES: rec.ExceptionCode = EXCEPTION_FLT_INEXACT_RESULT; break; #endif #ifdef FPE_FLTINV case FPE_FLTINV: #endif default: rec.ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION; break; } setup_exception( sigcontext, &rec ); } /********************************************************************** * int_handler * * Handler for SIGINT. */ static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { HANDLE handle; if (!p__wine_ctrl_routine) return; if (!NtCreateThreadEx( &handle, THREAD_ALL_ACCESS, NULL, NtCurrentProcess(), p__wine_ctrl_routine, 0 /* CTRL_C_EVENT */, 0, 0, 0, 0, NULL )) NtClose( handle ); } /********************************************************************** * abrt_handler * * Handler for SIGABRT. */ static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { EXCEPTION_RECORD rec = { EXCEPTION_WINE_ASSERTION, EH_NONCONTINUABLE }; setup_exception( sigcontext, &rec ); } /********************************************************************** * quit_handler * * Handler for SIGQUIT. */ static void quit_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { abort_thread(0); } /********************************************************************** * usr1_handler * * Handler for SIGUSR1, used to signal a thread that it got suspended. */ static void usr1_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { CONTEXT context; if (is_inside_syscall( sigcontext )) { context.ContextFlags = CONTEXT_FULL; NtGetContextThread( GetCurrentThread(), &context ); wait_suspend( &context ); NtSetContextThread( GetCurrentThread(), &context ); } else { save_context( &context, sigcontext ); wait_suspend( &context ); restore_context( &context, sigcontext ); } } /********************************************************************** * get_thread_ldt_entry */ NTSTATUS get_thread_ldt_entry( HANDLE handle, void *data, ULONG len, ULONG *ret_len ) { return STATUS_NOT_IMPLEMENTED; } /****************************************************************************** * NtSetLdtEntries (NTDLL.@) * ZwSetLdtEntries (NTDLL.@) */ NTSTATUS WINAPI NtSetLdtEntries( ULONG sel1, LDT_ENTRY entry1, ULONG sel2, LDT_ENTRY entry2 ) { return STATUS_NOT_IMPLEMENTED; } /********************************************************************** * signal_init_threading */ void signal_init_threading(void) { } /********************************************************************** * signal_alloc_thread */ NTSTATUS signal_alloc_thread( TEB *teb ) { teb->WOW32Reserved = __wine_syscall_dispatcher; return STATUS_SUCCESS; } /********************************************************************** * signal_free_thread */ void signal_free_thread( TEB *teb ) { } /********************************************************************** * signal_init_thread */ void signal_init_thread( TEB *teb ) { __asm__ __volatile__( "mcr p15, 0, %0, c13, c0, 2" : : "r" (teb) ); } /********************************************************************** * signal_init_process */ void signal_init_process(void) { struct sigaction sig_act; void *kernel_stack = (char *)ntdll_get_thread_data()->kernel_stack + kernel_stack_size; arm_thread_data()->syscall_frame = (struct syscall_frame *)kernel_stack - 1; sig_act.sa_mask = server_block_set; sig_act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK; sig_act.sa_sigaction = int_handler; if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = fpe_handler; if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = abrt_handler; if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = quit_handler; if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = usr1_handler; if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = trap_handler; if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = segv_handler; if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error; if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error; if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error; return; error: perror("sigaction"); exit(1); } /*********************************************************************** * call_init_thunk */ void DECLSPEC_HIDDEN call_init_thunk( LPTHREAD_START_ROUTINE entry, void *arg, BOOL suspend, TEB *teb ) { struct arm_thread_data *thread_data = (struct arm_thread_data *)&teb->GdiTebBatch; struct syscall_frame *frame = thread_data->syscall_frame; CONTEXT *ctx, context = { CONTEXT_ALL }; context.R0 = (DWORD)entry; context.R1 = (DWORD)arg; context.Sp = (DWORD)teb->Tib.StackBase; context.Pc = (DWORD)pRtlUserThreadStart; if (context.Pc & 1) context.Cpsr |= 0x20; /* thumb mode */ if ((ctx = get_cpu_area( IMAGE_FILE_MACHINE_ARMNT ))) *ctx = context; if (suspend) wait_suspend( &context ); ctx = (CONTEXT *)((ULONG_PTR)context.Sp & ~15) - 1; *ctx = context; ctx->ContextFlags = CONTEXT_FULL; memset( frame, 0, sizeof(*frame) ); NtSetContextThread( GetCurrentThread(), ctx ); frame->sp = (DWORD)ctx; frame->pc = (DWORD)pLdrInitializeThunk; frame->r0 = (DWORD)ctx; frame->prev_frame = NULL; frame->restore_flags |= CONTEXT_INTEGER; frame->syscall_table = KeServiceDescriptorTable; pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL ); __wine_syscall_dispatcher_return( frame, 0 ); } /*********************************************************************** * signal_start_thread */ __ASM_GLOBAL_FUNC( signal_start_thread, "push {r4-r12,lr}\n\t" /* store exit frame */ "str sp, [r3, #0x1d4]\n\t" /* arm_thread_data()->exit_frame */ /* set syscall frame */ "ldr r6, [r3, #0x1d8]\n\t" /* arm_thread_data()->syscall_frame */ "cbnz r6, 1f\n\t" "sub r6, sp, #0x160\n\t" /* sizeof(struct syscall_frame) */ "str r6, [r3, #0x1d8]\n\t" /* arm_thread_data()->syscall_frame */ "1:\tmov sp, r6\n\t" "bl " __ASM_NAME("call_init_thunk") ) /*********************************************************************** * signal_exit_thread */ __ASM_GLOBAL_FUNC( signal_exit_thread, "ldr r3, [r2, #0x1d4]\n\t" /* arm_thread_data()->exit_frame */ "mov ip, #0\n\t" "str ip, [r2, #0x1d4]\n\t" "cmp r3, ip\n\t" "it ne\n\t" "movne sp, r3\n\t" "blx r1" ) /*********************************************************************** * __wine_syscall_dispatcher */ __ASM_GLOBAL_FUNC( __wine_syscall_dispatcher, "mrc p15, 0, r1, c13, c0, 2\n\t" /* NtCurrentTeb() */ "ldr r1, [r1, #0x1d8]\n\t" /* arm_thread_data()->syscall_frame */ "add r0, r1, #0x10\n\t" "stm r0, {r4-r12,lr}\n\t" "add r2, sp, #0x10\n\t" "str r2, [r1, #0x38]\n\t" "str r3, [r1, #0x3c]\n\t" "mrs r0, CPSR\n\t" "bfi r0, lr, #5, #1\n\t" /* set thumb bit */ "str r0, [r1, #0x40]\n\t" "mov r0, #0\n\t" "str r0, [r1, #0x44]\n\t" /* frame->restore_flags */ #ifndef __SOFTFP__ "vmrs r0, fpscr\n\t" "str r0, [r1, #0x48]\n\t" "add r0, r1, #0x60\n\t" "vstm r0, {d0-d15}\n\t" #endif "mov r6, sp\n\t" "mov sp, r1\n\t" "mov r8, r1\n\t" "ldr r5, [r1, #0x50]\n\t" /* frame->syscall_table */ "ubfx r4, ip, #12, #2\n\t" /* syscall table number */ "bfc ip, #12, #20\n\t" /* syscall number */ "add r4, r5, r4, lsl #4\n\t" "ldr r5, [r4, #8]\n\t" /* table->ServiceLimit */ "cmp ip, r5\n\t" "bcs 5f\n\t" "ldr r5, [r4, #12]\n\t" /* table->ArgumentTable */ "ldrb r5, [r5, ip]\n\t" "cmp r5, #16\n\t" "it le\n\t" "movle r5, #16\n\t" "sub r0, sp, r5\n\t" "and r0, #~7\n\t" "mov sp, r0\n" "2:\tsubs r5, r5, #4\n\t" "ldr r0, [r6, r5]\n\t" "str r0, [sp, r5]\n\t" "bgt 2b\n\t" "pop {r0-r3}\n\t" /* first 4 args are in registers */ "ldr r5, [r4]\n\t" /* table->ServiceTable */ "ldr ip, [r5, ip, lsl #2]\n\t" "blx ip\n" "4:\tldr ip, [r8, #0x44]\n\t" /* frame->restore_flags */ #ifndef __SOFTFP__ "tst ip, #4\n\t" /* CONTEXT_FLOATING_POINT */ "beq 3f\n\t" "ldr r4, [r8, #0x48]\n\t" "vmsr fpscr, r4\n\t" "add r4, r8, #0x60\n\t" "vldm r4, {d0-d15}\n" "3:\n\t" #endif "tst ip, #2\n\t" /* CONTEXT_INTEGER */ "it ne\n\t" "ldmne r8, {r0-r3}\n\t" "ldr lr, [r8, #0x3c]\n\t" "ldr sp, [r8, #0x38]\n\t" "add r8, r8, #0x10\n\t" "ldm r8, {r4-r12,pc}\n" "5:\tmovw r0, #0x000d\n\t" /* STATUS_INVALID_PARAMETER */ "movt r0, #0xc000\n\t" "add sp, sp, #0x10\n\t" "b 4b\n" __ASM_NAME("__wine_syscall_dispatcher_return") ":\n\t" "mov r8, r0\n\t" "mov r0, r1\n\t" "b 4b" ) /*********************************************************************** * __wine_setjmpex */ __ASM_GLOBAL_FUNC( __wine_setjmpex, "stm r0, {r1,r4-r11}\n" /* jmp_buf->Frame,R4..R11 */ "str sp, [r0, #0x24]\n\t" /* jmp_buf->Sp */ "str lr, [r0, #0x28]\n\t" /* jmp_buf->Pc */ #ifndef __SOFTFP__ "vmrs r2, fpscr\n\t" "str r2, [r0, #0x2c]\n\t" /* jmp_buf->Fpscr */ "add r0, r0, #0x30\n\t" "vstm r0, {d8-d15}\n\t" /* jmp_buf->D[0..7] */ #endif "mov r0, #0\n\t" "bx lr" ) /*********************************************************************** * __wine_longjmp */ __ASM_GLOBAL_FUNC( __wine_longjmp, "ldm r0, {r3-r11}\n\t" /* jmp_buf->Frame,R4..R11 */ "ldr sp, [r0, #0x24]\n\t" /* jmp_buf->Sp */ "ldr r2, [r0, #0x28]\n\t" /* jmp_buf->Pc */ #ifndef __SOFTFP__ "ldr r3, [r0, #0x2c]\n\t" /* jmp_buf->Fpscr */ "vmsr fpscr, r3\n\t" "add r0, r0, #0x30\n\t" "vldm r0, {d8-d15}\n\t" /* jmp_buf->D[0..7] */ #endif "mov r0, r1\n\t" /* retval */ "bx r2" ) #endif /* __arm__ */
the_stack_data/115764705.c
/* * Author: lngost * See https://github.com/lngost/algorithm-practice */ #include <stdlib.h> #include <math.h> #ifndef _ORDER_DEFINED_ #define _ORDER_DEFINED_ typedef const int ORDER; #define ORDER_ND 1 // non-descending #define ORDER_NA 2 // non-ascending #endif static void merge(int a[], int p, int q, int r, ORDER order) { int n1 = q - p + 1; int n2 = r - q; int *lArray = malloc(n1 * sizeof(int)); int *rArray = malloc(n2 * sizeof(int)); for(int i=0; i<n1; i++) { lArray[i] = a[p+i]; } for(int j=0; j<n2; j++) { rArray[j] = a[q+j+1]; } int i = 0; int j = 0; switch(order) { case ORDER_ND: for(int k = p; k <= r; k++) { if(j >= n2 || (i < n1 && lArray[i] <= rArray[j])) { a[k] = lArray[i]; ++i; } else { a[k] = rArray[j]; ++j; } } break; case ORDER_NA: for(int k = p; k <= r; k++) { if(j >= n2 || (i < n1 && lArray[i] >= rArray[j])) { a[k] = lArray[i]; ++i; } else { a[k] = rArray[j]; ++j; } } break; default: break; } free(lArray); free(rArray); } void mergeSort(int a[], int p, int r, ORDER order) { if(p < r) { int q = (int)floor((p+r)/2); mergeSort(a, p, q, order); mergeSort(a, q+1, r, order); merge(a, p, q, r, order); } }
the_stack_data/103990.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #define true 1 #define false 0 typedef char *string; // Data type String typedef uint8_t BYTE; // unsigned char | 1 byte (8 bits) | 0 to 255 (2^8=256) int isJpeg(BYTE image[]); // Verify if it is the header of a jpeg image int main(int argc, char *argv[]) { // Validate input if (argc <= 1) { printf("Usage: ./recover image\n"); return 1; } string inputFilename = argv[1]; // Open the file provided FILE *inputFile = fopen(inputFilename, "r"); if (inputFile == NULL) { printf("Could not open %s.\n", inputFilename); return 2; } int block_size = 512; BYTE memChuck[block_size]; // track the number of bytes read from the inputFile int bytesRead = -1; int fileIsOpen = false; // track the number of images (.jpeg files) found int counter = 0; char imgName[8] = {'\0'}; FILE *img = NULL; // Read from file while (feof(inputFile) == 0) { bytesRead = fread(memChuck, sizeof(BYTE), block_size, inputFile); if (bytesRead <= 0) { continue; } // unsure it is a jpeg file if (isJpeg(memChuck)) { if (fileIsOpen) { // Close img fclose(img); img = NULL; fileIsOpen = false; } sprintf(imgName, "%03i.jpg", counter); img = fopen(imgName, "w"); if (inputFile == NULL) { printf("Could not open %s.\n", imgName); return 3; } fwrite(memChuck, sizeof(BYTE), block_size, img); fileIsOpen = true; counter++; } else if (fileIsOpen) { fwrite(memChuck, sizeof(BYTE), block_size, img); } } if (fileIsOpen) { // Close img fclose(img); } // Close inputFile fclose(inputFile); } int isJpeg(BYTE image[]) { if (image[0] == 0xff && image[1] == 0xd8 && image[2] == 0xff && ((image[3] & 0xf0) == 0xe0)) { return true; } return false; }
the_stack_data/83325.c
#include <stdio.h> void scilab_rt_barh_i2i2_(int in00, int in01, int matrixin0[in00][in01], int in10, int in11, int matrixin1[in10][in11]) { int i; int j; int val0 = 0; int val1 = 0; for (i = 0; i < in00; ++i) { for (j = 0; j < in01; ++j) { val0 += matrixin0[i][j]; } } printf("%d", val0); for (i = 0; i < in10; ++i) { for (j = 0; j < in11; ++j) { val1 += matrixin1[i][j]; } } printf("%d", val1); }
the_stack_data/232954938.c
#include <sys/types.h> #include <sys/mman.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <inttypes.h> #include <fcntl.h> #include <sys/stat.h> int64_t maprwfile_(char *fname, int *fd, int64_t *size, int32_t *irtc) { caddr_t src; struct stat statbuf; if((*fd = open(fname, O_RDONLY)) < 0) {*irtc=1; return 0;} if ( fstat(*fd, &statbuf) < 0 ) {*irtc=2; return 0;} if ((src = mmap(0, *size = statbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, *fd, 0)) == (caddr_t) -1) { *irtc=3; return 0;} *irtc=0; return (int64_t) src; }
the_stack_data/57951041.c
/* posix */ #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> /* bsd extensions */ #include <sys/uio.h> #include <sys/socket.h> int socketpair(int domain, int , int , int *sv) { switch(domain){ case PF_UNIX: return pipe(sv); default: errno = EOPNOTSUPP; return -1; } }
the_stack_data/54824531.c
/* * $XConsortium: parsedpy.c,v 1.9 94/04/17 20:37:51 hersh Exp $ * $XFree86: xc/programs/xauth/parsedpy.c,v 3.0 1996/06/10 09:17:48 dawes Exp $ * * parse_displayname - utility routine for splitting up display name strings * * Copyright (c) 1989 X Consortium Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of the X Consortium shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium. * * * Author: Jim Fulton, MIT X Consortium */ #include <stdio.h> /* for NULL */ #include <ctype.h> /* for isascii() and isdigit() */ #include <X11/Xos.h> /* for strchr() and string routines */ #include <X11/Xlib.h> /* for Family contants */ #ifdef hpux #include <sys/utsname.h> /* for struct utsname */ #endif #include <X11/Xauth.h> /* for FamilyLocal */ #include <X11/Xmu/SysUtil.h> #ifdef UNIXCONN #define UNIX_CONNECTION "unix" #define UNIX_CONNECTION_LENGTH 4 #endif #ifdef X_NOT_STDC_ENV extern char *malloc(); #else #include <stdlib.h> #endif /* * private utility routines */ /*static*/ char *copystring (src, len) char *src; int len; { char *cp; if (!src && len != 0) return NULL; cp = malloc (len + 1); if (cp) { if (src) strncpy (cp, src, len); cp[len] = '\0'; } return cp; } char *get_local_hostname (buf, maxlen) char *buf; int maxlen; { buf[0] = '\0'; (void) XmuGetHostname (buf, maxlen); return (buf[0] ? buf : NULL); } #ifndef UNIXCONN static char *copyhostname () { char buf[256]; return (get_local_hostname (buf, sizeof buf) ? copystring (buf, strlen (buf)) : NULL); } #endif /* * parse_displayname - display a display string up into its component parts */ Bool parse_displayname (displayname, familyp, hostp, dpynump, scrnump, restp) char *displayname; int *familyp; /* return */ char **hostp; /* return */ int *dpynump, *scrnump; /* return */ char **restp; /* return */ { char *ptr; /* work variables */ int len; /* work variable */ int family = -1; /* value to be returned */ char *host = NULL; /* must free if set and error return */ int dpynum = -1; /* value to be returned */ int scrnum = 0; /* value to be returned */ char *rest = NULL; /* must free if set and error return */ Bool dnet = False; /* if true then using DECnet */ /* check the name */ if (!displayname || !displayname[0]) return False; /* must have at least :number */ ptr = strchr(displayname, ':'); if (!ptr || !ptr[1]) return False; if (ptr[1] == ':') { if (ptr[2] == '\0') return False; dnet = True; } /* * get the host string; if none is given, use the most effiecient path */ len = (ptr - displayname); /* length of host name */ if (len == 0) { /* choose most efficient path */ #ifdef UNIXCONN host = copystring (UNIX_CONNECTION, UNIX_CONNECTION_LENGTH); family = FamilyLocal; #else if (dnet) { host = copystring ("0", 1); family = FamilyDECnet; } else { host = copyhostname (); family = FamilyInternet; } #endif } else { host = copystring (displayname, len); if (dnet) { family = dnet; } else { #ifdef UNIXCONN if (host && strcmp (host, UNIX_CONNECTION) == 0) family = FamilyLocal; else #endif family = FamilyInternet; } } if (!host) return False; /* * get the display number; we know that there is something after the * colon (or colons) from above. note that host is now set and must * be freed if there is an error. */ if (dnet) ptr++; /* skip the extra DECnet colon */ ptr++; /* move to start of display num */ { register char *cp; for (cp = ptr; *cp && isascii(*cp) && isdigit(*cp); cp++) ; len = (cp - ptr); /* check present and valid follow */ if (len == 0 || (*cp && *cp != '.')) { free (host); return False; } dpynum = atoi (ptr); /* it will handle num. as well */ ptr = cp; } /* * now get screen number if given; ptr may point to nul at this point */ if (ptr[0] == '.') { register char *cp; ptr++; for (cp = ptr; *cp && isascii(*cp) && isdigit(*cp); cp++) ; len = (cp - ptr); if (len == 0 || (*cp && *cp != '.')) { /* all prop name */ free (host); return False; } scrnum = atoi (ptr); /* it will handle num. as well */ ptr = cp; } /* * and finally, get any additional stuff that might be following the * the screen number; ptr must point to a period if there is anything */ if (ptr[0] == '.') { ptr++; len = strlen (ptr); if (len > 0) { rest = copystring (ptr, len); if (!rest) { free (host); return False; } } } /* * and we are done! */ *familyp = family; *hostp = host; *dpynump = dpynum; *scrnump = scrnum; *restp = rest; return True; }
the_stack_data/193893665.c
/********************************************************************** * Copyright (C) 2010 Signove Tecnologia Corporation. * All rights reserved. * Contact: Signove Tecnologia Corporation ([email protected]) * * $LICENSE_TEXT:BEGIN$ * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation and appearing * in the file LICENSE included in the packaging of this file; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * $LICENSE_TEXT:END$ * * testfsm.c * * Created on: Jun 22, 2010 * Author: fabricio.silva **********************************************************************/ #ifdef TEST_ENABLED #include "testlinkedlist.h" #include "src/util/linkedlist.h" #include "Basic.h" #include <stdio.h> static int test_init_suite(void) { return 0; } static int test_finish_suite(void) { return 0; } void testllist_add_suite() { CU_pSuite suite = CU_add_suite("Linked list Test Suite", test_init_suite, test_finish_suite); /* Add tests here - Start */ CU_add_test(suite, "testllist_test", testllist_test); /* Add tests here - End */ } static int search(void *arg, void *element) { return arg == element; } void testllist_test() { LinkedList *l = llist_new(); llist_add(l, (void *) 10); llist_add(l, (void *) 20); llist_add(l, (void *) 30); llist_add(l, (void *) 40); llist_add(l, (void *) 50); CU_ASSERT_EQUAL(5, l->size); CU_ASSERT_EQUAL((void *) 10, llist_get(l, 0)); CU_ASSERT_EQUAL(0, llist_index_of(l, (void *) 10)); CU_ASSERT_EQUAL((void *) 20, llist_get(l, 1)); CU_ASSERT_EQUAL(1, llist_index_of(l, (void *) 20)); CU_ASSERT_EQUAL((void *) 30, llist_get(l, 2)); CU_ASSERT_EQUAL(2, llist_index_of(l, (void *) 30)); CU_ASSERT_EQUAL((void *) 10, llist_search_first(l, (void *) 10, search)); CU_ASSERT_EQUAL((void *) 20, llist_search_first(l, (void *) 20, search)); CU_ASSERT_EQUAL((void *) 30, llist_search_first(l, (void *) 30, search)); CU_ASSERT_TRUE(llist_remove(l, (void *) 10)); CU_ASSERT_EQUAL(4, l->size); CU_ASSERT_PTR_NULL(llist_search_first(l, (void *) 10, search)); CU_ASSERT_TRUE(llist_remove(l, (void *) 20)); CU_ASSERT_EQUAL(3, l->size); CU_ASSERT_PTR_NULL(llist_search_first(l, (void *) 20, search)); CU_ASSERT_TRUE(llist_remove(l, (void *) 30)); CU_ASSERT_EQUAL(2, l->size); CU_ASSERT_PTR_NULL(llist_search_first(l, (void *) 20, search)); llist_destroy(l, NULL); } #endif
the_stack_data/152650.c
/* PGI Fortran wants my_module_ when calling any my_module symbol. */ void my_module_(void) {}
the_stack_data/156394075.c
#include<stdio.h> int ma[105][105]; int main(){ int n; scanf("%d",&n); int i,j; for(i = 1;i <= n;i++) for(j = 1;j <= n;j++) scanf("%d",&ma[i][j]); int temp; for(i = 1;i <= n;i++){ for(j = 1;j <= n;j++){ scanf("%d",&temp); ma[i][j] += temp; if(j < n) printf("%d ",ma[i][j]); else printf("%d\n",ma[i][j]); } } return 0; }