keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
2D | JaeHyunLee94/mpm2d | external/glfw/docs/CONTRIBUTING.md | .md | 15,407 | 392 | # Contribution Guide
## Contents
- [Asking a question](#asking-a-question)
- [Reporting a bug](#reporting-a-bug)
- [Reporting a compile or link bug](#reporting-a-compile-or-link-bug)
- [Reporting a segfault or other crash bug](#reporting-a-segfault-or-other-crash-bug)
- [Reporting a context creation bug](#reporting-a-context-creation-bug)
- [Reporting a monitor or video mode bug](#reporting-a-monitor-or-video-mode-bug)
- [Reporting a window, input or event bug](#reporting-a-window-input-or-event-bug)
- [Reporting some other library bug](#reporting-some-other-library-bug)
- [Reporting a documentation bug](#reporting-a-documentation-bug)
- [Reporting a website bug](#reporting-a-website-bug)
- [Requesting a feature](#requesting-a-feature)
- [Contributing a bug fix](#contributing-a-bug-fix)
- [Contributing a feature](#contributing-a-feature)
## Asking a question
Questions about how to use GLFW should be asked either in the [support
section](https://discourse.glfw.org/c/support) of the forum, under the [Stack
Overflow tag](https://stackoverflow.com/questions/tagged/glfw) or [Game
Development tag](https://gamedev.stackexchange.com/questions/tagged/glfw) on
Stack Exchange or in the IRC channel `#glfw` on
[Freenode](http://freenode.net/).
Questions about the design or implementation of GLFW or about future plans
should be asked in the [dev section](https://discourse.glfw.org/c/dev) of the
forum or in the IRC channel. Please don't open a GitHub issue to discuss design
questions without first checking with a maintainer.
## Reporting a bug
If GLFW is behaving unexpectedly at run-time, start by setting an [error
callback](https://www.glfw.org/docs/latest/intro_guide.html#error_handling).
GLFW will often tell you the cause of an error via this callback. If it
doesn't, that might be a separate bug.
If GLFW is crashing or triggering asserts, make sure that all your object
handles and other pointers are valid.
For bugs where it makes sense, a short, self contained example is absolutely
invaluable. Just put it inline in the body text. Note that if the bug is
reproducible with one of the test programs that come with GLFW, just mention
that instead.
__Don't worry about adding too much information__. Unimportant information can
be abbreviated or removed later, but missing information can stall bug fixing,
especially when your schedule doesn't align with that of the maintainer.
__Please provide text as text, not as images__. This includes code, error
messages and any other text. Text in images cannot be found by other users
searching for the same problem and may have to be re-typed by maintainers when
debugging.
You don't need to manually indent your code or other text to quote it with
GitHub Markdown; just surround it with triple backticks:
```
Some quoted text.
```
You can also add syntax highlighting by appending the common file extension:
```c
int five(void)
{
return 5;
}
```
There are issue labels for both platforms and GPU manufacturers, so there is no
need to mention these in the subject line. If you do, it will be removed when
the issue is labeled.
If your bug is already reported, please add any new information you have, or if
it already has everything, give it a :+1:.
### Reporting a compile or link bug
__Note:__ GLFW needs many system APIs to do its job, which on some platforms
means linking to many system libraries. If you are using GLFW as a static
library, that means your application needs to link to these in addition to GLFW.
__Note:__ Check the [Compiling
GLFW](https://www.glfw.org/docs/latest/compile.html) guide and or [Building
applications](https://www.glfw.org/docs/latest/build.html) guide for before
opening an issue of this kind. Most issues are caused by a missing package or
linker flag.
Always include the __operating system name and version__ (e.g. `Windows
7 64-bit` or `Ubuntu 15.10`) and the __compiler name and version__ (e.g. `Visual
C++ 2015 Update 2`). If you are using an official release of GLFW,
include the __GLFW release version__ (e.g. `3.1.2`), otherwise include the
__GLFW commit ID__ (e.g. `3795d78b14ef06008889cc422a1fb8d642597751`) from Git.
Please also include the __complete build log__ from your compiler and linker,
even if it's long. It can always be shortened later, if necessary.
#### Quick template
```
OS and version:
Compiler version:
Release or commit:
Build log:
```
### Reporting a segfault or other crash bug
Always include the __operating system name and version__ (e.g. `Windows
7 64-bit` or `Ubuntu 15.10`). If you are using an official release of GLFW,
include the __GLFW release version__ (e.g. `3.1.2`), otherwise include the
__GLFW commit ID__ (e.g. `3795d78b14ef06008889cc422a1fb8d642597751`) from Git.
Please also include any __error messages__ provided to your application via the
[error
callback](https://www.glfw.org/docs/latest/intro_guide.html#error_handling) and
the __full call stack__ of the crash, or if the crash does not occur in debug
mode, mention that instead.
#### Quick template
```
OS and version:
Release or commit:
Error messages:
Call stack:
```
### Reporting a context creation bug
__Note:__ Windows ships with graphics drivers that do not support OpenGL. If
GLFW says that your machine lacks support for OpenGL, it very likely does.
Install drivers from the computer manufacturer or graphics card manufacturer
([Nvidia](https://www.geforce.com/drivers),
[AMD](https://www.amd.com/en/support),
[Intel](https://www-ssl.intel.com/content/www/us/en/support/detect.html)) to
fix this.
__Note:__ AMD only supports OpenGL ES on Windows via EGL. See the
[GLFW\_CONTEXT\_CREATION\_API](https://www.glfw.org/docs/latest/window_guide.html#window_hints_ctx)
hint for how to select EGL.
Please verify that context creation also fails with the `glfwinfo` tool before
reporting it as a bug. This tool is included in the GLFW source tree as
`tests/glfwinfo.c` and is built along with the library. It has switches for all
GLFW context and framebuffer hints. Run `glfwinfo -h` for a complete list.
Always include the __operating system name and version__ (e.g. `Windows
7 64-bit` or `Ubuntu 15.10`). If you are using an official release of GLFW,
include the __GLFW release version__ (e.g. `3.1.2`), otherwise include the
__GLFW commit ID__ (e.g. `3795d78b14ef06008889cc422a1fb8d642597751`) from Git.
If you are running your program in a virtual machine, please mention this and
include the __VM name and version__ (e.g. `VirtualBox 5.1`).
Please also include the __GLFW version string__ (`3.2.0 X11 EGL clock_gettime
/dev/js`), as described
[here](https://www.glfw.org/docs/latest/intro.html#intro_version_string), the
__GPU model and driver version__ (e.g. `GeForce GTX660 with 352.79`), and the
__output of `glfwinfo`__ (with switches matching any hints you set in your
code) when reporting this kind of bug. If this tool doesn't run on the machine,
mention that instead.
#### Quick template
```
OS and version:
GPU and driver:
Release or commit:
Version string:
glfwinfo output:
```
### Reporting a monitor or video mode bug
__Note:__ On headless systems on some platforms, no monitors are reported. This
causes glfwGetPrimaryMonitor to return `NULL`, which not all applications are
prepared for.
__Note:__ Some third-party tools report more video modes than are approved of
by the OS. For safety and compatibility, GLFW only reports video modes the OS
wants programs to use. This is not a bug.
The `monitors` tool is included in the GLFW source tree as `tests/monitors.c`
and is built along with the library. It lists all information GLFW provides
about monitors it detects.
Always include the __operating system name and version__ (e.g. `Windows
7 64-bit` or `Ubuntu 15.10`). If you are using an official release of GLFW,
include the __GLFW release version__ (e.g. `3.1.2`), otherwise include the
__GLFW commit ID__ (e.g. `3795d78b14ef06008889cc422a1fb8d642597751`) from Git.
If you are running your program in a virtual machine, please mention this and
include the __VM name and version__ (e.g. `VirtualBox 5.1`).
Please also include any __error messages__ provided to your application via the
[error
callback](https://www.glfw.org/docs/latest/intro_guide.html#error_handling) and
the __output of `monitors`__ when reporting this kind of bug. If this tool
doesn't run on the machine, mention this instead.
#### Quick template
```
OS and version:
Release or commit:
Error messages:
monitors output:
```
### Reporting a window, input or event bug
__Note:__ The exact ordering of related window events will sometimes differ.
__Note:__ Window moving and resizing (by the user) will block the main thread on
some platforms. This is not a bug. Set a [refresh
callback](https://www.glfw.org/docs/latest/window.html#window_refresh) if you
want to keep the window contents updated during a move or size operation.
The `events` tool is included in the GLFW source tree as `tests/events.c` and is
built along with the library. It prints all information provided to every
callback supported by GLFW as events occur. Each event is listed with the time
and a unique number to make discussions about event logs easier. The tool has
command-line options for creating multiple windows and full screen windows.
Always include the __operating system name and version__ (e.g. `Windows
7 64-bit` or `Ubuntu 15.10`). If you are using an official release of GLFW,
include the __GLFW release version__ (e.g. `3.1.2`), otherwise include the
__GLFW commit ID__ (e.g. `3795d78b14ef06008889cc422a1fb8d642597751`) from Git.
If you are running your program in a virtual machine, please mention this and
include the __VM name and version__ (e.g. `VirtualBox 5.1`).
Please also include any __error messages__ provided to your application via the
[error
callback](https://www.glfw.org/docs/latest/intro_guide.html#error_handling) and
if relevant, the __output of `events`__ when reporting this kind of bug. If
this tool doesn't run on the machine, mention this instead.
__X11:__ If possible, please include what desktop environment (e.g. GNOME,
Unity, KDE) and/or window manager (e.g. Openbox, dwm, Window Maker) you are
running. If the bug is related to keyboard input, please include any input
method (e.g. ibus, SCIM) you are using.
#### Quick template
```
OS and version:
Release or commit:
Error messages:
events output:
```
### Reporting some other library bug
Always include the __operating system name and version__ (e.g. `Windows
7 64-bit` or `Ubuntu 15.10`). If you are using an official release of GLFW,
include the __GLFW release version__ (e.g. `3.1.2`), otherwise include the
__GLFW commit ID__ (e.g. `3795d78b14ef06008889cc422a1fb8d642597751`) from Git.
Please also include any __error messages__ provided to your application via the
[error
callback](https://www.glfw.org/docs/latest/intro_guide.html#error_handling), if
relevant.
#### Quick template
```
OS and version:
Release or commit:
Error messages:
```
### Reporting a documentation bug
If you found a bug in the documentation, including this file, then it's fine to
just link to that web page or mention that source file. You don't need to match
the source to the output or vice versa.
### Reporting a website bug
If the bug is in the documentation (anything under `/docs/`) then please see the
section above. Bugs in the rest of the site are reported to the [website
source repository](https://github.com/glfw/website/issues).
## Requesting a feature
Please explain why you need the feature and how you intend to use it. If you
have a specific API design in mind, please add that as well. If you have or are
planning to write code for the feature, see the section below.
If there already is a request for the feature you need, add your specific use
case unless it is already mentioned. If it is, give it a :+1:.
## Contributing a bug fix
__Note:__ You must have all necessary [intellectual
property rights](https://en.wikipedia.org/wiki/Intellectual_property) to any
code you contribute. If you did not write the code yourself, you must explain
where it came from and under what license you received it. Even code using the
same license as GLFW may not be copied without attribution.
__There is no preferred patch size__. A one character fix is just as welcome as
a thousand line one, if that is the appropriate size for the fix.
In addition to the code, a complete bug fix includes:
- Change log entry in `README.md`, describing the incorrect behavior
- Credits entries for all authors of the bug fix
Bug fixes will not be rejected because they don't include all the above parts,
but please keep in mind that maintainer time is finite and that there are many
other bugs and features to work on.
If the patch fixes a bug introduced after the last release, it should not get
a change log entry.
If you haven't already, read the excellent article [How to Write a Git Commit
Message](https://chris.beams.io/posts/git-commit/).
## Contributing a feature
__Note:__ You must have all necessary rights to any code you contribute. If you
did not write the code yourself, you must explain where it came from and under
what license. Even code using the same license as GLFW may not be copied
without attribution.
__Note:__ If you haven't already implemented the feature, check first if there
already is an open issue for it and if it's already being developed in an
[experimental branch](https://github.com/glfw/glfw/branches/all).
__There is no preferred patch size__. A one character change is just as welcome
as one adding a thousand line one, if that is the appropriate size for the
feature.
In addition to the code, a complete feature includes:
- Change log entry in `README.md`, listing all new symbols
- News page entry, briefly describing the feature
- Guide documentation, with minimal examples, in the relevant guide
- Reference documentation, with all applicable tags
- Cross-references and mentions in appropriate places
- Credits entries for all authors of the feature
If the feature requires platform-specific code, at minimum stubs must be added
for the new platform function to all supported and experimental platforms.
If it adds a new callback, support for it must be added to `tests/event.c`.
If it adds a new monitor property, support for it must be added to
`tests/monitor.c`.
If it adds a new OpenGL, OpenGL ES or Vulkan option or extension, support
for it must be added to `tests/glfwinfo.c` and the behavior of the library when
the extension is missing documented in `docs/compat.dox`.
If you haven't already, read the excellent article [How to Write a Git Commit
Message](https://chris.beams.io/posts/git-commit/).
Features will not be rejected because they don't include all the above parts,
but please keep in mind that maintainer time is finite and that there are many
other features and bugs to work on.
Please also keep in mind that any part of the public API that has been included
in a release cannot be changed until the next _major_ version. Features can be
added and existing parts can sometimes be overloaded (in the general sense of
doing more things, not in the C++ sense), but code written to the API of one
minor release should both compile and run on subsequent minor releases.
| Markdown |
2D | JaeHyunLee94/mpm2d | external/glfw/docs/SUPPORT.md | .md | 524 | 15 | # Support resources
See the [latest documentation](http://www.glfw.org/docs/latest/) for tutorials,
guides and the API reference.
If you have questions about using GLFW, we have a
[forum](https://discourse.glfw.org/), and the `#glfw` IRC channel on
[Freenode](http://freenode.net/).
Bugs are reported to our [issue tracker](https://github.com/glfw/glfw/issues).
Please check the [contribution
guide](https://github.com/glfw/glfw/blob/master/docs/CONTRIBUTING.md) for
information on what to include when reporting a bug.
| Markdown |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/monitors.c | .c | 7,717 | 263 | //========================================================================
// Monitor information tool
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test prints monitor and video mode information or verifies video
// modes
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "getopt.h"
enum Mode
{
LIST_MODE,
TEST_MODE
};
static void usage(void)
{
printf("Usage: monitors [-t]\n");
printf(" monitors -h\n");
}
static int euclid(int a, int b)
{
return b ? euclid(b, a % b) : a;
}
static const char* format_mode(const GLFWvidmode* mode)
{
static char buffer[512];
const int gcd = euclid(mode->width, mode->height);
snprintf(buffer,
sizeof(buffer),
"%i x %i x %i (%i:%i) (%i %i %i) %i Hz",
mode->width, mode->height,
mode->redBits + mode->greenBits + mode->blueBits,
mode->width / gcd, mode->height / gcd,
mode->redBits, mode->greenBits, mode->blueBits,
mode->refreshRate);
buffer[sizeof(buffer) - 1] = '\0';
return buffer;
}
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
printf("Framebuffer resized to %ix%i\n", width, height);
glViewport(0, 0, width, height);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
static void list_modes(GLFWmonitor* monitor)
{
int count, x, y, width_mm, height_mm, i;
int workarea_x, workarea_y, workarea_width, workarea_height;
float xscale, yscale;
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
const GLFWvidmode* modes = glfwGetVideoModes(monitor, &count);
glfwGetMonitorPos(monitor, &x, &y);
glfwGetMonitorPhysicalSize(monitor, &width_mm, &height_mm);
glfwGetMonitorContentScale(monitor, &xscale, &yscale);
glfwGetMonitorWorkarea(monitor, &workarea_x, &workarea_y, &workarea_width, &workarea_height);
printf("Name: %s (%s)\n",
glfwGetMonitorName(monitor),
glfwGetPrimaryMonitor() == monitor ? "primary" : "secondary");
printf("Current mode: %s\n", format_mode(mode));
printf("Virtual position: %i, %i\n", x, y);
printf("Content scale: %f x %f\n", xscale, yscale);
printf("Physical size: %i x %i mm (%0.2f dpi at %i x %i)\n",
width_mm, height_mm, mode->width * 25.4f / width_mm, mode->width, mode->height);
printf("Monitor work area: %i x %i starting at %i, %i\n",
workarea_width, workarea_height, workarea_x, workarea_y);
printf("Modes:\n");
for (i = 0; i < count; i++)
{
printf("%3u: %s", (unsigned int) i, format_mode(modes + i));
if (memcmp(mode, modes + i, sizeof(GLFWvidmode)) == 0)
printf(" (current mode)");
putchar('\n');
}
}
static void test_modes(GLFWmonitor* monitor)
{
int i, count;
GLFWwindow* window;
const GLFWvidmode* modes = glfwGetVideoModes(monitor, &count);
for (i = 0; i < count; i++)
{
const GLFWvidmode* mode = modes + i;
GLFWvidmode current;
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
printf("Testing mode %u on monitor %s: %s\n",
(unsigned int) i,
glfwGetMonitorName(monitor),
format_mode(mode));
window = glfwCreateWindow(mode->width, mode->height,
"Video Mode Test",
glfwGetPrimaryMonitor(),
NULL);
if (!window)
{
printf("Failed to enter mode %u: %s\n",
(unsigned int) i,
format_mode(mode));
continue;
}
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
glfwSetTime(0.0);
while (glfwGetTime() < 5.0)
{
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
if (glfwWindowShouldClose(window))
{
printf("User terminated program\n");
glfwTerminate();
exit(EXIT_SUCCESS);
}
}
glGetIntegerv(GL_RED_BITS, ¤t.redBits);
glGetIntegerv(GL_GREEN_BITS, ¤t.greenBits);
glGetIntegerv(GL_BLUE_BITS, ¤t.blueBits);
glfwGetWindowSize(window, ¤t.width, ¤t.height);
if (current.redBits != mode->redBits ||
current.greenBits != mode->greenBits ||
current.blueBits != mode->blueBits)
{
printf("*** Color bit mismatch: (%i %i %i) instead of (%i %i %i)\n",
current.redBits, current.greenBits, current.blueBits,
mode->redBits, mode->greenBits, mode->blueBits);
}
if (current.width != mode->width || current.height != mode->height)
{
printf("*** Size mismatch: %ix%i instead of %ix%i\n",
current.width, current.height,
mode->width, mode->height);
}
printf("Closing window\n");
glfwDestroyWindow(window);
window = NULL;
glfwPollEvents();
}
}
int main(int argc, char** argv)
{
int ch, i, count, mode = LIST_MODE;
GLFWmonitor** monitors;
while ((ch = getopt(argc, argv, "th")) != -1)
{
switch (ch)
{
case 'h':
usage();
exit(EXIT_SUCCESS);
case 't':
mode = TEST_MODE;
break;
default:
usage();
exit(EXIT_FAILURE);
}
}
glfwSetErrorCallback(error_callback);
glfwInitHint(GLFW_COCOA_MENUBAR, GLFW_FALSE);
if (!glfwInit())
exit(EXIT_FAILURE);
monitors = glfwGetMonitors(&count);
for (i = 0; i < count; i++)
{
if (mode == LIST_MODE)
list_modes(monitors[i]);
else if (mode == TEST_MODE)
test_modes(monitors[i]);
}
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/reopen.c | .c | 6,725 | 241 | //========================================================================
// Window re-opener (open/close stress test)
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test came about as the result of bug #1262773
//
// It closes and re-opens the GLFW window every five seconds, alternating
// between windowed and full screen mode
//
// It also times and logs opening and closing actions and attempts to separate
// user initiated window closing from its own
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include "linmath.h"
static const char* vertex_shader_text =
"#version 110\n"
"uniform mat4 MVP;\n"
"attribute vec2 vPos;\n"
"void main()\n"
"{\n"
" gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n"
"}\n";
static const char* fragment_shader_text =
"#version 110\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(1.0);\n"
"}\n";
static const vec2 vertices[4] =
{
{ -0.5f, -0.5f },
{ 0.5f, -0.5f },
{ 0.5f, 0.5f },
{ -0.5f, 0.5f }
};
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void window_close_callback(GLFWwindow* window)
{
printf("Close callback triggered\n");
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_Q:
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
}
}
static void close_window(GLFWwindow* window)
{
double base = glfwGetTime();
glfwDestroyWindow(window);
printf("Closing window took %0.3f seconds\n", glfwGetTime() - base);
}
int main(int argc, char** argv)
{
int count = 0;
double base;
GLFWwindow* window;
srand((unsigned int) time(NULL));
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
for (;;)
{
int width, height;
GLFWmonitor* monitor = NULL;
GLuint vertex_shader, fragment_shader, program, vertex_buffer;
GLint mvp_location, vpos_location;
if (count & 1)
{
int monitorCount;
GLFWmonitor** monitors = glfwGetMonitors(&monitorCount);
monitor = monitors[rand() % monitorCount];
}
if (monitor)
{
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
width = mode->width;
height = mode->height;
}
else
{
width = 640;
height = 480;
}
base = glfwGetTime();
window = glfwCreateWindow(width, height, "Window Re-opener", monitor, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
if (monitor)
{
printf("Opening full screen window on monitor %s took %0.3f seconds\n",
glfwGetMonitorName(monitor),
glfwGetTime() - base);
}
else
{
printf("Opening regular window took %0.3f seconds\n",
glfwGetTime() - base);
}
glfwSetWindowCloseCallback(window, window_close_callback);
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
glCompileShader(vertex_shader);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
glCompileShader(fragment_shader);
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
mvp_location = glGetUniformLocation(program, "MVP");
vpos_location = glGetAttribLocation(program, "vPos");
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(vpos_location);
glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
sizeof(vertices[0]), (void*) 0);
glfwSetTime(0.0);
while (glfwGetTime() < 5.0)
{
float ratio;
int width, height;
mat4x4 m, p, mvp;
glfwGetFramebufferSize(window, &width, &height);
ratio = width / (float) height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 0.f, 1.f);
mat4x4_identity(m);
mat4x4_rotate_Z(m, m, (float) glfwGetTime());
mat4x4_mul(mvp, p, m);
glUseProgram(program);
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glfwSwapBuffers(window);
glfwPollEvents();
if (glfwWindowShouldClose(window))
{
close_window(window);
printf("User closed window\n");
glfwTerminate();
exit(EXIT_SUCCESS);
}
}
printf("Closing window\n");
close_window(window);
count++;
}
glfwTerminate();
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/tearing.c | .c | 7,152 | 251 | //========================================================================
// Vsync enabling test
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test renders a high contrast, horizontally moving bar, allowing for
// visual verification of whether the set swap interval is indeed obeyed
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "linmath.h"
static const struct
{
float x, y;
} vertices[4] =
{
{ -0.25f, -1.f },
{ 0.25f, -1.f },
{ 0.25f, 1.f },
{ -0.25f, 1.f }
};
static const char* vertex_shader_text =
"#version 110\n"
"uniform mat4 MVP;\n"
"attribute vec2 vPos;\n"
"void main()\n"
"{\n"
" gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n"
"}\n";
static const char* fragment_shader_text =
"#version 110\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(1.0);\n"
"}\n";
static int swap_tear;
static int swap_interval;
static double frame_rate;
static void update_window_title(GLFWwindow* window)
{
char title[256];
snprintf(title, sizeof(title), "Tearing detector (interval %i%s, %0.1f Hz)",
swap_interval,
(swap_tear && swap_interval < 0) ? " (swap tear)" : "",
frame_rate);
glfwSetWindowTitle(window, title);
}
static void set_swap_interval(GLFWwindow* window, int interval)
{
swap_interval = interval;
glfwSwapInterval(swap_interval);
update_window_title(window);
}
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_UP:
{
if (swap_interval + 1 > swap_interval)
set_swap_interval(window, swap_interval + 1);
break;
}
case GLFW_KEY_DOWN:
{
if (swap_tear)
{
if (swap_interval - 1 < swap_interval)
set_swap_interval(window, swap_interval - 1);
}
else
{
if (swap_interval - 1 >= 0)
set_swap_interval(window, swap_interval - 1);
}
break;
}
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, 1);
break;
case GLFW_KEY_F11:
case GLFW_KEY_ENTER:
{
static int x, y, width, height;
if (mods != GLFW_MOD_ALT)
return;
if (glfwGetWindowMonitor(window))
glfwSetWindowMonitor(window, NULL, x, y, width, height, 0);
else
{
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwGetWindowPos(window, &x, &y);
glfwGetWindowSize(window, &width, &height);
glfwSetWindowMonitor(window, monitor,
0, 0, mode->width, mode->height,
mode->refreshRate);
}
break;
}
}
}
int main(int argc, char** argv)
{
unsigned long frame_count = 0;
double last_time, current_time;
GLFWwindow* window;
GLuint vertex_buffer, vertex_shader, fragment_shader, program;
GLint mvp_location, vpos_location;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
window = glfwCreateWindow(640, 480, "Tearing detector", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
set_swap_interval(window, 0);
last_time = glfwGetTime();
frame_rate = 0.0;
swap_tear = (glfwExtensionSupported("WGL_EXT_swap_control_tear") ||
glfwExtensionSupported("GLX_EXT_swap_control_tear"));
glfwSetKeyCallback(window, key_callback);
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
glCompileShader(vertex_shader);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
glCompileShader(fragment_shader);
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
mvp_location = glGetUniformLocation(program, "MVP");
vpos_location = glGetAttribLocation(program, "vPos");
glEnableVertexAttribArray(vpos_location);
glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
sizeof(vertices[0]), (void*) 0);
while (!glfwWindowShouldClose(window))
{
int width, height;
mat4x4 m, p, mvp;
float position = cosf((float) glfwGetTime() * 4.f) * 0.75f;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
mat4x4_ortho(p, -1.f, 1.f, -1.f, 1.f, 0.f, 1.f);
mat4x4_translate(m, position, 0.f, 0.f);
mat4x4_mul(mvp, p, m);
glUseProgram(program);
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glfwSwapBuffers(window);
glfwPollEvents();
frame_count++;
current_time = glfwGetTime();
if (current_time - last_time > 1.0)
{
frame_rate = frame_count / (current_time - last_time);
frame_count = 0;
last_time = current_time;
update_window_title(window);
}
}
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/iconify.c | .c | 8,630 | 298 | //========================================================================
// Iconify/restore test program
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This program is used to test the iconify/restore functionality for
// both full screen and windowed mode windows
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include "getopt.h"
static int windowed_xpos, windowed_ypos, windowed_width, windowed_height;
static void usage(void)
{
printf("Usage: iconify [-h] [-f [-a] [-n]]\n");
printf("Options:\n");
printf(" -a create windows for all monitors\n");
printf(" -f create full screen window(s)\n");
printf(" -h show this help\n");
}
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
printf("%0.2f Key %s\n",
glfwGetTime(),
action == GLFW_PRESS ? "pressed" : "released");
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_I:
glfwIconifyWindow(window);
break;
case GLFW_KEY_M:
glfwMaximizeWindow(window);
break;
case GLFW_KEY_R:
glfwRestoreWindow(window);
break;
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
case GLFW_KEY_A:
glfwSetWindowAttrib(window, GLFW_AUTO_ICONIFY, !glfwGetWindowAttrib(window, GLFW_AUTO_ICONIFY));
break;
case GLFW_KEY_B:
glfwSetWindowAttrib(window, GLFW_RESIZABLE, !glfwGetWindowAttrib(window, GLFW_RESIZABLE));
break;
case GLFW_KEY_D:
glfwSetWindowAttrib(window, GLFW_DECORATED, !glfwGetWindowAttrib(window, GLFW_DECORATED));
break;
case GLFW_KEY_F:
glfwSetWindowAttrib(window, GLFW_FLOATING, !glfwGetWindowAttrib(window, GLFW_FLOATING));
break;
case GLFW_KEY_F11:
case GLFW_KEY_ENTER:
{
if (mods != GLFW_MOD_ALT)
return;
if (glfwGetWindowMonitor(window))
{
glfwSetWindowMonitor(window, NULL,
windowed_xpos, windowed_ypos,
windowed_width, windowed_height,
0);
}
else
{
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
if (monitor)
{
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwGetWindowPos(window, &windowed_xpos, &windowed_ypos);
glfwGetWindowSize(window, &windowed_width, &windowed_height);
glfwSetWindowMonitor(window, monitor,
0, 0, mode->width, mode->height,
mode->refreshRate);
}
}
break;
}
}
}
static void window_size_callback(GLFWwindow* window, int width, int height)
{
printf("%0.2f Window resized to %ix%i\n", glfwGetTime(), width, height);
}
static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
printf("%0.2f Framebuffer resized to %ix%i\n", glfwGetTime(), width, height);
}
static void window_focus_callback(GLFWwindow* window, int focused)
{
printf("%0.2f Window %s\n",
glfwGetTime(),
focused ? "focused" : "defocused");
}
static void window_iconify_callback(GLFWwindow* window, int iconified)
{
printf("%0.2f Window %s\n",
glfwGetTime(),
iconified ? "iconified" : "uniconified");
}
static void window_maximize_callback(GLFWwindow* window, int maximized)
{
printf("%0.2f Window %s\n",
glfwGetTime(),
maximized ? "maximized" : "unmaximized");
}
static void window_refresh_callback(GLFWwindow* window)
{
printf("%0.2f Window refresh\n", glfwGetTime());
glfwMakeContextCurrent(window);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
static GLFWwindow* create_window(GLFWmonitor* monitor)
{
int width, height;
GLFWwindow* window;
if (monitor)
{
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
width = mode->width;
height = mode->height;
}
else
{
width = 640;
height = 480;
}
window = glfwCreateWindow(width, height, "Iconify", monitor, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
return window;
}
int main(int argc, char** argv)
{
int ch, i, window_count;
int fullscreen = GLFW_FALSE, all_monitors = GLFW_FALSE;
GLFWwindow** windows;
while ((ch = getopt(argc, argv, "afhn")) != -1)
{
switch (ch)
{
case 'a':
all_monitors = GLFW_TRUE;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'f':
fullscreen = GLFW_TRUE;
break;
default:
usage();
exit(EXIT_FAILURE);
}
}
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
if (fullscreen && all_monitors)
{
int monitor_count;
GLFWmonitor** monitors = glfwGetMonitors(&monitor_count);
window_count = monitor_count;
windows = calloc(window_count, sizeof(GLFWwindow*));
for (i = 0; i < monitor_count; i++)
{
windows[i] = create_window(monitors[i]);
if (!windows[i])
break;
}
}
else
{
GLFWmonitor* monitor = NULL;
if (fullscreen)
monitor = glfwGetPrimaryMonitor();
window_count = 1;
windows = calloc(window_count, sizeof(GLFWwindow*));
windows[0] = create_window(monitor);
}
for (i = 0; i < window_count; i++)
{
glfwSetKeyCallback(windows[i], key_callback);
glfwSetFramebufferSizeCallback(windows[i], framebuffer_size_callback);
glfwSetWindowSizeCallback(windows[i], window_size_callback);
glfwSetWindowFocusCallback(windows[i], window_focus_callback);
glfwSetWindowIconifyCallback(windows[i], window_iconify_callback);
glfwSetWindowMaximizeCallback(windows[i], window_maximize_callback);
glfwSetWindowRefreshCallback(windows[i], window_refresh_callback);
window_refresh_callback(windows[i]);
printf("Window is %s and %s\n",
glfwGetWindowAttrib(windows[i], GLFW_ICONIFIED) ? "iconified" : "restored",
glfwGetWindowAttrib(windows[i], GLFW_FOCUSED) ? "focused" : "defocused");
}
for (;;)
{
glfwWaitEvents();
for (i = 0; i < window_count; i++)
{
if (glfwWindowShouldClose(windows[i]))
break;
}
if (i < window_count)
break;
// Workaround for an issue with msvcrt and mintty
fflush(stdout);
}
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/clipboard.c | .c | 3,718 | 146 | //========================================================================
// Clipboard test program
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This program is used to test the clipboard functionality.
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include "getopt.h"
#if defined(__APPLE__)
#define MODIFIER GLFW_MOD_SUPER
#else
#define MODIFIER GLFW_MOD_CONTROL
#endif
static void usage(void)
{
printf("Usage: clipboard [-h]\n");
}
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
case GLFW_KEY_V:
if (mods == MODIFIER)
{
const char* string;
string = glfwGetClipboardString(NULL);
if (string)
printf("Clipboard contains \"%s\"\n", string);
else
printf("Clipboard does not contain a string\n");
}
break;
case GLFW_KEY_C:
if (mods == MODIFIER)
{
const char* string = "Hello GLFW World!";
glfwSetClipboardString(NULL, string);
printf("Setting clipboard to \"%s\"\n", string);
}
break;
}
}
int main(int argc, char** argv)
{
int ch;
GLFWwindow* window;
while ((ch = getopt(argc, argv, "h")) != -1)
{
switch (ch)
{
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
usage();
exit(EXIT_FAILURE);
}
}
glfwSetErrorCallback(error_callback);
if (!glfwInit())
{
fprintf(stderr, "Failed to initialize GLFW\n");
exit(EXIT_FAILURE);
}
window = glfwCreateWindow(200, 200, "Clipboard Test", NULL, NULL);
if (!window)
{
glfwTerminate();
fprintf(stderr, "Failed to open GLFW window\n");
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
glfwSetKeyCallback(window, key_callback);
glClearColor(0.5f, 0.5f, 0.5f, 0);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwWaitEvents();
}
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/cursor.c | .c | 14,167 | 489 | //========================================================================
// Cursor & input mode tests
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test provides an interface to the cursor image and cursor mode
// parts of the API.
//
// Custom cursor image generation by urraka.
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#if defined(_MSC_VER)
// Make MS math.h define M_PI
#define _USE_MATH_DEFINES
#endif
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "linmath.h"
#define CURSOR_FRAME_COUNT 60
static const char* vertex_shader_text =
"#version 110\n"
"uniform mat4 MVP;\n"
"attribute vec2 vPos;\n"
"void main()\n"
"{\n"
" gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n"
"}\n";
static const char* fragment_shader_text =
"#version 110\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(1.0);\n"
"}\n";
static double cursor_x;
static double cursor_y;
static int swap_interval = 1;
static int wait_events = GLFW_TRUE;
static int animate_cursor = GLFW_FALSE;
static int track_cursor = GLFW_FALSE;
static GLFWcursor* standard_cursors[10];
static GLFWcursor* tracking_cursor = NULL;
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static float star(int x, int y, float t)
{
const float c = 64 / 2.f;
const float i = (0.25f * (float) sin(2.f * M_PI * t) + 0.75f);
const float k = 64 * 0.046875f * i;
const float dist = (float) sqrt((x - c) * (x - c) + (y - c) * (y - c));
const float salpha = 1.f - dist / c;
const float xalpha = (float) x == c ? c : k / (float) fabs(x - c);
const float yalpha = (float) y == c ? c : k / (float) fabs(y - c);
return (float) fmax(0.f, fmin(1.f, i * salpha * 0.2f + salpha * xalpha * yalpha));
}
static GLFWcursor* create_cursor_frame(float t)
{
int i = 0, x, y;
unsigned char buffer[64 * 64 * 4];
const GLFWimage image = { 64, 64, buffer };
for (y = 0; y < image.width; y++)
{
for (x = 0; x < image.height; x++)
{
buffer[i++] = 255;
buffer[i++] = 255;
buffer[i++] = 255;
buffer[i++] = (unsigned char) (255 * star(x, y, t));
}
}
return glfwCreateCursor(&image, image.width / 2, image.height / 2);
}
static GLFWcursor* create_tracking_cursor(void)
{
int i = 0, x, y;
unsigned char buffer[32 * 32 * 4];
const GLFWimage image = { 32, 32, buffer };
for (y = 0; y < image.width; y++)
{
for (x = 0; x < image.height; x++)
{
if (x == 7 || y == 7)
{
buffer[i++] = 255;
buffer[i++] = 0;
buffer[i++] = 0;
buffer[i++] = 255;
}
else
{
buffer[i++] = 0;
buffer[i++] = 0;
buffer[i++] = 0;
buffer[i++] = 0;
}
}
}
return glfwCreateCursor(&image, 7, 7);
}
static void cursor_position_callback(GLFWwindow* window, double x, double y)
{
printf("%0.3f: Cursor position: %f %f (%+f %+f)\n",
glfwGetTime(),
x, y, x - cursor_x, y - cursor_y);
cursor_x = x;
cursor_y = y;
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_A:
{
animate_cursor = !animate_cursor;
if (!animate_cursor)
glfwSetCursor(window, NULL);
break;
}
case GLFW_KEY_ESCAPE:
{
if (glfwGetInputMode(window, GLFW_CURSOR) != GLFW_CURSOR_DISABLED)
{
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
}
/* FALLTHROUGH */
}
case GLFW_KEY_N:
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
glfwGetCursorPos(window, &cursor_x, &cursor_y);
printf("(( cursor is normal ))\n");
break;
case GLFW_KEY_D:
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
printf("(( cursor is disabled ))\n");
break;
case GLFW_KEY_H:
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
printf("(( cursor is hidden ))\n");
break;
case GLFW_KEY_R:
if (!glfwRawMouseMotionSupported())
break;
if (glfwGetInputMode(window, GLFW_RAW_MOUSE_MOTION))
{
glfwSetInputMode(window, GLFW_RAW_MOUSE_MOTION, GLFW_FALSE);
printf("(( raw input is disabled ))\n");
}
else
{
glfwSetInputMode(window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
printf("(( raw input is enabled ))\n");
}
break;
case GLFW_KEY_SPACE:
swap_interval = 1 - swap_interval;
printf("(( swap interval: %i ))\n", swap_interval);
glfwSwapInterval(swap_interval);
break;
case GLFW_KEY_W:
wait_events = !wait_events;
printf("(( %sing for events ))\n", wait_events ? "wait" : "poll");
break;
case GLFW_KEY_T:
track_cursor = !track_cursor;
if (track_cursor)
glfwSetCursor(window, tracking_cursor);
else
glfwSetCursor(window, NULL);
break;
case GLFW_KEY_P:
{
double x, y;
glfwGetCursorPos(window, &x, &y);
printf("Query before set: %f %f (%+f %+f)\n",
x, y, x - cursor_x, y - cursor_y);
cursor_x = x;
cursor_y = y;
glfwSetCursorPos(window, cursor_x, cursor_y);
glfwGetCursorPos(window, &x, &y);
printf("Query after set: %f %f (%+f %+f)\n",
x, y, x - cursor_x, y - cursor_y);
cursor_x = x;
cursor_y = y;
break;
}
case GLFW_KEY_UP:
glfwSetCursorPos(window, 0, 0);
glfwGetCursorPos(window, &cursor_x, &cursor_y);
break;
case GLFW_KEY_DOWN:
{
int width, height;
glfwGetWindowSize(window, &width, &height);
glfwSetCursorPos(window, width - 1, height - 1);
glfwGetCursorPos(window, &cursor_x, &cursor_y);
break;
}
case GLFW_KEY_0:
glfwSetCursor(window, NULL);
break;
case GLFW_KEY_1:
case GLFW_KEY_2:
case GLFW_KEY_3:
case GLFW_KEY_4:
case GLFW_KEY_5:
case GLFW_KEY_6:
case GLFW_KEY_7:
case GLFW_KEY_8:
case GLFW_KEY_9:
{
int index = key - GLFW_KEY_1;
if (mods & GLFW_MOD_SHIFT)
index += 9;
if (index < sizeof(standard_cursors) / sizeof(standard_cursors[0]))
glfwSetCursor(window, standard_cursors[index]);
break;
}
case GLFW_KEY_F11:
case GLFW_KEY_ENTER:
{
static int x, y, width, height;
if (mods != GLFW_MOD_ALT)
return;
if (glfwGetWindowMonitor(window))
glfwSetWindowMonitor(window, NULL, x, y, width, height, 0);
else
{
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwGetWindowPos(window, &x, &y);
glfwGetWindowSize(window, &width, &height);
glfwSetWindowMonitor(window, monitor,
0, 0, mode->width, mode->height,
mode->refreshRate);
}
glfwGetCursorPos(window, &cursor_x, &cursor_y);
break;
}
}
}
int main(void)
{
int i;
GLFWwindow* window;
GLFWcursor* star_cursors[CURSOR_FRAME_COUNT];
GLFWcursor* current_frame = NULL;
GLuint vertex_buffer, vertex_shader, fragment_shader, program;
GLint mvp_location, vpos_location;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
tracking_cursor = create_tracking_cursor();
if (!tracking_cursor)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
for (i = 0; i < CURSOR_FRAME_COUNT; i++)
{
star_cursors[i] = create_cursor_frame(i / (float) CURSOR_FRAME_COUNT);
if (!star_cursors[i])
{
glfwTerminate();
exit(EXIT_FAILURE);
}
}
for (i = 0; i < sizeof(standard_cursors) / sizeof(standard_cursors[0]); i++)
{
const int shapes[] = {
GLFW_ARROW_CURSOR,
GLFW_IBEAM_CURSOR,
GLFW_CROSSHAIR_CURSOR,
GLFW_POINTING_HAND_CURSOR,
GLFW_RESIZE_EW_CURSOR,
GLFW_RESIZE_NS_CURSOR,
GLFW_RESIZE_NWSE_CURSOR,
GLFW_RESIZE_NESW_CURSOR,
GLFW_RESIZE_ALL_CURSOR,
GLFW_NOT_ALLOWED_CURSOR
};
standard_cursors[i] = glfwCreateStandardCursor(shapes[i]);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
window = glfwCreateWindow(640, 480, "Cursor Test", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
glCompileShader(vertex_shader);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
glCompileShader(fragment_shader);
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
mvp_location = glGetUniformLocation(program, "MVP");
vpos_location = glGetAttribLocation(program, "vPos");
glEnableVertexAttribArray(vpos_location);
glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
sizeof(vec2), (void*) 0);
glUseProgram(program);
glfwGetCursorPos(window, &cursor_x, &cursor_y);
printf("Cursor position: %f %f\n", cursor_x, cursor_y);
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwSetKeyCallback(window, key_callback);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
if (track_cursor)
{
int wnd_width, wnd_height, fb_width, fb_height;
float scale;
vec2 vertices[4];
mat4x4 mvp;
glfwGetWindowSize(window, &wnd_width, &wnd_height);
glfwGetFramebufferSize(window, &fb_width, &fb_height);
glViewport(0, 0, fb_width, fb_height);
scale = (float) fb_width / (float) wnd_width;
vertices[0][0] = 0.5f;
vertices[0][1] = (float) (fb_height - floor(cursor_y * scale) - 1.f + 0.5f);
vertices[1][0] = (float) fb_width + 0.5f;
vertices[1][1] = (float) (fb_height - floor(cursor_y * scale) - 1.f + 0.5f);
vertices[2][0] = (float) floor(cursor_x * scale) + 0.5f;
vertices[2][1] = 0.5f;
vertices[3][0] = (float) floor(cursor_x * scale) + 0.5f;
vertices[3][1] = (float) fb_height + 0.5f;
glBufferData(GL_ARRAY_BUFFER,
sizeof(vertices),
vertices,
GL_STREAM_DRAW);
mat4x4_ortho(mvp, 0.f, (float) fb_width, 0.f, (float) fb_height, 0.f, 1.f);
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
glDrawArrays(GL_LINES, 0, 4);
}
glfwSwapBuffers(window);
if (animate_cursor)
{
const int i = (int) (glfwGetTime() * 30.0) % CURSOR_FRAME_COUNT;
if (current_frame != star_cursors[i])
{
glfwSetCursor(window, star_cursors[i]);
current_frame = star_cursors[i];
}
}
else
current_frame = NULL;
if (wait_events)
{
if (animate_cursor)
glfwWaitEventsTimeout(1.0 / 30.0);
else
glfwWaitEvents();
}
else
glfwPollEvents();
// Workaround for an issue with msvcrt and mintty
fflush(stdout);
}
glfwDestroyWindow(window);
for (i = 0; i < CURSOR_FRAME_COUNT; i++)
glfwDestroyCursor(star_cursors[i]);
for (i = 0; i < sizeof(standard_cursors) / sizeof(standard_cursors[0]); i++)
glfwDestroyCursor(standard_cursors[i]);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/gamma.c | .c | 5,607 | 181 | //========================================================================
// Gamma correction test program
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This program is used to test the gamma correction functionality for
// both full screen and windowed mode windows
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#define NK_IMPLEMENTATION
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_BUTTON_TRIGGER_ON_RELEASE
#include <nuklear.h>
#define NK_GLFW_GL2_IMPLEMENTATION
#include <nuklear_glfw_gl2.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action == GLFW_PRESS && key == GLFW_KEY_ESCAPE)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
static void chart_ramp_array(struct nk_context* nk,
struct nk_color color,
int count, unsigned short int* values)
{
if (nk_chart_begin_colored(nk, NK_CHART_LINES,
color, nk_rgb(255, 255, 255),
count, 0, 65535))
{
int i;
for (i = 0; i < count; i++)
{
char buffer[1024];
if (nk_chart_push(nk, values[i]))
{
snprintf(buffer, sizeof(buffer), "#%u: %u (%0.5f) ",
i, values[i], values[i] / 65535.f);
nk_tooltip(nk, buffer);
}
}
nk_chart_end(nk);
}
}
int main(int argc, char** argv)
{
GLFWmonitor* monitor = NULL;
GLFWwindow* window;
GLFWgammaramp orig_ramp;
struct nk_context* nk;
struct nk_font_atlas* atlas;
float gamma_value = 1.f;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
monitor = glfwGetPrimaryMonitor();
glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE);
glfwWindowHint(GLFW_WIN32_KEYBOARD_MENU, GLFW_TRUE);
window = glfwCreateWindow(800, 400, "Gamma Test", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
{
const GLFWgammaramp* ramp = glfwGetGammaRamp(monitor);
const size_t array_size = ramp->size * sizeof(short);
orig_ramp.size = ramp->size;
orig_ramp.red = malloc(array_size);
orig_ramp.green = malloc(array_size);
orig_ramp.blue = malloc(array_size);
memcpy(orig_ramp.red, ramp->red, array_size);
memcpy(orig_ramp.green, ramp->green, array_size);
memcpy(orig_ramp.blue, ramp->blue, array_size);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
nk = nk_glfw3_init(window, NK_GLFW3_INSTALL_CALLBACKS);
nk_glfw3_font_stash_begin(&atlas);
nk_glfw3_font_stash_end();
glfwSetKeyCallback(window, key_callback);
while (!glfwWindowShouldClose(window))
{
int width, height;
struct nk_rect area;
glfwGetWindowSize(window, &width, &height);
area = nk_rect(0.f, 0.f, (float) width, (float) height);
nk_window_set_bounds(nk, "", area);
glClear(GL_COLOR_BUFFER_BIT);
nk_glfw3_new_frame();
if (nk_begin(nk, "", area, 0))
{
const GLFWgammaramp* ramp;
nk_layout_row_dynamic(nk, 30, 3);
if (nk_slider_float(nk, 0.1f, &gamma_value, 5.f, 0.1f))
glfwSetGamma(monitor, gamma_value);
nk_labelf(nk, NK_TEXT_LEFT, "%0.1f", gamma_value);
if (nk_button_label(nk, "Revert"))
glfwSetGammaRamp(monitor, &orig_ramp);
ramp = glfwGetGammaRamp(monitor);
nk_layout_row_dynamic(nk, height - 60.f, 3);
chart_ramp_array(nk, nk_rgb(255, 0, 0), ramp->size, ramp->red);
chart_ramp_array(nk, nk_rgb(0, 255, 0), ramp->size, ramp->green);
chart_ramp_array(nk, nk_rgb(0, 0, 255), ramp->size, ramp->blue);
}
nk_end(nk);
nk_glfw3_render(NK_ANTI_ALIASING_ON);
glfwSwapBuffers(window);
glfwWaitEventsTimeout(1.0);
}
free(orig_ramp.red);
free(orig_ramp.green);
free(orig_ramp.blue);
nk_glfw3_shutdown();
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/icon.c | .c | 3,888 | 150 | //========================================================================
// Window icon test program
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This program is used to test the icon feature.
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// a simple glfw logo
const char* const logo[] =
{
"................",
"................",
"...0000..0......",
"...0.....0......",
"...0.00..0......",
"...0..0..0......",
"...0000..0000...",
"................",
"................",
"...000..0...0...",
"...0....0...0...",
"...000..0.0.0...",
"...0....0.0.0...",
"...0....00000...",
"................",
"................"
};
const unsigned char icon_colors[5][4] =
{
{ 0, 0, 0, 255 }, // black
{ 255, 0, 0, 255 }, // red
{ 0, 255, 0, 255 }, // green
{ 0, 0, 255, 255 }, // blue
{ 255, 255, 255, 255 } // white
};
static int cur_icon_color = 0;
static void set_icon(GLFWwindow* window, int icon_color)
{
int x, y;
unsigned char pixels[16 * 16 * 4];
unsigned char* target = pixels;
GLFWimage img = { 16, 16, pixels };
for (y = 0; y < img.width; y++)
{
for (x = 0; x < img.height; x++)
{
if (logo[y][x] == '0')
memcpy(target, icon_colors[icon_color], 4);
else
memset(target, 0, 4);
target += 4;
}
}
glfwSetWindowIcon(window, 1, &img);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
case GLFW_KEY_SPACE:
cur_icon_color = (cur_icon_color + 1) % 5;
set_icon(window, cur_icon_color);
break;
case GLFW_KEY_X:
glfwSetWindowIcon(window, 0, NULL);
break;
}
}
int main(int argc, char** argv)
{
GLFWwindow* window;
if (!glfwInit())
{
fprintf(stderr, "Failed to initialize GLFW\n");
exit(EXIT_FAILURE);
}
window = glfwCreateWindow(200, 200, "Window Icon", NULL, NULL);
if (!window)
{
glfwTerminate();
fprintf(stderr, "Failed to open GLFW window\n");
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSetKeyCallback(window, key_callback);
set_icon(window, cur_icon_color);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwWaitEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/window.c | .c | 17,238 | 418 | //========================================================================
// Window properties test
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdarg.h>
#define NK_IMPLEMENTATION
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_BUTTON_TRIGGER_ON_RELEASE
#include <nuklear.h>
#define NK_GLFW_GL2_IMPLEMENTATION
#include <nuklear_glfw_gl2.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(int argc, char** argv)
{
int windowed_x, windowed_y, windowed_width, windowed_height;
int last_xpos = INT_MIN, last_ypos = INT_MIN;
int last_width = INT_MIN, last_height = INT_MIN;
int limit_aspect_ratio = false, aspect_numer = 1, aspect_denom = 1;
int limit_min_size = false, min_width = 400, min_height = 400;
int limit_max_size = false, max_width = 400, max_height = 400;
char width_buffer[10] = "", height_buffer[10] = "";
char xpos_buffer[10] = "", ypos_buffer[10] = "";
char numer_buffer[10] = "", denom_buffer[10] = "";
char min_width_buffer[10] = "", min_height_buffer[10] = "";
char max_width_buffer[10] = "", max_height_buffer[10] = "";
int may_close = true;
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE);
glfwWindowHint(GLFW_WIN32_KEYBOARD_MENU, GLFW_TRUE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
GLFWwindow* window = glfwCreateWindow(600, 600, "Window Features", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(0);
bool position_supported = true;
glfwGetError(NULL);
glfwGetWindowPos(window, &last_xpos, &last_ypos);
sprintf(xpos_buffer, "%i", last_xpos);
sprintf(ypos_buffer, "%i", last_ypos);
if (glfwGetError(NULL) == GLFW_FEATURE_UNAVAILABLE)
position_supported = false;
glfwGetWindowSize(window, &last_width, &last_height);
sprintf(width_buffer, "%i", last_width);
sprintf(height_buffer, "%i", last_height);
sprintf(numer_buffer, "%i", aspect_numer);
sprintf(denom_buffer, "%i", aspect_denom);
sprintf(min_width_buffer, "%i", min_width);
sprintf(min_height_buffer, "%i", min_height);
sprintf(max_width_buffer, "%i", max_width);
sprintf(max_height_buffer, "%i", max_height);
struct nk_context* nk = nk_glfw3_init(window, NK_GLFW3_INSTALL_CALLBACKS);
struct nk_font_atlas* atlas;
nk_glfw3_font_stash_begin(&atlas);
nk_glfw3_font_stash_end();
while (!(may_close && glfwWindowShouldClose(window)))
{
int width, height;
glfwGetWindowSize(window, &width, &height);
struct nk_rect area = nk_rect(0.f, 0.f, (float) width, (float) height);
nk_window_set_bounds(nk, "main", area);
nk_glfw3_new_frame();
if (nk_begin(nk, "main", area, 0))
{
nk_layout_row_dynamic(nk, 30, 4);
if (nk_button_label(nk, "Toggle Fullscreen"))
{
if (glfwGetWindowMonitor(window))
{
glfwSetWindowMonitor(window, NULL,
windowed_x, windowed_y,
windowed_width, windowed_height, 0);
}
else
{
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwGetWindowPos(window, &windowed_x, &windowed_y);
glfwGetWindowSize(window, &windowed_width, &windowed_height);
glfwSetWindowMonitor(window, monitor,
0, 0, mode->width, mode->height,
mode->refreshRate);
}
}
if (nk_button_label(nk, "Maximize"))
glfwMaximizeWindow(window);
if (nk_button_label(nk, "Iconify"))
glfwIconifyWindow(window);
if (nk_button_label(nk, "Restore"))
glfwRestoreWindow(window);
nk_layout_row_dynamic(nk, 30, 1);
if (glfwGetWindowAttrib(window, GLFW_MOUSE_PASSTHROUGH))
{
nk_label(nk, "Press H to disable mouse passthrough", NK_TEXT_CENTERED);
if (glfwGetKey(window, GLFW_KEY_H))
glfwSetWindowAttrib(window, GLFW_MOUSE_PASSTHROUGH, false);
}
nk_label(nk, "Press Enter in a text field to set value", NK_TEXT_CENTERED);
nk_flags events;
const nk_flags flags = NK_EDIT_FIELD |
NK_EDIT_SIG_ENTER |
NK_EDIT_GOTO_END_ON_ACTIVATE;
if (position_supported)
{
int xpos, ypos;
glfwGetWindowPos(window, &xpos, &ypos);
nk_layout_row_dynamic(nk, 30, 3);
nk_label(nk, "Position", NK_TEXT_LEFT);
events = nk_edit_string_zero_terminated(nk, flags, xpos_buffer,
sizeof(xpos_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
xpos = atoi(xpos_buffer);
glfwSetWindowPos(window, xpos, ypos);
}
else if (xpos != last_xpos || (events & NK_EDIT_DEACTIVATED))
sprintf(xpos_buffer, "%i", xpos);
events = nk_edit_string_zero_terminated(nk, flags, ypos_buffer,
sizeof(ypos_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
ypos = atoi(ypos_buffer);
glfwSetWindowPos(window, xpos, ypos);
}
else if (ypos != last_ypos || (events & NK_EDIT_DEACTIVATED))
sprintf(ypos_buffer, "%i", ypos);
last_xpos = xpos;
last_ypos = ypos;
}
else
nk_label(nk, "Position not supported", NK_TEXT_LEFT);
nk_layout_row_dynamic(nk, 30, 3);
nk_label(nk, "Size", NK_TEXT_LEFT);
events = nk_edit_string_zero_terminated(nk, flags, width_buffer,
sizeof(width_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
width = atoi(width_buffer);
glfwSetWindowSize(window, width, height);
}
else if (width != last_width || (events & NK_EDIT_DEACTIVATED))
sprintf(width_buffer, "%i", width);
events = nk_edit_string_zero_terminated(nk, flags, height_buffer,
sizeof(height_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
height = atoi(height_buffer);
glfwSetWindowSize(window, width, height);
}
else if (height != last_height || (events & NK_EDIT_DEACTIVATED))
sprintf(height_buffer, "%i", height);
last_width = width;
last_height = height;
bool update_ratio_limit = false;
if (nk_checkbox_label(nk, "Aspect Ratio", &limit_aspect_ratio))
update_ratio_limit = true;
events = nk_edit_string_zero_terminated(nk, flags, numer_buffer,
sizeof(numer_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
aspect_numer = abs(atoi(numer_buffer));
update_ratio_limit = true;
}
else if (events & NK_EDIT_DEACTIVATED)
sprintf(numer_buffer, "%i", aspect_numer);
events = nk_edit_string_zero_terminated(nk, flags, denom_buffer,
sizeof(denom_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
aspect_denom = abs(atoi(denom_buffer));
update_ratio_limit = true;
}
else if (events & NK_EDIT_DEACTIVATED)
sprintf(denom_buffer, "%i", aspect_denom);
if (update_ratio_limit)
{
if (limit_aspect_ratio)
glfwSetWindowAspectRatio(window, aspect_numer, aspect_denom);
else
glfwSetWindowAspectRatio(window, GLFW_DONT_CARE, GLFW_DONT_CARE);
}
bool update_size_limit = false;
if (nk_checkbox_label(nk, "Minimum Size", &limit_min_size))
update_size_limit = true;
events = nk_edit_string_zero_terminated(nk, flags, min_width_buffer,
sizeof(min_width_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
min_width = abs(atoi(min_width_buffer));
update_size_limit = true;
}
else if (events & NK_EDIT_DEACTIVATED)
sprintf(min_width_buffer, "%i", min_width);
events = nk_edit_string_zero_terminated(nk, flags, min_height_buffer,
sizeof(min_height_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
min_height = abs(atoi(min_height_buffer));
update_size_limit = true;
}
else if (events & NK_EDIT_DEACTIVATED)
sprintf(min_height_buffer, "%i", min_height);
if (nk_checkbox_label(nk, "Maximum Size", &limit_max_size))
update_size_limit = true;
events = nk_edit_string_zero_terminated(nk, flags, max_width_buffer,
sizeof(max_width_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
max_width = abs(atoi(max_width_buffer));
update_size_limit = true;
}
else if (events & NK_EDIT_DEACTIVATED)
sprintf(max_width_buffer, "%i", max_width);
events = nk_edit_string_zero_terminated(nk, flags, max_height_buffer,
sizeof(max_height_buffer),
nk_filter_decimal);
if (events & NK_EDIT_COMMITED)
{
max_height = abs(atoi(max_height_buffer));
update_size_limit = true;
}
else if (events & NK_EDIT_DEACTIVATED)
sprintf(max_height_buffer, "%i", max_height);
if (update_size_limit)
{
glfwSetWindowSizeLimits(window,
limit_min_size ? min_width : GLFW_DONT_CARE,
limit_min_size ? min_height : GLFW_DONT_CARE,
limit_max_size ? max_width : GLFW_DONT_CARE,
limit_max_size ? max_height : GLFW_DONT_CARE);
}
int fb_width, fb_height;
glfwGetFramebufferSize(window, &fb_width, &fb_height);
nk_label(nk, "Framebuffer Size", NK_TEXT_LEFT);
nk_labelf(nk, NK_TEXT_LEFT, "%i", fb_width);
nk_labelf(nk, NK_TEXT_LEFT, "%i", fb_height);
float xscale, yscale;
glfwGetWindowContentScale(window, &xscale, &yscale);
nk_label(nk, "Content Scale", NK_TEXT_LEFT);
nk_labelf(nk, NK_TEXT_LEFT, "%f", xscale);
nk_labelf(nk, NK_TEXT_LEFT, "%f", yscale);
nk_layout_row_begin(nk, NK_DYNAMIC, 30, 5);
int frame_left, frame_top, frame_right, frame_bottom;
glfwGetWindowFrameSize(window, &frame_left, &frame_top, &frame_right, &frame_bottom);
nk_layout_row_push(nk, 1.f / 3.f);
nk_label(nk, "Frame Size:", NK_TEXT_LEFT);
nk_layout_row_push(nk, 1.f / 6.f);
nk_labelf(nk, NK_TEXT_LEFT, "%i", frame_left);
nk_layout_row_push(nk, 1.f / 6.f);
nk_labelf(nk, NK_TEXT_LEFT, "%i", frame_top);
nk_layout_row_push(nk, 1.f / 6.f);
nk_labelf(nk, NK_TEXT_LEFT, "%i", frame_right);
nk_layout_row_push(nk, 1.f / 6.f);
nk_labelf(nk, NK_TEXT_LEFT, "%i", frame_bottom);
nk_layout_row_end(nk);
nk_layout_row_begin(nk, NK_DYNAMIC, 30, 2);
float opacity = glfwGetWindowOpacity(window);
nk_layout_row_push(nk, 1.f / 3.f);
nk_labelf(nk, NK_TEXT_LEFT, "Opacity: %0.3f", opacity);
nk_layout_row_push(nk, 2.f / 3.f);
if (nk_slider_float(nk, 0.f, &opacity, 1.f, 0.001f))
glfwSetWindowOpacity(window, opacity);
nk_layout_row_end(nk);
nk_layout_row_begin(nk, NK_DYNAMIC, 30, 2);
int should_close = glfwWindowShouldClose(window);
nk_layout_row_push(nk, 1.f / 3.f);
if (nk_checkbox_label(nk, "Should Close", &should_close))
glfwSetWindowShouldClose(window, should_close);
nk_layout_row_push(nk, 2.f / 3.f);
nk_checkbox_label(nk, "May Close", &may_close);
nk_layout_row_end(nk);
nk_layout_row_dynamic(nk, 30, 1);
nk_label(nk, "Attributes", NK_TEXT_CENTERED);
nk_layout_row_dynamic(nk, 30, width > 200 ? width / 200 : 1);
int decorated = glfwGetWindowAttrib(window, GLFW_DECORATED);
if (nk_checkbox_label(nk, "Decorated", &decorated))
glfwSetWindowAttrib(window, GLFW_DECORATED, decorated);
int resizable = glfwGetWindowAttrib(window, GLFW_RESIZABLE);
if (nk_checkbox_label(nk, "Resizable", &resizable))
glfwSetWindowAttrib(window, GLFW_RESIZABLE, resizable);
int floating = glfwGetWindowAttrib(window, GLFW_FLOATING);
if (nk_checkbox_label(nk, "Floating", &floating))
glfwSetWindowAttrib(window, GLFW_FLOATING, floating);
int passthrough = glfwGetWindowAttrib(window, GLFW_MOUSE_PASSTHROUGH);
if (nk_checkbox_label(nk, "Mouse Passthrough", &passthrough))
glfwSetWindowAttrib(window, GLFW_MOUSE_PASSTHROUGH, passthrough);
int auto_iconify = glfwGetWindowAttrib(window, GLFW_AUTO_ICONIFY);
if (nk_checkbox_label(nk, "Auto Iconify", &auto_iconify))
glfwSetWindowAttrib(window, GLFW_AUTO_ICONIFY, auto_iconify);
nk_value_bool(nk, "Focused", glfwGetWindowAttrib(window, GLFW_FOCUSED));
nk_value_bool(nk, "Hovered", glfwGetWindowAttrib(window, GLFW_HOVERED));
nk_value_bool(nk, "Visible", glfwGetWindowAttrib(window, GLFW_VISIBLE));
nk_value_bool(nk, "Iconified", glfwGetWindowAttrib(window, GLFW_ICONIFIED));
nk_value_bool(nk, "Maximized", glfwGetWindowAttrib(window, GLFW_MAXIMIZED));
}
nk_end(nk);
glClear(GL_COLOR_BUFFER_BIT);
nk_glfw3_render(NK_ANTI_ALIASING_ON);
glfwSwapBuffers(window);
glfwWaitEvents();
}
nk_glfw3_shutdown();
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/timeout.c | .c | 2,797 | 99 | //========================================================================
// Event wait timeout test
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test is intended to verify that waiting for events with timeout works
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
static float nrand(void)
{
return (float) rand() / (float) RAND_MAX;
}
int main(void)
{
GLFWwindow* window;
srand((unsigned int) time(NULL));
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
window = glfwCreateWindow(640, 480, "Event Wait Timeout Test", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSetKeyCallback(window, key_callback);
while (!glfwWindowShouldClose(window))
{
int width, height;
float r = nrand(), g = nrand(), b = nrand();
float l = (float) sqrt(r * r + g * g + b * b);
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClearColor(r / l, g / l, b / l, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwWaitEventsTimeout(1.0);
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/empty.c | .c | 3,411 | 133 | //========================================================================
// Empty event test
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test is intended to verify that posting of empty events works
//
//========================================================================
#include "tinycthread.h"
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
static volatile int running = GLFW_TRUE;
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static int thread_main(void* data)
{
struct timespec time;
while (running)
{
clock_gettime(CLOCK_REALTIME, &time);
time.tv_sec += 1;
thrd_sleep(&time, NULL);
glfwPostEmptyEvent();
}
return 0;
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
static float nrand(void)
{
return (float) rand() / (float) RAND_MAX;
}
int main(void)
{
int result;
thrd_t thread;
GLFWwindow* window;
srand((unsigned int) time(NULL));
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
window = glfwCreateWindow(640, 480, "Empty Event Test", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSetKeyCallback(window, key_callback);
if (thrd_create(&thread, thread_main, NULL) != thrd_success)
{
fprintf(stderr, "Failed to create secondary thread\n");
glfwTerminate();
exit(EXIT_FAILURE);
}
while (running)
{
int width, height;
float r = nrand(), g = nrand(), b = nrand();
float l = (float) sqrt(r * r + g * g + b * b);
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClearColor(r / l, g / l, b / l, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwWaitEvents();
if (glfwWindowShouldClose(window))
running = GLFW_FALSE;
}
glfwHideWindow(window);
thrd_join(thread, &result);
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/joysticks.c | .c | 10,821 | 346 | //========================================================================
// Joystick input test
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test displays the state of every button and axis of every connected
// joystick and/or gamepad
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#define NK_IMPLEMENTATION
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_BUTTON_TRIGGER_ON_RELEASE
#include <nuklear.h>
#define NK_GLFW_GL2_IMPLEMENTATION
#include <nuklear_glfw_gl2.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef _MSC_VER
#define strdup(x) _strdup(x)
#endif
static GLFWwindow* window;
static int joysticks[GLFW_JOYSTICK_LAST + 1];
static int joystick_count = 0;
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void joystick_callback(int jid, int event)
{
if (event == GLFW_CONNECTED)
joysticks[joystick_count++] = jid;
else if (event == GLFW_DISCONNECTED)
{
int i;
for (i = 0; i < joystick_count; i++)
{
if (joysticks[i] == jid)
break;
}
for (i = i + 1; i < joystick_count; i++)
joysticks[i - 1] = joysticks[i];
joystick_count--;
}
if (!glfwGetWindowAttrib(window, GLFW_FOCUSED))
glfwRequestWindowAttention(window);
}
static void drop_callback(GLFWwindow* window, int count, const char* paths[])
{
int i;
for (i = 0; i < count; i++)
{
long size;
char* text;
FILE* stream = fopen(paths[i], "rb");
if (!stream)
continue;
fseek(stream, 0, SEEK_END);
size = ftell(stream);
fseek(stream, 0, SEEK_SET);
text = malloc(size + 1);
text[size] = '\0';
if (fread(text, 1, size, stream) == size)
glfwUpdateGamepadMappings(text);
free(text);
fclose(stream);
}
}
static const char* joystick_label(int jid)
{
static char label[1024];
snprintf(label, sizeof(label), "%i: %s", jid + 1, glfwGetJoystickName(jid));
return label;
}
static void hat_widget(struct nk_context* nk, unsigned char state)
{
float radius;
struct nk_rect area;
struct nk_vec2 center;
if (nk_widget(&area, nk) == NK_WIDGET_INVALID)
return;
center = nk_vec2(area.x + area.w / 2.f, area.y + area.h / 2.f);
radius = NK_MIN(area.w, area.h) / 2.f;
nk_stroke_circle(nk_window_get_canvas(nk),
nk_rect(center.x - radius,
center.y - radius,
radius * 2.f,
radius * 2.f),
1.f,
nk_rgb(175, 175, 175));
if (state)
{
const float angles[] =
{
0.f, 0.f,
NK_PI * 1.5f, NK_PI * 1.75f,
NK_PI, 0.f,
NK_PI * 1.25f, 0.f,
NK_PI * 0.5f, NK_PI * 0.25f,
0.f, 0.f,
NK_PI * 0.75f, 0.f,
};
const float cosa = nk_cos(angles[state]);
const float sina = nk_sin(angles[state]);
const struct nk_vec2 p0 = nk_vec2(0.f, -radius);
const struct nk_vec2 p1 = nk_vec2( radius / 2.f, -radius / 3.f);
const struct nk_vec2 p2 = nk_vec2(-radius / 2.f, -radius / 3.f);
nk_fill_triangle(nk_window_get_canvas(nk),
center.x + cosa * p0.x + sina * p0.y,
center.y + cosa * p0.y - sina * p0.x,
center.x + cosa * p1.x + sina * p1.y,
center.y + cosa * p1.y - sina * p1.x,
center.x + cosa * p2.x + sina * p2.y,
center.y + cosa * p2.y - sina * p2.x,
nk_rgb(175, 175, 175));
}
}
int main(void)
{
int jid, hat_buttons = GLFW_FALSE;
struct nk_context* nk;
struct nk_font_atlas* atlas;
memset(joysticks, 0, sizeof(joysticks));
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE);
glfwWindowHint(GLFW_WIN32_KEYBOARD_MENU, GLFW_TRUE);
window = glfwCreateWindow(800, 600, "Joystick Test", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
nk = nk_glfw3_init(window, NK_GLFW3_INSTALL_CALLBACKS);
nk_glfw3_font_stash_begin(&atlas);
nk_glfw3_font_stash_end();
for (jid = GLFW_JOYSTICK_1; jid <= GLFW_JOYSTICK_LAST; jid++)
{
if (glfwJoystickPresent(jid))
joysticks[joystick_count++] = jid;
}
glfwSetJoystickCallback(joystick_callback);
glfwSetDropCallback(window, drop_callback);
while (!glfwWindowShouldClose(window))
{
int i, width, height;
glfwGetWindowSize(window, &width, &height);
glClear(GL_COLOR_BUFFER_BIT);
nk_glfw3_new_frame();
if (nk_begin(nk,
"Joysticks",
nk_rect(width - 200.f, 0.f, 200.f, (float) height),
NK_WINDOW_MINIMIZABLE |
NK_WINDOW_TITLE))
{
nk_layout_row_dynamic(nk, 30, 1);
nk_checkbox_label(nk, "Hat buttons", &hat_buttons);
if (joystick_count)
{
for (i = 0; i < joystick_count; i++)
{
if (nk_button_label(nk, joystick_label(joysticks[i])))
nk_window_set_focus(nk, joystick_label(joysticks[i]));
}
}
else
nk_label(nk, "No joysticks connected", NK_TEXT_LEFT);
}
nk_end(nk);
for (i = 0; i < joystick_count; i++)
{
if (nk_begin(nk,
joystick_label(joysticks[i]),
nk_rect(i * 20.f, i * 20.f, 550.f, 570.f),
NK_WINDOW_BORDER |
NK_WINDOW_MOVABLE |
NK_WINDOW_SCALABLE |
NK_WINDOW_MINIMIZABLE |
NK_WINDOW_TITLE))
{
int j, axis_count, button_count, hat_count;
const float* axes;
const unsigned char* buttons;
const unsigned char* hats;
GLFWgamepadstate state;
nk_layout_row_dynamic(nk, 30, 1);
nk_labelf(nk, NK_TEXT_LEFT, "Hardware GUID %s",
glfwGetJoystickGUID(joysticks[i]));
nk_label(nk, "Joystick state", NK_TEXT_LEFT);
axes = glfwGetJoystickAxes(joysticks[i], &axis_count);
buttons = glfwGetJoystickButtons(joysticks[i], &button_count);
hats = glfwGetJoystickHats(joysticks[i], &hat_count);
if (!hat_buttons)
button_count -= hat_count * 4;
for (j = 0; j < axis_count; j++)
nk_slide_float(nk, -1.f, axes[j], 1.f, 0.1f);
nk_layout_row_dynamic(nk, 30, 12);
for (j = 0; j < button_count; j++)
{
char name[16];
snprintf(name, sizeof(name), "%i", j + 1);
nk_select_label(nk, name, NK_TEXT_CENTERED, buttons[j]);
}
nk_layout_row_dynamic(nk, 30, 8);
for (j = 0; j < hat_count; j++)
hat_widget(nk, hats[j]);
nk_layout_row_dynamic(nk, 30, 1);
if (glfwGetGamepadState(joysticks[i], &state))
{
int hat = 0;
const char* names[GLFW_GAMEPAD_BUTTON_LAST + 1 - 4] =
{
"A", "B", "X", "Y",
"LB", "RB",
"Back", "Start", "Guide",
"LT", "RT",
};
nk_labelf(nk, NK_TEXT_LEFT,
"Gamepad state: %s",
glfwGetGamepadName(joysticks[i]));
nk_layout_row_dynamic(nk, 30, 2);
for (j = 0; j <= GLFW_GAMEPAD_AXIS_LAST; j++)
nk_slide_float(nk, -1.f, state.axes[j], 1.f, 0.1f);
nk_layout_row_dynamic(nk, 30, GLFW_GAMEPAD_BUTTON_LAST + 1 - 4);
for (j = 0; j <= GLFW_GAMEPAD_BUTTON_LAST - 4; j++)
nk_select_label(nk, names[j], NK_TEXT_CENTERED, state.buttons[j]);
if (state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_UP])
hat |= GLFW_HAT_UP;
if (state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_RIGHT])
hat |= GLFW_HAT_RIGHT;
if (state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_DOWN])
hat |= GLFW_HAT_DOWN;
if (state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_LEFT])
hat |= GLFW_HAT_LEFT;
nk_layout_row_dynamic(nk, 30, 8);
hat_widget(nk, hat);
}
else
nk_label(nk, "Joystick has no gamepad mapping", NK_TEXT_LEFT);
}
nk_end(nk);
}
nk_glfw3_render(NK_ANTI_ALIASING_ON);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/title.c | .c | 2,081 | 73 | //========================================================================
// UTF-8 window title test
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test sets a UTF-8 window title
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
int main(void)
{
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
window = glfwCreateWindow(400, 400, "English 日本語 русский язык 官話", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwWaitEvents();
}
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/inputlag.c | .c | 9,202 | 310 | //========================================================================
// Input lag test
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test renders a marker at the cursor position reported by GLFW to
// check how much it lags behind the hardware mouse cursor
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#define NK_IMPLEMENTATION
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_STANDARD_VARARGS
#include <nuklear.h>
#define NK_GLFW_GL2_IMPLEMENTATION
#include <nuklear_glfw_gl2.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "getopt.h"
void usage(void)
{
printf("Usage: inputlag [-h] [-f]\n");
printf("Options:\n");
printf(" -f create full screen window\n");
printf(" -h show this help\n");
}
struct nk_vec2 cursor_new, cursor_pos, cursor_vel;
enum { cursor_sync_query, cursor_input_message } cursor_method = cursor_sync_query;
void sample_input(GLFWwindow* window)
{
float a = .25; // exponential smoothing factor
if (cursor_method == cursor_sync_query) {
double x, y;
glfwGetCursorPos(window, &x, &y);
cursor_new.x = (float) x;
cursor_new.y = (float) y;
}
cursor_vel.x = (cursor_new.x - cursor_pos.x) * a + cursor_vel.x * (1 - a);
cursor_vel.y = (cursor_new.y - cursor_pos.y) * a + cursor_vel.y * (1 - a);
cursor_pos = cursor_new;
}
void cursor_pos_callback(GLFWwindow* window, double xpos, double ypos)
{
cursor_new.x = (float) xpos;
cursor_new.y = (float) ypos;
}
int enable_vsync = nk_true;
void update_vsync()
{
glfwSwapInterval(enable_vsync == nk_true ? 1 : 0);
}
int swap_clear = nk_false;
int swap_finish = nk_true;
int swap_occlusion_query = nk_false;
int swap_read_pixels = nk_false;
GLuint occlusion_query;
void swap_buffers(GLFWwindow* window)
{
glfwSwapBuffers(window);
if (swap_clear)
glClear(GL_COLOR_BUFFER_BIT);
if (swap_finish)
glFinish();
if (swap_occlusion_query) {
GLint occlusion_result;
if (!occlusion_query)
glGenQueries(1, &occlusion_query);
glBeginQuery(GL_SAMPLES_PASSED, occlusion_query);
glBegin(GL_POINTS);
glVertex2f(0, 0);
glEnd();
glEndQuery(GL_SAMPLES_PASSED);
glGetQueryObjectiv(occlusion_query, GL_QUERY_RESULT, &occlusion_result);
}
if (swap_read_pixels) {
unsigned char rgba[4];
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, rgba);
}
}
void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, 1);
break;
}
}
void draw_marker(struct nk_command_buffer* canvas, int lead, struct nk_vec2 pos)
{
struct nk_color colors[4] = { nk_rgb(255,0,0), nk_rgb(255,255,0), nk_rgb(0,255,0), nk_rgb(0,96,255) };
struct nk_rect rect = { -5 + pos.x, -5 + pos.y, 10, 10 };
nk_fill_circle(canvas, rect, colors[lead]);
}
int main(int argc, char** argv)
{
int ch, width, height;
unsigned long frame_count = 0;
double last_time, current_time;
double frame_rate = 0;
int fullscreen = GLFW_FALSE;
GLFWmonitor* monitor = NULL;
GLFWwindow* window;
struct nk_context* nk;
struct nk_font_atlas* atlas;
int show_forecasts = nk_true;
while ((ch = getopt(argc, argv, "fh")) != -1)
{
switch (ch)
{
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'f':
fullscreen = GLFW_TRUE;
break;
}
}
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
if (fullscreen)
{
const GLFWvidmode* mode;
monitor = glfwGetPrimaryMonitor();
mode = glfwGetVideoMode(monitor);
width = mode->width;
height = mode->height;
}
else
{
width = 640;
height = 480;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE);
glfwWindowHint(GLFW_WIN32_KEYBOARD_MENU, GLFW_TRUE);
window = glfwCreateWindow(width, height, "Input lag test", monitor, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
update_vsync();
last_time = glfwGetTime();
nk = nk_glfw3_init(window, NK_GLFW3_INSTALL_CALLBACKS);
nk_glfw3_font_stash_begin(&atlas);
nk_glfw3_font_stash_end();
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, cursor_pos_callback);
while (!glfwWindowShouldClose(window))
{
int width, height;
struct nk_rect area;
glfwPollEvents();
sample_input(window);
glfwGetWindowSize(window, &width, &height);
area = nk_rect(0.f, 0.f, (float) width, (float) height);
glClear(GL_COLOR_BUFFER_BIT);
nk_glfw3_new_frame();
if (nk_begin(nk, "", area, 0))
{
nk_flags align_left = NK_TEXT_ALIGN_LEFT | NK_TEXT_ALIGN_MIDDLE;
struct nk_command_buffer *canvas = nk_window_get_canvas(nk);
int lead;
for (lead = show_forecasts ? 3 : 0; lead >= 0; lead--)
draw_marker(canvas, lead, nk_vec2(cursor_pos.x + cursor_vel.x * lead,
cursor_pos.y + cursor_vel.y * lead));
// print instructions
nk_layout_row_dynamic(nk, 20, 1);
nk_label(nk, "Move mouse uniformly and check marker under cursor:", align_left);
for (lead = 0; lead <= 3; lead++) {
nk_layout_row_begin(nk, NK_STATIC, 12, 2);
nk_layout_row_push(nk, 25);
draw_marker(canvas, lead, nk_layout_space_to_screen(nk, nk_vec2(20, 5)));
nk_label(nk, "", 0);
nk_layout_row_push(nk, 500);
if (lead == 0)
nk_label(nk, "- current cursor position (no input lag)", align_left);
else
nk_labelf(nk, align_left, "- %d-frame forecast (input lag is %d frame)", lead, lead);
nk_layout_row_end(nk);
}
nk_layout_row_dynamic(nk, 20, 1);
nk_checkbox_label(nk, "Show forecasts", &show_forecasts);
nk_label(nk, "Input method:", align_left);
if (nk_option_label(nk, "glfwGetCursorPos (sync query)", cursor_method == cursor_sync_query))
cursor_method = cursor_sync_query;
if (nk_option_label(nk, "glfwSetCursorPosCallback (latest input message)", cursor_method == cursor_input_message))
cursor_method = cursor_input_message;
nk_label(nk, "", 0); // separator
nk_value_float(nk, "FPS", (float) frame_rate);
if (nk_checkbox_label(nk, "Enable vsync", &enable_vsync))
update_vsync();
nk_label(nk, "", 0); // separator
nk_label(nk, "After swap:", align_left);
nk_checkbox_label(nk, "glClear", &swap_clear);
nk_checkbox_label(nk, "glFinish", &swap_finish);
nk_checkbox_label(nk, "draw with occlusion query", &swap_occlusion_query);
nk_checkbox_label(nk, "glReadPixels", &swap_read_pixels);
}
nk_end(nk);
nk_glfw3_render(NK_ANTI_ALIASING_ON);
swap_buffers(window);
frame_count++;
current_time = glfwGetTime();
if (current_time - last_time > 1.0)
{
frame_rate = frame_count / (current_time - last_time);
frame_count = 0;
last_time = current_time;
}
}
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/glfwinfo.c | .c | 35,933 | 987 | //========================================================================
// Context creation and information tool
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <glad/gl.h>
#include <glad/vulkan.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "getopt.h"
#ifdef _MSC_VER
#define strcasecmp(x, y) _stricmp(x, y)
#endif
#define API_NAME_OPENGL "gl"
#define API_NAME_OPENGL_ES "es"
#define API_NAME_NATIVE "native"
#define API_NAME_EGL "egl"
#define API_NAME_OSMESA "osmesa"
#define PROFILE_NAME_CORE "core"
#define PROFILE_NAME_COMPAT "compat"
#define STRATEGY_NAME_NONE "none"
#define STRATEGY_NAME_LOSE "lose"
#define BEHAVIOR_NAME_NONE "none"
#define BEHAVIOR_NAME_FLUSH "flush"
#define ANGLE_TYPE_OPENGL "gl"
#define ANGLE_TYPE_OPENGLES "es"
#define ANGLE_TYPE_D3D9 "d3d9"
#define ANGLE_TYPE_D3D11 "d3d11"
#define ANGLE_TYPE_VULKAN "vk"
#define ANGLE_TYPE_METAL "mtl"
static void usage(void)
{
printf("Usage: glfwinfo [OPTION]...\n");
printf("Options:\n");
printf(" -a, --client-api=API the client API to use ("
API_NAME_OPENGL " or "
API_NAME_OPENGL_ES ")\n");
printf(" -b, --behavior=BEHAVIOR the release behavior to use ("
BEHAVIOR_NAME_NONE " or "
BEHAVIOR_NAME_FLUSH ")\n");
printf(" -c, --context-api=API the context creation API to use ("
API_NAME_NATIVE " or "
API_NAME_EGL " or "
API_NAME_OSMESA ")\n");
printf(" -d, --debug request a debug context\n");
printf(" -f, --forward require a forward-compatible context\n");
printf(" -h, --help show this help\n");
printf(" -l, --list-extensions list all Vulkan and client API extensions\n");
printf(" --list-layers list all Vulkan layers\n");
printf(" -m, --major=MAJOR the major number of the required "
"client API version\n");
printf(" -n, --minor=MINOR the minor number of the required "
"client API version\n");
printf(" -p, --profile=PROFILE the OpenGL profile to use ("
PROFILE_NAME_CORE " or "
PROFILE_NAME_COMPAT ")\n");
printf(" -s, --robustness=STRATEGY the robustness strategy to use ("
STRATEGY_NAME_NONE " or "
STRATEGY_NAME_LOSE ")\n");
printf(" -v, --version print version information\n");
printf(" --red-bits=N the number of red bits to request\n");
printf(" --green-bits=N the number of green bits to request\n");
printf(" --blue-bits=N the number of blue bits to request\n");
printf(" --alpha-bits=N the number of alpha bits to request\n");
printf(" --depth-bits=N the number of depth bits to request\n");
printf(" --stencil-bits=N the number of stencil bits to request\n");
printf(" --accum-red-bits=N the number of red bits to request\n");
printf(" --accum-green-bits=N the number of green bits to request\n");
printf(" --accum-blue-bits=N the number of blue bits to request\n");
printf(" --accum-alpha-bits=N the number of alpha bits to request\n");
printf(" --aux-buffers=N the number of aux buffers to request\n");
printf(" --samples=N the number of MSAA samples to request\n");
printf(" --stereo request stereo rendering\n");
printf(" --srgb request an sRGB capable framebuffer\n");
printf(" --singlebuffer request single-buffering\n");
printf(" --no-error request a context that does not emit errors\n");
printf(" --angle-type=TYPE the ANGLE platform type to use ("
ANGLE_TYPE_OPENGL ", "
ANGLE_TYPE_OPENGLES ", "
ANGLE_TYPE_D3D9 ", "
ANGLE_TYPE_D3D11 ", "
ANGLE_TYPE_VULKAN " or "
ANGLE_TYPE_METAL ")\n");
printf(" --graphics-switching request macOS graphics switching\n");
printf(" --disable-xcb-surface disable VK_KHR_xcb_surface extension\n");
}
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static const char* get_device_type_name(VkPhysicalDeviceType type)
{
if (type == VK_PHYSICAL_DEVICE_TYPE_OTHER)
return "other";
else if (type == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU)
return "integrated GPU";
else if (type == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
return "discrete GPU";
else if (type == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU)
return "virtual GPU";
else if (type == VK_PHYSICAL_DEVICE_TYPE_CPU)
return "CPU";
return "unknown";
}
static const char* get_api_name(int api)
{
if (api == GLFW_OPENGL_API)
return "OpenGL";
else if (api == GLFW_OPENGL_ES_API)
return "OpenGL ES";
return "Unknown API";
}
static const char* get_profile_name_gl(GLint mask)
{
if (mask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT)
return PROFILE_NAME_COMPAT;
if (mask & GL_CONTEXT_CORE_PROFILE_BIT)
return PROFILE_NAME_CORE;
return "unknown";
}
static const char* get_profile_name_glfw(int profile)
{
if (profile == GLFW_OPENGL_COMPAT_PROFILE)
return PROFILE_NAME_COMPAT;
if (profile == GLFW_OPENGL_CORE_PROFILE)
return PROFILE_NAME_CORE;
return "unknown";
}
static const char* get_strategy_name_gl(GLint strategy)
{
if (strategy == GL_LOSE_CONTEXT_ON_RESET_ARB)
return STRATEGY_NAME_LOSE;
if (strategy == GL_NO_RESET_NOTIFICATION_ARB)
return STRATEGY_NAME_NONE;
return "unknown";
}
static const char* get_strategy_name_glfw(int strategy)
{
if (strategy == GLFW_LOSE_CONTEXT_ON_RESET)
return STRATEGY_NAME_LOSE;
if (strategy == GLFW_NO_RESET_NOTIFICATION)
return STRATEGY_NAME_NONE;
return "unknown";
}
static void list_context_extensions(int client, int major, int minor)
{
printf("%s context extensions:\n", get_api_name(client));
if (client == GLFW_OPENGL_API && major > 2)
{
GLint count;
glGetIntegerv(GL_NUM_EXTENSIONS, &count);
for (int i = 0; i < count; i++)
printf(" %s\n", (const char*) glGetStringi(GL_EXTENSIONS, i));
}
else
{
const GLubyte* extensions = glGetString(GL_EXTENSIONS);
while (*extensions != '\0')
{
putchar(' ');
while (*extensions != '\0' && *extensions != ' ')
{
putchar(*extensions);
extensions++;
}
while (*extensions == ' ')
extensions++;
putchar('\n');
}
}
}
static void list_vulkan_instance_extensions(void)
{
printf("Vulkan instance extensions:\n");
uint32_t ep_count;
vkEnumerateInstanceExtensionProperties(NULL, &ep_count, NULL);
VkExtensionProperties* ep = calloc(ep_count, sizeof(VkExtensionProperties));
vkEnumerateInstanceExtensionProperties(NULL, &ep_count, ep);
for (uint32_t i = 0; i < ep_count; i++)
printf(" %s (spec version %u)\n", ep[i].extensionName, ep[i].specVersion);
free(ep);
}
static void list_vulkan_instance_layers(void)
{
printf("Vulkan instance layers:\n");
uint32_t lp_count;
vkEnumerateInstanceLayerProperties(&lp_count, NULL);
VkLayerProperties* lp = calloc(lp_count, sizeof(VkLayerProperties));
vkEnumerateInstanceLayerProperties(&lp_count, lp);
for (uint32_t i = 0; i < lp_count; i++)
{
printf(" %s (spec version %u) \"%s\"\n",
lp[i].layerName,
lp[i].specVersion >> 22,
lp[i].description);
}
free(lp);
}
static void list_vulkan_device_extensions(VkInstance instance, VkPhysicalDevice device)
{
printf("Vulkan device extensions:\n");
uint32_t ep_count;
vkEnumerateDeviceExtensionProperties(device, NULL, &ep_count, NULL);
VkExtensionProperties* ep = calloc(ep_count, sizeof(VkExtensionProperties));
vkEnumerateDeviceExtensionProperties(device, NULL, &ep_count, ep);
for (uint32_t i = 0; i < ep_count; i++)
printf(" %s (spec version %u)\n", ep[i].extensionName, ep[i].specVersion);
free(ep);
}
static void list_vulkan_device_layers(VkInstance instance, VkPhysicalDevice device)
{
printf("Vulkan device layers:\n");
uint32_t lp_count;
vkEnumerateDeviceLayerProperties(device, &lp_count, NULL);
VkLayerProperties* lp = calloc(lp_count, sizeof(VkLayerProperties));
vkEnumerateDeviceLayerProperties(device, &lp_count, lp);
for (uint32_t i = 0; i < lp_count; i++)
{
printf(" %s (spec version %u) \"%s\"\n",
lp[i].layerName,
lp[i].specVersion >> 22,
lp[i].description);
}
free(lp);
}
static bool valid_version(void)
{
int major, minor, revision;
glfwGetVersion(&major, &minor, &revision);
if (major != GLFW_VERSION_MAJOR)
{
printf("*** ERROR: GLFW major version mismatch! ***\n");
return false;
}
if (minor != GLFW_VERSION_MINOR || revision != GLFW_VERSION_REVISION)
printf("*** WARNING: GLFW version mismatch! ***\n");
return true;
}
static void print_version(void)
{
int major, minor, revision;
glfwGetVersion(&major, &minor, &revision);
printf("GLFW header version: %u.%u.%u\n",
GLFW_VERSION_MAJOR,
GLFW_VERSION_MINOR,
GLFW_VERSION_REVISION);
printf("GLFW library version: %u.%u.%u\n", major, minor, revision);
printf("GLFW library version string: \"%s\"\n", glfwGetVersionString());
}
static GLADapiproc glad_vulkan_callback(const char* name, void* user)
{
return glfwGetInstanceProcAddress((VkInstance) user, name);
}
int main(int argc, char** argv)
{
int ch;
bool list_extensions = false, list_layers = false;
// These duplicate the defaults for each hint
int client_api = GLFW_OPENGL_API;
int context_major = 1;
int context_minor = 0;
int context_release = GLFW_ANY_RELEASE_BEHAVIOR;
int context_creation_api = GLFW_NATIVE_CONTEXT_API;
int context_robustness = GLFW_NO_ROBUSTNESS;
bool context_debug = false;
bool context_no_error = false;
bool opengl_forward = false;
int opengl_profile = GLFW_OPENGL_ANY_PROFILE;
int fb_red_bits = 8;
int fb_green_bits = 8;
int fb_blue_bits = 8;
int fb_alpha_bits = 8;
int fb_depth_bits = 24;
int fb_stencil_bits = 8;
int fb_accum_red_bits = 0;
int fb_accum_green_bits = 0;
int fb_accum_blue_bits = 0;
int fb_accum_alpha_bits = 0;
int fb_aux_buffers = 0;
int fb_samples = 0;
bool fb_stereo = false;
bool fb_srgb = false;
bool fb_doublebuffer = true;
int angle_type = GLFW_ANGLE_PLATFORM_TYPE_NONE;
bool cocoa_graphics_switching = false;
bool disable_xcb_surface = false;
enum { CLIENT, CONTEXT, BEHAVIOR, DEBUG_CONTEXT, FORWARD, HELP,
EXTENSIONS, LAYERS,
MAJOR, MINOR, PROFILE, ROBUSTNESS, VERSION,
REDBITS, GREENBITS, BLUEBITS, ALPHABITS, DEPTHBITS, STENCILBITS,
ACCUMREDBITS, ACCUMGREENBITS, ACCUMBLUEBITS, ACCUMALPHABITS,
AUXBUFFERS, SAMPLES, STEREO, SRGB, SINGLEBUFFER, NOERROR_SRSLY,
ANGLE_TYPE, GRAPHICS_SWITCHING, XCB_SURFACE };
const struct option options[] =
{
{ "behavior", 1, NULL, BEHAVIOR },
{ "client-api", 1, NULL, CLIENT },
{ "context-api", 1, NULL, CONTEXT },
{ "debug", 0, NULL, DEBUG_CONTEXT },
{ "forward", 0, NULL, FORWARD },
{ "help", 0, NULL, HELP },
{ "list-extensions", 0, NULL, EXTENSIONS },
{ "list-layers", 0, NULL, LAYERS },
{ "major", 1, NULL, MAJOR },
{ "minor", 1, NULL, MINOR },
{ "profile", 1, NULL, PROFILE },
{ "robustness", 1, NULL, ROBUSTNESS },
{ "version", 0, NULL, VERSION },
{ "red-bits", 1, NULL, REDBITS },
{ "green-bits", 1, NULL, GREENBITS },
{ "blue-bits", 1, NULL, BLUEBITS },
{ "alpha-bits", 1, NULL, ALPHABITS },
{ "depth-bits", 1, NULL, DEPTHBITS },
{ "stencil-bits", 1, NULL, STENCILBITS },
{ "accum-red-bits", 1, NULL, ACCUMREDBITS },
{ "accum-green-bits", 1, NULL, ACCUMGREENBITS },
{ "accum-blue-bits", 1, NULL, ACCUMBLUEBITS },
{ "accum-alpha-bits", 1, NULL, ACCUMALPHABITS },
{ "aux-buffers", 1, NULL, AUXBUFFERS },
{ "samples", 1, NULL, SAMPLES },
{ "stereo", 0, NULL, STEREO },
{ "srgb", 0, NULL, SRGB },
{ "singlebuffer", 0, NULL, SINGLEBUFFER },
{ "no-error", 0, NULL, NOERROR_SRSLY },
{ "angle-type", 1, NULL, ANGLE_TYPE },
{ "graphics-switching", 0, NULL, GRAPHICS_SWITCHING },
{ "vk-xcb-surface", 0, NULL, XCB_SURFACE },
{ NULL, 0, NULL, 0 }
};
while ((ch = getopt_long(argc, argv, "a:b:c:dfhlm:n:p:s:v", options, NULL)) != -1)
{
switch (ch)
{
case 'a':
case CLIENT:
if (strcasecmp(optarg, API_NAME_OPENGL) == 0)
client_api = GLFW_OPENGL_API;
else if (strcasecmp(optarg, API_NAME_OPENGL_ES) == 0)
client_api = GLFW_OPENGL_ES_API;
else
{
usage();
exit(EXIT_FAILURE);
}
break;
case 'b':
case BEHAVIOR:
if (strcasecmp(optarg, BEHAVIOR_NAME_NONE) == 0)
context_release = GLFW_RELEASE_BEHAVIOR_NONE;
else if (strcasecmp(optarg, BEHAVIOR_NAME_FLUSH) == 0)
context_release = GLFW_RELEASE_BEHAVIOR_FLUSH;
else
{
usage();
exit(EXIT_FAILURE);
}
break;
case 'c':
case CONTEXT:
if (strcasecmp(optarg, API_NAME_NATIVE) == 0)
context_creation_api = GLFW_NATIVE_CONTEXT_API;
else if (strcasecmp(optarg, API_NAME_EGL) == 0)
context_creation_api = GLFW_EGL_CONTEXT_API;
else if (strcasecmp(optarg, API_NAME_OSMESA) == 0)
context_creation_api = GLFW_OSMESA_CONTEXT_API;
else
{
usage();
exit(EXIT_FAILURE);
}
break;
case 'd':
case DEBUG_CONTEXT:
context_debug = true;
break;
case 'f':
case FORWARD:
opengl_forward = true;
break;
case 'h':
case HELP:
usage();
exit(EXIT_SUCCESS);
case 'l':
case EXTENSIONS:
list_extensions = true;
break;
case LAYERS:
list_layers = true;
break;
case 'm':
case MAJOR:
context_major = atoi(optarg);
break;
case 'n':
case MINOR:
context_minor = atoi(optarg);
break;
case 'p':
case PROFILE:
if (strcasecmp(optarg, PROFILE_NAME_CORE) == 0)
opengl_profile = GLFW_OPENGL_CORE_PROFILE;
else if (strcasecmp(optarg, PROFILE_NAME_COMPAT) == 0)
opengl_profile = GLFW_OPENGL_COMPAT_PROFILE;
else
{
usage();
exit(EXIT_FAILURE);
}
break;
case 's':
case ROBUSTNESS:
if (strcasecmp(optarg, STRATEGY_NAME_NONE) == 0)
context_robustness = GLFW_NO_RESET_NOTIFICATION;
else if (strcasecmp(optarg, STRATEGY_NAME_LOSE) == 0)
context_robustness = GLFW_LOSE_CONTEXT_ON_RESET;
else
{
usage();
exit(EXIT_FAILURE);
}
break;
case 'v':
case VERSION:
print_version();
exit(EXIT_SUCCESS);
case REDBITS:
if (strcmp(optarg, "-") == 0)
fb_red_bits = GLFW_DONT_CARE;
else
fb_red_bits = atoi(optarg);
break;
case GREENBITS:
if (strcmp(optarg, "-") == 0)
fb_green_bits = GLFW_DONT_CARE;
else
fb_green_bits = atoi(optarg);
break;
case BLUEBITS:
if (strcmp(optarg, "-") == 0)
fb_blue_bits = GLFW_DONT_CARE;
else
fb_blue_bits = atoi(optarg);
break;
case ALPHABITS:
if (strcmp(optarg, "-") == 0)
fb_alpha_bits = GLFW_DONT_CARE;
else
fb_alpha_bits = atoi(optarg);
break;
case DEPTHBITS:
if (strcmp(optarg, "-") == 0)
fb_depth_bits = GLFW_DONT_CARE;
else
fb_depth_bits = atoi(optarg);
break;
case STENCILBITS:
if (strcmp(optarg, "-") == 0)
fb_stencil_bits = GLFW_DONT_CARE;
else
fb_stencil_bits = atoi(optarg);
break;
case ACCUMREDBITS:
if (strcmp(optarg, "-") == 0)
fb_accum_red_bits = GLFW_DONT_CARE;
else
fb_accum_red_bits = atoi(optarg);
break;
case ACCUMGREENBITS:
if (strcmp(optarg, "-") == 0)
fb_accum_green_bits = GLFW_DONT_CARE;
else
fb_accum_green_bits = atoi(optarg);
break;
case ACCUMBLUEBITS:
if (strcmp(optarg, "-") == 0)
fb_accum_blue_bits = GLFW_DONT_CARE;
else
fb_accum_blue_bits = atoi(optarg);
break;
case ACCUMALPHABITS:
if (strcmp(optarg, "-") == 0)
fb_accum_alpha_bits = GLFW_DONT_CARE;
else
fb_accum_alpha_bits = atoi(optarg);
break;
case AUXBUFFERS:
if (strcmp(optarg, "-") == 0)
fb_aux_buffers = GLFW_DONT_CARE;
else
fb_aux_buffers = atoi(optarg);
break;
case SAMPLES:
if (strcmp(optarg, "-") == 0)
fb_samples = GLFW_DONT_CARE;
else
fb_samples = atoi(optarg);
break;
case STEREO:
fb_stereo = true;
break;
case SRGB:
fb_srgb = true;
break;
case SINGLEBUFFER:
fb_doublebuffer = false;
break;
case NOERROR_SRSLY:
context_no_error = true;
break;
case ANGLE_TYPE:
if (strcmp(optarg, ANGLE_TYPE_OPENGL) == 0)
angle_type = GLFW_ANGLE_PLATFORM_TYPE_OPENGL;
else if (strcmp(optarg, ANGLE_TYPE_OPENGLES) == 0)
angle_type = GLFW_ANGLE_PLATFORM_TYPE_OPENGLES;
else if (strcmp(optarg, ANGLE_TYPE_D3D9) == 0)
angle_type = GLFW_ANGLE_PLATFORM_TYPE_D3D9;
else if (strcmp(optarg, ANGLE_TYPE_D3D11) == 0)
angle_type = GLFW_ANGLE_PLATFORM_TYPE_D3D11;
else if (strcmp(optarg, ANGLE_TYPE_VULKAN) == 0)
angle_type = GLFW_ANGLE_PLATFORM_TYPE_VULKAN;
else if (strcmp(optarg, ANGLE_TYPE_METAL) == 0)
angle_type = GLFW_ANGLE_PLATFORM_TYPE_METAL;
else
{
usage();
exit(EXIT_FAILURE);
}
break;
case GRAPHICS_SWITCHING:
cocoa_graphics_switching = true;
break;
case XCB_SURFACE:
disable_xcb_surface = true;
break;
default:
usage();
exit(EXIT_FAILURE);
}
}
// Initialize GLFW and create window
if (!valid_version())
exit(EXIT_FAILURE);
glfwSetErrorCallback(error_callback);
glfwInitHint(GLFW_COCOA_MENUBAR, false);
glfwInitHint(GLFW_ANGLE_PLATFORM_TYPE, angle_type);
glfwInitHint(GLFW_X11_XCB_VULKAN_SURFACE, !disable_xcb_surface);
if (!glfwInit())
exit(EXIT_FAILURE);
print_version();
glfwWindowHint(GLFW_VISIBLE, false);
glfwWindowHint(GLFW_CLIENT_API, client_api);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, context_major);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, context_minor);
glfwWindowHint(GLFW_CONTEXT_RELEASE_BEHAVIOR, context_release);
glfwWindowHint(GLFW_CONTEXT_CREATION_API, context_creation_api);
glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS, context_robustness);
glfwWindowHint(GLFW_CONTEXT_DEBUG, context_debug);
glfwWindowHint(GLFW_CONTEXT_NO_ERROR, context_no_error);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, opengl_forward);
glfwWindowHint(GLFW_OPENGL_PROFILE, opengl_profile);
glfwWindowHint(GLFW_RED_BITS, fb_red_bits);
glfwWindowHint(GLFW_BLUE_BITS, fb_blue_bits);
glfwWindowHint(GLFW_GREEN_BITS, fb_green_bits);
glfwWindowHint(GLFW_ALPHA_BITS, fb_alpha_bits);
glfwWindowHint(GLFW_DEPTH_BITS, fb_depth_bits);
glfwWindowHint(GLFW_STENCIL_BITS, fb_stencil_bits);
glfwWindowHint(GLFW_ACCUM_RED_BITS, fb_accum_red_bits);
glfwWindowHint(GLFW_ACCUM_GREEN_BITS, fb_accum_green_bits);
glfwWindowHint(GLFW_ACCUM_BLUE_BITS, fb_accum_blue_bits);
glfwWindowHint(GLFW_ACCUM_ALPHA_BITS, fb_accum_alpha_bits);
glfwWindowHint(GLFW_AUX_BUFFERS, fb_aux_buffers);
glfwWindowHint(GLFW_SAMPLES, fb_samples);
glfwWindowHint(GLFW_STEREO, fb_stereo);
glfwWindowHint(GLFW_SRGB_CAPABLE, fb_srgb);
glfwWindowHint(GLFW_DOUBLEBUFFER, fb_doublebuffer);
glfwWindowHint(GLFW_COCOA_GRAPHICS_SWITCHING, cocoa_graphics_switching);
GLFWwindow* window = glfwCreateWindow(200, 200, "Version", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
const GLenum error = glGetError();
if (error != GL_NO_ERROR)
printf("*** OpenGL error after make current: 0x%08x ***\n", error);
// Report client API version
const int client = glfwGetWindowAttrib(window, GLFW_CLIENT_API);
const int major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
const int minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
const int revision = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
const int profile = glfwGetWindowAttrib(window, GLFW_OPENGL_PROFILE);
printf("%s context version string: \"%s\"\n",
get_api_name(client),
glGetString(GL_VERSION));
printf("%s context version parsed by GLFW: %u.%u.%u\n",
get_api_name(client),
major, minor, revision);
// Report client API context properties
if (client == GLFW_OPENGL_API)
{
if (major >= 3)
{
GLint flags;
glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
printf("%s context flags (0x%08x):", get_api_name(client), flags);
if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
printf(" forward-compatible");
if (flags & 2/*GL_CONTEXT_FLAG_DEBUG_BIT*/)
printf(" debug");
if (flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB)
printf(" robustness");
if (flags & 8/*GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR*/)
printf(" no-error");
putchar('\n');
printf("%s context flags parsed by GLFW:", get_api_name(client));
if (glfwGetWindowAttrib(window, GLFW_OPENGL_FORWARD_COMPAT))
printf(" forward-compatible");
if (glfwGetWindowAttrib(window, GLFW_CONTEXT_DEBUG))
printf(" debug");
if (glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS) == GLFW_LOSE_CONTEXT_ON_RESET)
printf(" robustness");
if (glfwGetWindowAttrib(window, GLFW_CONTEXT_NO_ERROR))
printf(" no-error");
putchar('\n');
}
if (major >= 4 || (major == 3 && minor >= 2))
{
GLint mask;
glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask);
printf("%s profile mask (0x%08x): %s\n",
get_api_name(client),
mask,
get_profile_name_gl(mask));
printf("%s profile mask parsed by GLFW: %s\n",
get_api_name(client),
get_profile_name_glfw(profile));
}
if (GLAD_GL_ARB_robustness)
{
const int robustness = glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS);
GLint strategy;
glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);
printf("%s robustness strategy (0x%08x): %s\n",
get_api_name(client),
strategy,
get_strategy_name_gl(strategy));
printf("%s robustness strategy parsed by GLFW: %s\n",
get_api_name(client),
get_strategy_name_glfw(robustness));
}
}
printf("%s context renderer string: \"%s\"\n",
get_api_name(client),
glGetString(GL_RENDERER));
printf("%s context vendor string: \"%s\"\n",
get_api_name(client),
glGetString(GL_VENDOR));
if (major >= 2)
{
printf("%s context shading language version: \"%s\"\n",
get_api_name(client),
glGetString(GL_SHADING_LANGUAGE_VERSION));
}
printf("%s framebuffer:\n", get_api_name(client));
GLint redbits, greenbits, bluebits, alphabits, depthbits, stencilbits;
if (client == GLFW_OPENGL_API && profile == GLFW_OPENGL_CORE_PROFILE)
{
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
GL_BACK_LEFT,
GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE,
&redbits);
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
GL_BACK_LEFT,
GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE,
&greenbits);
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
GL_BACK_LEFT,
GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE,
&bluebits);
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
GL_BACK_LEFT,
GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
&alphabits);
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
GL_DEPTH,
GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE,
&depthbits);
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
GL_STENCIL,
GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE,
&stencilbits);
}
else
{
glGetIntegerv(GL_RED_BITS, &redbits);
glGetIntegerv(GL_GREEN_BITS, &greenbits);
glGetIntegerv(GL_BLUE_BITS, &bluebits);
glGetIntegerv(GL_ALPHA_BITS, &alphabits);
glGetIntegerv(GL_DEPTH_BITS, &depthbits);
glGetIntegerv(GL_STENCIL_BITS, &stencilbits);
}
printf(" red: %u green: %u blue: %u alpha: %u depth: %u stencil: %u\n",
redbits, greenbits, bluebits, alphabits, depthbits, stencilbits);
if (client == GLFW_OPENGL_ES_API ||
GLAD_GL_ARB_multisample ||
major > 1 || minor >= 3)
{
GLint samples, samplebuffers;
glGetIntegerv(GL_SAMPLES, &samples);
glGetIntegerv(GL_SAMPLE_BUFFERS, &samplebuffers);
printf(" samples: %u sample buffers: %u\n", samples, samplebuffers);
}
if (client == GLFW_OPENGL_API && profile != GLFW_OPENGL_CORE_PROFILE)
{
GLint accumredbits, accumgreenbits, accumbluebits, accumalphabits;
GLint auxbuffers;
glGetIntegerv(GL_ACCUM_RED_BITS, &accumredbits);
glGetIntegerv(GL_ACCUM_GREEN_BITS, &accumgreenbits);
glGetIntegerv(GL_ACCUM_BLUE_BITS, &accumbluebits);
glGetIntegerv(GL_ACCUM_ALPHA_BITS, &accumalphabits);
glGetIntegerv(GL_AUX_BUFFERS, &auxbuffers);
printf(" accum red: %u accum green: %u accum blue: %u accum alpha: %u aux buffers: %u\n",
accumredbits, accumgreenbits, accumbluebits, accumalphabits, auxbuffers);
}
if (list_extensions)
list_context_extensions(client, major, minor);
glfwDestroyWindow(window);
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
window = glfwCreateWindow(200, 200, "Version", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
printf("Vulkan loader: %s\n",
glfwVulkanSupported() ? "available" : "missing");
if (glfwVulkanSupported())
{
gladLoadVulkanUserPtr(NULL, glad_vulkan_callback, NULL);
uint32_t loader_version = VK_API_VERSION_1_0;
if (vkEnumerateInstanceVersion)
{
uint32_t version;
if (vkEnumerateInstanceVersion(&version) == VK_SUCCESS)
loader_version = version;
}
printf("Vulkan loader API version: %i.%i\n",
VK_VERSION_MAJOR(loader_version),
VK_VERSION_MINOR(loader_version));
uint32_t re_count;
const char** re = glfwGetRequiredInstanceExtensions(&re_count);
if (re)
{
printf("Vulkan window surface required instance extensions:\n");
for (uint32_t i = 0; i < re_count; i++)
printf(" %s\n", re[i]);
}
else
printf("Vulkan window surface extensions missing\n");
if (list_extensions)
list_vulkan_instance_extensions();
if (list_layers)
list_vulkan_instance_layers();
VkApplicationInfo ai = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
ai.pApplicationName = "glfwinfo";
ai.applicationVersion = VK_MAKE_VERSION(GLFW_VERSION_MAJOR,
GLFW_VERSION_MINOR,
GLFW_VERSION_REVISION);
if (loader_version >= VK_API_VERSION_1_1)
ai.apiVersion = VK_API_VERSION_1_1;
else
ai.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo ici = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
ici.pApplicationInfo = &ai;
ici.enabledExtensionCount = re_count;
ici.ppEnabledExtensionNames = re;
VkInstance instance = VK_NULL_HANDLE;
if (vkCreateInstance(&ici, NULL, &instance) != VK_SUCCESS)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
gladLoadVulkanUserPtr(NULL, glad_vulkan_callback, instance);
if (re)
{
VkSurfaceKHR surface = VK_NULL_HANDLE;
if (glfwCreateWindowSurface(instance, window, NULL, &surface) == VK_SUCCESS)
{
printf("Vulkan window surface created successfully\n");
vkDestroySurfaceKHR(instance, surface, NULL);
}
else
printf("Failed to create Vulkan window surface\n");
}
uint32_t pd_count;
vkEnumeratePhysicalDevices(instance, &pd_count, NULL);
VkPhysicalDevice* pd = calloc(pd_count, sizeof(VkPhysicalDevice));
vkEnumeratePhysicalDevices(instance, &pd_count, pd);
for (uint32_t i = 0; i < pd_count; i++)
{
VkPhysicalDeviceProperties pdp;
vkGetPhysicalDeviceProperties(pd[i], &pdp);
printf("Vulkan %s device: \"%s\" (API version %i.%i)\n",
get_device_type_name(pdp.deviceType),
pdp.deviceName,
VK_VERSION_MAJOR(pdp.apiVersion),
VK_VERSION_MINOR(pdp.apiVersion));
uint32_t qfp_count;
vkGetPhysicalDeviceQueueFamilyProperties(pd[i], &qfp_count, NULL);
printf("Vulkan device queue family presentation support:\n");
for (uint32_t j = 0; j < qfp_count; j++)
{
printf(" %u: ", j);
if (glfwGetPhysicalDevicePresentationSupport(instance, pd[i], j))
printf("supported\n");
else
printf("no\n");
}
if (list_extensions)
list_vulkan_device_extensions(instance, pd[i]);
if (list_layers)
list_vulkan_device_layers(instance, pd[i]);
}
free(pd);
vkDestroyInstance(instance, NULL);
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/events.c | .c | 22,117 | 671 | //========================================================================
// Event linter (event spewer)
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test hooks every available callback and outputs their arguments
//
// Log messages go to stdout, error messages to stderr
//
// Every event also gets a (sequential) number to aid discussion of logs
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <locale.h>
#include "getopt.h"
// Event index
static unsigned int counter = 0;
typedef struct
{
GLFWwindow* window;
int number;
int closeable;
} Slot;
static void usage(void)
{
printf("Usage: events [-f] [-h] [-n WINDOWS]\n");
printf("Options:\n");
printf(" -f use full screen\n");
printf(" -h show this help\n");
printf(" -n the number of windows to create\n");
}
static const char* get_key_name(int key)
{
switch (key)
{
// Printable keys
case GLFW_KEY_A: return "A";
case GLFW_KEY_B: return "B";
case GLFW_KEY_C: return "C";
case GLFW_KEY_D: return "D";
case GLFW_KEY_E: return "E";
case GLFW_KEY_F: return "F";
case GLFW_KEY_G: return "G";
case GLFW_KEY_H: return "H";
case GLFW_KEY_I: return "I";
case GLFW_KEY_J: return "J";
case GLFW_KEY_K: return "K";
case GLFW_KEY_L: return "L";
case GLFW_KEY_M: return "M";
case GLFW_KEY_N: return "N";
case GLFW_KEY_O: return "O";
case GLFW_KEY_P: return "P";
case GLFW_KEY_Q: return "Q";
case GLFW_KEY_R: return "R";
case GLFW_KEY_S: return "S";
case GLFW_KEY_T: return "T";
case GLFW_KEY_U: return "U";
case GLFW_KEY_V: return "V";
case GLFW_KEY_W: return "W";
case GLFW_KEY_X: return "X";
case GLFW_KEY_Y: return "Y";
case GLFW_KEY_Z: return "Z";
case GLFW_KEY_1: return "1";
case GLFW_KEY_2: return "2";
case GLFW_KEY_3: return "3";
case GLFW_KEY_4: return "4";
case GLFW_KEY_5: return "5";
case GLFW_KEY_6: return "6";
case GLFW_KEY_7: return "7";
case GLFW_KEY_8: return "8";
case GLFW_KEY_9: return "9";
case GLFW_KEY_0: return "0";
case GLFW_KEY_SPACE: return "SPACE";
case GLFW_KEY_MINUS: return "MINUS";
case GLFW_KEY_EQUAL: return "EQUAL";
case GLFW_KEY_LEFT_BRACKET: return "LEFT BRACKET";
case GLFW_KEY_RIGHT_BRACKET: return "RIGHT BRACKET";
case GLFW_KEY_BACKSLASH: return "BACKSLASH";
case GLFW_KEY_SEMICOLON: return "SEMICOLON";
case GLFW_KEY_APOSTROPHE: return "APOSTROPHE";
case GLFW_KEY_GRAVE_ACCENT: return "GRAVE ACCENT";
case GLFW_KEY_COMMA: return "COMMA";
case GLFW_KEY_PERIOD: return "PERIOD";
case GLFW_KEY_SLASH: return "SLASH";
case GLFW_KEY_WORLD_1: return "WORLD 1";
case GLFW_KEY_WORLD_2: return "WORLD 2";
// Function keys
case GLFW_KEY_ESCAPE: return "ESCAPE";
case GLFW_KEY_F1: return "F1";
case GLFW_KEY_F2: return "F2";
case GLFW_KEY_F3: return "F3";
case GLFW_KEY_F4: return "F4";
case GLFW_KEY_F5: return "F5";
case GLFW_KEY_F6: return "F6";
case GLFW_KEY_F7: return "F7";
case GLFW_KEY_F8: return "F8";
case GLFW_KEY_F9: return "F9";
case GLFW_KEY_F10: return "F10";
case GLFW_KEY_F11: return "F11";
case GLFW_KEY_F12: return "F12";
case GLFW_KEY_F13: return "F13";
case GLFW_KEY_F14: return "F14";
case GLFW_KEY_F15: return "F15";
case GLFW_KEY_F16: return "F16";
case GLFW_KEY_F17: return "F17";
case GLFW_KEY_F18: return "F18";
case GLFW_KEY_F19: return "F19";
case GLFW_KEY_F20: return "F20";
case GLFW_KEY_F21: return "F21";
case GLFW_KEY_F22: return "F22";
case GLFW_KEY_F23: return "F23";
case GLFW_KEY_F24: return "F24";
case GLFW_KEY_F25: return "F25";
case GLFW_KEY_UP: return "UP";
case GLFW_KEY_DOWN: return "DOWN";
case GLFW_KEY_LEFT: return "LEFT";
case GLFW_KEY_RIGHT: return "RIGHT";
case GLFW_KEY_LEFT_SHIFT: return "LEFT SHIFT";
case GLFW_KEY_RIGHT_SHIFT: return "RIGHT SHIFT";
case GLFW_KEY_LEFT_CONTROL: return "LEFT CONTROL";
case GLFW_KEY_RIGHT_CONTROL: return "RIGHT CONTROL";
case GLFW_KEY_LEFT_ALT: return "LEFT ALT";
case GLFW_KEY_RIGHT_ALT: return "RIGHT ALT";
case GLFW_KEY_TAB: return "TAB";
case GLFW_KEY_ENTER: return "ENTER";
case GLFW_KEY_BACKSPACE: return "BACKSPACE";
case GLFW_KEY_INSERT: return "INSERT";
case GLFW_KEY_DELETE: return "DELETE";
case GLFW_KEY_PAGE_UP: return "PAGE UP";
case GLFW_KEY_PAGE_DOWN: return "PAGE DOWN";
case GLFW_KEY_HOME: return "HOME";
case GLFW_KEY_END: return "END";
case GLFW_KEY_KP_0: return "KEYPAD 0";
case GLFW_KEY_KP_1: return "KEYPAD 1";
case GLFW_KEY_KP_2: return "KEYPAD 2";
case GLFW_KEY_KP_3: return "KEYPAD 3";
case GLFW_KEY_KP_4: return "KEYPAD 4";
case GLFW_KEY_KP_5: return "KEYPAD 5";
case GLFW_KEY_KP_6: return "KEYPAD 6";
case GLFW_KEY_KP_7: return "KEYPAD 7";
case GLFW_KEY_KP_8: return "KEYPAD 8";
case GLFW_KEY_KP_9: return "KEYPAD 9";
case GLFW_KEY_KP_DIVIDE: return "KEYPAD DIVIDE";
case GLFW_KEY_KP_MULTIPLY: return "KEYPAD MULTIPLY";
case GLFW_KEY_KP_SUBTRACT: return "KEYPAD SUBTRACT";
case GLFW_KEY_KP_ADD: return "KEYPAD ADD";
case GLFW_KEY_KP_DECIMAL: return "KEYPAD DECIMAL";
case GLFW_KEY_KP_EQUAL: return "KEYPAD EQUAL";
case GLFW_KEY_KP_ENTER: return "KEYPAD ENTER";
case GLFW_KEY_PRINT_SCREEN: return "PRINT SCREEN";
case GLFW_KEY_NUM_LOCK: return "NUM LOCK";
case GLFW_KEY_CAPS_LOCK: return "CAPS LOCK";
case GLFW_KEY_SCROLL_LOCK: return "SCROLL LOCK";
case GLFW_KEY_PAUSE: return "PAUSE";
case GLFW_KEY_LEFT_SUPER: return "LEFT SUPER";
case GLFW_KEY_RIGHT_SUPER: return "RIGHT SUPER";
case GLFW_KEY_MENU: return "MENU";
default: return "UNKNOWN";
}
}
static const char* get_action_name(int action)
{
switch (action)
{
case GLFW_PRESS:
return "pressed";
case GLFW_RELEASE:
return "released";
case GLFW_REPEAT:
return "repeated";
}
return "caused unknown action";
}
static const char* get_button_name(int button)
{
switch (button)
{
case GLFW_MOUSE_BUTTON_LEFT:
return "left";
case GLFW_MOUSE_BUTTON_RIGHT:
return "right";
case GLFW_MOUSE_BUTTON_MIDDLE:
return "middle";
default:
{
static char name[16];
snprintf(name, sizeof(name), "%i", button);
return name;
}
}
}
static const char* get_mods_name(int mods)
{
static char name[512];
if (mods == 0)
return " no mods";
name[0] = '\0';
if (mods & GLFW_MOD_SHIFT)
strcat(name, " shift");
if (mods & GLFW_MOD_CONTROL)
strcat(name, " control");
if (mods & GLFW_MOD_ALT)
strcat(name, " alt");
if (mods & GLFW_MOD_SUPER)
strcat(name, " super");
if (mods & GLFW_MOD_CAPS_LOCK)
strcat(name, " capslock-on");
if (mods & GLFW_MOD_NUM_LOCK)
strcat(name, " numlock-on");
return name;
}
static size_t encode_utf8(char* s, unsigned int ch)
{
size_t count = 0;
if (ch < 0x80)
s[count++] = (char) ch;
else if (ch < 0x800)
{
s[count++] = (ch >> 6) | 0xc0;
s[count++] = (ch & 0x3f) | 0x80;
}
else if (ch < 0x10000)
{
s[count++] = (ch >> 12) | 0xe0;
s[count++] = ((ch >> 6) & 0x3f) | 0x80;
s[count++] = (ch & 0x3f) | 0x80;
}
else if (ch < 0x110000)
{
s[count++] = (ch >> 18) | 0xf0;
s[count++] = ((ch >> 12) & 0x3f) | 0x80;
s[count++] = ((ch >> 6) & 0x3f) | 0x80;
s[count++] = (ch & 0x3f) | 0x80;
}
return count;
}
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void window_pos_callback(GLFWwindow* window, int x, int y)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Window position: %i %i\n",
counter++, slot->number, glfwGetTime(), x, y);
}
static void window_size_callback(GLFWwindow* window, int width, int height)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Window size: %i %i\n",
counter++, slot->number, glfwGetTime(), width, height);
}
static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Framebuffer size: %i %i\n",
counter++, slot->number, glfwGetTime(), width, height);
}
static void window_content_scale_callback(GLFWwindow* window, float xscale, float yscale)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Window content scale: %0.3f %0.3f\n",
counter++, slot->number, glfwGetTime(), xscale, yscale);
}
static void window_close_callback(GLFWwindow* window)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Window close\n",
counter++, slot->number, glfwGetTime());
if (!slot->closeable)
{
printf("(( closing is disabled, press %s to re-enable )\n",
glfwGetKeyName(GLFW_KEY_C, 0));
}
glfwSetWindowShouldClose(window, slot->closeable);
}
static void window_refresh_callback(GLFWwindow* window)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Window refresh\n",
counter++, slot->number, glfwGetTime());
glfwMakeContextCurrent(window);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
static void window_focus_callback(GLFWwindow* window, int focused)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Window %s\n",
counter++, slot->number, glfwGetTime(),
focused ? "focused" : "defocused");
}
static void window_iconify_callback(GLFWwindow* window, int iconified)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Window was %s\n",
counter++, slot->number, glfwGetTime(),
iconified ? "iconified" : "uniconified");
}
static void window_maximize_callback(GLFWwindow* window, int maximized)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Window was %s\n",
counter++, slot->number, glfwGetTime(),
maximized ? "maximized" : "unmaximized");
}
static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Mouse button %i (%s) (with%s) was %s\n",
counter++, slot->number, glfwGetTime(), button,
get_button_name(button),
get_mods_name(mods),
get_action_name(action));
}
static void cursor_position_callback(GLFWwindow* window, double x, double y)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Cursor position: %f %f\n",
counter++, slot->number, glfwGetTime(), x, y);
}
static void cursor_enter_callback(GLFWwindow* window, int entered)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Cursor %s window\n",
counter++, slot->number, glfwGetTime(),
entered ? "entered" : "left");
}
static void scroll_callback(GLFWwindow* window, double x, double y)
{
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Scroll: %0.3f %0.3f\n",
counter++, slot->number, glfwGetTime(), x, y);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
Slot* slot = glfwGetWindowUserPointer(window);
const char* name = glfwGetKeyName(key, scancode);
if (name)
{
printf("%08x to %i at %0.3f: Key 0x%04x Scancode 0x%04x (%s) (%s) (with%s) was %s\n",
counter++, slot->number, glfwGetTime(), key, scancode,
get_key_name(key),
name,
get_mods_name(mods),
get_action_name(action));
}
else
{
printf("%08x to %i at %0.3f: Key 0x%04x Scancode 0x%04x (%s) (with%s) was %s\n",
counter++, slot->number, glfwGetTime(), key, scancode,
get_key_name(key),
get_mods_name(mods),
get_action_name(action));
}
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_C:
{
slot->closeable = !slot->closeable;
printf("(( closing %s ))\n", slot->closeable ? "enabled" : "disabled");
break;
}
case GLFW_KEY_L:
{
const int state = glfwGetInputMode(window, GLFW_LOCK_KEY_MODS);
glfwSetInputMode(window, GLFW_LOCK_KEY_MODS, !state);
printf("(( lock key mods %s ))\n", !state ? "enabled" : "disabled");
break;
}
}
}
static void char_callback(GLFWwindow* window, unsigned int codepoint)
{
Slot* slot = glfwGetWindowUserPointer(window);
char string[5] = "";
encode_utf8(string, codepoint);
printf("%08x to %i at %0.3f: Character 0x%08x (%s) input\n",
counter++, slot->number, glfwGetTime(), codepoint, string);
}
static void drop_callback(GLFWwindow* window, int count, const char* paths[])
{
int i;
Slot* slot = glfwGetWindowUserPointer(window);
printf("%08x to %i at %0.3f: Drop input\n",
counter++, slot->number, glfwGetTime());
for (i = 0; i < count; i++)
printf(" %i: \"%s\"\n", i, paths[i]);
}
static void monitor_callback(GLFWmonitor* monitor, int event)
{
if (event == GLFW_CONNECTED)
{
int x, y, widthMM, heightMM;
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwGetMonitorPos(monitor, &x, &y);
glfwGetMonitorPhysicalSize(monitor, &widthMM, &heightMM);
printf("%08x at %0.3f: Monitor %s (%ix%i at %ix%i, %ix%i mm) was connected\n",
counter++,
glfwGetTime(),
glfwGetMonitorName(monitor),
mode->width, mode->height,
x, y,
widthMM, heightMM);
}
else if (event == GLFW_DISCONNECTED)
{
printf("%08x at %0.3f: Monitor %s was disconnected\n",
counter++,
glfwGetTime(),
glfwGetMonitorName(monitor));
}
}
static void joystick_callback(int jid, int event)
{
if (event == GLFW_CONNECTED)
{
int axisCount, buttonCount, hatCount;
glfwGetJoystickAxes(jid, &axisCount);
glfwGetJoystickButtons(jid, &buttonCount);
glfwGetJoystickHats(jid, &hatCount);
printf("%08x at %0.3f: Joystick %i (%s) was connected with %i axes, %i buttons, and %i hats\n",
counter++, glfwGetTime(),
jid,
glfwGetJoystickName(jid),
axisCount,
buttonCount,
hatCount);
if (glfwJoystickIsGamepad(jid))
{
printf(" Joystick %i (%s) has a gamepad mapping (%s)\n",
jid,
glfwGetJoystickGUID(jid),
glfwGetGamepadName(jid));
}
else
{
printf(" Joystick %i (%s) has no gamepad mapping\n",
jid,
glfwGetJoystickGUID(jid));
}
}
else
{
printf("%08x at %0.3f: Joystick %i was disconnected\n",
counter++, glfwGetTime(), jid);
}
}
int main(int argc, char** argv)
{
Slot* slots;
GLFWmonitor* monitor = NULL;
int ch, i, width, height, count = 1;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
printf("Library initialized\n");
glfwSetMonitorCallback(monitor_callback);
glfwSetJoystickCallback(joystick_callback);
while ((ch = getopt(argc, argv, "hfn:")) != -1)
{
switch (ch)
{
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'f':
monitor = glfwGetPrimaryMonitor();
break;
case 'n':
count = (int) strtoul(optarg, NULL, 10);
break;
default:
usage();
exit(EXIT_FAILURE);
}
}
if (monitor)
{
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
width = mode->width;
height = mode->height;
}
else
{
width = 640;
height = 480;
}
slots = calloc(count, sizeof(Slot));
for (i = 0; i < count; i++)
{
char title[128];
slots[i].closeable = GLFW_TRUE;
slots[i].number = i + 1;
snprintf(title, sizeof(title), "Event Linter (Window %i)", slots[i].number);
if (monitor)
{
printf("Creating full screen window %i (%ix%i on %s)\n",
slots[i].number,
width, height,
glfwGetMonitorName(monitor));
}
else
{
printf("Creating windowed mode window %i (%ix%i)\n",
slots[i].number,
width, height);
}
slots[i].window = glfwCreateWindow(width, height, title, monitor, NULL);
if (!slots[i].window)
{
free(slots);
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetWindowUserPointer(slots[i].window, slots + i);
glfwSetWindowPosCallback(slots[i].window, window_pos_callback);
glfwSetWindowSizeCallback(slots[i].window, window_size_callback);
glfwSetFramebufferSizeCallback(slots[i].window, framebuffer_size_callback);
glfwSetWindowContentScaleCallback(slots[i].window, window_content_scale_callback);
glfwSetWindowCloseCallback(slots[i].window, window_close_callback);
glfwSetWindowRefreshCallback(slots[i].window, window_refresh_callback);
glfwSetWindowFocusCallback(slots[i].window, window_focus_callback);
glfwSetWindowIconifyCallback(slots[i].window, window_iconify_callback);
glfwSetWindowMaximizeCallback(slots[i].window, window_maximize_callback);
glfwSetMouseButtonCallback(slots[i].window, mouse_button_callback);
glfwSetCursorPosCallback(slots[i].window, cursor_position_callback);
glfwSetCursorEnterCallback(slots[i].window, cursor_enter_callback);
glfwSetScrollCallback(slots[i].window, scroll_callback);
glfwSetKeyCallback(slots[i].window, key_callback);
glfwSetCharCallback(slots[i].window, char_callback);
glfwSetDropCallback(slots[i].window, drop_callback);
glfwMakeContextCurrent(slots[i].window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
}
printf("Main loop starting\n");
for (;;)
{
for (i = 0; i < count; i++)
{
if (glfwWindowShouldClose(slots[i].window))
break;
}
if (i < count)
break;
glfwWaitEvents();
// Workaround for an issue with msvcrt and mintty
fflush(stdout);
}
free(slots);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/msaa.c | .c | 6,134 | 221 | //========================================================================
// Multisample anti-aliasing test
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test renders two high contrast, slowly rotating quads, one aliased
// and one (hopefully) anti-aliased, thus allowing for visual verification
// of whether MSAA is indeed enabled
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#if defined(_MSC_VER)
// Make MS math.h define M_PI
#define _USE_MATH_DEFINES
#endif
#include "linmath.h"
#include <stdio.h>
#include <stdlib.h>
#include "getopt.h"
static const vec2 vertices[4] =
{
{ -0.6f, -0.6f },
{ 0.6f, -0.6f },
{ 0.6f, 0.6f },
{ -0.6f, 0.6f }
};
static const char* vertex_shader_text =
"#version 110\n"
"uniform mat4 MVP;\n"
"attribute vec2 vPos;\n"
"void main()\n"
"{\n"
" gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n"
"}\n";
static const char* fragment_shader_text =
"#version 110\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(1.0);\n"
"}\n";
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_SPACE:
glfwSetTime(0.0);
break;
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
}
}
static void usage(void)
{
printf("Usage: msaa [-h] [-s SAMPLES]\n");
}
int main(int argc, char** argv)
{
int ch, samples = 4;
GLFWwindow* window;
GLuint vertex_buffer, vertex_shader, fragment_shader, program;
GLint mvp_location, vpos_location;
while ((ch = getopt(argc, argv, "hs:")) != -1)
{
switch (ch)
{
case 'h':
usage();
exit(EXIT_SUCCESS);
case 's':
samples = atoi(optarg);
break;
default:
usage();
exit(EXIT_FAILURE);
}
}
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
if (samples)
printf("Requesting MSAA with %i samples\n", samples);
else
printf("Requesting that MSAA not be available\n");
glfwWindowHint(GLFW_SAMPLES, samples);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
window = glfwCreateWindow(800, 400, "Aliasing Detector", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
glGetIntegerv(GL_SAMPLES, &samples);
if (samples)
printf("Context reports MSAA is available with %i samples\n", samples);
else
printf("Context reports MSAA is unavailable\n");
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
glCompileShader(vertex_shader);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
glCompileShader(fragment_shader);
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
mvp_location = glGetUniformLocation(program, "MVP");
vpos_location = glGetAttribLocation(program, "vPos");
glEnableVertexAttribArray(vpos_location);
glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
sizeof(vertices[0]), (void*) 0);
while (!glfwWindowShouldClose(window))
{
float ratio;
int width, height;
mat4x4 m, p, mvp;
const double angle = glfwGetTime() * M_PI / 180.0;
glfwGetFramebufferSize(window, &width, &height);
ratio = width / (float) height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 0.f, 1.f);
mat4x4_translate(m, -1.f, 0.f, 0.f);
mat4x4_rotate_Z(m, m, (float) angle);
mat4x4_mul(mvp, p, m);
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
glDisable(GL_MULTISAMPLE);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
mat4x4_translate(m, 1.f, 0.f, 0.f);
mat4x4_rotate_Z(m, m, (float) angle);
mat4x4_mul(mvp, p, m);
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
glEnable(GL_MULTISAMPLE);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/threads.c | .c | 4,098 | 153 | //========================================================================
// Multi-threading test
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This test is intended to verify whether the OpenGL context part of
// the GLFW API is able to be used from multiple threads
//
//========================================================================
#include "tinycthread.h"
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct
{
GLFWwindow* window;
const char* title;
float r, g, b;
thrd_t id;
} Thread;
static volatile int running = GLFW_TRUE;
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
static int thread_main(void* data)
{
const Thread* thread = data;
glfwMakeContextCurrent(thread->window);
glfwSwapInterval(1);
while (running)
{
const float v = (float) fabs(sin(glfwGetTime() * 2.f));
glClearColor(thread->r * v, thread->g * v, thread->b * v, 0.f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(thread->window);
}
glfwMakeContextCurrent(NULL);
return 0;
}
int main(void)
{
int i, result;
Thread threads[] =
{
{ NULL, "Red", 1.f, 0.f, 0.f, 0 },
{ NULL, "Green", 0.f, 1.f, 0.f, 0 },
{ NULL, "Blue", 0.f, 0.f, 1.f, 0 }
};
const int count = sizeof(threads) / sizeof(Thread);
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
for (i = 0; i < count; i++)
{
threads[i].window = glfwCreateWindow(200, 200,
threads[i].title,
NULL, NULL);
if (!threads[i].window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(threads[i].window, key_callback);
glfwSetWindowPos(threads[i].window, 200 + 250 * i, 200);
glfwShowWindow(threads[i].window);
}
glfwMakeContextCurrent(threads[0].window);
gladLoadGL(glfwGetProcAddress);
glfwMakeContextCurrent(NULL);
for (i = 0; i < count; i++)
{
if (thrd_create(&threads[i].id, thread_main, threads + i) !=
thrd_success)
{
fprintf(stderr, "Failed to create secondary thread\n");
glfwTerminate();
exit(EXIT_FAILURE);
}
}
while (running)
{
glfwWaitEvents();
for (i = 0; i < count; i++)
{
if (glfwWindowShouldClose(threads[i].window))
running = GLFW_FALSE;
}
}
for (i = 0; i < count; i++)
glfwHideWindow(threads[i].window);
for (i = 0; i < count; i++)
thrd_join(threads[i].id, &result);
exit(EXIT_SUCCESS);
}
| C |
2D | JaeHyunLee94/mpm2d | external/glfw/tests/triangle-vulkan.c | .c | 80,777 | 2,134 | /*
* Copyright (c) 2015-2016 The Khronos Group Inc.
* Copyright (c) 2015-2016 Valve Corporation
* Copyright (c) 2015-2016 LunarG, Inc.
*
* 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.
*
* Author: Chia-I Wu <olvaffe@gmail.com>
* Author: Cody Northrop <cody@lunarg.com>
* Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
* Author: Ian Elliott <ian@LunarG.com>
* Author: Jon Ashburn <jon@lunarg.com>
* Author: Piers Daniell <pdaniell@nvidia.com>
* Author: Gwan-gyeong Mun <elongbug@gmail.com>
* Porter: Camilla Löwy <elmindreda@glfw.org>
*/
/*
* Draw a textured triangle with depth testing. This is written against Intel
* ICD. It does not do state transition nor object memory binding like it
* should. It also does no error checking.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include <signal.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include <glad/vulkan.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#define DEMO_TEXTURE_COUNT 1
#define VERTEX_BUFFER_BIND_ID 0
#define APP_SHORT_NAME "tri"
#define APP_LONG_NAME "The Vulkan Triangle Demo Program"
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
#if defined(NDEBUG) && defined(__GNUC__)
#define U_ASSERT_ONLY __attribute__((unused))
#else
#define U_ASSERT_ONLY
#endif
#define ERR_EXIT(err_msg, err_class) \
do { \
printf(err_msg); \
fflush(stdout); \
exit(1); \
} while (0)
static GLADapiproc glad_vulkan_callback(const char* name, void* user)
{
return glfwGetInstanceProcAddress((VkInstance) user, name);
}
static const uint32_t fragShaderCode[] = {
0x07230203,0x00010000,0x00080007,0x00000014,0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x00000011,0x00030010,
0x00000004,0x00000007,0x00030003,0x00000002,0x00000190,0x00090004,0x415f4c47,0x735f4252,
0x72617065,0x5f657461,0x64616873,0x6f5f7265,0x63656a62,0x00007374,0x00090004,0x415f4c47,
0x735f4252,0x69646168,0x6c5f676e,0x75676e61,0x5f656761,0x70303234,0x006b6361,0x00040005,
0x00000004,0x6e69616d,0x00000000,0x00050005,0x00000009,0x61724675,0x6c6f4367,0x0000726f,
0x00030005,0x0000000d,0x00786574,0x00050005,0x00000011,0x63786574,0x64726f6f,0x00000000,
0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x00000022,0x00000000,
0x00040047,0x0000000d,0x00000021,0x00000000,0x00040047,0x00000011,0x0000001e,0x00000000,
0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,
0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003,0x00000007,
0x0004003b,0x00000008,0x00000009,0x00000003,0x00090019,0x0000000a,0x00000006,0x00000001,
0x00000000,0x00000000,0x00000000,0x00000001,0x00000000,0x0003001b,0x0000000b,0x0000000a,
0x00040020,0x0000000c,0x00000000,0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000000,
0x00040017,0x0000000f,0x00000006,0x00000002,0x00040020,0x00000010,0x00000001,0x0000000f,
0x0004003b,0x00000010,0x00000011,0x00000001,0x00050036,0x00000002,0x00000004,0x00000000,
0x00000003,0x000200f8,0x00000005,0x0004003d,0x0000000b,0x0000000e,0x0000000d,0x0004003d,
0x0000000f,0x00000012,0x00000011,0x00050057,0x00000007,0x00000013,0x0000000e,0x00000012,
0x0003003e,0x00000009,0x00000013,0x000100fd,0x00010038
};
static const uint32_t vertShaderCode[] = {
0x07230203,0x00010000,0x00080007,0x00000018,0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
0x0009000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000b,0x00000010,
0x00000014,0x00030003,0x00000002,0x00000190,0x00090004,0x415f4c47,0x735f4252,0x72617065,
0x5f657461,0x64616873,0x6f5f7265,0x63656a62,0x00007374,0x00090004,0x415f4c47,0x735f4252,
0x69646168,0x6c5f676e,0x75676e61,0x5f656761,0x70303234,0x006b6361,0x00040005,0x00000004,
0x6e69616d,0x00000000,0x00050005,0x00000009,0x63786574,0x64726f6f,0x00000000,0x00040005,
0x0000000b,0x72747461,0x00000000,0x00060005,0x0000000e,0x505f6c67,0x65567265,0x78657472,
0x00000000,0x00060006,0x0000000e,0x00000000,0x505f6c67,0x7469736f,0x006e6f69,0x00030005,
0x00000010,0x00000000,0x00030005,0x00000014,0x00736f70,0x00040047,0x00000009,0x0000001e,
0x00000000,0x00040047,0x0000000b,0x0000001e,0x00000001,0x00050048,0x0000000e,0x00000000,
0x0000000b,0x00000000,0x00030047,0x0000000e,0x00000002,0x00040047,0x00000014,0x0000001e,
0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,
0x00000020,0x00040017,0x00000007,0x00000006,0x00000002,0x00040020,0x00000008,0x00000003,
0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040020,0x0000000a,0x00000001,
0x00000007,0x0004003b,0x0000000a,0x0000000b,0x00000001,0x00040017,0x0000000d,0x00000006,
0x00000004,0x0003001e,0x0000000e,0x0000000d,0x00040020,0x0000000f,0x00000003,0x0000000e,
0x0004003b,0x0000000f,0x00000010,0x00000003,0x00040015,0x00000011,0x00000020,0x00000001,
0x0004002b,0x00000011,0x00000012,0x00000000,0x00040020,0x00000013,0x00000001,0x0000000d,
0x0004003b,0x00000013,0x00000014,0x00000001,0x00040020,0x00000016,0x00000003,0x0000000d,
0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x0004003d,
0x00000007,0x0000000c,0x0000000b,0x0003003e,0x00000009,0x0000000c,0x0004003d,0x0000000d,
0x00000015,0x00000014,0x00050041,0x00000016,0x00000017,0x00000010,0x00000012,0x0003003e,
0x00000017,0x00000015,0x000100fd,0x00010038
};
struct texture_object {
VkSampler sampler;
VkImage image;
VkImageLayout imageLayout;
VkDeviceMemory mem;
VkImageView view;
int32_t tex_width, tex_height;
};
static int validation_error = 0;
VKAPI_ATTR VkBool32 VKAPI_CALL
BreakCallback(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType,
uint64_t srcObject, size_t location, int32_t msgCode,
const char *pLayerPrefix, const char *pMsg,
void *pUserData) {
#ifdef _WIN32
DebugBreak();
#else
raise(SIGTRAP);
#endif
return false;
}
typedef struct {
VkImage image;
VkCommandBuffer cmd;
VkImageView view;
} SwapchainBuffers;
struct demo {
GLFWwindow* window;
VkSurfaceKHR surface;
bool use_staging_buffer;
VkInstance inst;
VkPhysicalDevice gpu;
VkDevice device;
VkQueue queue;
VkPhysicalDeviceProperties gpu_props;
VkPhysicalDeviceFeatures gpu_features;
VkQueueFamilyProperties *queue_props;
uint32_t graphics_queue_node_index;
uint32_t enabled_extension_count;
uint32_t enabled_layer_count;
const char *extension_names[64];
const char *enabled_layers[64];
int width, height;
VkFormat format;
VkColorSpaceKHR color_space;
uint32_t swapchainImageCount;
VkSwapchainKHR swapchain;
SwapchainBuffers *buffers;
VkCommandPool cmd_pool;
struct {
VkFormat format;
VkImage image;
VkDeviceMemory mem;
VkImageView view;
} depth;
struct texture_object textures[DEMO_TEXTURE_COUNT];
struct {
VkBuffer buf;
VkDeviceMemory mem;
VkPipelineVertexInputStateCreateInfo vi;
VkVertexInputBindingDescription vi_bindings[1];
VkVertexInputAttributeDescription vi_attrs[2];
} vertices;
VkCommandBuffer setup_cmd; // Command Buffer for initialization commands
VkCommandBuffer draw_cmd; // Command Buffer for drawing commands
VkPipelineLayout pipeline_layout;
VkDescriptorSetLayout desc_layout;
VkPipelineCache pipelineCache;
VkRenderPass render_pass;
VkPipeline pipeline;
VkShaderModule vert_shader_module;
VkShaderModule frag_shader_module;
VkDescriptorPool desc_pool;
VkDescriptorSet desc_set;
VkFramebuffer *framebuffers;
VkPhysicalDeviceMemoryProperties memory_properties;
int32_t curFrame;
int32_t frameCount;
bool validate;
bool use_break;
VkDebugReportCallbackEXT msg_callback;
float depthStencil;
float depthIncrement;
uint32_t current_buffer;
uint32_t queue_count;
};
VKAPI_ATTR VkBool32 VKAPI_CALL
dbgFunc(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType,
uint64_t srcObject, size_t location, int32_t msgCode,
const char *pLayerPrefix, const char *pMsg, void *pUserData) {
char *message = (char *)malloc(strlen(pMsg) + 100);
assert(message);
validation_error = 1;
if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
sprintf(message, "ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode,
pMsg);
} else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
sprintf(message, "WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode,
pMsg);
} else {
return false;
}
printf("%s\n", message);
fflush(stdout);
free(message);
/*
* false indicates that layer should not bail-out of an
* API call that had validation failures. This may mean that the
* app dies inside the driver due to invalid parameter(s).
* That's what would happen without validation layers, so we'll
* keep that behavior here.
*/
return false;
}
// Forward declaration:
static void demo_resize(struct demo *demo);
static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits,
VkFlags requirements_mask,
uint32_t *typeIndex) {
uint32_t i;
// Search memtypes to find first index with those properties
for (i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
if ((typeBits & 1) == 1) {
// Type is available, does it match user properties?
if ((demo->memory_properties.memoryTypes[i].propertyFlags &
requirements_mask) == requirements_mask) {
*typeIndex = i;
return true;
}
}
typeBits >>= 1;
}
// No memory types matched, return failure
return false;
}
static void demo_flush_init_cmd(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
if (demo->setup_cmd == VK_NULL_HANDLE)
return;
err = vkEndCommandBuffer(demo->setup_cmd);
assert(!err);
const VkCommandBuffer cmd_bufs[] = {demo->setup_cmd};
VkFence nullFence = {VK_NULL_HANDLE};
VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = NULL,
.waitSemaphoreCount = 0,
.pWaitSemaphores = NULL,
.pWaitDstStageMask = NULL,
.commandBufferCount = 1,
.pCommandBuffers = cmd_bufs,
.signalSemaphoreCount = 0,
.pSignalSemaphores = NULL};
err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence);
assert(!err);
err = vkQueueWaitIdle(demo->queue);
assert(!err);
vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
demo->setup_cmd = VK_NULL_HANDLE;
}
static void demo_set_image_layout(struct demo *demo, VkImage image,
VkImageAspectFlags aspectMask,
VkImageLayout old_image_layout,
VkImageLayout new_image_layout,
VkAccessFlagBits srcAccessMask) {
VkResult U_ASSERT_ONLY err;
if (demo->setup_cmd == VK_NULL_HANDLE) {
const VkCommandBufferAllocateInfo cmd = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.pNext = NULL,
.commandPool = demo->cmd_pool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = 1,
};
err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->setup_cmd);
assert(!err);
VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = NULL,
.flags = 0,
.pInheritanceInfo = NULL,
};
err = vkBeginCommandBuffer(demo->setup_cmd, &cmd_buf_info);
assert(!err);
}
VkImageMemoryBarrier image_memory_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = srcAccessMask,
.dstAccessMask = 0,
.oldLayout = old_image_layout,
.newLayout = new_image_layout,
.image = image,
.subresourceRange = {aspectMask, 0, 1, 0, 1}};
if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
/* Make sure anything that was copying from this image has completed */
image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
}
if (new_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
image_memory_barrier.dstAccessMask =
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
}
if (new_image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
image_memory_barrier.dstAccessMask =
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
}
if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
/* Make sure any Copy or CPU writes to image are flushed */
image_memory_barrier.dstAccessMask =
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
}
VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier;
VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
vkCmdPipelineBarrier(demo->setup_cmd, src_stages, dest_stages, 0, 0, NULL,
0, NULL, 1, pmemory_barrier);
}
static void demo_draw_build_cmd(struct demo *demo) {
const VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = NULL,
.flags = 0,
.pInheritanceInfo = NULL,
};
const VkClearValue clear_values[2] = {
[0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
[1] = {.depthStencil = {demo->depthStencil, 0}},
};
const VkRenderPassBeginInfo rp_begin = {
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
.pNext = NULL,
.renderPass = demo->render_pass,
.framebuffer = demo->framebuffers[demo->current_buffer],
.renderArea.offset.x = 0,
.renderArea.offset.y = 0,
.renderArea.extent.width = demo->width,
.renderArea.extent.height = demo->height,
.clearValueCount = 2,
.pClearValues = clear_values,
};
VkResult U_ASSERT_ONLY err;
err = vkBeginCommandBuffer(demo->draw_cmd, &cmd_buf_info);
assert(!err);
// We can use LAYOUT_UNDEFINED as a wildcard here because we don't care what
// happens to the previous contents of the image
VkImageMemoryBarrier image_memory_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = 0,
.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = demo->buffers[demo->current_buffer].image,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
vkCmdPipelineBarrier(demo->draw_cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
NULL, 1, &image_memory_barrier);
vkCmdBeginRenderPass(demo->draw_cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS,
demo->pipeline);
vkCmdBindDescriptorSets(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS,
demo->pipeline_layout, 0, 1, &demo->desc_set, 0,
NULL);
VkViewport viewport;
memset(&viewport, 0, sizeof(viewport));
viewport.height = (float)demo->height;
viewport.width = (float)demo->width;
viewport.minDepth = (float)0.0f;
viewport.maxDepth = (float)1.0f;
vkCmdSetViewport(demo->draw_cmd, 0, 1, &viewport);
VkRect2D scissor;
memset(&scissor, 0, sizeof(scissor));
scissor.extent.width = demo->width;
scissor.extent.height = demo->height;
scissor.offset.x = 0;
scissor.offset.y = 0;
vkCmdSetScissor(demo->draw_cmd, 0, 1, &scissor);
VkDeviceSize offsets[1] = {0};
vkCmdBindVertexBuffers(demo->draw_cmd, VERTEX_BUFFER_BIND_ID, 1,
&demo->vertices.buf, offsets);
vkCmdDraw(demo->draw_cmd, 3, 1, 0, 0);
vkCmdEndRenderPass(demo->draw_cmd);
VkImageMemoryBarrier prePresentBarrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
prePresentBarrier.image = demo->buffers[demo->current_buffer].image;
VkImageMemoryBarrier *pmemory_barrier = &prePresentBarrier;
vkCmdPipelineBarrier(demo->draw_cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
NULL, 1, pmemory_barrier);
err = vkEndCommandBuffer(demo->draw_cmd);
assert(!err);
}
static void demo_draw(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
VkSemaphore imageAcquiredSemaphore, drawCompleteSemaphore;
VkSemaphoreCreateInfo semaphoreCreateInfo = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
.pNext = NULL,
.flags = 0,
};
err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo,
NULL, &imageAcquiredSemaphore);
assert(!err);
err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo,
NULL, &drawCompleteSemaphore);
assert(!err);
// Get the index of the next available swapchain image:
err = vkAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX,
imageAcquiredSemaphore,
(VkFence)0, // TODO: Show use of fence
&demo->current_buffer);
if (err == VK_ERROR_OUT_OF_DATE_KHR) {
// demo->swapchain is out of date (e.g. the window was resized) and
// must be recreated:
demo_resize(demo);
demo_draw(demo);
vkDestroySemaphore(demo->device, imageAcquiredSemaphore, NULL);
vkDestroySemaphore(demo->device, drawCompleteSemaphore, NULL);
return;
} else if (err == VK_SUBOPTIMAL_KHR) {
// demo->swapchain is not as optimal as it could be, but the platform's
// presentation engine will still present the image correctly.
} else {
assert(!err);
}
demo_flush_init_cmd(demo);
// Wait for the present complete semaphore to be signaled to ensure
// that the image won't be rendered to until the presentation
// engine has fully released ownership to the application, and it is
// okay to render to the image.
demo_draw_build_cmd(demo);
VkFence nullFence = VK_NULL_HANDLE;
VkPipelineStageFlags pipe_stage_flags =
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = NULL,
.waitSemaphoreCount = 1,
.pWaitSemaphores = &imageAcquiredSemaphore,
.pWaitDstStageMask = &pipe_stage_flags,
.commandBufferCount = 1,
.pCommandBuffers = &demo->draw_cmd,
.signalSemaphoreCount = 1,
.pSignalSemaphores = &drawCompleteSemaphore};
err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence);
assert(!err);
VkPresentInfoKHR present = {
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
.pNext = NULL,
.waitSemaphoreCount = 1,
.pWaitSemaphores = &drawCompleteSemaphore,
.swapchainCount = 1,
.pSwapchains = &demo->swapchain,
.pImageIndices = &demo->current_buffer,
};
err = vkQueuePresentKHR(demo->queue, &present);
if (err == VK_ERROR_OUT_OF_DATE_KHR) {
// demo->swapchain is out of date (e.g. the window was resized) and
// must be recreated:
demo_resize(demo);
} else if (err == VK_SUBOPTIMAL_KHR) {
// demo->swapchain is not as optimal as it could be, but the platform's
// presentation engine will still present the image correctly.
} else {
assert(!err);
}
err = vkQueueWaitIdle(demo->queue);
assert(err == VK_SUCCESS);
vkDestroySemaphore(demo->device, imageAcquiredSemaphore, NULL);
vkDestroySemaphore(demo->device, drawCompleteSemaphore, NULL);
}
static void demo_prepare_buffers(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
VkSwapchainKHR oldSwapchain = demo->swapchain;
// Check the surface capabilities and formats
VkSurfaceCapabilitiesKHR surfCapabilities;
err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
demo->gpu, demo->surface, &surfCapabilities);
assert(!err);
uint32_t presentModeCount;
err = vkGetPhysicalDeviceSurfacePresentModesKHR(
demo->gpu, demo->surface, &presentModeCount, NULL);
assert(!err);
VkPresentModeKHR *presentModes =
(VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
assert(presentModes);
err = vkGetPhysicalDeviceSurfacePresentModesKHR(
demo->gpu, demo->surface, &presentModeCount, presentModes);
assert(!err);
VkExtent2D swapchainExtent;
// width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
if (surfCapabilities.currentExtent.width == 0xFFFFFFFF) {
// If the surface size is undefined, the size is set to the size
// of the images requested, which must fit within the minimum and
// maximum values.
swapchainExtent.width = demo->width;
swapchainExtent.height = demo->height;
if (swapchainExtent.width < surfCapabilities.minImageExtent.width) {
swapchainExtent.width = surfCapabilities.minImageExtent.width;
} else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) {
swapchainExtent.width = surfCapabilities.maxImageExtent.width;
}
if (swapchainExtent.height < surfCapabilities.minImageExtent.height) {
swapchainExtent.height = surfCapabilities.minImageExtent.height;
} else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) {
swapchainExtent.height = surfCapabilities.maxImageExtent.height;
}
} else {
// If the surface size is defined, the swap chain size must match
swapchainExtent = surfCapabilities.currentExtent;
demo->width = surfCapabilities.currentExtent.width;
demo->height = surfCapabilities.currentExtent.height;
}
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
// Determine the number of VkImage's to use in the swap chain.
// Application desires to only acquire 1 image at a time (which is
// "surfCapabilities.minImageCount").
uint32_t desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
// If maxImageCount is 0, we can ask for as many images as we want;
// otherwise we're limited to maxImageCount
if ((surfCapabilities.maxImageCount > 0) &&
(desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
// Application must settle for fewer images than desired:
desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
}
VkSurfaceTransformFlagsKHR preTransform;
if (surfCapabilities.supportedTransforms &
VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
} else {
preTransform = surfCapabilities.currentTransform;
}
const VkSwapchainCreateInfoKHR swapchain = {
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
.pNext = NULL,
.surface = demo->surface,
.minImageCount = desiredNumOfSwapchainImages,
.imageFormat = demo->format,
.imageColorSpace = demo->color_space,
.imageExtent =
{
.width = swapchainExtent.width, .height = swapchainExtent.height,
},
.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
.preTransform = preTransform,
.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
.imageArrayLayers = 1,
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = NULL,
.presentMode = swapchainPresentMode,
.oldSwapchain = oldSwapchain,
.clipped = true,
};
uint32_t i;
err = vkCreateSwapchainKHR(demo->device, &swapchain, NULL, &demo->swapchain);
assert(!err);
// If we just re-created an existing swapchain, we should destroy the old
// swapchain at this point.
// Note: destroying the swapchain also cleans up all its associated
// presentable images once the platform is done with them.
if (oldSwapchain != VK_NULL_HANDLE) {
vkDestroySwapchainKHR(demo->device, oldSwapchain, NULL);
}
err = vkGetSwapchainImagesKHR(demo->device, demo->swapchain,
&demo->swapchainImageCount, NULL);
assert(!err);
VkImage *swapchainImages =
(VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage));
assert(swapchainImages);
err = vkGetSwapchainImagesKHR(demo->device, demo->swapchain,
&demo->swapchainImageCount,
swapchainImages);
assert(!err);
demo->buffers = (SwapchainBuffers *)malloc(sizeof(SwapchainBuffers) *
demo->swapchainImageCount);
assert(demo->buffers);
for (i = 0; i < demo->swapchainImageCount; i++) {
VkImageViewCreateInfo color_attachment_view = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = NULL,
.format = demo->format,
.components =
{
.r = VK_COMPONENT_SWIZZLE_R,
.g = VK_COMPONENT_SWIZZLE_G,
.b = VK_COMPONENT_SWIZZLE_B,
.a = VK_COMPONENT_SWIZZLE_A,
},
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1},
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.flags = 0,
};
demo->buffers[i].image = swapchainImages[i];
color_attachment_view.image = demo->buffers[i].image;
err = vkCreateImageView(demo->device, &color_attachment_view, NULL,
&demo->buffers[i].view);
assert(!err);
}
demo->current_buffer = 0;
if (NULL != presentModes) {
free(presentModes);
}
}
static void demo_prepare_depth(struct demo *demo) {
const VkFormat depth_format = VK_FORMAT_D16_UNORM;
const VkImageCreateInfo image = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = NULL,
.imageType = VK_IMAGE_TYPE_2D,
.format = depth_format,
.extent = {demo->width, demo->height, 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
.flags = 0,
};
VkMemoryAllocateInfo mem_alloc = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = NULL,
.allocationSize = 0,
.memoryTypeIndex = 0,
};
VkImageViewCreateInfo view = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = NULL,
.image = VK_NULL_HANDLE,
.format = depth_format,
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1},
.flags = 0,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
};
VkMemoryRequirements mem_reqs;
VkResult U_ASSERT_ONLY err;
bool U_ASSERT_ONLY pass;
demo->depth.format = depth_format;
/* create image */
err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image);
assert(!err);
/* get memory requirements for this object */
vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs);
/* select memory size and type */
mem_alloc.allocationSize = mem_reqs.size;
pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
0, /* No requirements */
&mem_alloc.memoryTypeIndex);
assert(pass);
/* allocate memory */
err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->depth.mem);
assert(!err);
/* bind memory */
err =
vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0);
assert(!err);
demo_set_image_layout(demo, demo->depth.image, VK_IMAGE_ASPECT_DEPTH_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
0);
/* create image view */
view.image = demo->depth.image;
err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view);
assert(!err);
}
static void
demo_prepare_texture_image(struct demo *demo, const uint32_t *tex_colors,
struct texture_object *tex_obj, VkImageTiling tiling,
VkImageUsageFlags usage, VkFlags required_props) {
const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;
const int32_t tex_width = 2;
const int32_t tex_height = 2;
VkResult U_ASSERT_ONLY err;
bool U_ASSERT_ONLY pass;
tex_obj->tex_width = tex_width;
tex_obj->tex_height = tex_height;
const VkImageCreateInfo image_create_info = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = NULL,
.imageType = VK_IMAGE_TYPE_2D,
.format = tex_format,
.extent = {tex_width, tex_height, 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = tiling,
.usage = usage,
.flags = 0,
.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED
};
VkMemoryAllocateInfo mem_alloc = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = NULL,
.allocationSize = 0,
.memoryTypeIndex = 0,
};
VkMemoryRequirements mem_reqs;
err =
vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image);
assert(!err);
vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs);
mem_alloc.allocationSize = mem_reqs.size;
pass =
memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
required_props, &mem_alloc.memoryTypeIndex);
assert(pass);
/* allocate memory */
err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &tex_obj->mem);
assert(!err);
/* bind memory */
err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0);
assert(!err);
if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
const VkImageSubresource subres = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.arrayLayer = 0,
};
VkSubresourceLayout layout;
void *data;
int32_t x, y;
vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres,
&layout);
err = vkMapMemory(demo->device, tex_obj->mem, 0,
mem_alloc.allocationSize, 0, &data);
assert(!err);
for (y = 0; y < tex_height; y++) {
uint32_t *row = (uint32_t *)((char *)data + layout.rowPitch * y);
for (x = 0; x < tex_width; x++)
row[x] = tex_colors[(x & 1) ^ (y & 1)];
}
vkUnmapMemory(demo->device, tex_obj->mem);
}
tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
demo_set_image_layout(demo, tex_obj->image, VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_LAYOUT_PREINITIALIZED, tex_obj->imageLayout,
VK_ACCESS_HOST_WRITE_BIT);
/* setting the image layout does not reference the actual memory so no need
* to add a mem ref */
}
static void demo_destroy_texture_image(struct demo *demo,
struct texture_object *tex_obj) {
/* clean up staging resources */
vkDestroyImage(demo->device, tex_obj->image, NULL);
vkFreeMemory(demo->device, tex_obj->mem, NULL);
}
static void demo_prepare_textures(struct demo *demo) {
const VkFormat tex_format = VK_FORMAT_B8G8R8A8_UNORM;
VkFormatProperties props;
const uint32_t tex_colors[DEMO_TEXTURE_COUNT][2] = {
{0xffff0000, 0xff00ff00},
};
uint32_t i;
VkResult U_ASSERT_ONLY err;
vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props);
for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
if ((props.linearTilingFeatures &
VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) &&
!demo->use_staging_buffer) {
/* Device can texture using linear textures */
demo_prepare_texture_image(
demo, tex_colors[i], &demo->textures[i], VK_IMAGE_TILING_LINEAR,
VK_IMAGE_USAGE_SAMPLED_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
} else if (props.optimalTilingFeatures &
VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
/* Must use staging buffer to copy linear texture to optimized */
struct texture_object staging_texture;
memset(&staging_texture, 0, sizeof(staging_texture));
demo_prepare_texture_image(
demo, tex_colors[i], &staging_texture, VK_IMAGE_TILING_LINEAR,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
demo_prepare_texture_image(
demo, tex_colors[i], &demo->textures[i],
VK_IMAGE_TILING_OPTIMAL,
(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
demo_set_image_layout(demo, staging_texture.image,
VK_IMAGE_ASPECT_COLOR_BIT,
staging_texture.imageLayout,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
0);
demo_set_image_layout(demo, demo->textures[i].image,
VK_IMAGE_ASPECT_COLOR_BIT,
demo->textures[i].imageLayout,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
0);
VkImageCopy copy_region = {
.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffset = {0, 0, 0},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffset = {0, 0, 0},
.extent = {staging_texture.tex_width,
staging_texture.tex_height, 1},
};
vkCmdCopyImage(
demo->setup_cmd, staging_texture.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, demo->textures[i].image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region);
demo_set_image_layout(demo, demo->textures[i].image,
VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
demo->textures[i].imageLayout,
0);
demo_flush_init_cmd(demo);
demo_destroy_texture_image(demo, &staging_texture);
} else {
/* Can't support VK_FORMAT_B8G8R8A8_UNORM !? */
assert(!"No support for B8G8R8A8_UNORM as texture image format");
}
const VkSamplerCreateInfo sampler = {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.pNext = NULL,
.magFilter = VK_FILTER_NEAREST,
.minFilter = VK_FILTER_NEAREST,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1,
.compareOp = VK_COMPARE_OP_NEVER,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
.unnormalizedCoordinates = VK_FALSE,
};
VkImageViewCreateInfo view = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = NULL,
.image = VK_NULL_HANDLE,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = tex_format,
.components =
{
VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A,
},
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
.flags = 0,
};
/* create sampler */
err = vkCreateSampler(demo->device, &sampler, NULL,
&demo->textures[i].sampler);
assert(!err);
/* create image view */
view.image = demo->textures[i].image;
err = vkCreateImageView(demo->device, &view, NULL,
&demo->textures[i].view);
assert(!err);
}
}
static void demo_prepare_vertices(struct demo *demo) {
// clang-format off
const float vb[3][5] = {
/* position texcoord */
{ -1.0f, -1.0f, 0.25f, 0.0f, 0.0f },
{ 1.0f, -1.0f, 0.25f, 1.0f, 0.0f },
{ 0.0f, 1.0f, 1.0f, 0.5f, 1.0f },
};
// clang-format on
const VkBufferCreateInfo buf_info = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = NULL,
.size = sizeof(vb),
.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
.flags = 0,
};
VkMemoryAllocateInfo mem_alloc = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = NULL,
.allocationSize = 0,
.memoryTypeIndex = 0,
};
VkMemoryRequirements mem_reqs;
VkResult U_ASSERT_ONLY err;
bool U_ASSERT_ONLY pass;
void *data;
memset(&demo->vertices, 0, sizeof(demo->vertices));
err = vkCreateBuffer(demo->device, &buf_info, NULL, &demo->vertices.buf);
assert(!err);
vkGetBufferMemoryRequirements(demo->device, demo->vertices.buf, &mem_reqs);
assert(!err);
mem_alloc.allocationSize = mem_reqs.size;
pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&mem_alloc.memoryTypeIndex);
assert(pass);
err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->vertices.mem);
assert(!err);
err = vkMapMemory(demo->device, demo->vertices.mem, 0,
mem_alloc.allocationSize, 0, &data);
assert(!err);
memcpy(data, vb, sizeof(vb));
vkUnmapMemory(demo->device, demo->vertices.mem);
err = vkBindBufferMemory(demo->device, demo->vertices.buf,
demo->vertices.mem, 0);
assert(!err);
demo->vertices.vi.sType =
VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
demo->vertices.vi.pNext = NULL;
demo->vertices.vi.vertexBindingDescriptionCount = 1;
demo->vertices.vi.pVertexBindingDescriptions = demo->vertices.vi_bindings;
demo->vertices.vi.vertexAttributeDescriptionCount = 2;
demo->vertices.vi.pVertexAttributeDescriptions = demo->vertices.vi_attrs;
demo->vertices.vi_bindings[0].binding = VERTEX_BUFFER_BIND_ID;
demo->vertices.vi_bindings[0].stride = sizeof(vb[0]);
demo->vertices.vi_bindings[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
demo->vertices.vi_attrs[0].binding = VERTEX_BUFFER_BIND_ID;
demo->vertices.vi_attrs[0].location = 0;
demo->vertices.vi_attrs[0].format = VK_FORMAT_R32G32B32_SFLOAT;
demo->vertices.vi_attrs[0].offset = 0;
demo->vertices.vi_attrs[1].binding = VERTEX_BUFFER_BIND_ID;
demo->vertices.vi_attrs[1].location = 1;
demo->vertices.vi_attrs[1].format = VK_FORMAT_R32G32_SFLOAT;
demo->vertices.vi_attrs[1].offset = sizeof(float) * 3;
}
static void demo_prepare_descriptor_layout(struct demo *demo) {
const VkDescriptorSetLayoutBinding layout_binding = {
.binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = DEMO_TEXTURE_COUNT,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
.pImmutableSamplers = NULL,
};
const VkDescriptorSetLayoutCreateInfo descriptor_layout = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.pNext = NULL,
.bindingCount = 1,
.pBindings = &layout_binding,
};
VkResult U_ASSERT_ONLY err;
err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL,
&demo->desc_layout);
assert(!err);
const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.pNext = NULL,
.setLayoutCount = 1,
.pSetLayouts = &demo->desc_layout,
};
err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL,
&demo->pipeline_layout);
assert(!err);
}
static void demo_prepare_render_pass(struct demo *demo) {
const VkAttachmentDescription attachments[2] = {
[0] =
{
.format = demo->format,
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
},
[1] =
{
.format = demo->depth.format,
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.initialLayout =
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
.finalLayout =
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
},
};
const VkAttachmentReference color_reference = {
.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
};
const VkAttachmentReference depth_reference = {
.attachment = 1,
.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
};
const VkSubpassDescription subpass = {
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.flags = 0,
.inputAttachmentCount = 0,
.pInputAttachments = NULL,
.colorAttachmentCount = 1,
.pColorAttachments = &color_reference,
.pResolveAttachments = NULL,
.pDepthStencilAttachment = &depth_reference,
.preserveAttachmentCount = 0,
.pPreserveAttachments = NULL,
};
const VkRenderPassCreateInfo rp_info = {
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
.pNext = NULL,
.attachmentCount = 2,
.pAttachments = attachments,
.subpassCount = 1,
.pSubpasses = &subpass,
.dependencyCount = 0,
.pDependencies = NULL,
};
VkResult U_ASSERT_ONLY err;
err = vkCreateRenderPass(demo->device, &rp_info, NULL, &demo->render_pass);
assert(!err);
}
static VkShaderModule
demo_prepare_shader_module(struct demo *demo, const void *code, size_t size) {
VkShaderModuleCreateInfo moduleCreateInfo;
VkShaderModule module;
VkResult U_ASSERT_ONLY err;
moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
moduleCreateInfo.pNext = NULL;
moduleCreateInfo.codeSize = size;
moduleCreateInfo.pCode = code;
moduleCreateInfo.flags = 0;
err = vkCreateShaderModule(demo->device, &moduleCreateInfo, NULL, &module);
assert(!err);
return module;
}
static VkShaderModule demo_prepare_vs(struct demo *demo) {
size_t size = sizeof(vertShaderCode);
demo->vert_shader_module =
demo_prepare_shader_module(demo, vertShaderCode, size);
return demo->vert_shader_module;
}
static VkShaderModule demo_prepare_fs(struct demo *demo) {
size_t size = sizeof(fragShaderCode);
demo->frag_shader_module =
demo_prepare_shader_module(demo, fragShaderCode, size);
return demo->frag_shader_module;
}
static void demo_prepare_pipeline(struct demo *demo) {
VkGraphicsPipelineCreateInfo pipeline;
VkPipelineCacheCreateInfo pipelineCache;
VkPipelineVertexInputStateCreateInfo vi;
VkPipelineInputAssemblyStateCreateInfo ia;
VkPipelineRasterizationStateCreateInfo rs;
VkPipelineColorBlendStateCreateInfo cb;
VkPipelineDepthStencilStateCreateInfo ds;
VkPipelineViewportStateCreateInfo vp;
VkPipelineMultisampleStateCreateInfo ms;
VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE];
VkPipelineDynamicStateCreateInfo dynamicState;
VkResult U_ASSERT_ONLY err;
memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
memset(&dynamicState, 0, sizeof dynamicState);
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.pDynamicStates = dynamicStateEnables;
memset(&pipeline, 0, sizeof(pipeline));
pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline.layout = demo->pipeline_layout;
vi = demo->vertices.vi;
memset(&ia, 0, sizeof(ia));
ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
memset(&rs, 0, sizeof(rs));
rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rs.polygonMode = VK_POLYGON_MODE_FILL;
rs.cullMode = VK_CULL_MODE_BACK_BIT;
rs.frontFace = VK_FRONT_FACE_CLOCKWISE;
rs.depthClampEnable = VK_FALSE;
rs.rasterizerDiscardEnable = VK_FALSE;
rs.depthBiasEnable = VK_FALSE;
rs.lineWidth = 1.0f;
memset(&cb, 0, sizeof(cb));
cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
VkPipelineColorBlendAttachmentState att_state[1];
memset(att_state, 0, sizeof(att_state));
att_state[0].colorWriteMask = 0xf;
att_state[0].blendEnable = VK_FALSE;
cb.attachmentCount = 1;
cb.pAttachments = att_state;
memset(&vp, 0, sizeof(vp));
vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
vp.viewportCount = 1;
dynamicStateEnables[dynamicState.dynamicStateCount++] =
VK_DYNAMIC_STATE_VIEWPORT;
vp.scissorCount = 1;
dynamicStateEnables[dynamicState.dynamicStateCount++] =
VK_DYNAMIC_STATE_SCISSOR;
memset(&ds, 0, sizeof(ds));
ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
ds.depthTestEnable = VK_TRUE;
ds.depthWriteEnable = VK_TRUE;
ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
ds.depthBoundsTestEnable = VK_FALSE;
ds.back.failOp = VK_STENCIL_OP_KEEP;
ds.back.passOp = VK_STENCIL_OP_KEEP;
ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
ds.stencilTestEnable = VK_FALSE;
ds.front = ds.back;
memset(&ms, 0, sizeof(ms));
ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
ms.pSampleMask = NULL;
ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
// Two stages: vs and fs
pipeline.stageCount = 2;
VkPipelineShaderStageCreateInfo shaderStages[2];
memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStages[0].module = demo_prepare_vs(demo);
shaderStages[0].pName = "main";
shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStages[1].module = demo_prepare_fs(demo);
shaderStages[1].pName = "main";
pipeline.pVertexInputState = &vi;
pipeline.pInputAssemblyState = &ia;
pipeline.pRasterizationState = &rs;
pipeline.pColorBlendState = &cb;
pipeline.pMultisampleState = &ms;
pipeline.pViewportState = &vp;
pipeline.pDepthStencilState = &ds;
pipeline.pStages = shaderStages;
pipeline.renderPass = demo->render_pass;
pipeline.pDynamicState = &dynamicState;
memset(&pipelineCache, 0, sizeof(pipelineCache));
pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL,
&demo->pipelineCache);
assert(!err);
err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1,
&pipeline, NULL, &demo->pipeline);
assert(!err);
vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL);
vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL);
}
static void demo_prepare_descriptor_pool(struct demo *demo) {
const VkDescriptorPoolSize type_count = {
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = DEMO_TEXTURE_COUNT,
};
const VkDescriptorPoolCreateInfo descriptor_pool = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.pNext = NULL,
.maxSets = 1,
.poolSizeCount = 1,
.pPoolSizes = &type_count,
};
VkResult U_ASSERT_ONLY err;
err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL,
&demo->desc_pool);
assert(!err);
}
static void demo_prepare_descriptor_set(struct demo *demo) {
VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
VkWriteDescriptorSet write;
VkResult U_ASSERT_ONLY err;
uint32_t i;
VkDescriptorSetAllocateInfo alloc_info = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.pNext = NULL,
.descriptorPool = demo->desc_pool,
.descriptorSetCount = 1,
.pSetLayouts = &demo->desc_layout};
err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->desc_set);
assert(!err);
memset(&tex_descs, 0, sizeof(tex_descs));
for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
tex_descs[i].sampler = demo->textures[i].sampler;
tex_descs[i].imageView = demo->textures[i].view;
tex_descs[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
}
memset(&write, 0, sizeof(write));
write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write.dstSet = demo->desc_set;
write.descriptorCount = DEMO_TEXTURE_COUNT;
write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write.pImageInfo = tex_descs;
vkUpdateDescriptorSets(demo->device, 1, &write, 0, NULL);
}
static void demo_prepare_framebuffers(struct demo *demo) {
VkImageView attachments[2];
attachments[1] = demo->depth.view;
const VkFramebufferCreateInfo fb_info = {
.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
.pNext = NULL,
.renderPass = demo->render_pass,
.attachmentCount = 2,
.pAttachments = attachments,
.width = demo->width,
.height = demo->height,
.layers = 1,
};
VkResult U_ASSERT_ONLY err;
uint32_t i;
demo->framebuffers = (VkFramebuffer *)malloc(demo->swapchainImageCount *
sizeof(VkFramebuffer));
assert(demo->framebuffers);
for (i = 0; i < demo->swapchainImageCount; i++) {
attachments[0] = demo->buffers[i].view;
err = vkCreateFramebuffer(demo->device, &fb_info, NULL,
&demo->framebuffers[i]);
assert(!err);
}
}
static void demo_prepare(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
const VkCommandPoolCreateInfo cmd_pool_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.pNext = NULL,
.queueFamilyIndex = demo->graphics_queue_node_index,
.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
};
err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL,
&demo->cmd_pool);
assert(!err);
const VkCommandBufferAllocateInfo cmd = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.pNext = NULL,
.commandPool = demo->cmd_pool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = 1,
};
err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->draw_cmd);
assert(!err);
demo_prepare_buffers(demo);
demo_prepare_depth(demo);
demo_prepare_textures(demo);
demo_prepare_vertices(demo);
demo_prepare_descriptor_layout(demo);
demo_prepare_render_pass(demo);
demo_prepare_pipeline(demo);
demo_prepare_descriptor_pool(demo);
demo_prepare_descriptor_set(demo);
demo_prepare_framebuffers(demo);
}
static void demo_error_callback(int error, const char* description) {
printf("GLFW error: %s\n", description);
fflush(stdout);
}
static void demo_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
static void demo_refresh_callback(GLFWwindow* window) {
struct demo* demo = glfwGetWindowUserPointer(window);
demo_draw(demo);
}
static void demo_resize_callback(GLFWwindow* window, int width, int height) {
struct demo* demo = glfwGetWindowUserPointer(window);
demo->width = width;
demo->height = height;
demo_resize(demo);
}
static void demo_run(struct demo *demo) {
while (!glfwWindowShouldClose(demo->window)) {
glfwPollEvents();
demo_draw(demo);
if (demo->depthStencil > 0.99f)
demo->depthIncrement = -0.001f;
if (demo->depthStencil < 0.8f)
demo->depthIncrement = 0.001f;
demo->depthStencil += demo->depthIncrement;
// Wait for work to finish before updating MVP.
vkDeviceWaitIdle(demo->device);
demo->curFrame++;
if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount)
glfwSetWindowShouldClose(demo->window, GLFW_TRUE);
}
}
static void demo_create_window(struct demo *demo) {
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
demo->window = glfwCreateWindow(demo->width,
demo->height,
APP_LONG_NAME,
NULL,
NULL);
if (!demo->window) {
// It didn't work, so try to give a useful error:
printf("Cannot create a window in which to draw!\n");
fflush(stdout);
exit(1);
}
glfwSetWindowUserPointer(demo->window, demo);
glfwSetWindowRefreshCallback(demo->window, demo_refresh_callback);
glfwSetFramebufferSizeCallback(demo->window, demo_resize_callback);
glfwSetKeyCallback(demo->window, demo_key_callback);
}
/*
* Return 1 (true) if all layer names specified in check_names
* can be found in given layer properties.
*/
static VkBool32 demo_check_layers(uint32_t check_count, const char **check_names,
uint32_t layer_count,
VkLayerProperties *layers) {
uint32_t i, j;
for (i = 0; i < check_count; i++) {
VkBool32 found = 0;
for (j = 0; j < layer_count; j++) {
if (!strcmp(check_names[i], layers[j].layerName)) {
found = 1;
break;
}
}
if (!found) {
fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
return 0;
}
}
return 1;
}
static void demo_init_vk(struct demo *demo) {
VkResult err;
uint32_t i = 0;
uint32_t required_extension_count = 0;
uint32_t instance_extension_count = 0;
uint32_t instance_layer_count = 0;
uint32_t validation_layer_count = 0;
const char **required_extensions = NULL;
const char **instance_validation_layers = NULL;
demo->enabled_extension_count = 0;
demo->enabled_layer_count = 0;
char *instance_validation_layers_alt1[] = {
"VK_LAYER_LUNARG_standard_validation"
};
char *instance_validation_layers_alt2[] = {
"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation",
"VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_image",
"VK_LAYER_LUNARG_core_validation", "VK_LAYER_LUNARG_swapchain",
"VK_LAYER_GOOGLE_unique_objects"
};
/* Look for validation layers */
VkBool32 validation_found = 0;
if (demo->validate) {
err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL);
assert(!err);
instance_validation_layers = (const char**) instance_validation_layers_alt1;
if (instance_layer_count > 0) {
VkLayerProperties *instance_layers =
malloc(sizeof (VkLayerProperties) * instance_layer_count);
err = vkEnumerateInstanceLayerProperties(&instance_layer_count,
instance_layers);
assert(!err);
validation_found = demo_check_layers(
ARRAY_SIZE(instance_validation_layers_alt1),
instance_validation_layers, instance_layer_count,
instance_layers);
if (validation_found) {
demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1);
demo->enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation";
validation_layer_count = 1;
} else {
// use alternative set of validation layers
instance_validation_layers =
(const char**) instance_validation_layers_alt2;
demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
validation_found = demo_check_layers(
ARRAY_SIZE(instance_validation_layers_alt2),
instance_validation_layers, instance_layer_count,
instance_layers);
validation_layer_count =
ARRAY_SIZE(instance_validation_layers_alt2);
for (i = 0; i < validation_layer_count; i++) {
demo->enabled_layers[i] = instance_validation_layers[i];
}
}
free(instance_layers);
}
if (!validation_found) {
ERR_EXIT("vkEnumerateInstanceLayerProperties failed to find "
"required validation layer.\n\n"
"Please look at the Getting Started guide for additional "
"information.\n",
"vkCreateInstance Failure");
}
}
/* Look for instance extensions */
required_extensions = glfwGetRequiredInstanceExtensions(&required_extension_count);
if (!required_extensions) {
ERR_EXIT("glfwGetRequiredInstanceExtensions failed to find the "
"platform surface extensions.\n\nDo you have a compatible "
"Vulkan installable client driver (ICD) installed?\nPlease "
"look at the Getting Started guide for additional "
"information.\n",
"vkCreateInstance Failure");
}
for (i = 0; i < required_extension_count; i++) {
demo->extension_names[demo->enabled_extension_count++] = required_extensions[i];
assert(demo->enabled_extension_count < 64);
}
err = vkEnumerateInstanceExtensionProperties(
NULL, &instance_extension_count, NULL);
assert(!err);
if (instance_extension_count > 0) {
VkExtensionProperties *instance_extensions =
malloc(sizeof(VkExtensionProperties) * instance_extension_count);
err = vkEnumerateInstanceExtensionProperties(
NULL, &instance_extension_count, instance_extensions);
assert(!err);
for (i = 0; i < instance_extension_count; i++) {
if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME,
instance_extensions[i].extensionName)) {
if (demo->validate) {
demo->extension_names[demo->enabled_extension_count++] =
VK_EXT_DEBUG_REPORT_EXTENSION_NAME;
}
}
assert(demo->enabled_extension_count < 64);
}
free(instance_extensions);
}
const VkApplicationInfo app = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pNext = NULL,
.pApplicationName = APP_SHORT_NAME,
.applicationVersion = 0,
.pEngineName = APP_SHORT_NAME,
.engineVersion = 0,
.apiVersion = VK_API_VERSION_1_0,
};
VkInstanceCreateInfo inst_info = {
.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
.pNext = NULL,
.pApplicationInfo = &app,
.enabledLayerCount = demo->enabled_layer_count,
.ppEnabledLayerNames = (const char *const *)instance_validation_layers,
.enabledExtensionCount = demo->enabled_extension_count,
.ppEnabledExtensionNames = (const char *const *)demo->extension_names,
};
uint32_t gpu_count;
err = vkCreateInstance(&inst_info, NULL, &demo->inst);
if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
ERR_EXIT("Cannot find a compatible Vulkan installable client driver "
"(ICD).\n\nPlease look at the Getting Started guide for "
"additional information.\n",
"vkCreateInstance Failure");
} else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) {
ERR_EXIT("Cannot find a specified extension library"
".\nMake sure your layers path is set appropriately\n",
"vkCreateInstance Failure");
} else if (err) {
ERR_EXIT("vkCreateInstance failed.\n\nDo you have a compatible Vulkan "
"installable client driver (ICD) installed?\nPlease look at "
"the Getting Started guide for additional information.\n",
"vkCreateInstance Failure");
}
gladLoadVulkanUserPtr(NULL, glad_vulkan_callback, demo->inst);
/* Make initial call to query gpu_count, then second call for gpu info*/
err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, NULL);
assert(!err && gpu_count > 0);
if (gpu_count > 0) {
VkPhysicalDevice *physical_devices =
malloc(sizeof(VkPhysicalDevice) * gpu_count);
err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count,
physical_devices);
assert(!err);
/* For tri demo we just grab the first physical device */
demo->gpu = physical_devices[0];
free(physical_devices);
} else {
ERR_EXIT("vkEnumeratePhysicalDevices reported zero accessible devices."
"\n\nDo you have a compatible Vulkan installable client"
" driver (ICD) installed?\nPlease look at the Getting Started"
" guide for additional information.\n",
"vkEnumeratePhysicalDevices Failure");
}
gladLoadVulkanUserPtr(demo->gpu, glad_vulkan_callback, demo->inst);
/* Look for device extensions */
uint32_t device_extension_count = 0;
VkBool32 swapchainExtFound = 0;
demo->enabled_extension_count = 0;
err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL,
&device_extension_count, NULL);
assert(!err);
if (device_extension_count > 0) {
VkExtensionProperties *device_extensions =
malloc(sizeof(VkExtensionProperties) * device_extension_count);
err = vkEnumerateDeviceExtensionProperties(
demo->gpu, NULL, &device_extension_count, device_extensions);
assert(!err);
for (i = 0; i < device_extension_count; i++) {
if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME,
device_extensions[i].extensionName)) {
swapchainExtFound = 1;
demo->extension_names[demo->enabled_extension_count++] =
VK_KHR_SWAPCHAIN_EXTENSION_NAME;
}
assert(demo->enabled_extension_count < 64);
}
free(device_extensions);
}
if (!swapchainExtFound) {
ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find "
"the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
" extension.\n\nDo you have a compatible "
"Vulkan installable client driver (ICD) installed?\nPlease "
"look at the Getting Started guide for additional "
"information.\n",
"vkCreateInstance Failure");
}
if (demo->validate) {
VkDebugReportCallbackCreateInfoEXT dbgCreateInfo;
dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
dbgCreateInfo.flags =
VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
dbgCreateInfo.pfnCallback = demo->use_break ? BreakCallback : dbgFunc;
dbgCreateInfo.pUserData = demo;
dbgCreateInfo.pNext = NULL;
err = vkCreateDebugReportCallbackEXT(demo->inst, &dbgCreateInfo, NULL,
&demo->msg_callback);
switch (err) {
case VK_SUCCESS:
break;
case VK_ERROR_OUT_OF_HOST_MEMORY:
ERR_EXIT("CreateDebugReportCallback: out of host memory\n",
"CreateDebugReportCallback Failure");
break;
default:
ERR_EXIT("CreateDebugReportCallback: unknown failure\n",
"CreateDebugReportCallback Failure");
break;
}
}
vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props);
// Query with NULL data to get count
vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count,
NULL);
demo->queue_props = (VkQueueFamilyProperties *)malloc(
demo->queue_count * sizeof(VkQueueFamilyProperties));
vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count,
demo->queue_props);
assert(demo->queue_count >= 1);
vkGetPhysicalDeviceFeatures(demo->gpu, &demo->gpu_features);
// Graphics queue and MemMgr queue can be separate.
// TODO: Add support for separate queues, including synchronization,
// and appropriate tracking for QueueSubmit
}
static void demo_init_device(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
float queue_priorities[1] = {0.0};
const VkDeviceQueueCreateInfo queue = {
.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
.pNext = NULL,
.queueFamilyIndex = demo->graphics_queue_node_index,
.queueCount = 1,
.pQueuePriorities = queue_priorities};
VkPhysicalDeviceFeatures features;
memset(&features, 0, sizeof(features));
if (demo->gpu_features.shaderClipDistance) {
features.shaderClipDistance = VK_TRUE;
}
VkDeviceCreateInfo device = {
.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
.pNext = NULL,
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &queue,
.enabledLayerCount = 0,
.ppEnabledLayerNames = NULL,
.enabledExtensionCount = demo->enabled_extension_count,
.ppEnabledExtensionNames = (const char *const *)demo->extension_names,
.pEnabledFeatures = &features,
};
err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device);
assert(!err);
}
static void demo_init_vk_swapchain(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
uint32_t i;
// Create a WSI surface for the window:
glfwCreateWindowSurface(demo->inst, demo->window, NULL, &demo->surface);
// Iterate over each queue to learn whether it supports presenting:
VkBool32 *supportsPresent =
(VkBool32 *)malloc(demo->queue_count * sizeof(VkBool32));
for (i = 0; i < demo->queue_count; i++) {
vkGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface,
&supportsPresent[i]);
}
// Search for a graphics and a present queue in the array of queue
// families, try to find one that supports both
uint32_t graphicsQueueNodeIndex = UINT32_MAX;
uint32_t presentQueueNodeIndex = UINT32_MAX;
for (i = 0; i < demo->queue_count; i++) {
if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
if (graphicsQueueNodeIndex == UINT32_MAX) {
graphicsQueueNodeIndex = i;
}
if (supportsPresent[i] == VK_TRUE) {
graphicsQueueNodeIndex = i;
presentQueueNodeIndex = i;
break;
}
}
}
if (presentQueueNodeIndex == UINT32_MAX) {
// If didn't find a queue that supports both graphics and present, then
// find a separate present queue.
for (i = 0; i < demo->queue_count; ++i) {
if (supportsPresent[i] == VK_TRUE) {
presentQueueNodeIndex = i;
break;
}
}
}
free(supportsPresent);
// Generate error if could not find both a graphics and a present queue
if (graphicsQueueNodeIndex == UINT32_MAX ||
presentQueueNodeIndex == UINT32_MAX) {
ERR_EXIT("Could not find a graphics and a present queue\n",
"Swapchain Initialization Failure");
}
// TODO: Add support for separate queues, including presentation,
// synchronization, and appropriate tracking for QueueSubmit.
// NOTE: While it is possible for an application to use a separate graphics
// and a present queues, this demo program assumes it is only using
// one:
if (graphicsQueueNodeIndex != presentQueueNodeIndex) {
ERR_EXIT("Could not find a common graphics and a present queue\n",
"Swapchain Initialization Failure");
}
demo->graphics_queue_node_index = graphicsQueueNodeIndex;
demo_init_device(demo);
vkGetDeviceQueue(demo->device, demo->graphics_queue_node_index, 0,
&demo->queue);
// Get the list of VkFormat's that are supported:
uint32_t formatCount;
err = vkGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface,
&formatCount, NULL);
assert(!err);
VkSurfaceFormatKHR *surfFormats =
(VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
err = vkGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface,
&formatCount, surfFormats);
assert(!err);
// If the format list includes just one entry of VK_FORMAT_UNDEFINED,
// the surface has no preferred format. Otherwise, at least one
// supported format will be returned.
if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) {
demo->format = VK_FORMAT_B8G8R8A8_UNORM;
} else {
assert(formatCount >= 1);
demo->format = surfFormats[0].format;
}
demo->color_space = surfFormats[0].colorSpace;
demo->curFrame = 0;
// Get Memory information and properties
vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties);
}
static void demo_init_connection(struct demo *demo) {
glfwSetErrorCallback(demo_error_callback);
if (!glfwInit()) {
printf("Cannot initialize GLFW.\nExiting ...\n");
fflush(stdout);
exit(1);
}
if (!glfwVulkanSupported()) {
printf("GLFW failed to find the Vulkan loader.\nExiting ...\n");
fflush(stdout);
exit(1);
}
gladLoadVulkanUserPtr(NULL, glad_vulkan_callback, NULL);
}
static void demo_init(struct demo *demo, const int argc, const char *argv[])
{
int i;
memset(demo, 0, sizeof(*demo));
demo->frameCount = INT32_MAX;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--use_staging") == 0) {
demo->use_staging_buffer = true;
continue;
}
if (strcmp(argv[i], "--break") == 0) {
demo->use_break = true;
continue;
}
if (strcmp(argv[i], "--validate") == 0) {
demo->validate = true;
continue;
}
if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX &&
i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 &&
demo->frameCount >= 0) {
i++;
continue;
}
fprintf(stderr, "Usage:\n %s [--use_staging] [--validate] [--break] "
"[--c <framecount>]\n",
APP_SHORT_NAME);
fflush(stderr);
exit(1);
}
demo_init_connection(demo);
demo_init_vk(demo);
demo->width = 300;
demo->height = 300;
demo->depthStencil = 1.0;
demo->depthIncrement = -0.01f;
}
static void demo_cleanup(struct demo *demo) {
uint32_t i;
for (i = 0; i < demo->swapchainImageCount; i++) {
vkDestroyFramebuffer(demo->device, demo->framebuffers[i], NULL);
}
free(demo->framebuffers);
vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
if (demo->setup_cmd) {
vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->setup_cmd);
}
vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->draw_cmd);
vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
vkDestroyPipeline(demo->device, demo->pipeline, NULL);
vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
vkDestroyBuffer(demo->device, demo->vertices.buf, NULL);
vkFreeMemory(demo->device, demo->vertices.mem, NULL);
for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
vkDestroyImage(demo->device, demo->textures[i].image, NULL);
vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
}
for (i = 0; i < demo->swapchainImageCount; i++) {
vkDestroyImageView(demo->device, demo->buffers[i].view, NULL);
}
vkDestroyImageView(demo->device, demo->depth.view, NULL);
vkDestroyImage(demo->device, demo->depth.image, NULL);
vkFreeMemory(demo->device, demo->depth.mem, NULL);
vkDestroySwapchainKHR(demo->device, demo->swapchain, NULL);
free(demo->buffers);
vkDestroyDevice(demo->device, NULL);
if (demo->validate) {
vkDestroyDebugReportCallbackEXT(demo->inst, demo->msg_callback, NULL);
}
vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
vkDestroyInstance(demo->inst, NULL);
free(demo->queue_props);
glfwDestroyWindow(demo->window);
glfwTerminate();
}
static void demo_resize(struct demo *demo) {
uint32_t i;
// In order to properly resize the window, we must re-create the swapchain
// AND redo the command buffers, etc.
//
// First, perform part of the demo_cleanup() function:
for (i = 0; i < demo->swapchainImageCount; i++) {
vkDestroyFramebuffer(demo->device, demo->framebuffers[i], NULL);
}
free(demo->framebuffers);
vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
if (demo->setup_cmd) {
vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->setup_cmd);
demo->setup_cmd = VK_NULL_HANDLE;
}
vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->draw_cmd);
vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
vkDestroyPipeline(demo->device, demo->pipeline, NULL);
vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
vkDestroyBuffer(demo->device, demo->vertices.buf, NULL);
vkFreeMemory(demo->device, demo->vertices.mem, NULL);
for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
vkDestroyImage(demo->device, demo->textures[i].image, NULL);
vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
}
for (i = 0; i < demo->swapchainImageCount; i++) {
vkDestroyImageView(demo->device, demo->buffers[i].view, NULL);
}
vkDestroyImageView(demo->device, demo->depth.view, NULL);
vkDestroyImage(demo->device, demo->depth.image, NULL);
vkFreeMemory(demo->device, demo->depth.mem, NULL);
free(demo->buffers);
// Second, re-perform the demo_prepare() function, which will re-create the
// swapchain:
demo_prepare(demo);
}
int main(const int argc, const char *argv[]) {
struct demo demo;
demo_init(&demo, argc, argv);
demo_create_window(&demo);
demo_init_vk_swapchain(&demo);
demo_prepare(&demo);
demo_run(&demo);
demo_cleanup(&demo);
return validation_error;
}
| C |
2D | gvanderheide/discreteMarkovChain | setup.py | .py | 1,495 | 45 | """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='discreteMarkovChain',
version='0.22',
description='Solve Markov chains with a discrete state space.',
long_description=long_description,
url='https://github.com/gvanderheide/discreteMarkovChain',
author='Gerlach van der Heide',
author_email='g.van.der.heide@rug.nl',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Mathematics',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Operating System :: OS Independent',
],
keywords='Markov chain stochastic stationary steady state',
packages=find_packages(),
install_requires=['numpy','scipy'],
test_suite='tests',
)
| Python |
2D | gvanderheide/discreteMarkovChain | backup.md | .md | 8,109 | 176 | #discreteMarkovChain
While for statistical and scientific programming languages such as R various packages are available for analyzing Markov chains, equivalent packages in Python are rather scarce. This discreteMarkovChain package for Python addresses the problem of obtaining the steady state distribution of a Markov chain, also known as the stationary distribution, limiting distribution or invariant measure. The package is for Markov chains with discrete and finite state spaces, which are most commonly encountered in practical applications.
This package is based on numpy and scipy for efficient computations and limited use of resources. Markov chains with several million states can be solved. The package introduces the `markovChain` class which has the following features.
* States can be either integers or vectors of integers.
* Steady state distributions can be calculated for continous time Markov chains (CTMC) as well as discrete time Markov chains (DTMC).
* The user can either manually specify the probability/rate matrix of the Markov chain, or let the program do this automatically using an indirect or direct method.
* The indirect method requires the user to specify an initial state and transition function (giving for each state the reachable states and their probabilities/rates).
* By repeatedly calling the transition function on unvisited states, the state space and the probability matrix are built up automatically.
* This makes it easy to implement your own Markov chains!
* The direct method requires the user to specify a transition function and a function that gives the complete state space.
* While the implementation is typically more complex, this may have some computational advantage over the indirect method for large state spaces with vector states.
* The steady state distribution can be calculated by a method of choice:
* The power method,
* Solving a system of linear equations,
* Determing the first left eigenvector,
* Searching in Krylov subspace.
* Checks are included to see whether all states in the Markov chain are connected.
* Memory consumption is reduced by using sparse matrices.
When the user calls a certain solution method, the `markovChain` object gets the attribute `pi` which specifies the steady state probability of each state. When the user uses the direct or indirect method, the object gets the `mapping` attribute which is a dictionary that links each index of `pi` with a corresponding state. Using the `mapping` and `pi`, it becomes simple to calculate performance measures for your Markov chain, such as the average cost per time unit or the number of blocked customers in a queue with blocking.
###Installation
The package can be installed with the command
pip install discreteMarkovChain
or by downloading the source distribution and installing manually with
python setup.py install
###Examples
The `markovChain` class can be used to initialize your own Markov chains. We import it by using
```python
from discreteMarkovChain import markovChain
```
First, lets consider a simple Markov chain with two states, where we already know the probability matrix `P`.
```python
P = np.array([[0.5,0.5],[0.6,0.4]])
mc = markovChain(P)
mc.computePi('linear') #We can also use 'power', 'krylov' or 'eigen'
print(mc.pi)
```
We get the following steady state probabilities:
```python
[ 0.54545455 0.45454545]
```
Now we show an example of a one-dimensional random walk in continuous time between integers `m` and `M`. We move up and down with rates 1. We will use the indirect method to determine the rate matrix for us automatically. The indirect method is rather flexible, and allows the transition function to return a dictionary with reachable states and rates. We first introduce our `randomWalk` class.
```python
class randomWalk(markovChain):
#A random walk where we move up and down with rate 1.0 in each state between bounds m and M.
#For the transition function to work well, we define some class variables in the __init__ function.
def __init__(self,m,M):
super(randomWalk, self).__init__() #always use this as first line when creating your own __init__
self.initialState = m
self.m = m
self.M = M
self.uprate = 1.0
self.downrate = 1.0
def transition(self,state):
#Specify the reachable states from state and their rates.
#A dictionary is extremely easy here!
rates = {}
if self.m < state < self.M:
rates[state+1] = self.uprate
rates[state-1] = self.downrate
elif state == self.m:
rates[state+1] = self.uprate
elif state == self.M:
rates[state-1] = self.downrate
return rates
```
Now we initialize the random walk with some values for `m` and `M` and calculate the steady-state vector `pi`.
```python
mc = randomWalk(0,5)
mc.computePi()
mc.printPi()
```
The stationary probabilities are given below.
```python
0 0.166666666667
1 0.166666666667
2 0.166666666667
3 0.166666666667
4 0.166666666667
5 0.166666666667
```
Not unexpectedly, they are the same for each state. We can repeat this for a multi-dimensional random walk. Now we use the direct method. Here, we need to use a transition function returning numpy arrays and we need to define a function that calculates the state space. For explanation of the transition function, see the example [here](docs/multirandomwalk.ipynb).
```python
from discreteMarkovChain import partition
class randomWalkNumpy(markovChain):
#Now we do the same thing with a transition function that returns a 2d numpy array.
#We also specify the statespace function so we can use the direct method.
#This one is defined immediately for general n.
def __init__(self,m,M,n,direct=True):
super(randomWalkNumpy, self).__init__(direct=direct)
self.initialState = m*np.ones(n,dtype=int)
self.n = n
self.m = m
self.M = M
self.uprate = 1.0
self.downrate = 1.0
#It is useful to define the variable 'events' for the the transition function.
#The possible events are 'move up' or 'move down' in one of the random walks.
#The rates of these events are given in 'eventRates'.
self.events = np.vstack((np.eye(n,dtype=int),-np.eye(n,dtype=int)))
self.eventRates = np.array([self.uprate]*n+[self.downrate]*n)
def transition(self,state):
#First check for the current state which of the 'move up' and 'move down' events are possible.
up = state < self.M
down = state > self.m
possibleEvents = np.concatenate((up,down)) #Combine into one boolean array.
#The possible states after the transition follow by adding the possible 'move up'/'move down' events to the current state.
newstates = state+self.events[possibleEvents]
rates = self.eventRates[possibleEvents]
return newstates,rates
def statespace(self):
#Each random walk can be in a state between m and M.
#The function partition() gives all partitions of integers between min_range and max_range.
min_range = [self.m]*self.n
max_range = [self.M]*self.n
return partition(min_range,max_range)
```
Now we initialize `n=2` random walks between `m=0` and `M=2` and print the stationary distribution.
```python
mc = randomWalkNumpy(0,2,n=2)
mc.computePi('linear')
mc.printPi()
[0 0] 0.111111111111
[1 0] 0.111111111111
[2 0] 0.111111111111
[0 1] 0.111111111111
[1 1] 0.111111111111
[2 1] 0.111111111111
[0 2] 0.111111111111
[1 2] 0.111111111111
[2 2] 0.111111111111
```
We could also solve much larger models. The example below has random walks in 5 dimensions with 100.000 states. For these larger models, it is often better to use the power method. The linear algebra solver may run into memory problems.
```python
mc = randomWalkNumpy(0,9,n=5)
mc.computePi('power')
```
On a dual core computer from 2006, the rate matrix and `pi` can be calculated within 10 seconds.
| Markdown |
2D | gvanderheide/discreteMarkovChain | discreteMarkovChain/hitting_time.py | .py | 1,491 | 72 | import numpy as np
from numpy import linalg as LA
from discreteMarkovChain import markovChain
class randomWalk(markovChain):
"""
A random walk where we move up and down with rate 1.0 in each
state between bounds m and M.
For the transition function to work well, we define some
class variables in the __init__ function.
"""
def __init__(self,m,M):
super(randomWalk, self).__init__()
self.initialState = m
self.m = m
self.M = M
self.uprate = 1.0
self.downrate = 1.0
def transition(self,state):
#Specify the reachable states from state and their rates.
#A dictionary is extremely easy here!
rates = {}
if self.m < state < self.M:
rates[state+1] = self.uprate
rates[state-1] = self.downrate
elif state == self.m:
rates[state+1] = self.uprate
elif state == self.M:
rates[state-1] = self.downrate
return rates
mc = randomWalk(0,5)
P = mc.getTransitionMatrix()
hittingset=[0]
one = np.ones(mc.size)
one[hittingset] = 0
k = np.zeros(mc.size)
for i in range(100):
k = P.dot(k)+one
k[hittingset] = 0
print(k)
mask = np.zeros(mc.size)
for i in range(mc.size):
if i in hittingset:
mask[i]=1
k1 = np.zeros(mc.size)
k2 = one + P.dot(k1)
i = 0
while(LA.norm(k1-k2)>1e-6):
k1=k2
k2 = one + P.dot(k1)
np.putmask(k2, mask, 0)
i += 1
print(k2)
print(i)
| Python |
2D | gvanderheide/discreteMarkovChain | discreteMarkovChain/__init__.py | .py | 68 | 2 | from .markovChain import markovChain
from .usefulFunctions import * | Python |
2D | gvanderheide/discreteMarkovChain | discreteMarkovChain/usefulFunctions.py | .py | 5,174 | 142 | from __future__ import print_function
import numpy as np
def uniqueStates(states,rates):
"""
Returns unique states and sums up the corresponding rates.
States should be a 2d numpy array with on each row a state, and rates a 1d numpy array with length equal to the number of rows in states.
This may be helpful in the transition function for summing up the rates of different transitions that lead to the same state
"""
order = np.lexsort(states.T)
states = states[order]
diff = np.ones(len(states), 'bool')
diff[1:] = (states[1:] != states[:-1]).any(-1)
sums = np.bincount(diff.cumsum() - 1, rates[order])
return states[diff], sums
def number_of_partitions(max_range, max_sum):
'''
Returns an array arr of the same shape as max_range, where
arr[j] = number of admissible partitions for
j summands bounded by max_range[j:] and with sum <= max_sum
'''
M = max_sum + 1
N = len(max_range)
arr = np.zeros(shape=(M,N), dtype = int)
arr[:,-1] = np.where(np.arange(M) <= min(max_range[-1], max_sum), 1, 0)
for i in range(N-2,-1,-1):
for j in range(max_range[i]+1):
arr[j:,i] += arr[:M-j,i+1]
return arr.sum(axis = 0)
def partition_zero(max_range, max_sum, out = None, n_part = None):
'''
Function that can be helpful for obtaining the state space of a discrete Markov chain or Markov decision processes.
Returns a 2d-array with on the rows all possible partitions of the ranges `0,...,max_range[j]` that add up to at most `max_sum`.
Code due to ptrj, see http://stackoverflow.com/a/36563744/1479342.
Parameters
----------
max_range : array or list of ints
Gives the ranges for each element in the output array. Element `j` has range `np.arange(max_range[j]+1)`.
max_sum : int
The maximum sum for each partition in the output array.
Returns
-------
out : array
2d array with all possible partitions of the ranges `0,...,max_range[j]` summing up to at most `max_sum`.
Example
-------
>>> max_range=np.array([1,3,2])
>>> max_sum = 3
>>> partition_zero(max_range,max_sum)
array([[0, 0, 0],
[0, 0, 1],
[0, 0, 2],
[0, 1, 0],
[0, 1, 1],
[0, 1, 2],
[0, 2, 0],
[0, 2, 1],
[0, 3, 0],
[1, 0, 0],
[1, 0, 1],
[1, 0, 2],
[1, 1, 0],
[1, 1, 1],
[1, 2, 0]])
'''
if out is None:
max_range = np.asarray(max_range, dtype = int).ravel()
n_part = number_of_partitions(max_range, max_sum)
out = np.zeros(shape = (n_part[0], max_range.size), dtype = int)
if(max_range.size == 1):
out[:] = np.arange(min(max_range[0],max_sum) + 1, dtype = int).reshape(-1,1)
return out
P = partition_zero(max_range[1:], max_sum, out=out[:n_part[1],1:], n_part = n_part[1:])
S = np.minimum(max_sum - P.sum(axis = 1), max_range[0])
offset, sz = 0, S.size
out[:sz,0] = 0
for i in range(1, max_range[0]+1):
ind, = np.nonzero(S)
offset, sz = offset + sz, ind.size
out[offset:offset+sz, 0] = i
out[offset:offset+sz, 1:] = P[ind]
S[ind] -= 1
return out
def partition(min_range,max_range,max_sum=None):
'''
Function that can be helpful for obtaining the state space of a discrete Markov chain or Markov decision processes.
Returns a 2d-array with on the rows all possible partitions of the ranges `min_range[j],...,max_range[j]` for each j.
If the argument `max_sum` is specified, the numbers will add up to at most `max_sum`
Parameters
----------
min_range : array or list of ints
`min_range[j]` gives the minimum value for element `j` in the output array.
max_range : array or list of ints
`max_range[j]` gives the maximum value for element `j` in the output array.
max_sum : int
Optional argument. The maximum sum for each partition in the output array.
Returns
-------
out : array
2d array with all possible partitions of the ranges `min_range[j],...,max_range[j]` summing up to at most `max_sum`.
Example
-------
>>> min_range=np.array([1,2,1])
>>> max_range=np.array([2,4,3])
>>> max_sum = 6
>>> partition(min_range,max_range,max_sum)
array([[1, 2, 1],
[1, 2, 2],
[1, 2, 3],
[1, 3, 1],
[1, 3, 2],
[1, 4, 1],
[2, 2, 1],
[2, 2, 2],
[2, 3, 1]])
'''
max_range = np.asarray(max_range, dtype = int).ravel()
min_range = np.asarray(min_range, dtype = int).ravel()
full_range = max_range-min_range
if any(full_range<0):
raise ValueError("max_range needs to be larger than min_range")
if max_sum == None:
max_sum = np.sum(full_range)
else:
max_sum -= np.sum(min_range)
out = partition_zero(full_range,max_sum)
out += min_range
return out | Python |
2D | gvanderheide/discreteMarkovChain | discreteMarkovChain/markovChain.py | .py | 29,464 | 642 | """
Possible fixes:
-Check that the state codes do not suffer from integer overflow.
-Improve memory usage.
"""
from __future__ import print_function
import numpy as np
from scipy.sparse import coo_matrix,csr_matrix, csgraph, eye, vstack, isspmatrix, isspmatrix_csr
from scipy.sparse.linalg import eigs, gmres, spsolve, inv
from numpy.linalg import norm
from collections import OrderedDict,defaultdict
from scipy.sparse import dok_matrix
try: #For python 3 functionality.
from itertools import imap
except ImportError:
imap = map
class markovChain(object):
"""
A class for calculating the steady state distribution of a Markov chain with a finite and discrete state space.
The Markov chain can be defined on continuous time or discrete time and states can be integers or vectors of integers.
Summary
-------
If the transition matrix ``P`` is specified by the user, we use that for calculating the steady-state distribution.
Otherwise, we derive ``P`` automatically using an indirect or a direct method.
Both the indirect and direct method require the function :func:`transition` to be defined within the class, calculating for each state the reachable states and corresponding rates/probabilities.
Implementing this function is similar in difficulty as constructing ``P`` manually, since when you construct ``P`` you also have to determine where you can go from any given state.
For the indirect method the user needs to specify an initial state in the class attribute ``initialState``.
By repeatedly calling the transition function on unvisited states, all reachable states are determined starting from this initial state.
For the direct method the function :func:`statespace` is required, giving the complete state space in a 2d numpy array.
We build up ``P`` by calling :func:`transition` on each state in the statespace.
Steady state distributions can be calculated by calling :func:`computePi` with a method of choice.
Parameters
----------
P : array(float,ndim=2), optional(default=None)
Optional argument. The transition matrix of the Markov chain. Needs to have an equal number of columns and rows. Can be sparse or dense.
direct : bool, optional(default=False)
Specifies whether the indirect method is used or the direct method in case ``P`` is not defined. By default, ``direct=False``.
Attributes
----------
pi : array(float)
The steady state probabilities for each state in the state space.
mapping : dict
The keys are the indices of the states in ``P`` and ``pi``, the values are the states. Useful only when using the direct/indirect method.
size : int
The size of the state space.
P : scipy.sparse.csr_matrix
The sparse transition/rate matrix.
initialState : int or array_like(int)
State from which to start the indirect method. Should be provided in the subclass by the user.
Methods
-------
transition(state)
Transition function of the Markov chain, returning the reachable states from `state` and their probabilities/rates.
Should be be provided in the subclass by the user when using the indirect/direct method.
statespace()
Returns the state space of the Markov chain. Should be be provided in the subclass by the user when using the direct method.
computePi(method='power')
Call with 'power','linear','eigen' or 'krylov' to use a certain method for obtaining ``pi``.
printPi()
Print all states and their corresponding steady state probabilities. Not recommended for large state spaces.
linearMethod()
Use :func:`spsolve`, the standard linear algebra solver for sparse matrices, to obtain ``pi``.
powerMethod(tol=1e-8,numIter=1e5)
Use repeated multiplication of the transition matrix to obtain ``pi``.
eigenMethod(tol=1e-8,numIter=1e5)
Search for the first left eigenvalue to obtain ``pi``.
krylovMethod(tol=1e-8)
Search for ``pi`` in Krylov subspace using the :func:`gmres` procedure for sparse matrices.
Example
-------
>>> P = np.array([[0.5,0.5],[0.6,0.4]])
>>> mc = markovChain(P)
>>> mc.computePi('power') #alternative: 'linear','eigen' or 'krylov'.
>>> print(mc.pi)
[ 0.54545455 0.45454545]
"""
def __init__(self,P=None,direct=False):
self.P = P
self.direct = direct
self.pi = None #steady state probability vector
self.mapping = {} #mapping used to identify states
self.initialState = None #a dummy initial state
@property
def size(self):
"""
Return the number of states in the state space, if ``self.mapping`` is defined.
"""
return len(self.mapping)
def statespace(self):
"""
To be provided by the subclass. Return the state space
in an integer 2d numpy array with a state on each row.
"""
raise NotImplementedError('Implement the function statespace() in the subclass')
def transition(self, state):
"""
To be provided by the subclass.
Return a 2d numpy array with reachable states and a 1d numpy array with transition rates.
For the iterative method, it is also allowed to return a dictionary where the keys are tuples with the state and the values are the transition rates.
Ensure that unique states are returned.
"""
raise NotImplementedError('Implement the function transition() in the subclass')
def checkInitialState(self,initialState):
"""
Check whether the initial state is of the correct type.
The state should be either an int, list, tuple or np.array and all its elements must be integer.
Returns an int if the state is an integer, otherwise a tuple.
"""
assert initialState is not None, "Initial state has not been specified."
assert isinstance(initialState,(int,list,tuple,np.ndarray,set)), "initialState %r is not an int, tuple, list, set or numpy array" % initialState
if isinstance(initialState,list):
#Check whether all entries of the list are ints. Return an int if the len ==1, otherwise a tuple.
assert all(isinstance(i, int) for i in initialState), "initialState %r is not integer" % initialState
initialState = int(initialState) if len(initialState)==1 else tuple(initialState)
elif isinstance(initialState,tuple):
#Check whether all entries are ints. Return an int if the len ==1, otherwise a tuple.
assert all(isinstance(i, int) for i in initialState), "initialState %r is not integer" % initialState
if len(initialState)==1:
initialState = int(initialState)
elif isinstance(initialState,np.ndarray):
#Check whether the state is a 1d numpy array. Return an int if it has length 1.
assert issubclass(initialState.dtype.type, np.integer) and initialState.ndim==1, "initialState %r is not a one-dimensional integer numpy array" % initialState
initialState = int(initialState) if len(initialState)==1 else tuple(initialState)
elif isinstance(initialState,set):
#If we have a set, then check whether all elements are ints or tuples.
for state in initialState:
assert isinstance(state,(tuple,int)), "the set initialState %r should contain tuples or ints" % initialState
if isinstance(state,tuple):
assert all(isinstance(i,int) for i in state), "the state %r should be integer" % initialState
return initialState
def checkTransitionType(self,state):
"""
Check whether the transition function returns output of the correct types.
This can be either a dictionary with as keys ints/tuples and values floats.
Or a tuple consisting of a 2d integer numpy array with states and a 1d numpy array with rates.
"""
test = self.transition(state)
assert isinstance(test,(dict,tuple)), "Transition function does not return a dict or tuple"
if isinstance(test,dict):
assert all(isinstance(states, (int,tuple)) for states in test.keys()), "Transition function returns a dict, but states are not represented as tuples or integers"
assert all(isinstance(rates, float) for rates in test.values()), "Transition function returns a dict, but the rates should be floats."
usesNumpy=False
if isinstance(test,tuple):
assert len(test)==2, "The transition function should return two variables: states and rates."
states,rates = test
assert isinstance(states, np.ndarray) and states.ndim==2 and issubclass(states.dtype.type, np.integer), "The states returned by the transition function need to be an integer 2d numpy array: %r" %states
assert isinstance(rates, np.ndarray) and rates.ndim==1, "The rates returned by the transition function need to be a 1d numpy array: %r" % rates
usesNumpy = True
return usesNumpy
def convertToTransitionDict(self,transitions):
"""
If numpy is used, then this converts the output from transition() into a dict.
"""
states,rates = transitions
rateDict = defaultdict(float)
if states.shape[1] == 1:
for idx,state in enumerate(states):
rateDict[int(state)] += rates[idx]
else:
for idx,state in enumerate(states):
rateDict[tuple(state)] += rates[idx]
return rateDict
def indirectInitialMatrix(self, initialState):
"""
Given some initial state, this iteratively determines new states.
We repeatedly call the transition function on unvisited states in the frontier set.
Each newly visited state is put in a dictionary called 'mapping' and the rates are stored in a dictionary.
"""
mapping = {}
rates = OrderedDict()
#Check whether the initial state is defined and of the correct type, and convert to a tuple or int.
convertedState = self.checkInitialState(initialState)
if isinstance(convertedState,set):
#If initialstates is a set, include all states in the set in the mapping.
frontier = set( convertedState )
for idx,state in enumerate(convertedState):
mapping[state] = idx
if idx == 0: #Test the return type of the transition function (dict or numpy).
usesNumpy = self.checkTransitionType(initialState)
else:
#Otherwise include only the single state.
frontier = set( [convertedState] )
usesNumpy = self.checkTransitionType(initialState)
mapping[convertedState] = 0
while len(frontier) > 0:
fromstate = frontier.pop()
fromindex = mapping[fromstate]
if usesNumpy: #If numpy is used, convert to a dictionary with tuples and rates.
transitions = self.transition(np.array(fromstate))
transitions = self.convertToTransitionDict(transitions)
else:
transitions = self.transition(fromstate)
for tostate,rate in transitions.items():
if tostate not in mapping:
frontier.add(tostate)
mapping[tostate] = len(mapping)
toindex = mapping[tostate]
rates[(fromindex, toindex)] = rate
#Inverse the keys and values in mapping to get a dictionary with indices and states.
self.mapping = {value: key for key, value in list(mapping.items())}
#Use the `rates` dictionary to fill a sparse dok matrix.
D = dok_matrix((self.size,self.size))
D.update(rates)
return D.tocsr()
def getStateCode(self,state):
"""
Calculates the state code for a specific state or set of states.
We transform the states so that they are nonnegative and take an inner product.
The resulting number is unique because we use numeral system with a large enough base.
"""
return np.dot(state-self.minvalues,self.statecode)
def setStateCodes(self):
"""
Generates (sorted) codes for the states in the statespace
This is used to quickly identify which states occur after a transition/action
"""
#calculate the statespace and determine the minima and maxima each element in the state vector
statespace = self.statespace()
self.minvalues = np.amin(statespace,axis=0)
self.maxvalues = np.amax(statespace,axis=0)
#calculate the largest number of values and create a state code
statesize = statespace.shape[1]
largestRange = 1+np.max(self.maxvalues-self.minvalues)
self.statecode = np.power(largestRange, np.arange(statesize),dtype=int)
#Calculate the codes, sort them, and store them in self.codes
codes = self.getStateCode(statespace)
sorted_indices = np.argsort(codes)
self.codes = codes[sorted_indices]
if np.unique(self.codes).shape != self.codes.shape:
raise "Non-unique coding of states, results are unreliable"
#For the end results, it is useful to put the indices and corresponding states in a dictionary
mapping = OrderedDict()
for index,state in enumerate(statespace[sorted_indices]):
mapping[index] = state
self.mapping = mapping
def getStateIndex(self,state):
"""
Returns the index of a state by calculating the state code and searching for this code a sorted list.
Can be called on multiple states at once.
"""
statecodes = self.getStateCode(state)
return np.searchsorted(self.codes,statecodes).astype(int)
def transitionStates(self,state):
"""
Return the indices of new states and their rates.
"""
newstates,rates = self.transition(state)
newindices = self.getStateIndex(newstates)
return newindices,rates
def directInitialMatrix(self):
"""
We generate an initial sparse matrix with all the transition rates (or probabilities).
We later transform this matrix into a rate or probability matrix depending on the preferred method of obtaining pi.
"""
#First initialize state codes and the mapping with states.
self.setStateCodes()
#For each state, calculate the indices of reached states and rates using the transition function.
results = imap(self.transitionStates, self.mapping.values())
#Simpler alternative that uses less memory.
#Would be competitive if the conversion from dok to csr is faster.
# D = dok_matrix((self.size,self.size),dtype=float)
# for index,(col,rate) in enumerate(results):
# D.update({(index,c): r for c,r in zip(col,rate)})
# return D.tocsr()
#preallocate memory for the rows, cols and rates of the sparse matrix
rows = np.empty(self.size,dtype=int)
cols = np.empty(self.size,dtype=int)
rates = np.empty(self.size,dtype=float)
#now fill the arrays with the results, increasing their size if current memory is too small.
right = 0
for index,(col,rate) in enumerate(results): #more robust alternative: in izip(self.mapping.keys(),results)
left = right
right += len(col)
if right >= len(cols):
new_capacity = int(round(right * 1.5)) #increase the allocated memory if the vectors turn out to be too small.
cols.resize(new_capacity)
rates.resize(new_capacity)
rows.resize(new_capacity)
rows[left:right] = index #since states are sorted, the index indeed corresponds to the state.
cols[left:right] = col
rates[left:right] = rate
#Place all data in a coo_matrix and convert to a csr_matrix for quick computations.
return coo_matrix((rates[:right],(rows[:right],cols[:right])),shape=(self.size,self.size)).tocsr()
def convertToRateMatrix(self, Q):
"""
Converts the initial matrix to a rate matrix.
We make all rows in Q sum to zero by subtracting the row sums from the diagonal.
"""
rowSums = Q.sum(axis=1).getA1()
idxRange = np.arange(Q.shape[0])
Qdiag = coo_matrix((rowSums,(idxRange,idxRange)),shape=Q.shape).tocsr()
return Q-Qdiag
def convertToProbabilityMatrix(self, Q):
"""
Converts the initial matrix to a probability matrix
We calculate P = I + Q/l, with l the largest diagonal element.
Even if Q is already a probability matrix, this step helps for numerical stability.
By adding a small probability on the diagonal (0.00001), periodicity can be prevented.
"""
rowSums = Q.sum(axis=1).getA1()
l = np.max(rowSums)*1.00001
diagonalElements = 1.-rowSums/l
idxRange = np.arange(Q.shape[0])
Qdiag = coo_matrix((diagonalElements,(idxRange,idxRange)),shape=Q.shape).tocsr()
return Qdiag+Q.multiply(1./l)
def assertSingleClass(self,P):
"""
Check whether the rate/probability matrix consists of a single connected class.
If this is not the case, the steady state distribution is not well defined.
"""
components, _ = csgraph.connected_components(P, directed=True, connection='weak')
assert components==1, "The Markov chain has %r communicating classes. Make sure there is a single communicating class." %components
def getTransitionMatrix(self,probabilities=True):
"""
If self.P has been given already, we will reuse it and convert it to a sparse csr matrix if needed.
Otherwise, we will generate it using the direct or indirect method.
Since most solution methods use a probability matrix, this is the default setting.
By setting probabilities=False we can also return a rate matrix.
"""
if self.P is not None:
if isspmatrix(self.P):
if not isspmatrix_csr(self.P):
self.P = self.P.tocsr()
else:
assert isinstance(self.P, np.ndarray) and self.P.ndim==2 and self.P.shape[0]==self.P.shape[1],'P needs to be a 2d numpy array with an equal number of columns and rows'
self.P = csr_matrix(self.P)
elif self.direct == True:
self.P = self.directInitialMatrix()
else:
self.P = self.indirectInitialMatrix(self.initialState)
if probabilities:
P = self.convertToProbabilityMatrix(self.P)
else:
P = self.convertToRateMatrix(self.P)
return P
def getIrreducibleTransitionMatrix(self,probabilities=True):
#Gets the transitionmatrix and assert that it consists of a single irreducible class.
P = self.getTransitionMatrix(probabilities=True)
self.assertSingleClass(P)
return P
def powerMethod(self, tol = 1e-8, maxiter = 1e5):
"""
Carry out the power method and store the result in the class attribute ``pi``.
Repeatedly takes the dot product between ``P`` and ``pi`` until the norm is smaller than the prespecified tolerance ``tol``.
Parameters
----------
tol : float, optional(default=1e-8)
Tolerance level for the precision of the end result. A lower tolerance leads to more accurate estimate of ``pi``.
maxiter : int, optional(default=1e5)
The maximum number of power iterations to be carried out.
Example
-------
>>> P = np.array([[0.5,0.5],[0.6,0.4]])
>>> mc = markovChain(P)
>>> mc.powerMethod()
>>> print(mc.pi)
[ 0.54545455 0.45454545]
Remarks
-------
The power method is robust even when state space becomes large (more than 500.000 states), whereas the other methods may have some issues with memory or convergence.
The power method may converge slowly for Markov chains where states are rather disconnected. That is, when the expected time to go from one state to another is large.
"""
P = self.getIrreducibleTransitionMatrix().T #take transpose now to speed up dot product.
size = P.shape[0]
pi = np.zeros(size); pi1 = np.zeros(size)
pi[0] = 1;
n = norm(pi - pi1,1); i = 0;
while n > tol and i < maxiter:
pi1 = P.dot(pi)
pi = P.dot(pi1)
n = norm(pi - pi1,1); i += 1
self.pi = pi
def eigenMethod(self, tol = 1e-8, maxiter = 1e5):
"""
Determines ``pi`` by searching for the eigenvector corresponding to the first eigenvalue, using the :func:`eigs` function.
The result is stored in the class attribute ``pi``.
Parameters
----------
tol : float, optional(default=1e-8)
Tolerance level for the precision of the end result. A lower tolerance leads to more accurate estimate of ``pi``.
maxiter : int, optional(default=1e5)
The maximum number of iterations to be carried out.
Example
-------
>>> P = np.array([[0.5,0.5],[0.6,0.4]])
>>> mc = markovChain(P)
>>> mc.eigenMethod()
>>> print(mc.pi)
[ 0.54545455 0.45454545]
Remarks
-------
The speed of convergence depends heavily on the choice of the initial guess for ``pi``.
Here we let the initial ``pi`` be a vector of ones.
For large state spaces, this method may not work well.
At the moment, we call :func:`powerMethod` if the number of states is 2.
Code is due to a colleague: http://nicky.vanforeest.com/probability/markovChains/markovChain.html
"""
Q = self.getIrreducibleTransitionMatrix(probabilities=False)
if Q.shape == (1, 1):
self.pi = np.array([1.0])
return
if Q.shape == (2, 2):
self.pi= np.array([Q[1,0],Q[0,1]]/(Q[0,1]+Q[1,0]))
return
size = Q.shape[0]
guess = np.ones(size,dtype=float)
w, v = eigs(Q.T, k=1, v0=guess, sigma=1e-6, which='LM',tol=tol, maxiter=maxiter)
pi = v[:, 0].real
pi /= pi.sum()
self.pi = pi
def linearMethod(self):
"""
Determines ``pi`` by solving a system of linear equations using :func:`spsolve`.
The method has no parameters since it is an exact method. The result is stored in the class attribute ``pi``.
Example
-------
>>> P = np.array([[0.5,0.5],[0.6,0.4]])
>>> mc = markovChain(P)
>>> mc.linearMethod()
>>> print(mc.pi)
[ 0.54545455 0.45454545]
Remarks
-------
For large state spaces, the linear algebra solver may not work well due to memory overflow.
Code due to http://stackoverflow.com/questions/21308848/
"""
P = self.getIrreducibleTransitionMatrix()
#if P consists of one element, then set self.pi = 1.0
if P.shape == (1, 1):
self.pi = np.array([1.0])
return
size = P.shape[0]
dP = P - eye(size)
#Replace the first equation by the normalizing condition.
A = vstack([np.ones(size), dP.T[1:,:]]).tocsr()
rhs = np.zeros((size,))
rhs[0] = 1
self.pi = spsolve(A, rhs)
def krylovMethod(self,tol=1e-8):
"""
We obtain ``pi`` by using the :func:``gmres`` solver for the system of linear equations.
It searches in Krylov subspace for a vector with minimal residual. The result is stored in the class attribute ``pi``.
Example
-------
>>> P = np.array([[0.5,0.5],[0.6,0.4]])
>>> mc = markovChain(P)
>>> mc.krylovMethod()
>>> print(mc.pi)
[ 0.54545455 0.45454545]
Parameters
----------
tol : float, optional(default=1e-8)
Tolerance level for the precision of the end result. A lower tolerance leads to more accurate estimate of ``pi``.
Remarks
-------
For large state spaces, this method may not always give a solution.
Code due to http://stackoverflow.com/questions/21308848/
"""
P = self.getIrreducibleTransitionMatrix()
#if P consists of one element, then set self.pi = 1.0
if P.shape == (1, 1):
self.pi = np.array([1.0])
return
size = P.shape[0]
dP = P - eye(size)
#Replace the first equation by the normalizing condition.
A = vstack([np.ones(size), dP.T[1:,:]]).tocsr()
rhs = np.zeros((size,))
rhs[0] = 1
pi, info = gmres(A, rhs, tol=tol)
if info != 0:
raise RuntimeError("gmres did not converge")
self.pi = pi
def computePi(self,method='power'):
"""
Calculate the steady state distribution using your preferred method and store it in the attribute `pi`.
By default uses the most robust method, 'power'. Other methods are 'eigen','linear', and 'krylov'
Parameters
----------
method : string, optional(default='power')
The method for obtaining ``pi``. The possible options are 'power','eigen','linear','krylov'.
Example
-------
>>> P = np.array([[0.5,0.5],[0.6,0.4]])
>>> mc = markovChain(P)
>>> mc.computePi('power')
>>> print(mc.pi)
[ 0.54545455 0.45454545]
See Also
--------
For details about the specific methods see
:func:`powerMethod`,
:func:`eigenMethod`,
:func:`linearMethod`, and
:func:`krylovMethod` .
"""
methodSet = ['power','eigen','linear','krylov']
assert method in methodSet, "Incorrect method specified. Choose from %r" % methodSet
method = method + 'Method'
return getattr(self,method)()
def printPi(self):
"""
Prints all states state and their steady state probabilities.
Not recommended for large state spaces.
"""
assert self.pi is not None, "Calculate pi before calling printPi()"
assert len(self.mapping)>0, "printPi() can only be used in combination with the direct or indirect method. Use print(mc.pi) if your subclass is called mc."
for key,state in self.mapping.items():
print(state,self.pi[key])
class finiteMarkovChain(markovChain):
def __init__(self,P=None):
super(finiteMarkovChain,self).__init__(P)
def absorbTime(self):
P = self.getTransitionMatrix(probabilities=True)
components,labels = csgraph.connected_components(P, directed=True, connection='strong',return_labels=True)
if components == 1:
print("no absorbing states")
return
transientStates = np.ones(P.shape[0],dtype=bool)
for component in range(components):
indices = np.where(labels==component)[0]
n = len(indices)
if n==1:
probSum = P[indices,indices].sum()
else:
probSum = P[np.ix_(indices,indices)].sum()
if np.isclose(probSum,n):
transientStates[indices] = False
indices = np.where(transientStates)[0]
n = len(indices)
if n==1:
Q = P[indices,indices]
else:
Q = P[np.ix_(indices,indices)]
#N will be dense
N = inv(eye(n)-Q).A
N2 = N*(2*N[np.arange(n),np.arange(n)]-np.eye(n))-np.power(N,2)
t = np.zeros(P.shape[0])
t[indices] = np.sum(N,axis=1)
for index in indices:
print( self.mapping[index],t[index] )
| Python |
2D | gvanderheide/discreteMarkovChain | discreteMarkovChain/examples.py | .py | 7,470 | 193 | from __future__ import print_function
import numpy as np
from markovChain import markovChain,finiteMarkovChain
from usefulFunctions import partition
class randomWalk(markovChain):
#A random walk where we move up and down with rate 1.0 in each state between bounds m and M.
#For the transition function to work well, we define some class variables in the __init__ function.
def __init__(self,m,M,direct=False):
super(randomWalk, self).__init__(direct=direct) #always use this as first line when creating your own __init__
self.initialState = m
self.m = m
self.M = M
self.uprate = 1.0
self.downrate = 1.0
def transition(self,state):
#Using a dictionary here is quite simple!
rates = {}
if self.m < state < self.M:
rates[state+1] = self.uprate
rates[state-1] = self.downrate
elif state == self.m:
rates[state+1] = self.uprate
elif state == self.M:
rates[state-1] = self.downrate
return rates
class absorbingWalk(finiteMarkovChain):
#A random walk where we move up and down with rate 1.0 in each state between bounds m and M.
#For the transition function to work well, we define some class variables in the __init__ function.
def __init__(self,m,M):
super(absorbingWalk, self).__init__() #always use this as first line when creating your own __init__
self.initialState = M
self.m = m
self.M = M
self.uprate = 1.0
self.downrate = 1.0
def transition(self,state):
#Using a dictionary here is quite simple!
rates = {}
if self.m < state < self.M:
rates[state+1] = self.uprate
rates[state-1] = self.downrate
elif state == self.m:
rates[state] = self.uprate
elif state == self.M:
rates[state-1] = self.downrate
return rates
class randomWalkMulti(markovChain):
#Now we move up an down on multiple dimensions.
def __init__(self,m,M,n,direct=False):
super(randomWalkMulti, self).__init__(direct=direct)
assert n > 1 and isinstance(n,int), "n should be an integer greater than 1"
self.initialState = tuple([m]*n)
self.n = n
self.m = m
self.M = M
self.uprate = 1.0
self.downrate = 1.0
def tupleAdd(self,state,i,b):
#add amount 'b' to entry 'i' of tuple 'state'.
newstate = list(state)
newstate[i] += b
return tuple(newstate)
def transition(self,state):
#now we need to loop over the states
rates = {}
for i in range(self.n):
if self.m < state[i] < self.M:
rates[self.tupleAdd(state,i,1)] = self.uprate
rates[self.tupleAdd(state,i,-1)] = self.downrate
elif state[i] == self.m:
rates[self.tupleAdd(state,i,1)] = self.uprate
elif state[i] == self.M:
rates[self.tupleAdd(state,i,-1)] = self.downrate
return rates
class randomWalkNumpy(markovChain):
#Now we do the same thing with a transition function that returns a 2d numpy array.
#We also specify the statespace function so we can use the direct method.
#This one is defined immediately for general n.
def __init__(self,m,M,n,direct=True):
super(randomWalkNumpy, self).__init__(direct=direct)
self.initialState = m*np.ones(n,dtype=int)
self.n = n
self.m = m
self.M = M
self.uprate = 1.0
self.downrate = 1.0
#It is useful to define the variable 'events' for the the transition function.
#The possible events are 'move up' or 'move down' in one of the random walks.
#The rates of these events are given in 'eventRates'.
self.events = np.vstack((np.eye(n,dtype=int),-np.eye(n,dtype=int)))
self.eventRates = np.array([self.uprate]*n+[self.downrate]*n)
def transition(self,state):
#First check for the current state which of the 'move up' and 'move down' events are possible.
up = state < self.M
down = state > self.m
possibleEvents = np.concatenate((up,down)) #Combine into one boolean array.
#The possible states after the transition follow by adding the possible 'move up'/'move down' events to the current state.
newstates = state+self.events[possibleEvents]
rates = self.eventRates[possibleEvents]
return newstates,rates
def statespace(self):
#Each random walk can be in a state between m and M.
#The function partition() gives all partitions of integers between min_range and max_range.
min_range = [self.m]*self.n
max_range = [self.M]*self.n
return partition(min_range,max_range)
from collections import namedtuple
State = namedtuple('State', "x y")
class randomWalk2D(markovChain):
def __init__(self):
super(randomWalk2D, self).__init__()
self.initialState = State(x=0,y=0)
self.left = 0
self.right = 10
self.up = 5
self.down = 0
self.uprate = self.downrate = 1.
self.leftrate = 2.
self.rightrate = 1.
def transition(self,state):
rates = {}
x,y = state.x, state.y
if x > self.left:
rates[State(x=x-1, y=y)] = self.leftrate
if x < self.right:
rates[State(x=x+1, y=y)] = self.rightrate
if y > self.down:
rates[State(x=x, y=y-1)] = self.downrate
if y < self.up:
rates[State(x=x, y= y+1)] = self.uprate
return rates
if __name__ == '__main__':
import time
P = np.array([[0.5,0.5],[0.6,0.4]])
mc = markovChain(P)
mc.computePi('linear')
print(mc.pi)
#for a one-dimensional state space, calculate the steady state distribution.
#provided uprate and downrate are the same, each state is equally likely
m = 0; M = 2
mc = randomWalk(m,M)
mc.computePi('linear')
mc.printPi()
mc = randomWalkNumpy(m,M,n=1)
mc.computePi('linear')
mc.printPi()
mc = randomWalkNumpy(0,2,n=2)
mc.computePi('linear')
mc.printPi()
mc = absorbingWalk(m,M).absorbTime()
mc = randomWalk2D()
mc.computePi('linear')
mc.printPi()
#When states are scalar integers, the indirect method is faster here.
#The linear algebra solver is quite fast for these one-dimensional problems (here, krylov and power method have really poor performance)
# M = 100000
# tm=time.clock(); randomWalk(m,M).computePi('linear'); print("Indirect:",time.clock()-tm)
# tm=time.clock(); randomWalkNumpy(m,M,n=1).computePi('linear'); print("Direct:", time.clock()-tm)
#Now a multidimensional case with an equal number of states.
#Since building the state space is much more complex, the direct approach is faster.
#Here the krylov method and power method seem to work best.
#The linear algebra solver has memory problems, likely due to fill up of the sparse matrix.
# n = 5; m = 0; M = 9
# tm=time.clock(); randomWalkMulti(m,M,n).computePi('krylov'); print("Indirect:", time.clock()-tm)
# tm=time.clock(); randomWalkNumpy(m,M,n).computePi('krylov'); print("Direct:",time.clock()-tm)
| Python |
2D | gvanderheide/discreteMarkovChain | docs/multirandomwalk.ipynb | .ipynb | 5,105 | 229 | {
"metadata": {
"name": "",
"signature": "sha256:505ba4c2550b28b16b276cf231b060ef5e3f50cdf4a960b88f87e937c819b046"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"import numpy as np"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First lets assign the variables for our random walk."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"n = 2\n",
"m = 0\n",
"M = 4\n",
"uprate = 2.\n",
"downrate = 1."
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let's look at the transitions for a specific state, namely:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"state = np.array([0,3])"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The possible transitions are going up in either of the two random walks, or going down in the 2nd random walk. Below we define the possible events, which are simply two stacked identity matrices."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"events = np.vstack((np.eye(n,dtype=int),-np.eye(n,dtype=int)))\n",
"events\n"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 3,
"text": [
"array([[ 1, 0],\n",
" [ 0, 1],\n",
" [-1, 0],\n",
" [ 0, -1]])"
]
}
],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"state + events"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 5,
"text": [
"array([[ 1, 3],\n",
" [ 0, 4],\n",
" [-1, 3],\n",
" [ 0, 2]])"
]
}
],
"prompt_number": 5
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"These are the states after the transitions, but clearly there is a mistake since [-1,3] is not allowed. We are going to fix that now, by looking only at the possible events in our state."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"up = state < M \n",
"down = state > m\n",
"possibleEvents = np.concatenate((up,down))\n",
"possibleEvents"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 6,
"text": [
"array([ True, True, False, True], dtype=bool)"
]
}
],
"prompt_number": 6
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"state + events[possibleEvents]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 7,
"text": [
"array([[1, 3],\n",
" [0, 4],\n",
" [0, 2]])"
]
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is correct now. We can also calculate the corresponding transition rates:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"\n",
"eventRates = np.concatenate((uprate*np.ones(n),downrate*np.ones(n)))\n",
"eventRates\n",
" "
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 4,
"text": [
"array([ 2., 2., 1., 1.])"
]
}
],
"prompt_number": 4
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The ones that correspond to our state are simply"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"eventRates[possibleEvents]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 8,
"text": [
"array([ 2., 2., 1.])"
]
}
],
"prompt_number": 8
}
],
"metadata": {}
}
]
}
| Unknown |
2D | gvanderheide/discreteMarkovChain | tests/test_markovChain.py | .py | 309 | 14 | from __future__ import print_function
import unittest
import numpy as np
from discreteMarkovChain.markovChain import markovChain
class TestMarkovChain(unittest.TestCase):
def test_example1(self):
P = np.array([[0.5,0.5], [0.6,0.4]])
mc = markovChain(P)
mc.computePi('linear')
| Python |
2D | gvanderheide/discreteMarkovChain | tests/__init__.py | .py | 0 | 0 | null | Python |
2D | PSLer/TopRank3 | TopRank3.m | .m | 32,288 | 886 | %% This code is created for performing the 2D homogenization-based topology optimization subject to multiple loading conditions
%% Author: Junpeng Wang
%% Copyright (c) All Rights Reserved.
%% Version: 2023-11-10
%% E-mail: junpeng.wang@tum.de
function [optiAlphaList, optiThetaList, optiLog, cValuesPerLoadHist] = TopRank3(mesh_, fixingCond_, loadingCond_, matProp_, optiSet_, outPath)
%%1. SETTINGS
%%1.1 Material Properties
%%Only 3==RN is supported for optimization, others can only be used for FEA. To adapt to optimization involving a higner rank,
%%works in derivative computation needs to be extended, typically on the computation of derivatives of "M" in Rank-N
RN = 3; RN = max(2, RN);
E0 = matProp_.modulus;
Emin = matProp_.minModulus;
v0 = matProp_.PossionRatio;
%%1.2 Geometric Modeling
nelX = mesh_.resX;
nelY = mesh_.resY;
numElements = mesh_.numElements;
eDofMat = mesh_.eDofMat;
eleIndexMapForward = mesh_.eleMapForward;
eleMapBack = mesh_.eleMapBack;
eleCentroidList = mesh_.eleCentroidList;
eleSize = mesh_.eleSize(1);
%%1.3 Apply for Boundary Condition
[F, freeDOFs] = ApplyBoundaryCondition(mesh_, fixingCond_, loadingCond_);
%%1.4 Optimization Description
move = 0.01;
thetaMove = 1.0*pi/180;
Vf = optiSet_.Vf;
wqList = optiSet_.perLoadContri;
rMin = 2.6;
nLoop = optiSet_.nloop;
passiveEles = optiSet_.passiveEles;
OPT_OriStartingGuess = optiSet_.OPT_OriStartingGuess;
OPT_Theta3Only = optiSet_.OPT_Theta3Only;
W = optiSet_.W; %%weight factor for compliance item, 1-W for orientation regularization item
alphaUpperBound = optiSet_.alphaBounds(2);
alphaLowerBound = optiSet_.alphaBounds(1);
if 3~=RN, OPT_Theta3Only = 0; end
%%2. Setup
%%2.1 FEA
strainMatrixGP = ObtainStrainMatrix();
Stensor4thSolid = HookeLaw4th(E0, v0);
Stensor4thVoid = HookeLaw4th(Emin, v0);
[eK2gKrowMap, eK2gKcolMap, ~] = find(ones(8));
iK = eDofMat(:,eK2gKrowMap)'; iK = iK(:);
jK = eDofMat(:,eK2gKcolMap)'; jK = jK(:);
%%2.2 Rank-N Theory
Stensor2ndSolid = Tensor4thToTensor2nd(Stensor4thSolid);
Stensor2ndVoid = Tensor4thToTensor2nd(Stensor4thVoid);
C0 = inv(Stensor2ndSolid-Stensor2ndVoid);
S0Plus = E0 / (1-v0^2);
%%2.3 Filter and Orientation Regularization
[H, Hs] = BuildDensityFilter(rMin, nelX, nelY, numElements, eleIndexMapForward, eleCentroidList, eleSize);
eleAdjacencyMap = BuildElementAdjacency(numElements, nelX, nelY, eleIndexMapForward, eleMapBack);
%%2.4 Evaluate Compliance of Fully Solid Domain
[U, ~, ce] = PerformFEA(Stensor4thSolid, F, freeDOFs, strainMatrixGP, iK, jK, numElements, eDofMat);
cSolid = sum(ce,1)*wqList(:);
disp(['Compliance of Fully Solid Domain: ' sprintf('%16.6e',cSolid)]);
%%2.5 Ini. for Starting Guess
alphaList = repmat(Vf/RN, numElements, RN);
if 3==RN
switch OPT_OriStartingGuess
case 'SGu'
iniTheta3 = pi/2; %%Normal of Layer-3
thetaList = OrientationStartingGuess_Uniform(numElements, iniTheta3);
case 'SGp'
thetaList = OrientationStartingGuess_PrincipalStress(numElements, eDofMat, U, Stensor4thSolid);
otherwise
error('Wrong Option for Starting Guess Strategy!');
end
else
thetaTemp = linspace(0,pi,RN+1);
thetaList = repmat(thetaTemp(1:end-1), numElements, 1); %%Initialization by User
warning('Not Rank-3 Laminate! Optimization Functionality not Supported!');
end
alphaList(passiveEles,:) = ones(size(passiveEles,1), RN);
%%3. Preparation for Optimization Loop
%%3.1 Setup
alphaTildeList = alphaList;
thetaTildeList = thetaList;
optiAlphaList = alphaTildeList;
optiThetaList = thetaTildeList;
rhoRN = 1-prod(1-alphaTildeList,2);
%%3.2 Ini. for Orientation Regularization
%%Initial Values of Different Items in Objective Function
Mmat = ComputeMmat(alphaTildeList, thetaTildeList, v0, RN);
Stensor4thRankN = AeembleStensor4thRankN(Mmat, Stensor2ndSolid, rhoRN, C0, S0Plus);
[~, ~, ce] = PerformFEA(Stensor4thRankN, F, freeDOFs, strainMatrixGP, iK, jK, numElements, eDofMat);
c0Total = sum(ce*wqList(:),1);
[p0Total, ~] = GetLayerOrientationDeviationMetric(thetaTildeList, eleAdjacencyMap, OPT_Theta3Only);
p0Total = max(p0Total,1);
%%3.3 Ini. for Optimizer
if 1==OPT_Theta3Only
xold1_theta = thetaList(:,3);
else
xold1_theta = thetaList(:);
end
xold2_theta = xold1_theta;
low = 0;
upp = 0;
loop = 0;
%%3.4 Ini. for Output
oHist = [];
cHist = [];
pHist = [];
volHist = [];
cValuesPerLoadHist = [];
designVariablesRank3_ = [alphaList thetaList];
designVariablesRank3_ = ProjectTheta0to360(designVariablesRank3_);
fileName = sprintf(strcat(outPath, 'designVariablesRank3-It-%d.mat'), loop);
save(fileName, 'designVariablesRank3_');
%%4. Optimization Loop
while loop < nLoop
loop = loop + 1;
%%4.1 FEA, Objective, and Sensitivity Analysis
Mmat = ComputeMmat(alphaTildeList, thetaTildeList, v0, RN);
Stensor4thRankN = AeembleStensor4thRankN(Mmat, Stensor2ndSolid, rhoRN, C0, S0Plus);
[~, Ue2, ce] = PerformFEA(Stensor4thRankN, F, freeDOFs, strainMatrixGP, iK, jK, numElements, eDofMat);
cValuesPerLoad = sum(ce, 1);
ce0 = cValuesPerLoad*wqList(:);
[pe0, ~] = GetLayerOrientationDeviationMetric(thetaTildeList, eleAdjacencyMap, OPT_Theta3Only);
f0val = W*ce0/c0Total + (1-W)*pe0/p0Total;
[df0dAlpha, df0dTheta] = Def0DeX(alphaTildeList, thetaTildeList, Mmat, Ue2, wqList, strainMatrixGP, ...
C0, S0Plus, v0, c0Total, p0Total, OPT_Theta3Only, W, RN, eleAdjacencyMap);
fval = sum(1-prod(1-alphaTildeList,2))/(numElements*Vf) - 1;
dfdAlpha = zeros(size(alphaTildeList));
allRanks = 1:RN;
for jj=1:RN
restRanks = setdiff(allRanks, jj);
dfdAlpha(:,jj) = prod(1-alphaTildeList(:,restRanks),2);
end
dfdAlpha = dfdAlpha/(numElements*Vf);
dfdTheta = 0.0e-12*ones(size(df0dTheta)); %% Constant Small Values
%% 4.2 Filtering
df0dAlpha = H*(df0dAlpha./Hs);
dfdAlpha = H*(dfdAlpha./Hs);
df0dTheta = H*(df0dTheta./Hs);
%% 4.3 Update of Design Variables by Optimizer
%% 4.3.1 Alpha
l1 = 0; l2 = 1e5;
while (l2-l1)/(l1+l2) > 1e-3
lmid = 0.5*(l2+l1);
alphaListNew = max(alphaLowerBound, max(alphaList-move, min(alphaUpperBound, min(alphaList+move, alphaList.*real(sqrt(-df0dAlpha./dfdAlpha/lmid))))));
tmp = alphaListNew;
alphaTildeList = H * tmp ./ Hs;
alphaTildeList(passiveEles,:) = ones(size(passiveEles,1), RN);
fval = sum(1-prod(1-alphaTildeList,2))/(numElements*Vf) - 1;
if fval > 0, l1 = lmid; else l2 = lmid; end
end
changeAlpha = max([abs(alphaListNew(:)-alphaList(:))]);
alphaList = alphaListNew;
rhoRN = 1-prod(1-alphaTildeList,2);
optiAlphaList = alphaTildeList;
%% 4.3.2 Theta
m = 1;
iter = loop;
a0 = 1;
a = zeros(m,1);
c_ = ones(m,1)*1000;
d = zeros(m,1);
if 1==OPT_Theta3Only
xval_MMA_theta = thetaList(:,3);
else
xval_MMA_theta = thetaList(:);
end
xold1_MMA_theta = xold1_theta;
xold2_MMA_theta = xold2_theta;
df0dx_MMA_theta = df0dTheta(:);
df0dx2_MMA_theta = zeros(size(df0dx_MMA_theta));
dfdx_MMA_theta = dfdTheta(:);
dfdx2_MMA_theta = zeros(size(dfdx_MMA_theta));
n = numel(xval_MMA_theta);
xmin_MMA_theta = xval_MMA_theta;
xmax_MMA_theta = xval_MMA_theta;
xmax_MMA_theta = min(4*pi, xmax_MMA_theta+thetaMove);
xmin_MMA_theta = max(-4*pi, xmin_MMA_theta-thetaMove);
[xmma_MMA_theta,~,~,~,~,~,~,~,~,low,upp] = ...
mmasub(m,n,iter,xval_MMA_theta,xmin_MMA_theta,xmax_MMA_theta,xold1_MMA_theta,xold2_MMA_theta,...
f0val,df0dx_MMA_theta,df0dx2_MMA_theta,fval,dfdx_MMA_theta',dfdx2_MMA_theta',low,upp,a0,a,c_,d);
xold1_theta = xval_MMA_theta;
xold2_theta = xold1_MMA_theta;
if 1==OPT_Theta3Only
thetaListNew = reshape(xmma_MMA_theta, numElements, 1);
changeTheta = max([abs(thetaListNew(:)-thetaList(:,3))]);
thetaList = [thetaListNew+2*pi/3 thetaListNew+pi/3 thetaListNew];
else
thetaListNew = reshape(xmma_MMA_theta, numElements, RN);
changeTheta = max([abs(thetaListNew(:)-thetaList(:))]);
thetaList = thetaListNew;
end
thetaTildeList = thetaList;
thetaTildeList = H * thetaTildeList ./ Hs;
optiThetaList = thetaTildeList;
change = max([changeAlpha changeTheta]);
%% 4.4 Print Results
disp([' It.: ' sprintf('%4i',loop) ' Obj.: ' sprintf('%10.4e',f0val) ' C0: ' sprintf('%10.4e',ce0) ' P0: ' sprintf('%10.4e',pe0) ...
' Vol.: ' sprintf('%6.3f',sum(rhoRN)/numElements) ' Cons.: ' sprintf('%10.4e ',fval)]);
%% 4.5 Plot and Write history
oHist(loop,1) = f0val;
cHist(loop,1) = ce0;
pHist(loop,1) = pe0;
volHist(loop,1) = sum(rhoRN)/numElements;
cValuesPerLoadHist(loop,:) = cValuesPerLoad;
designVariablesRank3_ = [alphaTildeList thetaTildeList];
designVariablesRank3_ = ProjectTheta0to360(designVariablesRank3_);
fileName = sprintf(strcat(outPath, 'designVariablesRank3-It-%d.mat'), loop);
save(fileName, 'designVariablesRank3_');
xPhys = zeros(nelX*nelY,1);
xPhys(eleMapBack) = rhoRN;
figure(2);clf;
colormap(gray);
imagesc(-reshape(xPhys, nelY, nelX), [-1 0]); axis('equal'); axis('off'); drawnow;
end
optiLog = [oHist volHist cHist pHist];
%% 5. Show Opti. Result
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%FEA Related
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [F_, freeDOFs_] = ApplyBoundaryCondition(mesh_, fixingCond_, loadingCond_)
%%Loading
nodDOF = 2;
loadingCond_ = loadingCond_(:);
numLoadSteps = numel(loadingCond_);
validLoadSteps = [];
for ii=1:numLoadSteps
if ~isempty(loadingCond_(ii).arr), validLoadSteps(end+1,1) = ii; end
end
loadingCond_ = loadingCond_(validLoadSteps);
numLoadSteps = numel(loadingCond_);
if numLoadSteps>0
F_ = sparse(mesh_(1).numDOFs, numLoadSteps);
for ii=1:numLoadSteps
iFVec = sparse(mesh_(1).numNodes, nodDOF);
iFVec(loadingCond_(ii).arr(:,1),:) = loadingCond_(ii).arr(:,2:end);
F_(:,ii) = reshape(iFVec',mesh_(1).numDOFs,1);
end
else
warning('No Loads!'); return;
end
%%Fixing
if ~isempty(fixingCond_(1).arr)
numFixations = numel(fixingCond_);
flexibleArr = struct('arr', []);
freeDOFs_ = repmat(flexibleArr, numFixations, 1);
for ii=1:numFixations
fixedDOFs = nodDOF*double(fixingCond_(ii).arr(:,1));
fixedDOFs = fixedDOFs - (nodDOF-1:-1:0);
fixedDOFs = reshape(fixedDOFs', numel(fixedDOFs), 1);
fixingState = fixingCond_(ii).arr(:,2:end)';
realFixedDOFs = fixedDOFs(find(1==fixingState(:)));
freeDOFs = setdiff((1:int32(mesh_(1).numDOFs))',realFixedDOFs);
freeDOFs_(ii).arr = freeDOFs;
end
else
warning('No Constraint!'); return;
end
end
function Bmat = ObtainStrainMatrix()
q3 = sqrt(3)/3;
Bmat = [ -1-q3 0 1+q3 0 1-q3 0 -1+q3 0; 0 -1-q3 0 -1+q3 0 1-q3 0 1+q3; -1-q3 -1-q3 -1+q3 1+q3 1-q3 1-q3 1+q3 -1+q3;
-1-q3 0 1+q3 0 1-q3 0 -1+q3 0; 0 -1+q3 0 -1-q3 0 1+q3 0 1-q3; -1+q3 -1-q3 -1-q3 1+q3 1+q3 1-q3 1-q3 -1+q3;
-1+q3 0 1-q3 0 1+q3 0 -1-q3 0; 0 -1+q3 0 -1-q3 0 1+q3 0 1-q3; -1+q3 -1+q3 -1-q3 1-q3 1+q3 1+q3 1-q3 -1-q3;
-1+q3 0 1-q3 0 1+q3 0 -1-q3 0; 0 -1-q3 0 -1+q3 0 1-q3 0 1+q3; -1-q3 -1+q3 -1+q3 1-q3 1-q3 1+q3 1+q3 -1-q3]/2;
end
function Stensor = HookeLaw4th(E, v)
%%Hooke's law
Stensor = E/(1-v^2)*[1 v 0; v 1 0; 0 0 (1-v)/2];
end
function [eleKarr, eleKmat] = ComputeElementStiffMatrix(S, B)
%%Integral(B' * D * B)
w = ones(1,12)*0.25; %%0.25 being specific to unit element
eleD = zeros(12);
for ii=1:4
index = (ii-1)*3+1:ii*3;
eleD(index,index) = S;
end
eleKmat = B'*(eleD.*w)*B;
eleKarr = eleKmat(:);
end
function [U, Ue2, ce] = PerformFEA(Stensor4th, F, freeDOFs, strainMatrixGP, iK, jK, numElements, eDofMat)
%%Solving
if 1 == size(Stensor4th,3)
[Ke, ~] = ComputeElementStiffMatrix(Stensor4th, strainMatrixGP);
Ks = repmat(Ke,1,numElements);
elseif numElements == size(Stensor4th,3)
Ks = zeros(8*8, numElements);
for ii=1:numElements
iD = Stensor4th(:,:,ii);
[Ks(:,ii), ~] = ComputeElementStiffMatrix(iD, strainMatrixGP);
end
else
error('Wrong Input of Elasticity Tensor!');
end
K = sparse(iK, jK, Ks(:));
U = zeros(size(F));
if numel(freeDOFs) == size(F,2) %%Concurrently varying loads and fixations
for ii=1:size(F,2)
iFreeDofs = freeDOFs(ii).arr;
U(iFreeDofs,ii) = K(iFreeDofs,iFreeDofs)\F(iFreeDofs,ii);
end
elseif 1==numel(freeDOFs) && size(F,2)>1 %%Constant fixations, only the loads vary
iFreeDofs = freeDOFs(1).arr;
U(iFreeDofs,:) = K(iFreeDofs,iFreeDofs)\F(iFreeDofs,:);
else
error('Inconsistent Boundary Conditions!')
end
%%PostP
ce = zeros(numElements, size(U,2));
Ue2 = zeros(64, numElements, size(U,2));
for jj=1:size(U,2)
ithU = U(:,jj);
ithUe = ithU(eDofMat');
ithUe2 = reshape(bsxfun(@times, reshape(ithUe,[1 8 numElements]), reshape(ithUe, [8 1 numElements])), 64, numElements);
ce(:,jj) = reshape(sum(Ks.*ithUe2,1),numElements,1);
Ue2(:,:,jj) = ithUe2;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Rank-N related
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Mmat = ComputeMmat(alphaList, thetaList, v0, RN)
rhoRN = 1-prod(1-alphaList,2);
numElements = size(alphaList,1);
PnList = alphaList;
for ii=RN-1:-1:1
PnList(:,ii) = prod(1-alphaList(:,ii+1:RN),2) .* alphaList(:,ii);
end
PnList = PnList ./ rhoRN;
h = 4*(1-v0);
l1 = cos(2*thetaList);
l2 = sin(2*thetaList);
l3 = cos(4*thetaList);
l4 = sin(4*thetaList);
m1 = sum(PnList.*l1, 2); m1 = reshape(m1, 1, 1, numElements);
m2 = sum(PnList.*l2, 2); m2 = reshape(m2, 1, 1, numElements);
m3 = sum(PnList.*l3, 2); m3 = reshape(m3, 1, 1, numElements);
m4 = sum(PnList.*l4, 2); m4 = reshape(m4, 1, 1, numElements);
Mmat = zeros(3,3,numElements);
Mmat(1,1,:) = (3-v0 - (1+v0)*m3) / h;
Mmat(1,2,:) = -(1+v0)*m4 / h;
Mmat(1,3,:) = m1 /2;
Mmat(2,2,:) = (3-v0 + (1+v0)*m3) / h;
Mmat(2,3,:) = m2 /2;
Mmat(3,3,:) = 1/2;
Mmat(2,1,:) = Mmat(1,2,:);
Mmat(3,1,:) = Mmat(1,3,:);
Mmat(3,2,:) = Mmat(2,3,:);
end
function Stensor4thRankN = AeembleStensor4thRankN(Mmat, Stensor2ndSolid, rhoRN, C0, S0Plus)
Stensor4thRankN = zeros(size(Mmat));
numElements = size(Mmat,3);
for ii=1:numElements
iRho = rhoRN(ii);
iStensor2ndRankN = Stensor2ndSolid - (1-iRho)*inv(C0-iRho/S0Plus*Mmat(:,:,ii));
Stensor4thRankN(:,:,ii) = Tensor2ndToTensor4th(iStensor2ndRankN);
end
end
function A4th = Tensor2ndToTensor4th(A2nd)
%% A2nd
%% A11 A12 A13
%% A22 A23
%% syms A33
%% outA
%% A1111 A1122 A1112
%% A2222 A2221
%% syms A1212
A4th = zeros(size(A2nd));
A4th(1,1,:) = 0.5*(A2nd(1,1,:)+A2nd(3,3,:))+A2nd(1,3,:);
A4th(1,2,:) = -0.5*(A2nd(1,1,:)-A2nd(3,3,:));
A4th(1,3,:) = 0.5*(A2nd(1,2,:)+A2nd(2,3,:));
A4th(2,2,:) = 0.5*(A2nd(1,1,:)+A2nd(3,3,:))-A2nd(1,3,:);
A4th(2,3,:) = -0.5*(A2nd(1,2,:)-A2nd(2,3,:));
A4th(3,3,:) = 0.5*A2nd(2,2,:);
A4th(2,1,:) = A4th(1,2,:);
A4th(3,1,:) = A4th(1,3,:);
A4th(3,2,:) = A4th(2,3,:);
end
function A2nd = Tensor4thToTensor2nd(A4th)
%% A4th
%% A1111 A1122 A1112
%% A2222 A2221
%% syms A1212
%% A2nd
%% A11 A12 A13
%% A22 A23
%% syms A33
A2nd = zeros(size(A4th));
A2nd(1,1,:) = 0.5*(A4th(1,1,:)+A4th(2,2,:))-A4th(1,2,:);
A2nd(1,2,:) = A4th(1,3,:)-A4th(2,3,:);
A2nd(1,3,:) = 0.5*(A4th(1,1,:)-A4th(2,2,:));
A2nd(2,2,:) = 2*A4th(3,3,:);
A2nd(2,3,:) = A4th(1,3,:)+A4th(2,3,:);
A2nd(3,3,:) = 0.5*(A4th(1,1,:)+A4th(2,2,:))+A4th(1,2,:);
A2nd(2,1,:) = A2nd(1,2,:);
A2nd(3,1,:) = A2nd(1,3,:);
A2nd(3,2,:) = A2nd(2,3,:);
end
function alphaAndThetaO = ProjectTheta0to360(alphaAndThetaI)
alphaAndThetaO = alphaAndThetaI;
thetaAng = alphaAndThetaI(:,4:6)/pi*180;
thetaAng = mod(thetaAng,360);
alphaAndThetaO(:,4:6) = thetaAng/180*pi;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Optimization related
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [H, Hs] = BuildDensityFilter(rMin, nelX, nelY, numElements, eleIndexMapForward, eleCentroidList, eleSize)
p = 2;
iH = zeros(numElements*(2*(ceil(rMin)-1)+1)^p, 1, 'int32');
jH = iH;
iIndex = 0;
%% 1 4 7
%% 2 5* 8
%% 3 6 9
for ii = 1:nelX
for jj = 1:nelY
e1 = eleIndexMapForward((ii-1)*nelY+jj);
if e1
for ii2 = max(ii-(ceil(rMin)-1),1):min(ii+(ceil(rMin)-1),nelX)
for jj2 = max(jj-(ceil(rMin)-1),1):min(jj+(ceil(rMin)-1),nelY)
e2 = eleIndexMapForward((ii2-1)*nelY+jj2);
if e2
iIndex = iIndex + 1;
iH(iIndex) = e1;
jH(iIndex) = e2;
end
end
end
end
end
end
iH = iH(1:iIndex,:);
jH = jH(1:iIndex,:);
% eleSize = 1;
sH = rMin*eleSize - vecnorm(eleCentroidList(iH,:)-eleCentroidList(jH,:),2,2);
sH(sH<0) = 0;
H = sparse(iH, jH, sH, numElements, numElements);
Hs = sum(H,2);
end
function eleAdjacencyMap = BuildElementAdjacency(numElements, nelX, nelY, eleMapForward, eleMapBack)
eleAdjacencyMap = struct('adjacentEles', []);
eleAdjacencyMap = repmat(eleAdjacencyMap, numElements, 1);
eleMapBackTmp = double(eleMapBack);
for ii=1:numElements
iEleGlobalIdx = eleMapBackTmp(ii);
adjEleLeft = iEleGlobalIdx-nelY;
adjEleRight = iEleGlobalIdx+nelY;
adjEleUp = iEleGlobalIdx-1;
adjEleDown = iEleGlobalIdx+1;
if 1==mod(iEleGlobalIdx, nelY) %%Top Row
adjEleUp = [];
end
if 0==mod(iEleGlobalIdx, nelY) %%Bottom Row
adjEleDown = [];
end
if iEleGlobalIdx<=nelY %%First Column
adjEleLeft = [];
end
if iEleGlobalIdx>(nelX-1)*nelY %%Last Column
adjEleRight = [];
end
adjacentElesGlobal = [adjEleLeft adjEleRight adjEleUp adjEleDown]';
adjacentElesLocal = eleMapForward(adjacentElesGlobal);
adjacentElesLocal(0==adjacentElesLocal) = [];
eleAdjacencyMap(ii).adjacentEles = adjacentElesLocal;
end
end
function [pTotal, pe] = GetLayerOrientationDeviationMetric(thetaList, eleAdjacencyMap, OPT_Theta3Only)
numElements = size(thetaList,1);
pe = zeros(numElements,1);
coefi = 6; %% 2: k*pi (min), k*pi/2 (max); 6: k*pi/3 (min), k*pi/6 (max)
for ii=1:numElements
iTheta = thetaList(ii,3);
iThetasAdjEles = thetaList(eleAdjacencyMap(ii).adjacentEles,3);
pe(ii) = sum(0.5 - 0.5 * cos(coefi*(iTheta-iThetasAdjEles)));
end
if ~OPT_Theta3Only
pe = repmat(pe,1,3);
for ii=1:numElements
iTheta2 = thetaList(ii,2);
iTheta1 = thetaList(ii,1);
iAdjacentEles = eleAdjacencyMap(ii).adjacentEles;
iThetas2AdjEles = thetaList(iAdjacentEles,2);
pe(ii,2) = sum(0.5 - 0.5 * cos(coefi*(iTheta2-iThetas2AdjEles)));
iThetas1AdjEles = thetaList(iAdjacentEles,1);
pe(ii,1) = sum(0.5 - 0.5 * cos(coefi*(iTheta1-iThetas1AdjEles)));
end
end
pTotal = sum(sum(pe));
end
function thetaList = OrientationStartingGuess_Uniform(numElements, iniTheta3)
thetaList = repmat(iniTheta3+[2*pi/3 pi/3 0], numElements, 1);
end
function thetaList = OrientationStartingGuess_PrincipalStress(numElements, eDofMat, U, Stensor)
strainMatrixMid = [-1 0 1 0 1 0 -1 0; 0 -1 0 -1 0 1 0 1; -1 -1 -1 1 1 1 1 -1]/2;
numLoads = size(U,2);
psPool = zeros(numElements,4*numLoads);
if 1==size(Stensor,3), Stensor = repmat(Stensor,1,1,numElements); end
for ii=1:numLoads
for jj=1:numElements
relativeDOFsIndex = eDofMat(jj,:);
iUe = U(relativeDOFsIndex,ii);
iEleStress = Stensor(:,:,jj) * (strainMatrixMid*iUe);
devTerm = sqrt( (iEleStress(1)-iEleStress(2))^2/4 + iEleStress(3)^2 );
ampMajor = (iEleStress(1)+iEleStress(2))/2 + devTerm;
ampMinor = (iEleStress(1)+iEleStress(2))/2 - devTerm;
oriMajor = atan((ampMajor-iEleStress(1)) ./ iEleStress(3));
oriMinor = oriMajor + pi/2;
if 0==sum(iUe), ampMajor = 1; oriMajor = 0; ampMinor = 1; oriMinor = pi/2; end
psPool(jj,4*(ii-1)+1:4*ii) = [ampMinor oriMinor ampMajor oriMajor];
end
end
psAmps = abs(psPool(:,1:2:end));
psDir = psPool(:,2:2:end);
[~,principalDirPos] = max(psAmps,[],2);
principalDir = zeros(numElements,1);
for jj=1:numElements
principalDir(jj) = psDir(jj,principalDirPos(jj));
end
principalDir = principalDir + pi/2;
thetaList = repmat(principalDir, 1, 3) + repmat([2*pi/3 pi/3 0], numElements, 1);
end
function [df0dAlpha, df0dTheta] = Def0DeX(alphaList, thetaList, Mmat, Ue2, ww, B, C0, S0Plus, v0, c0Total, p0Total, OPT_Theta3Only, ...
W, RN, eleAdjacencyMap)
numElements = size(alphaList,1);
eye3 = eye(3);
zeros12 = zeros(12,12);
%%1. Preparations
%%Rho, dRho_dAlpha
rhoRN = 1-prod(1-alphaList,2);
dRho_dAlpha = zeros(numElements, RN);
allRanks = 1:RN;
for ii=1:RN
restRanks = setdiff(allRanks, ii);
dRho_dAlpha(:,ii) = prod(1-alphaList(:,restRanks),2);
end
%%Y, YY
A0 = 1/S0Plus;
CAM = repmat(C0,1,1,numElements) - A0*reshape(rhoRN,1,1,numElements) .* Mmat;
Y = zeros(size(CAM));
YY = Y;
for ii=1:numElements
Y(:,:,ii) = eye3 / CAM(:,:,ii);
YY(:,:,ii) = Y(:,:,ii) / CAM(:,:,ii); %% dot or times WARNING! WARNING! WARNING!
end
%%RhoList (Rho_1, 2, 3), PnList, dRhoList_dAlpha
RhoList = alphaList;
for ii=RN-1:-1:1
RhoList(:,ii) = prod(1-alphaList(:,ii+1:RN),2) .* alphaList(:,ii);
end
PnList = RhoList ./ rhoRN;
% dRhoList_dAlpha = zeros(RN,RN,numElements);
%% dRho1_dAlpha1 dRho2_dAlpha1 dRho3_dAlpha1
%% dRhoList_dAlpha = dRho1_dAlpha2 dRho2_dAlpha2 dRho3_dAlpha2
%% dRho1_dAlpha3 dRho2_dAlpha3 dRho3_dAlpha3
dP_dAlpha = zeros(RN,RN,numElements);
%% dP1_dAlpha1 dP2_dAlpha1 dP3_dAlpha1
%% dP_dAlpha = dP1_dAlpha2 dP2_dAlpha2 dP3_dAlpha2
%% dP1_dAlpha3 dP2_dAlpha3 dP3_dAlpha3
tmpCons = 1 ./ rhoRN ./ rhoRN;
dRho1_dAlpha1 = (1-alphaList(:,3)).*(1-alphaList(:,2));
dP1_dAlpha1 = tmpCons .* (rhoRN .* dRho1_dAlpha1 - RhoList(:,1) .* dRho_dAlpha(:,1));
dP_dAlpha(1,1,:) = reshape(dP1_dAlpha1,1,1,numElements);
%%dRho2_dAlpha1 = [0];
dP2_dAlpha1 = tmpCons .* (-RhoList(:,2) .* dRho_dAlpha(:,1));
dP_dAlpha(1,2,:) = reshape(dP2_dAlpha1,1,1,numElements);
%%dRho3_dAlpha1 = [0];
dP3_dAlpha1 = tmpCons .* (-RhoList(:,3) .* dRho_dAlpha(:,1));
dP_dAlpha(1,3,:) = reshape(dP3_dAlpha1,1,1,numElements);
dP_dAlpha1 = [dP1_dAlpha1 dP2_dAlpha1 dP3_dAlpha1];
dRho1_dAlpha2 = (alphaList(:,3)-1).*alphaList(:,1);
dP1_dAlpha2 = tmpCons .* (rhoRN .* dRho1_dAlpha2 - RhoList(:,1) .* dRho_dAlpha(:,2));
dP_dAlpha(2,1,:) = reshape(dP1_dAlpha2,1,1,numElements);
dRho2_dAlpha2 = 1-alphaList(:,3);
dP2_dAlpha2 = tmpCons .* (rhoRN .* dRho2_dAlpha2 - RhoList(:,2) .* dRho_dAlpha(:,2));
dP_dAlpha(2,2,:) = reshape(dP2_dAlpha2,1,1,numElements);
%%dRho3_dAlpha2 = [0];
dP3_dAlpha2 = tmpCons .* (-RhoList(:,3) .* dRho_dAlpha(:,2));
dP_dAlpha(2,3,:) = reshape(dP3_dAlpha2,1,1,numElements);
dP_dAlpha2 = [dP1_dAlpha2 dP2_dAlpha2 dP3_dAlpha2];
dRho1_dAlpha3 = (alphaList(:,2)-1).*alphaList(:,1);
dP1_dAlpha3 = tmpCons .* (rhoRN .* dRho1_dAlpha3 - RhoList(:,1) .* dRho_dAlpha(:,3));
dP_dAlpha(3,1,:) = reshape(dP1_dAlpha3,1,1,numElements);
dRho2_dAlpha3 = -alphaList(:,2);
dP2_dAlpha3 = tmpCons .* (rhoRN .* dRho2_dAlpha3 - RhoList(:,2) .* dRho_dAlpha(:,3));
dP_dAlpha(3,2,:) = reshape(dP2_dAlpha3,1,1,numElements);
%%dRho3_dAlpha3 = [1];
dP3_dAlpha3 = tmpCons .* (rhoRN - RhoList(:,3) .* dRho_dAlpha(:,3));
dP_dAlpha(3,3,:) = reshape(dP3_dAlpha3,1,1,numElements);
dP_dAlpha3 = [dP1_dAlpha3 dP2_dAlpha3 dP3_dAlpha3];
%%dm1_dAlpha1, dm2_dAlpha1, dm3_dAlpha1, dm4_dAlpha1; by page
dmList_dAlpha = zeros(numElements,4,RN);
l1 = cos(2*thetaList);
l2 = sin(2*thetaList);
l3 = cos(4*thetaList);
l4 = sin(4*thetaList);
dmList_dAlpha(:,1,1) = sum(dP_dAlpha1 .* l1, 2); %dm1_dAlpha1
dmList_dAlpha(:,2,1) = sum(dP_dAlpha1 .* l2, 2); %dm2_dAlpha1
dmList_dAlpha(:,3,1) = sum(dP_dAlpha1 .* l3, 2); %dm3_dAlpha1
dmList_dAlpha(:,4,1) = sum(dP_dAlpha1 .* l4, 2); %dm4_dAlpha1
dmList_dAlpha(:,1,2) = sum(dP_dAlpha2 .* l1, 2); %dm1_dAlpha2
dmList_dAlpha(:,2,2) = sum(dP_dAlpha2 .* l2, 2); %dm2_dAlpha2
dmList_dAlpha(:,3,2) = sum(dP_dAlpha2 .* l3, 2); %dm3_dAlpha2
dmList_dAlpha(:,4,2) = sum(dP_dAlpha2 .* l4, 2); %dm4_dAlpha2
dmList_dAlpha(:,1,3) = sum(dP_dAlpha3 .* l1, 2); %dm1_dAlpha3
dmList_dAlpha(:,2,3) = sum(dP_dAlpha3 .* l2, 2); %dm2_dAlpha3
dmList_dAlpha(:,3,3) = sum(dP_dAlpha3 .* l3, 2); %dm3_dAlpha3
dmList_dAlpha(:,4,3) = sum(dP_dAlpha3 .* l4, 2); %dm4_dAlpha3
%%2. dM
%%2.1 dM_dAlpha
h0 = (1+v0) / 4/(1-v0);
dM_dAlpha = struct('arr', []); dM_dAlpha.arr = zeros(3,3,numElements); dM_dAlpha = repmat(dM_dAlpha, 1, RN);
for ii=1:RN
dM_dAlpha(ii).arr(1,1,:) = reshape(-h0 * dmList_dAlpha(:,3,ii),1,1,numElements);
dM_dAlpha(ii).arr(1,2,:) = reshape(-h0 * dmList_dAlpha(:,4,ii),1,1,numElements);
dM_dAlpha(ii).arr(1,3,:) = reshape(0.5 * dmList_dAlpha(:,1,ii),1,1,numElements);
dM_dAlpha(ii).arr(2,1,:) = dM_dAlpha(ii).arr(1,2,:);
dM_dAlpha(ii).arr(2,2,:) = reshape(h0 * dmList_dAlpha(:,3,ii),1,1,numElements);
dM_dAlpha(ii).arr(2,3,:) = reshape(0.5 * dmList_dAlpha(:,2,ii),1,1,numElements);
dM_dAlpha(ii).arr(3,1,:) = dM_dAlpha(ii).arr(1,3,:);
dM_dAlpha(ii).arr(3,2,:) = dM_dAlpha(ii).arr(2,3,:);
end
%%2.2 dM_dTheta
dl1 = -2*sin(2*thetaList);
dl2 = 2*cos(2*thetaList);
dl3 = -4*sin(4*thetaList);
dl4 = 4*cos(4*thetaList);
dmList_dTheta = zeros(numElements,4,RN);
dmList_dTheta(:,1,1) = PnList(:,1).*dl1(:,1); %dm1_dTheta1
dmList_dTheta(:,2,1) = PnList(:,1).*dl2(:,1); %dm2_dTheta1
dmList_dTheta(:,3,1) = PnList(:,1).*dl3(:,1); %dm3_dTheta1
dmList_dTheta(:,4,1) = PnList(:,1).*dl4(:,1); %dm4_dTheta1
dmList_dTheta(:,1,2) = PnList(:,2).*dl1(:,2); %dm1_dTheta2
dmList_dTheta(:,2,2) = PnList(:,2).*dl2(:,2); %dm2_dTheta2
dmList_dTheta(:,3,2) = PnList(:,2).*dl3(:,2); %dm3_dTheta2
dmList_dTheta(:,4,2) = PnList(:,2).*dl4(:,2); %dm4_dTheta2
dmList_dTheta(:,1,3) = PnList(:,3).*dl1(:,3); %dm1_dTheta3
dmList_dTheta(:,2,3) = PnList(:,3).*dl2(:,3); %dm2_dTheta3
dmList_dTheta(:,3,3) = PnList(:,3).*dl3(:,3); %dm3_dTheta3
dmList_dTheta(:,4,3) = PnList(:,3).*dl4(:,3); %dm4_dTheta3
dM_dTheta = struct('arr', []); dM_dTheta.arr = zeros(3,3,numElements);
if 1==OPT_Theta3Only
for ii=1:RN
dM_dTheta.arr(1,1,:) = dM_dTheta.arr(1,1,:) + reshape(-h0 * dmList_dTheta(:,3,ii),1,1,numElements);
dM_dTheta.arr(1,2,:) = dM_dTheta.arr(1,2,:) + reshape(-h0 * dmList_dTheta(:,4,ii),1,1,numElements);
dM_dTheta.arr(1,3,:) = dM_dTheta.arr(1,3,:) + reshape(0.5 * dmList_dTheta(:,1,ii),1,1,numElements);
dM_dTheta.arr(2,1,:) = dM_dTheta.arr(1,2,:);
dM_dTheta.arr(2,2,:) = dM_dTheta.arr(2,2,:) + reshape(h0 * dmList_dTheta(:,3,ii),1,1,numElements);
dM_dTheta.arr(2,3,:) = dM_dTheta.arr(2,3,:) + reshape(0.5 * dmList_dTheta(:,2,ii),1,1,numElements);
dM_dTheta.arr(3,1,:) = dM_dTheta.arr(1,3,:);
dM_dTheta.arr(3,2,:) = dM_dTheta.arr(2,3,:);
end
else
dM_dTheta = repmat(dM_dTheta, 1, RN);
for ii=1:RN
dM_dTheta(ii).arr(1,1,:) = reshape(-h0 * dmList_dTheta(:,3,ii),1,1,numElements);
dM_dTheta(ii).arr(1,2,:) = reshape(-h0 * dmList_dTheta(:,4,ii),1,1,numElements);
dM_dTheta(ii).arr(1,3,:) = reshape(0.5 * dmList_dTheta(:,1,ii),1,1,numElements);
dM_dTheta(ii).arr(2,1,:) = dM_dTheta(ii).arr(1,2,:);
dM_dTheta(ii).arr(2,2,:) = reshape(h0 * dmList_dTheta(:,3,ii),1,1,numElements);
dM_dTheta(ii).arr(2,3,:) = reshape(0.5 * dmList_dTheta(:,2,ii),1,1,numElements);
dM_dTheta(ii).arr(3,1,:) = dM_dTheta(ii).arr(1,3,:);
dM_dTheta(ii).arr(3,2,:) = dM_dTheta(ii).arr(2,3,:);
end
end
%%3. dY
%%3.1 dY_dAlpha
dY_dAlpha = struct('arr', []); dY_dAlpha.arr = zeros(3,3,numElements); dY_dAlpha = repmat(dY_dAlpha, 1, RN);
for ii=1:RN
for jj=1:numElements
dY_dAlpha(ii).arr(:,:,jj) = YY(:,:,jj) * dM_dAlpha(ii).arr(:,:,jj);
end
dY_dAlpha(ii).arr = A0*dY_dAlpha(ii).arr;
end
%%3.2 dY_dTheta
dY_dTheta = struct('arr', []); dY_dTheta.arr = zeros(3,3,numElements);
if 1==OPT_Theta3Only
for jj=1:numElements
dY_dTheta.arr(:,:,jj) = YY(:,:,jj) * dM_dTheta.arr(:,:,jj);
end
dY_dTheta.arr = A0*dY_dTheta.arr;
else
dY_dTheta = repmat(dY_dTheta, 1, RN);
for ii=1:RN
for jj=1:numElements
dY_dTheta(ii).arr(:,:,jj) = YY(:,:,jj) * dM_dTheta(ii).arr(:,:,jj);
end
dY_dTheta(ii).arr = A0*dY_dTheta(ii).arr;
end
end
%%4. dS
%%4.1 dS_dAlpha
dS_dAlpha = struct('arr', []); dS_dAlpha.arr = zeros(3,3,numElements); dS_dAlpha = repmat(dS_dAlpha, 1, RN);
for ii=1:RN
dS_dAlpha(ii).arr = times(Y, reshape(dRho_dAlpha(:,ii),1,1,numElements)) - times(dY_dAlpha(ii).arr, reshape(1-rhoRN,1,1,numElements));
%% Transfer 2nd-order Tensor to 4th-order Tensor
dS_dAlpha(ii).arr = Tensor2ndToTensor4th(dS_dAlpha(ii).arr);
end
%%4.2 dS_dTheta
dS_dTheta = struct('arr', []); dS_dTheta.arr = zeros(3,3,numElements);
if 1==OPT_Theta3Only
dS_dTheta.arr = times(dY_dTheta.arr, reshape(rhoRN-1,1,1,numElements));
%% Transfer 2nd-order Tensor to 4th-order Tensor
dS_dTheta.arr = Tensor2ndToTensor4th(dS_dTheta.arr);
else
dS_dTheta = repmat(dS_dTheta, 1, RN);
for ii=1:RN
dS_dTheta(ii).arr = times(dY_dTheta(ii).arr, reshape(rhoRN-1,1,1,numElements));
%% Transfer 2nd-order Tensor to 4th-order Tensor
dS_dTheta(ii).arr = Tensor2ndToTensor4th(dS_dTheta(ii).arr);
end
end
%%5. dKe
%%5.1 dKe_dAlpha
tmp_dK_dAlpha = struct('arr', []); tmp_dK_dAlpha.arr = zeros(8,8,numElements); tmp_dK_dAlpha = repmat(tmp_dK_dAlpha, 1, RN);
for ii=1:RN
for jj=1:numElements
idS_dAlpha = zeros12;
for kk=1:4
idx = (kk-1)*3+1:kk*3;
idS_dAlpha(idx,idx) = dS_dAlpha(ii).arr(:,:,jj);
end
iDe = B'*idS_dAlpha*B;%%Integral
tmp_dK_dAlpha(ii).arr(:,:,jj) = iDe/4;
end
end
%%5.2 dKe_dTheta
tmp_dK_dTheta = struct('arr', []); tmp_dK_dTheta.arr = zeros(8,8,numElements);
if 1==OPT_Theta3Only
for jj=1:numElements
idS_dTheta = zeros12;
for kk=1:4
idx = (kk-1)*3+1:kk*3;
idS_dTheta(idx,idx) = dS_dTheta.arr(:,:,jj);
end
iDe = B'*idS_dTheta*B;
tmp_dK_dTheta.arr(:,:,jj) = iDe/4;
end
else
tmp_dK_dTheta = repmat(tmp_dK_dTheta, 1, RN);
for ii=1:RN
for jj=1:numElements
idS_dTheta = zeros12;
for kk=1:4
idx = (kk-1)*3+1:kk*3;
idS_dTheta(idx,idx) = dS_dTheta(ii).arr(:,:,jj);
end
iDe = B'*idS_dTheta*B;
tmp_dK_dTheta(ii).arr(:,:,jj) = iDe/4;
end
end
end
%%6. Assemble
%%6.1 Width
df0dAlpha = zeros(size(alphaList));
dK_dAlpha = ones(64, numElements, RN);
for jj=1:RN
dK_dAlpha(:,:,jj) = reshape(tmp_dK_dAlpha(jj).arr, 64, numElements);
end
for jj=1:RN
for kk=1:size(Ue2,3)
df0dAlpha(:,jj) = df0dAlpha(:,jj) + ww(kk)*reshape(sum(dK_dAlpha(:,:,jj).*Ue2(:,:,kk),1),numElements,1);
end
end
df0dAlpha = W*df0dAlpha/c0Total;
%%6.2 Orientation
if 1==OPT_Theta3Only
df0dTheta = zeros(size(thetaList,1),1);
dK_dTheta = reshape(tmp_dK_dTheta.arr, 64, numElements);
for kk=1:size(Ue2,3)
df0dTheta = df0dTheta + ww(kk)*reshape(sum(dK_dTheta.*Ue2(:,:,kk),1),numElements,1);
end
else
df0dTheta = zeros(size(thetaList));
dK_dTheta = ones(64, numElements, RN);
for jj=1:RN
dK_dTheta(:,:,jj) = reshape(tmp_dK_dTheta(jj).arr, 64, numElements);
end
for jj=1:RN
for kk=1:size(Ue2,3)
df0dTheta(:,jj) = df0dTheta(:,jj) + ww(kk)*reshape(sum(dK_dTheta(:,:,jj).*Ue2(:,:,kk),1),numElements,1);
end
end
end
df0dTheta = W/c0Total*df0dTheta;
%%7. Regularization
coefi = 6; %% 2: k*pi (min), k*pi/2 (max); 6: k*pi/3 (min), k*pi/6 (max)
dp0dTheta = zeros(size(df0dTheta));
if W<1
if OPT_Theta3Only
for ii=1:numElements
ijTheta = thetaList(ii,3);
ijAdjacentEles = eleAdjacencyMap(ii).adjacentEles;
ijAdjacentThetas = thetaList(ijAdjacentEles,3);
% dp0dTheta(ii) = 2*sum(sin(coefi*ijTheta - coefi*ijAdjacentThetas));
dp0dTheta(ii) = sum(coefi*0.5*sin(coefi*ijAdjacentThetas - coefi*ijTheta));
end
else
for jj=1:RN
for ii=1:numElements
ijTheta = thetaList(ii,jj);
ijAdjacentEles = eleAdjacencyMap(ii).adjacentEles;
ijAdjacentThetas = thetaList(ijAdjacentEles,jj);
% dp0dTheta(ii,jj) = 2*sum(sin(2*ijTheta - 2*ijAdjacentThetas));
dp0dTheta(ii,jj) = sum(coefi*0.5*sin(coefi*ijAdjacentThetas - coefi*ijTheta));
end
end
end
dp0dTheta = (1-W)/p0Total*dp0dTheta;
end
df0dTheta = df0dTheta + dp0dTheta;
df0dAlpha = -df0dAlpha;
df0dTheta = -df0dTheta;
end | MATLAB |
2D | PSLer/TopRank3 | Demo.m | .m | 2,871 | 61 | %% ----TopRank3----
%% Author: Junpeng Wang
%% Copyright (c) All Rights Reserved.
%% Version: 2023-11-10
%% E-mail: junpeng.wang@tum.de
%%This repository was created for the paper "Design and Optimization of Functionally-graded Lattice Structures for Multiple Loading Conditions"
%% by Junpeng Wang, Rüdiger Westermann, Xifeng Gao and Jun Wu.
%%which was submitted to the journal "xxx", and also available in arXiv (xxxx.xxxxx)
clear; clc;
addpath('./supports');
%%1. Problem Description
if 1 %%User Tailored Model
%%1.1 Design Domain
mesh_ = CreateCartesianMesh2D(ones(40, 80));
%%1.2 Boundary Conditions
ndC = mesh_.nodeCoords(mesh_.nodMapBack(mesh_.nodesOnBoundary),:);
fixingCond_ = struct('arr', []);
fixedNodes = mesh_.nodesOnBoundary(find(mesh_.boundingBox(1,1)==ndC(:,1)));
fixingCond_.arr = [fixedNodes ones(length(fixedNodes), 2)];
loadingCond_ = struct('arr', []); loadingCond_ = repmat(loadingCond_,2,1);
force = [1 0; 0 -1];
loadedCoords = [mesh_.boundingBox(2,1) mesh_.boundingBox(2,2)/2; mesh_.boundingBox(2,1)/2 0];
[~,loadedNodes] = min(vecnorm(loadedCoords(1,:)-ndC,2,2));
loadingCond_(1).arr = [mesh_.nodesOnBoundary(loadedNodes) force(1,:)];
[~,loadedNodes] = min(vecnorm(loadedCoords(2,:)-ndC,2,2));
loadingCond_(2).arr = [mesh_.nodesOnBoundary(loadedNodes) force(2,:)];
else %%Import the external model involved in the associated paper
fileName = './data/femur_R150.txt';
[mesh_, fixingCond_, loadingCond_] = ImportExternalFEAmodel(fileName);
end
%%1.3 Material Properties
matProp_.modulus = 1.0;
matProp_.PossionRatio = 0.3;
matProp_.minModulus = 1.0e-6 * matProp_.modulus;
%%1.4 Optimization Settings
optiSet_.Vf = 0.5; %% Target Volume Fraction
optiSet_.perLoadContri = ones(1, numel(loadingCond_))/numel(loadingCond_);
optiSet_.OPT_Theta3Only = 1; %%1: (theta3, theta2 = theta3+pi/3, theta1 = theta3+2*pi/3), 0: (All Independent Thetas)
optiSet_.OPT_OriStartingGuess = 'SGp'; %% 'SGu' (Uniform), 'SGp' (Principal Stress-guided)
optiSet_.W = 0.5; %%Weight Factor for Compliance Item, 1-W for Orientation Regularization Item
optiSet_.alphaBounds = [1.0e-1 0.5]; %% Lower and Upper Bounds for Layer Widths (Alpha)
optiSet_.nloop = 300; %% Number of Iterations to Conduct
optiSet_.passiveEles = SetBoundaryElementsBePassive(mesh_, 0); %%Set Domain Boundary be Solid, the Second Argument Decides the Width of the Solid Boundary
ShowProblemDescription(mesh_, fixingCond_, loadingCond_);
%%2. Run Optimization
tStart = tic;
outPath = './out/'; if ~exist(outPath, 'dir'), mkdir(outPath); end
[alphaList_, thetaList_, optiLog_, cPerLoad_] = TopRank3(mesh_, fixingCond_, loadingCond_, matProp_, optiSet_, outPath);
disp(['Performing Optimization Costs ' sprintf('%10.3g',toc(tStart)) 's']);
%%3. Visualization
ShowRank3Laminate([alphaList_ thetaList_], mesh_, 0.5);
ShowRank3byStreamlines(alphaList_, thetaList_, mesh_, 30); | MATLAB |
2D | PSLer/TopRank3 | supports/CreateCartesianMesh2D.m | .m | 3,508 | 95 | function meshInfo = CreateCartesianMesh2D(voxelizedModel)
% __ x
% /
% -y
% 4--------3
% | |
% | |
% 1--------2
% rectangular element
%% initialize mesh
meshInfo = MeshStruct();
[ny, nx] = size(voxelizedModel);
meshInfo.resX = nx; meshInfo.resY = ny;
meshInfo.boundingBox = [0 0; [nx ny]];
meshInfo.eleSize = [meshInfo.boundingBox(2,:) - meshInfo.boundingBox(1,:)] ./ [nx ny];
%% identify solid&void elements
meshInfo.eleMapBack = find(1==voxelizedModel);
meshInfo.numElements = length(meshInfo.eleMapBack);
meshInfo.eleMapForward = zeros(nx*ny,1);
meshInfo.eleMapForward(meshInfo.eleMapBack) = (1:meshInfo.numElements)';
%% discretize
nodenrs = reshape(1:(nx+1)*(ny+1), 1+ny, 1+nx);
eNodVec = reshape(nodenrs(1:end-1,1:end-1)+1, nx*ny, 1);
meshInfo.eNodMat = repmat(eNodVec(meshInfo.eleMapBack),1,4);
tmp = [0 ny+[1 0] -1];
for ii=1:4
meshInfo.eNodMat(:,ii) = meshInfo.eNodMat(:,ii) + repmat(tmp(ii), meshInfo.numElements,1);
end
meshInfo.nodMapBack = unique(meshInfo.eNodMat);
meshInfo.numNodes = length(meshInfo.nodMapBack);
meshInfo.numDOFs = meshInfo.numNodes*2;
meshInfo.nodMapForward = zeros((nx+1)*(ny+1),1);
meshInfo.nodMapForward(meshInfo.nodMapBack) = (1:meshInfo.numNodes)';
for ii=1:4
meshInfo.eNodMat(:,ii) = meshInfo.nodMapForward(meshInfo.eNodMat(:,ii));
end
meshInfo.eDofMat = [2*meshInfo.eNodMat-1 2*meshInfo.eNodMat];
meshInfo.eDofMat = meshInfo.eDofMat(:, [1 5 2 6 3 7 4 8]);
meshInfo.nodeCoords = zeros((nx+1)*(ny+1),2);
xSeed = meshInfo.boundingBox(1,1):(meshInfo.boundingBox(2,1)-meshInfo.boundingBox(1,1))/nx:meshInfo.boundingBox(2,1);
ySeed = meshInfo.boundingBox(2,2):(meshInfo.boundingBox(1,2)-meshInfo.boundingBox(2,2))/ny:meshInfo.boundingBox(1,2);
meshInfo.nodeCoords(:,1) = reshape(repmat(xSeed, ny+1, 1), (nx+1)*(ny+1), 1);
meshInfo.nodeCoords(:,2) = repmat(ySeed, 1, nx+1)';
%% identify boundary info.
meshInfo.numNodsAroundEleVec = zeros(meshInfo.numNodes,1);
for ii=1:meshInfo.numElements
iNodes = meshInfo.eNodMat(ii,:);
meshInfo.numNodsAroundEleVec(iNodes,:) = meshInfo.numNodsAroundEleVec(iNodes) + 1;
end
meshInfo.nodesOnBoundary = find(meshInfo.numNodsAroundEleVec<4);
allNodes = zeros(meshInfo.numNodes,1);
allNodes(meshInfo.nodesOnBoundary) = 1;
tmp = zeros(meshInfo.numElements,1);
for ii=1:4
tmp = tmp + allNodes(meshInfo.eNodMat(:,ii));
end
meshInfo.elementsOnBoundary = find(tmp>0);
%% compute element centroids
eleCentX = meshInfo.nodeCoords(meshInfo.nodMapBack,1); eleCentX = eleCentX(meshInfo.eNodMat);
eleCentY = meshInfo.nodeCoords(meshInfo.nodMapBack,2); eleCentY = eleCentY(meshInfo.eNodMat);
meshInfo.eleCentroidList = [sum(eleCentX,2) sum(eleCentY,2)]/4;
meshInfo.boundaryNodeCoords = meshInfo.nodeCoords(meshInfo.nodMapBack(meshInfo(1).nodesOnBoundary),:);
end
function val = MeshStruct()
val = struct(...
'resX', 0, ...
'resY', 0, ...
'boundingBox', [], ...
'eleSize', [], ...
'numElements', 0, ...
'numNodes', 0, ...
'numDOFs', 0, ...
'nodeCoords', 0, ...
'eleCentroidList', 0, ...
'eNodMat', 0, ...
'eDofMat', 0, ...
'freeDOFs', 0, ...
'fixedDOFs', 0, ...
'eleMapBack', [], ...
'eleMapForward', [], ...
'nodMapBack', [], ...
'nodMapForward', [], ...
'nodesOnBoundary', [], ...
'boundaryNodeCoords', [], ...
'numNodsAroundEleVec', [], ...
'elementsOnBoundary', [], ...
'elementUpwardMap', [] ...
);
end | MATLAB |
2D | PSLer/TopRank3 | supports/ShowProblemDescription.m | .m | 1,849 | 44 | function ShowProblemDescription(meshInfo, fixingCond, loadingCond)
figure;
%%Design Domain
xPatchs = meshInfo.nodeCoords(meshInfo.nodMapBack,1); xPatchs = xPatchs(meshInfo.eNodMat');
yPatchs = meshInfo.nodeCoords(meshInfo.nodMapBack,2); yPatchs = yPatchs(meshInfo.eNodMat');
cPatchs = zeros(size(yPatchs));
hdDesignDomain = patch(xPatchs, yPatchs, cPatchs); hold on;
xlabel('X'); ylabel('Y');
set(hdDesignDomain, 'FaceColor', [0.5 0.5 0.5], 'FaceAlpha', 1, 'EdgeColor', 'None');
%%Fixations
for ii=1:numel(fixingCond)
tarNodeCoord = meshInfo.nodeCoords(meshInfo.nodMapBack(fixingCond(ii).arr(:,1)),:);
hold('on'); hdFixation = plot(tarNodeCoord(:,1), tarNodeCoord(:,2), 'x', 'Color', [0.0 0.0 0.0], 'LineWidth', 2, 'MarkerSize', 10);
end
%%Loads
lB = 0.2;
uB = 1.0;
numLoadSteps = numel(loadingCond);
amps = struct('arr', [], 'scalingFac', 1); amps = repmat(amps, numLoadSteps, 1);
for ii=1:numLoadSteps
amps(ii).arr = vecnorm(loadingCond(ii).arr(:,2:end),2,2)';
end
maxAmp = max([amps.arr]);
minAmp = min([amps.arr]);
if abs(minAmp-maxAmp)/(minAmp+maxAmp)>0.1
if minAmp/maxAmp>lB/uB, lB = minAmp/maxAmp; end
for ii=1:numLoadSteps
amps(ii).scalingFac = lB + (uB-lB)*(amps(ii).arr'-minAmp)/(maxAmp-minAmp);
end
end
for ii=1:numLoadSteps
loadingDirVec = loadingCond(ii).arr(:,2:end)./amps(ii).arr' .* amps(ii).scalingFac;
coordLoadedNodes = meshInfo.nodeCoords(meshInfo.nodMapBack(loadingCond(ii).arr(:,1)),:);
amplitudesF = mean(meshInfo.boundingBox(2,:)-meshInfo.boundingBox(1,:))/5 * loadingDirVec;
hold('on'); hdLoads = quiver(coordLoadedNodes(:,1), coordLoadedNodes(:,2), amplitudesF(:,1), ...
amplitudesF(:,2), 0, 'LineWidth', 2, 'MaxHeadSize', 1, 'MaxHeadSize', 1);
end
axis('equal'); axis('tight'); axis('on');
set(gca, 'FontName', 'Times New Roman', 'FontSize', 20);
end
| MATLAB |
2D | PSLer/TopRank3 | supports/ShowRank3Laminate.m | .m | 1,927 | 42 | function ShowRank3Laminate(rank3LaminateParas, meshInfo, lgthScale)
figure;
if 6~=size(rank3LaminateParas,2), warning('Only Works with Rank-3!'); return; end
alphaList = rank3LaminateParas(:,1:3);
thetaList = rank3LaminateParas(:,4:6);
densityField = 1-prod(1-alphaList,2);
xPatchs = meshInfo.nodeCoords(meshInfo.nodMapBack,1); xPatchs = xPatchs(meshInfo.eNodMat');
yPatchs = meshInfo.nodeCoords(meshInfo.nodMapBack,2); yPatchs = yPatchs(meshInfo.eNodMat');
cPatchs = densityField(:)';
cPatchs = repmat(cPatchs, 4, 1);
colormap(flip(gray));
hCells = patch(xPatchs, yPatchs, cPatchs); hold('on');
ctrs = meshInfo.eleCentroidList;
ang1 = thetaList(:,1);
ang2 = thetaList(:,2);
ang3 = thetaList(:,3);
if 0==lgthScale
lgthScale = 0.3;
amp1 = 1;
amp2 = 1;
amp3 = 1;
else
amp1 = alphaList(:,1).*(1-alphaList(:,2)).*(1-alphaList(:,3));
amp2 = alphaList(:,2).*(1-alphaList(:,3));
amp3 = alphaList(:,3);
amp1 = max(amp1,1.0e-6); amp2 = max(amp2,1.0e-6); amp3 = max(amp3,1.0e-6);
end
hDir11 = quiver(ctrs(:,1), ctrs(:,2), cos(ang1).*amp1, sin(ang1).*amp1, lgthScale); hold('on');
%hDir12 = quiver(ctrs(:,1), ctrs(:,2), -cos(ang1).*amp1, -sin(ang1).*amp1, lgthScale); hold('on');
hDir21 = quiver(ctrs(:,1), ctrs(:,2), cos(ang2).*amp2, sin(ang2).*amp2, lgthScale); hold('on');
%hDir22 = quiver(ctrs(:,1), ctrs(:,2), -cos(ang2).*amp2, -sin(ang2).*amp2, lgthScale); hold('on');
hDir31 = quiver(ctrs(:,1), ctrs(:,2), cos(ang3).*amp3, sin(ang3).*amp3, lgthScale); hold('on');
%hDir32 = quiver(ctrs(:,1), ctrs(:,2), -cos(ang3).*amp3, -sin(ang3).*amp3, lgthScale); hold('on');
set([hDir11], 'LineWidth', 2, 'Color', [252 141 98]/255);
set([hDir21], 'LineWidth', 2, 'Color', [102 194 165]/255);
set([hDir31], 'LineWidth', 2, 'Color', [0 0 255]/255);
set(hCells, 'FaceColor', 'flat', 'FaceAlpha', 1, 'EdgeColor', 'None');
axis('equal'); axis('tight'); axis('off');
end
| MATLAB |
2D | PSLer/TopRank3 | supports/ImportExternalFEAmodel.m | .m | 1,846 | 51 | function [mesh_, fixingCond_, loadingCond_] = ImportExternalFEAmodel(fileName)
fid = fopen(fileName, 'r');
tmp = fscanf(fid, '%s %s', 2);
domainType = fscanf(fid, '%s', 1);
tmp = fscanf(fid, '%s', 1);
tmp = fscanf(fid, '%d %d', 3);
nelx = tmp(1); nely = tmp(2);
tmp = fscanf(fid, '%s %s', 2);
numEles = fscanf(fid, '%d', 1);
eleList = fscanf(fid, '%d', [1 numEles])';
allEles = zeros(nelx*nely,1); allEles(eleList) = 1;
mesh_ = CreateCartesianMesh2D(reshape(allEles, nely, nelx));
tmp = fscanf(fid, '%s %s', 2);
numFixedNodes = fscanf(fid, '%d', 1);
fixingCond_ = struct('arr', []);
if numFixedNodes>0
fixingCond_(1).arr = fscanf(fid, '%d %d %d', [3 numFixedNodes])';
fixingCond_(1).arr(:,1) = mesh_.nodMapForward(fixingCond_(1).arr(:,1));
end
tmp = fscanf(fid, '%s %s', 2);
numLoadedNodes = fscanf(fid, '%d', 1);
if numLoadedNodes>0
loadingCond_(1).arr = fscanf(fid, '%d %e %e', [3 numLoadedNodes])';
loadingCond_(1).arr(:,1) = double(mesh_.nodMapForward(loadingCond_(1).arr(:,1)));
end
tmp1 = fscanf(fid, '%s %s %s', 3);
if ~isempty(tmp1)
if strcmp(tmp1, 'additionalboundaryconditions:')
numAdditionalBCs = fscanf(fid, '%d', 1);
for ii=1:numAdditionalBCs
%%Additional Loads
tmp = fscanf(fid, '%s %s', 2);
tmp1 = fscanf(fid, '%d %d', 2);
numLoadedNodes = tmp1(1);
iLoadIdx = tmp1(2);
tmp1 = fscanf(fid, '%d %e %e', [3 numLoadedNodes])';
tmp1(:,1) = double(mesh_.nodMapForward(tmp1(:,1)));
loadingCond_(iLoadIdx).arr = tmp1;
%%Additional Fixations
tmp = fscanf(fid, '%s %s', 2);
tmp1 = fscanf(fid, '%d %d', 2);
numFixedNodes = tmp1(1);
iFixationIdx = tmp1(2);
tmp1 = fscanf(fid, '%d %d %d', [3 numFixedNodes])';
tmp1(:,1) = mesh_.nodMapForward(tmp1(:,1));
fixingCond_(iFixationIdx).arr = tmp1;
end
end
end
fclose(fid);
end | MATLAB |
2D | PSLer/TopRank3 | supports/ShowRank3byStreamlines.m | .m | 23,548 | 645 | %% This code is to generate the domain-filling and evenly-spaced streamlines aligning with layering orientations
%% This code is adapted from the publicaly available stress visualizer "3D-TSV" (https://github.com/Junpeng-Wang-TUM/3D-TSV)
%% Author: Junpeng Wang (junpeng.wang@tum.de)
%% Version: 2021-08-05
%% Update: 2023-11-10
function ShowRank3byStreamlines(alphaList, thetaList, meshInfo, PSLsDensityCtrl)
global topRankNparas_;
global meshStruct_;
global followingLayerTabgent_;
global snappingOpt_;
global interceptionThreshold_;
meshStruct_ = meshInfo;
topRankNparas_ = zeros(meshStruct_.numElements, 9);
topRankNparas_(:, [1 4 7]) = alphaList;
topRankNparas_(:, [2 3 5 6 8 9]) = [cos(thetaList(:,1)) sin(thetaList(:,1)) ...
cos(thetaList(:,2)) sin(thetaList(:,2)) cos(thetaList(:,3)) sin(thetaList(:,3))];
followingLayerTabgent_ = 1;
interceptionThreshold_ = 6;
snappingOpt_ = 0;
Setup();
rankLayerOpt = [1 1 1];
CreatePSLsViaTSV(PSLsDensityCtrl, rankLayerOpt);
ShowStreamlines();
end
function Setup()
global meshStruct_;
global nodeCoords_;
global eleSize_;
global tracingStepWidth_;
global layer_1_StreamlinePool_;
global layer_2_StreamlinePool_;
global layer_3_StreamlinePool_;
nodeCoords_ = meshStruct_.nodeCoords(meshStruct_.nodMapBack,:);
eleSize_ = meshStruct_.eleSize(1);
layer_1_StreamlinePool_ = StreamlineStruct();
layer_2_StreamlinePool_ = StreamlineStruct();
layer_3_StreamlinePool_ = StreamlineStruct();
tracingStepWidth_ = eleSize_/2;
end
function CreatePSLsViaTSV(resCtrl, rankLayerOpt)
global eleSize_;
global nodeCoords_;
global meshStruct_;
global minimumEpsilon_;
global mergeTrigger_;
global seedPointsHistory_;
global seedPoints_;
global seedPointsValence_;
global startCoord_;
global relaxedFactor_;
global layer_1_StreamlinePool_;
global layer_2_StreamlinePool_;
global layer_3_StreamlinePool_;
global layer_1_CoordList_; layer_1_CoordList_ = [];
global layer_2_CoordList_; layer_2_CoordList_ = [];
global layer_3_CoordList_; layer_3_CoordList_ = [];
global seedPoints_layer_1_;
global seedPoints_layer_2_;
global seedPoints_layer_3_;
%%1. Create Seed Points
minimumEpsilon_ = min(meshStruct_.boundingBox(2,:)-meshStruct_.boundingBox(1,:))/resCtrl;
validNodes = zeros((meshStruct_.resX+1)*(meshStruct_.resY+1),1);
validNodes(meshStruct_.nodMapBack) = (1:length(meshStruct_.nodMapBack))';
validNodes = reshape(validNodes, meshStruct_.resY+1, meshStruct_.resX+1);
if min([meshStruct_.resX meshStruct_.resX])<100
seedDensCtrl = 1;
else
seedDensCtrl = max(ceil(minimumEpsilon_/eleSize_/10), 2);
end
sampledNodes = validNodes(seedDensCtrl+1:seedDensCtrl:meshStruct_.resY+1-seedDensCtrl, ...
seedDensCtrl+1:seedDensCtrl:meshStruct_.resX+1-seedDensCtrl);
sampledNodes = reshape(sampledNodes, numel(sampledNodes), 1);
sampledNodes(0==sampledNodes) = [];
sampledNodes = setdiff(sampledNodes, meshStruct_.nodesOnBoundary);
seedPointsHistory_ = nodeCoords_(sampledNodes,:);
%%2. Initialize PSL pool
relaxedFactor_ = 1;
startCoord_ = sum(meshStruct_.boundingBox,1)/2;
mergeTrigger_ = minimumEpsilon_;
seedPoints_ = seedPointsHistory_;
numSeedPoints = size(seedPoints_,1);
seedPointsValence_ = zeros(numSeedPoints, 1);
%%3. Streamline sampling via TSV
disp('Performing TSV to Generate Streamlines');
%%3.1 Layer 1
if rankLayerOpt(1)
seedPoints_layer_1_ = seedPointsHistory_;
seedValence_layer_1 = seedPointsValence_;
its = 0;
looper = sum(seedValence_layer_1);
while looper<1*numSeedPoints
its = its + 1;
unFinishedSpps = find(seedValence_layer_1<1);
spp = unFinishedSpps(1);
if 0==looper
[~, spp] = min(vecnorm(startCoord_-seedPoints_layer_1_,2,2));
else
[~, tarPos] = min(vecnorm(startCoord_-seedPoints_layer_1_(unFinishedSpps,:),2,2));
spp = unFinishedSpps(tarPos);
end
seed = seedPoints_layer_1_(spp,:);
seedValence_layer_1(spp,1) = 1;
iStreamline = Have1moreStreamline(seed, 'ONE');
if 0==iStreamline.length
looper = sum(seedValence_layer_1);
disp([' Iteration: ' sprintf('%4i',its) ' Progress: ' sprintf('%6i',looper) ' Total: ' sprintf('%6i',1*numSeedPoints)]);
continue;
end
layer_1_StreamlinePool_(end+1,1) = iStreamline;
layer_1_CoordList_(end+1:end+iStreamline.length,:) = iStreamline.phyCoordList;
sppsEmptyLayer1Valence = find(0==seedValence_layer_1);
if ~isempty(sppsEmptyLayer1Valence)
[potentialDisList1, potentialPosList1] = GetDisListOfPointList2Curve(seedPoints_layer_1_(...
sppsEmptyLayer1Valence,:), iStreamline.phyCoordList);
potentialSolidSpps1 = find(potentialDisList1<relaxedFactor_);
if ~isempty(potentialSolidSpps1)
spps2BeMerged = sppsEmptyLayer1Valence(potentialSolidSpps1);
seedPoints_layer_1_(spps2BeMerged,:) = potentialPosList1(potentialSolidSpps1,:);
seedValence_layer_1(spps2BeMerged,1) = 1;
end
end
looper = sum(seedValence_layer_1);
disp([' Iteration: ' sprintf('%4i',its) ' Progress: ' sprintf('%6i',looper) ' Total: ' sprintf('%6i',1*numSeedPoints)]);
end
end
%%3.2 Layer 2
if rankLayerOpt(2)
seedPoints_layer_2_ = seedPointsHistory_;
seedValence_layer_2 = seedPointsValence_;
its = 0;
looper = sum(seedValence_layer_2);
while looper<1*numSeedPoints
its = its + 1;
unFinishedSpps = find(seedValence_layer_2<1);
spp = unFinishedSpps(1);
if 0==looper
[~, spp] = min(vecnorm(startCoord_-seedPoints_layer_2_,2,2));
else
[~, tarPos] = min(vecnorm(startCoord_-seedPoints_layer_2_(unFinishedSpps,:),2,2));
spp = unFinishedSpps(tarPos);
end
seed = seedPoints_layer_2_(spp,:);
seedValence_layer_2(spp,1) = 1;
iStreamline = Have1moreStreamline(seed, 'TWO');
if 0==iStreamline.length
looper = sum(seedValence_layer_2);
disp([' Iteration: ' sprintf('%4i',its) ' Progress: ' sprintf('%6i',looper) ' Total: ' sprintf('%6i',1*numSeedPoints)]);
continue;
end
layer_2_StreamlinePool_(end+1,1) = iStreamline;
layer_2_CoordList_(end+1:end+iStreamline.length,:) = iStreamline.phyCoordList;
sppsEmptyLayer1Valence = find(0==seedValence_layer_2);
if ~isempty(sppsEmptyLayer1Valence)
[potentialDisList2, potentialPosList2] = GetDisListOfPointList2Curve(seedPoints_layer_2_(...
sppsEmptyLayer1Valence,:), iStreamline.phyCoordList);
potentialSolidSpps2 = find(potentialDisList2<relaxedFactor_);
if ~isempty(potentialSolidSpps2)
spps2BeMerged = sppsEmptyLayer1Valence(potentialSolidSpps2);
seedPoints_layer_2_(spps2BeMerged,:) = potentialPosList2(potentialSolidSpps2,:);
seedValence_layer_2(spps2BeMerged,1) = 1;
end
end
looper = sum(seedValence_layer_2);
disp([' Iteration: ' sprintf('%4i',its) ' Progress: ' sprintf('%6i',looper) ' Total: ' sprintf('%6i',1*numSeedPoints)]);
end
end
%%3.2 Layer 3
if rankLayerOpt(3)
seedPoints_layer_3_ = seedPointsHistory_;
seedValence_layer_3 = seedPointsValence_;
its = 0;
looper = sum(seedValence_layer_3);
while looper<1*numSeedPoints
its = its + 1;
unFinishedSpps = find(seedValence_layer_3<1);
spp = unFinishedSpps(1);
if 0==looper
[~, spp] = min(vecnorm(startCoord_-seedPoints_layer_3_,2,2));
else
[~, tarPos] = min(vecnorm(startCoord_-seedPoints_layer_3_(unFinishedSpps,:),2,2));
spp = unFinishedSpps(tarPos);
end
seed = seedPoints_layer_3_(spp,:);
seedValence_layer_3(spp,1) = 1;
iStreamline = Have1moreStreamline(seed, 'THREE');
if 0==iStreamline.length
looper = sum(seedValence_layer_3);
disp([' Iteration: ' sprintf('%4i',its) ' Progress: ' sprintf('%6i',looper) ' Total: ' sprintf('%6i',1*numSeedPoints)]);
continue;
end
layer_3_StreamlinePool_(end+1,1) = iStreamline;
layer_3_CoordList_(end+1:end+iStreamline.length,:) = iStreamline.phyCoordList;
sppsEmptyLayer1Valence = find(0==seedValence_layer_3);
if ~isempty(sppsEmptyLayer1Valence)
[potentialDisList3, potentialPosList3] = GetDisListOfPointList2Curve(seedPoints_layer_3_(...
sppsEmptyLayer1Valence,:), iStreamline.phyCoordList);
potentialSolidSpps3 = find(potentialDisList3<relaxedFactor_);
if ~isempty(potentialSolidSpps3)
spps2BeMerged = sppsEmptyLayer1Valence(potentialSolidSpps3);
seedPoints_layer_3_(spps2BeMerged,:) = potentialPosList3(potentialSolidSpps3,:);
seedValence_layer_3(spps2BeMerged,1) = 1;
end
end
looper = sum(seedValence_layer_3);
disp([' Iteration: ' sprintf('%4i',its) ' Progress: ' sprintf('%6i',looper) ' Total: ' sprintf('%6i',1*numSeedPoints)]);
end
end
%%Compact PSLs sets
minLength = 2;
PSLs2Bdiscarded = []; index = 0;
for ii=1:length(layer_1_StreamlinePool_)
if layer_1_StreamlinePool_(ii).length<minLength
index = index + 1;
PSLs2Bdiscarded(index) = ii;
end
end
layer_1_StreamlinePool_(PSLs2Bdiscarded) = [];
PSLs2Bdiscarded = []; index = 0;
for ii=1:length(layer_2_StreamlinePool_)
if layer_2_StreamlinePool_(ii).length<minLength
index = index + 1;
PSLs2Bdiscarded(index) = ii;
end
end
layer_2_StreamlinePool_(PSLs2Bdiscarded) = [];
PSLs2Bdiscarded = []; index = 0;
for ii=1:length(layer_3_StreamlinePool_)
if layer_3_StreamlinePool_(ii).length<minLength
index = index + 1;
PSLs2Bdiscarded(index) = ii;
end
end
layer_3_StreamlinePool_(PSLs2Bdiscarded) = [];
end
function iPSL = Have1moreStreamline(seed, psDir)
global snappingOpt_;
switch psDir
case 'ONE'
[iPSL, ~, ~] = GeneratePrincipalStressLines_elementWise(seed, psDir);
case 'TWO'
[~, iPSL, ~] = GeneratePrincipalStressLines_elementWise(seed, psDir);
case 'THREE'
[~, ~, iPSL] = GeneratePrincipalStressLines_elementWise(seed, psDir);
end
if snappingOpt_, iPSL = CroppingPSLifNeeded(iPSL, psDir); end
end
function [potentialDisList, potentialPosList] = GetDisListOfPointList2Curve(pointList, curveLine)
global mergeTrigger_;
disT = (curveLine(:,1) - pointList(:,1)').^2;
disT = disT + (curveLine(:,2) - pointList(:,2)').^2;
disT = sqrt(disT);
[minVal, minValPos] = min(disT,[],1);
potentialDisList = minVal';
potentialDisList = potentialDisList/mergeTrigger_;
potentialPosList = curveLine(minValPos,:);
end
function tarPSL = CroppingPSLifNeeded(srcPSL, psDir)
global mergeTrigger_;
global layer_1_CoordList_; global layer_2_CoordList_; global layer_3_CoordList_;
tarPSL = srcPSL;
if 5>=srcPSL.length, return; end
disThreshold = 1.5;
relaxedThreshold = 0.2;
switch psDir
case 'ONE'
if isempty(layer_1_CoordList_), return; end
srcCoordList = layer_1_CoordList_;
case 'TWO'
if isempty(layer_2_CoordList_), return; end
srcCoordList = layer_2_CoordList_;
case 'THREE'
if isempty(layer_3_CoordList_), return; end
srcCoordList = layer_3_CoordList_;
end
if srcPSL.midPointPosition == srcPSL.length || srcPSL.midPointPosition == 1
if 1==srcPSL.midPointPosition
tarCoordList = tarPSL.phyCoordList;
disT = (srcCoordList(:,1) - tarCoordList(:,1)').^2;
disT = disT + (srcCoordList(:,2) - tarCoordList(:,2)').^2;
disT = sqrt(disT);
miniDisList2SrcPSL = min(disT);
tarPositions = find(miniDisList2SrcPSL<mergeTrigger_/disThreshold);
%if isempty(tarPositions), return; end
if length(tarPositions)/size(tarCoordList,1)<relaxedThreshold, return; end
if length(tarPositions) == size(tarCoordList,1), tarPSL = StreamlineStruct(); return; end
startPos = 1; endPos = min(tarPositions);
else
tarCoordList = flip(tarPSL.phyCoordList,1);
disT = (srcCoordList(:,1) - tarCoordList(:,1)').^2;
disT = disT + (srcCoordList(:,2) - tarCoordList(:,2)').^2;
disT = sqrt(disT);
miniDisList2SrcPSL = min(disT);
tarPositions = find(miniDisList2SrcPSL<mergeTrigger_/disThreshold);
%if isempty(tarPositions), return; end
if length(tarPositions)/size(tarCoordList,1)<relaxedThreshold, return; end
if length(tarPositions) == size(tarCoordList,1), tarPSL = StreamlineStruct(); return; end
startPos = srcPSL.length - min(tarPositions) + 1; endPos = srcPSL.length;
end
else
tarCoordList = tarPSL.phyCoordList(srcPSL.midPointPosition:srcPSL.length,:);
disT = (srcCoordList(:,1) - tarCoordList(:,1)').^2;
disT = disT + (srcCoordList(:,2) - tarCoordList(:,2)').^2;
disT = sqrt(disT);
miniDisList2SrcPSL = min(disT);
tarPositions = find(miniDisList2SrcPSL<mergeTrigger_/disThreshold);
%if isempty(tarPositions)
if length(tarPositions)/size(tarCoordList,1)<relaxedThreshold
endPos = srcPSL.length;
elseif length(tarPositions) == size(tarCoordList,1)
endPos = srcPSL.midPointPosition;
else
endPos = srcPSL.midPointPosition+min(tarPositions)-1;
end
tarCoordList = flip(tarPSL.phyCoordList(1:srcPSL.midPointPosition,:),1);
disT = (srcCoordList(:,1) - tarCoordList(:,1)').^2;
disT = disT + (srcCoordList(:,2) - tarCoordList(:,2)').^2;
disT = sqrt(disT);
miniDisList2SrcPSL = min(disT);
tarPositions = find(miniDisList2SrcPSL<mergeTrigger_/disThreshold);
%if isempty(tarPositions)
if length(tarPositions)/size(tarCoordList,1)<relaxedThreshold
startPos = 1;
elseif length(tarPositions) == size(tarCoordList,1)
startPos = srcPSL.midPointPosition;
else
startPos = size(tarCoordList,1) - min(tarPositions) + 1;
end
end
tarPSL.eleIndexList = srcPSL.eleIndexList(startPos:endPos,:);
tarPSL.phyCoordList = srcPSL.phyCoordList(startPos:endPos,:);
tarPSL.alphaList = srcPSL.alphaList(startPos:endPos,:);
tarPSL.length = length(tarPSL.eleIndexList);
tarPSL.midPointPosition = 1;
end
function [layer_1_Streamline, layer_2_Streamline, layer_3_Streamline] = GeneratePrincipalStressLines_elementWise(initialSeed, typePSL)
global tracingStepWidth_;
global meshStruct_;
limiSteps = ceil(1.5*norm(meshStruct_.boundingBox(2,:)-meshStruct_.boundingBox(1,:))/tracingStepWidth_);
layer_1_Streamline = StreamlineStruct();
layer_2_Streamline = StreamlineStruct();
layer_3_Streamline = StreamlineStruct();
%%1. Spot the Starting Point
[eleIndex, phyCoord, layerPara, opt] = PreparingForTracing_elementWise(initialSeed);
if ~opt, return; end
%%2. Compute PSL(s)
switch typePSL
case 'ONE'
psDir = [2 3];
layer_1_Streamline = ComputePSL_elementWise(eleIndex, phyCoord, layerPara, psDir, layerPara(psDir), limiSteps);
case 'TWO'
psDir = [5 6];
layer_2_Streamline = ComputePSL_elementWise(eleIndex, phyCoord, layerPara, psDir, layerPara(psDir), limiSteps);
case 'THREE'
psDir = [8 9];
layer_3_Streamline = ComputePSL_elementWise(eleIndex, phyCoord, layerPara, psDir, layerPara(psDir), limiSteps);
case 'ALL'
psDir = [2 3];
layer_1_Streamline = ComputePSL_elementWise(eleIndex, phyCoord, layerPara, psDir, layerPara(psDir), limiSteps);
psDir = [5 6];
layer_2_Streamline = ComputePSL_elementWise(eleIndex, phyCoord, layerPara, psDir, layerPara(psDir), limiSteps);
psDir = [8 9];
layer_3_Streamline = ComputePSL_elementWise(eleIndex, phyCoord, layerPara, psDir, layerPara(psDir), limiSteps);
end
end
function iStreamline = ComputePSL_elementWise(eleIndex, phyCoord, layerPara, psDir, iniDir, limiSteps)
global tracingStepWidth_;
global followingLayerTabgent_;
if followingLayerTabgent_
iniDir = [-iniDir(2) iniDir(1)];
end
iStreamline = StreamlineStruct();
PSLphyCoordList = phyCoord;
PSLeleIndexList = eleIndex;
PSLprincipalStressList = layerPara;
%% tracing along first direction (v1)
nextPoint = phyCoord + tracingStepWidth_*iniDir;
[phyCoordList, eleIndexList, alphaList] = TracingPSL_elementWise(nextPoint, iniDir, eleIndex, psDir, limiSteps);
PSLphyCoordList = [PSLphyCoordList; phyCoordList];
PSLeleIndexList = [PSLeleIndexList; eleIndexList];
PSLprincipalStressList = [PSLprincipalStressList; alphaList];
%% tracing along second direction (-v1)
nextPoint = phyCoord - tracingStepWidth_*iniDir;
[phyCoordList, eleIndexList, alphaList] = TracingPSL_elementWise(nextPoint, -iniDir, eleIndex, psDir, limiSteps);
if size(phyCoordList,1) > 1
phyCoordList = flip(phyCoordList);
eleIndexList = flip(eleIndexList);
alphaList = flip(alphaList);
end
PSLphyCoordList = [phyCoordList; PSLphyCoordList];
PSLeleIndexList = [eleIndexList; PSLeleIndexList];
PSLprincipalStressList = [alphaList; PSLprincipalStressList];
iStreamline.midPointPosition = size(phyCoordList,1)+1;
%%2.3 finish Tracing the current major PSL
iStreamline.length = size(PSLphyCoordList,1);
iStreamline.eleIndexList = PSLeleIndexList;
iStreamline.phyCoordList = PSLphyCoordList;
iStreamline.alphaList = PSLprincipalStressList;
if 2==psDir(1)
iStreamline.type = 'ONE';
elseif 5==psDir(1)
iStreamline.type = 'TWO';
elseif 8==psDir(1)
iStreamline.type = 'THREE';
else
error('Wrong Input!');
end
end
function [eleIndex, phyCoord, layerPara, opt] = PreparingForTracing_elementWise(initialSeed)
global meshStruct_;
global nodeCoords_;
global topRankNparas_;
eleIndex = 0;
phyCoord = 0;
layerPara = 0;
if 3==size(initialSeed,2)
opt = 1;
formatedSeed = initialSeed;
eleIndex = formatedSeed(1,1);
elseif 2==size(initialSeed,2)
[eleIndex, paraCoordinates, opt] = FindAdjacentElement(initialSeed);
if opt
formatedSeed = [eleIndex paraCoordinates];
else
return;
end
else
error('Wrong Input!');
end
NIdx = meshStruct_.eNodMat(eleIndex,:)';
eleNodeCoords = nodeCoords_(NIdx,:);
paraCoord = formatedSeed(1, 2:3);
shapeFuncs = ShapeFunction(paraCoord(1), paraCoord(2));
phyCoord = shapeFuncs*eleNodeCoords;
layerPara = topRankNparas_(eleIndex,:);
end
function [phyCoordList, eleIndexList, alphaList] = TracingPSL_elementWise(nextPoint, iniDir, elementIndex, typePSL, limiSteps)
%% Tracing the PSL by 2-nd order Runge-Kutta Scheme
global tracingStepWidth_;
global topRankNparas_;
global followingLayerTabgent_;
phyCoordList = zeros(limiSteps,2);
eleIndexList = zeros(limiSteps,1);
alphaList = zeros(limiSteps,9);
index = 0;
dirDetectOpt = 1;
[elementIndex, ~, bool1] = FindAdjacentElement(nextPoint);
while 1==bool1
index = index + 1; if index > limiSteps, index = index-1; break; end
layerPara = topRankNparas_(elementIndex,:);
if followingLayerTabgent_
tmp = layerPara;
layerPara([2 5 8]) = -tmp([3 6 9]);
layerPara([3 6 9]) = tmp([2 5 8]);
end
if dirDetectOpt
nextDir = DirectionSelecting_elementWise(iniDir, layerPara(typePSL), -layerPara(typePSL));
else
dirList = [layerPara([2 3]); -layerPara([2 3]); layerPara([5 6]); -layerPara([5 6]); layerPara([8 9]); -layerPara([8 9])];
nextDir = DirectionSelecting_elementWise_new(iniDir, dirList);
end
if 0 == AngleTerminationCondition_elementWise(iniDir, nextDir), index = index-1; break; end
iniDir = nextDir;
phyCoordList(index,:) = nextPoint;
eleIndexList(index,:) = elementIndex;
alphaList(index,:) = layerPara;
nextPoint = nextPoint + tracingStepWidth_*iniDir;
[elementIndex, ~, bool1] = FindAdjacentElement(nextPoint);
end
phyCoordList = phyCoordList(1:index,:);
eleIndexList = eleIndexList(1:index,:);
alphaList = alphaList(1:index,:);
end
function val = AngleTerminationCondition_elementWise(dirct1, dirct2)
global interceptionThreshold_;
angle = acos((dirct1*dirct2') / (norm(dirct1)*norm(dirct2)));
if angle > pi/interceptionThreshold_
val = 0;
else
val = 1;
end
end
function targetDirection = DirectionSelecting_elementWise(originalVec, Vec1, Vec2)
angle1 = acos(originalVec*Vec1');
angle2 = acos(originalVec*Vec2');
if angle1 < angle2
targetDirection = Vec1;
else
targetDirection = Vec2;
end
end
function targetDirection = DirectionSelecting_elementWise_new(originalVec, dirList)
angList = acos(dirList*originalVec');
[~, minAngPos] = min(angList);
targetDirection = dirList(minAngPos,:);
end
function val = StreamlineStruct()
val = struct(...
'ith', 0, ...
'type', [], ...
'length', 0, ...
'midPointPosition', 0, ...
'phyCoordList', [], ...
'eleIndexList', [], ...
'alphaList', [] ...
);
end
function [nextElementIndex, paraCoordinates, opt] = FindAdjacentElement(physicalCoordinates)
global eleSize_;
global nodeCoords_;
global meshStruct_;
Lbound = meshStruct_.boundingBox(1,:);
nextElementIndex = 0; paraCoordinates = []; opt = 0;
physicalCoordinates = physicalCoordinates - Lbound;
if 0==physicalCoordinates(1)
eleX = 1;
else
eleX = ceil(physicalCoordinates(1)/eleSize_);
if eleX<1 || eleX>meshStruct_.resX, return; end
end
if 0==physicalCoordinates(2)
eleY = 1;
else
eleY = ceil(physicalCoordinates(2)/eleSize_);
if eleY<1 || eleY>meshStruct_.resY, return; end
end
tarEle = meshStruct_.resY*(eleX-1)+(meshStruct_.resY-eleY+1);
nextElementIndex = meshStruct_.eleMapForward(tarEle);
if nextElementIndex
opt = 1;
relatedNodes = meshStruct_.eNodMat(nextElementIndex,:);
relatedNodeCoords = nodeCoords_(relatedNodes',:)-Lbound;
paraCoordinates = 2*(physicalCoordinates - relatedNodeCoords(1,:)) / eleSize_ - 1;
end
end
function N = ShapeFunction(s, t)
% __s (parametric coordinate system)
% /-t
% *4 *3
% *1 *2
%
% nodes
s = s(:);
t = t(:);
N = zeros(size(s,1), 4);
N(:,1) = 0.25*(1-s).*(1-t);
N(:,2) = 0.25*(1+s).*(1-t);
N(:,3) = 0.25*(1+s).*(1+t);
N(:,4) = 0.25*(1-s).*(1+t);
end
function ShowStreamlines()
global meshStruct_;
global nodeCoords_;
global topRankNparas_;
global layer_1_StreamlinePool_;
global layer_2_StreamlinePool_;
global layer_3_StreamlinePool_;
lw = 2;
figure; axHandle_ = gca;
%%Show Density Layout
xPatchs = nodeCoords_(:,1); xPatchs = xPatchs(meshStruct_.eNodMat');
yPatchs = nodeCoords_(:,2); yPatchs = yPatchs(meshStruct_.eNodMat');
layerThickness = topRankNparas_(:, [1 4 7]);
cPatchs = 1 - prod(1-layerThickness,2);
[~,pos] = min(cPatchs); cPatchs(pos) = 0;
cPatchs = repmat(cPatchs, 1, 4)';
colormap(axHandle_, flip(gray));
hd = patch(axHandle_, xPatchs, yPatchs, cPatchs); hold(axHandle_, 'on');
%%Show Streamlines
for jj=1:length(layer_1_StreamlinePool_)
hold(axHandle_, 'on');
plot(axHandle_, layer_1_StreamlinePool_(jj).phyCoordList(:,1), layer_1_StreamlinePool_(jj).phyCoordList(:,2), ...
'-', 'color', [252 141 98]/255, 'LineWidth', lw);
end
for jj=1:length(layer_2_StreamlinePool_)
hold(axHandle_, 'on');
plot(axHandle_, layer_2_StreamlinePool_(jj).phyCoordList(:,1), layer_2_StreamlinePool_(jj).phyCoordList(:,2), ...
'-', 'color', [102 194 165]/255, 'LineWidth', lw);
end
for jj=1:length(layer_3_StreamlinePool_)
hold(axHandle_, 'on');
plot(axHandle_, layer_3_StreamlinePool_(jj).phyCoordList(:,1), layer_3_StreamlinePool_(jj).phyCoordList(:,2), ...
'-', 'color', [0 0 1]/1, 'LineWidth', lw); %%[141 160 203]/255
end
%%Show silhouette
if 0
edgeIndices = meshStruct_.eNodMat(:, [1 2 2 1 2 3 3 2 3 4 4 3 4 1 1 4])';
edgeIndices = reshape(edgeIndices(:), 4, 4*meshStruct_.numElements);
tmp = zeros(meshStruct_.numNodes,1);
tmp(meshStruct_.nodesOnBoundary) = 1;
tmp = tmp(edgeIndices);
tmp = sum(tmp,1);
boundaryEleEdges = edgeIndices(:,find(4==tmp));
domainSilhouette_.vertices = nodeCoords_;
domainSilhouette_.faces = boundaryEleEdges';
hold(axHandle_, 'on');
hdSilho = patch(axHandle_, domainSilhouette_);
set(hdSilho, 'FaceColor', 'None', 'EdgeColor', [0.5 0.5 0.5], 'LineWidth', 2);
end
set(hd, 'FaceColor', 'flat', 'FaceAlpha', 1, 'EdgeColor', 'None');
axis(axHandle_, 'equal'); axis(axHandle_, 'tight'); axis(axHandle_, 'off');
end
| MATLAB |
2D | PSLer/TopRank3 | supports/subsolv.m | .m | 6,465 | 221 | % This is the file subsolv.m
%
function [xmma,ymma,zmma,lamma,xsimma,etamma,mumma,zetmma,smma] = ...
subsolv(m,n,epsimin,low,upp,alfa,beta,p0,q0,P,Q,a0,a,b,c,d);
%
% Written in May 1999 by
% Krister Svanberg <krille@math.kth.se>
% Department of Mathematics
% SE-10044 Stockholm, Sweden.
%
% This function subsolv solves the MMA subproblem:
%
% minimize SUM[ p0j/(uppj-xj) + q0j/(xj-lowj) ] + a0*z +
% + SUM[ ci*yi + 0.5*di*(yi)^2 ],
%
% subject to SUM[ pij/(uppj-xj) + qij/(xj-lowj) ] - ai*z - yi <= bi,
% alfaj <= xj <= betaj, yi >= 0, z >= 0.
%
% Input: m, n, low, upp, alfa, beta, p0, q0, P, Q, a0, a, b, c, d.
% Output: xmma,ymma,zmma, slack variables and Lagrange multiplers.
%
een = ones(n,1);
eem = ones(m,1);
epsi = 1;
epsvecn = epsi*een;
epsvecm = epsi*eem;
x = 0.5*(alfa+beta);
y = eem;
z = 1;
lam = eem;
xsi = een./(x-alfa);
xsi = max(xsi,een);
eta = een./(beta-x);
eta = max(eta,een);
mu = max(eem,0.5*c);
zet = 1;
s = eem;
itera = 0;
while epsi > epsimin
epsvecn = epsi*een;
epsvecm = epsi*eem;
ux1 = upp-x;
xl1 = x-low;
ux2 = ux1.*ux1;
xl2 = xl1.*xl1;
uxinv1 = een./ux1;
xlinv1 = een./xl1;
plam = p0 + P'*lam ;
qlam = q0 + Q'*lam ;
gvec = P*uxinv1 + Q*xlinv1;
dpsidx = plam./ux2 - qlam./xl2 ;
rex = dpsidx - xsi + eta;
rey = c + d.*y - mu - lam;
rez = a0 - zet - a'*lam;
relam = gvec - a*z - y + s - b;
rexsi = xsi.*(x-alfa) - epsvecn;
reeta = eta.*(beta-x) - epsvecn;
remu = mu.*y - epsvecm;
rezet = zet*z - epsi;
res = lam.*s - epsvecm;
residu1 = [rex' rey' rez]';
residu2 = [relam' rexsi' reeta' remu' rezet res']';
residu = [residu1' residu2']';
residunorm = sqrt(residu'*residu);
residumax = max(abs(residu));
ittt = 0;
while residumax > 0.9*epsi & ittt < 100
ittt=ittt + 1;
itera=itera + 1;
if ittt == 100
disp('max inner iter reached')
end
ux1 = upp-x;
xl1 = x-low;
ux2 = ux1.*ux1;
xl2 = xl1.*xl1;
ux3 = ux1.*ux2;
xl3 = xl1.*xl2;
uxinv1 = een./ux1;
xlinv1 = een./xl1;
uxinv2 = een./ux2;
xlinv2 = een./xl2;
plam = p0 + P'*lam ;
qlam = q0 + Q'*lam ;
gvec = P*uxinv1 + Q*xlinv1;
GG = P*spdiags(uxinv2,0,n,n) - Q*spdiags(xlinv2,0,n,n);
dpsidx = plam./ux2 - qlam./xl2 ;
delx = dpsidx - epsvecn./(x-alfa) + epsvecn./(beta-x);
dely = c + d.*y - lam - epsvecm./y;
delz = a0 - a'*lam - epsi/z;
dellam = gvec - a*z - y - b + epsvecm./lam;
diagx = plam./ux3 + qlam./xl3;
diagx = 2*diagx + xsi./(x-alfa) + eta./(beta-x);
diagxinv = een./diagx;
diagy = d + mu./y;
diagyinv = eem./diagy;
diaglam = s./lam;
diaglamyi = diaglam+diagyinv;
if m < n
blam = dellam + dely./diagy - GG*(delx./diagx);
bb = [blam' delz]';
Alam = spdiags(diaglamyi,0,m,m) + GG*spdiags(diagxinv,0,n,n)*GG';
AA = [Alam a
a' -zet/z ];
solut = AA\bb;
dlam = solut(1:m);
dz = solut(m+1);
dx = -delx./diagx - (GG'*dlam)./diagx;
else
diaglamyiinv = eem./diaglamyi;
dellamyi = dellam + dely./diagy;
Axx = spdiags(diagx,0,n,n) + GG'*spdiags(diaglamyiinv,0,m,m)*GG;
azz = zet/z + a'*(a./diaglamyi);
axz = -GG'*(a./diaglamyi);
bx = delx + GG'*(dellamyi./diaglamyi);
bz = delz - a'*(dellamyi./diaglamyi);
AA = [Axx axz
axz' azz ];
bb = [-bx' -bz]';
solut = AA\bb;
dx = solut(1:n);
dz = solut(n+1);
dlam = (GG*dx)./diaglamyi - dz*(a./diaglamyi) + dellamyi./diaglamyi;
end
dy = -dely./diagy + dlam./diagy;
dxsi = -xsi + epsvecn./(x-alfa) - (xsi.*dx)./(x-alfa);
deta = -eta + epsvecn./(beta-x) + (eta.*dx)./(beta-x);
dmu = -mu + epsvecm./y - (mu.*dy)./y;
dzet = -zet + epsi/z - zet*dz/z;
ds = -s + epsvecm./lam - (s.*dlam)./lam;
xx = [ y' z lam' xsi' eta' mu' zet s']';
dxx = [dy' dz dlam' dxsi' deta' dmu' dzet ds']';
stepxx = -1.01*dxx./xx;
stmxx = max(stepxx);
stepalfa = -1.01*dx./(x-alfa);
stmalfa = max(stepalfa);
stepbeta = 1.01*dx./(beta-x);
stmbeta = max(stepbeta);
stmalbe = max(stmalfa,stmbeta);
stmalbexx = max(stmalbe,stmxx);
stminv = max(stmalbexx,1);
steg = 1/stminv;
xold = x;
yold = y;
zold = z;
lamold = lam;
xsiold = xsi;
etaold = eta;
muold = mu;
zetold = zet;
sold = s;
itto = 0;
resinew = 2*residunorm;
while resinew > residunorm & itto < 50
itto = itto+1;
x = xold + steg*dx;
y = yold + steg*dy;
z = zold + steg*dz;
lam = lamold + steg*dlam;
xsi = xsiold + steg*dxsi;
eta = etaold + steg*deta;
mu = muold + steg*dmu;
zet = zetold + steg*dzet;
s = sold + steg*ds;
ux1 = upp-x;
xl1 = x-low;
ux2 = ux1.*ux1;
xl2 = xl1.*xl1;
uxinv1 = een./ux1;
xlinv1 = een./xl1;
plam = p0 + P'*lam ;
qlam = q0 + Q'*lam ;
gvec = P*uxinv1 + Q*xlinv1;
dpsidx = plam./ux2 - qlam./xl2 ;
rex = dpsidx - xsi + eta;
rey = c + d.*y - mu - lam;
rez = a0 - zet - a'*lam;
relam = gvec - a*z - y + s - b;
rexsi = xsi.*(x-alfa) - epsvecn;
reeta = eta.*(beta-x) - epsvecn;
remu = mu.*y - epsvecm;
rezet = zet*z - epsi;
res = lam.*s - epsvecm;
residu1 = [rex' rey' rez]';
residu2 = [relam' rexsi' reeta' remu' rezet res']';
residu = [residu1' residu2']';
resinew = sqrt(residu'*residu);
steg = steg/2;
end
residunorm=resinew;
residumax = max(abs(residu));
steg = 2*steg;
end
epsi = 0.1*epsi;
end
xmma = x;
ymma = y;
zmma = z;
lamma = lam;
xsimma = xsi;
etamma = eta;
mumma = mu;
zetmma = zet;
smma = s;
| MATLAB |
2D | PSLer/TopRank3 | supports/SetBoundaryElementsBePassive.m | .m | 1,279 | 36 | function passiveEles = SetBoundaryElementsBePassive(meshInfo, numLayers)
%%numLayers -> 0: none passive elements
passiveEles = [];
if numLayers>0
index = 1;
while index<=numLayers
if 1==index
passiveEles = double(meshInfo.elementsOnBoundary);
else
passiveEles = RelateAdjacentElements(meshInfo, passiveEles);
end
index = index + 1;
end
end
end
function oEleList = RelateAdjacentElements(meshInfo, iEleList)
iEleListMapBack = meshInfo.eleMapBack(iEleList);
%% 1 4 7
%% 2 5* 8
%% 3 6 9
resX = meshInfo.resX;
resY = meshInfo.resY;
[eleX, eleY] = NodalizeDesignDomain([resX-1 resY-1], [1 1; resX resY]);
eleX = eleX(iEleListMapBack);
eleY = eleY(iEleListMapBack);
tmpX = [eleX-1 eleX-1 eleX-1 eleX eleX eleX eleX+1 eleX+1 eleX+1]; tmpX = tmpX(:);
tmpY = [eleY+1 eleY eleY-1 eleY+1 eleY eleY-1 eleY+1 eleY eleY-1]; tmpY = tmpY(:);
xNegative = find(tmpX<1); xPositive = find(tmpX>resX);
yNegative = find(tmpY<1); yPositive = find(tmpY>resY);
allInvalidEles = unique([xNegative; xPositive; yNegative; yPositive]);
tmpX(allInvalidEles) = []; tmpY(allInvalidEles) = [];
oEleListMapBack = resY*(tmpX-1) + resY-tmpY + 1;
oEleList = meshInfo.eleMapForward(oEleListMapBack);
oEleList(oEleList<1) = []; oEleList = unique(oEleList);
end | MATLAB |
2D | PSLer/TopRank3 | supports/mmasub.m | .m | 6,664 | 179 | % This is the file mmasub.m
%
function [xmma,ymma,zmma,lam,xsi,eta,mu,zet,s,low,upp,alfa,beta] = ...
mmasub(m,n,iter,xval,xmin,xmax,xold1,xold2, ...
f0val,df0dx,df0dx2,fval,dfdx,dfdx2,low,upp,a0,a,c,d);
%
% Written in May 1999 by
% Krister Svanberg <krille@math.kth.se>
% Department of Mathematics
% SE-10044 Stockholm, Sweden.
%
% Modified ("spdiags" instead of "diag") April 2002
%
%
% This function mmasub performs one MMA-iteration, aimed at
% solving the nonlinear programming problem:
%
% Minimize f_0(x) + a_0*z + sum( c_i*y_i + 0.5*d_i*(y_i)^2 )
% subject to f_i(x) - a_i*z - y_i <= 0, i = 1,...,m
% xmin_j <= x_j <= xmax_j, j = 1,...,n
% z >= 0, y_i >= 0, i = 1,...,m
%*** INPUT:
%
% m = The number of general constraints.
% n = The number of variables x_j.
% iter = Current iteration number ( =1 the first time mmasub is called).
% xval = Column vector with the current values of the variables x_j.
% xmin = Column vector with the lower bounds for the variables x_j.
% xmax = Column vector with the upper bounds for the variables x_j.
% xold1 = xval, one iteration ago (provided that iter>1).
% xold2 = xval, two iterations ago (provided that iter>2).
% f0val = The value of the objective function f_0 at xval.
% df0dx = Column vector with the derivatives of the objective function
% f_0 with respect to the variables x_j, calculated at xval.
% df0dx2 = Column vector with the non-mixed second derivatives of the
% objective function f_0 with respect to the variables x_j,
% calculated at xval. df0dx2(j) = the second derivative
% of f_0 with respect to x_j (twice).
% Important note: If second derivatives are not available,
% simply let df0dx2 = 0*df0dx.
% fval = Column vector with the values of the constraint functions f_i,
% calculated at xval.
% dfdx = (m x n)-matrix with the derivatives of the constraint functions
% f_i with respect to the variables x_j, calculated at xval.
% dfdx(i,j) = the derivative of f_i with respect to x_j.
% dfdx2 = (m x n)-matrix with the non-mixed second derivatives of the
% constraint functions f_i with respect to the variables x_j,
% calculated at xval. dfdx2(i,j) = the second derivative
% of f_i with respect to x_j (twice).
% Important note: If second derivatives are not available,
% simply let dfdx2 = 0*dfdx.
% low = Column vector with the lower asymptotes from the previous
% iteration (provided that iter>1).
% upp = Column vector with the upper asymptotes from the previous
% iteration (provided that iter>1).
% a0 = The constants a_0 in the term a_0*z.
% a = Column vector with the constants a_i in the terms a_i*z.
% c = Column vector with the constants c_i in the terms c_i*y_i.
% d = Column vector with the constants d_i in the terms 0.5*d_i*(y_i)^2.
%
%*** OUTPUT:
%
% xmma = Column vector with the optimal values of the variables x_j
% in the current MMA subproblem.
% ymma = Column vector with the optimal values of the variables y_i
% in the current MMA subproblem.
% zmma = Scalar with the optimal value of the variable z
% in the current MMA subproblem.
% lam = Lagrange multipliers for the m general MMA constraints.
% xsi = Lagrange multipliers for the n constraints alfa_j - x_j <= 0.
% eta = Lagrange multipliers for the n constraints x_j - beta_j <= 0.
% mu = Lagrange multipliers for the m constraints -y_i <= 0.
% zet = Lagrange multiplier for the single constraint -z <= 0.
% s = Slack variables for the m general MMA constraints.
% low = Column vector with the lower asymptotes, calculated and used
% in the current MMA subproblem.
% upp = Column vector with the upper asymptotes, calculated and used
% in the current MMA subproblem.
%
epsimin = sqrt(m+n)*10^(-9); % Eq. 5.9e - 5.9i
feps = 0.000001; % Eq. 3.3 - 3.4
asyinit = 0.5; % Eq. 3.11
asyincr = 1.07; % Eq. 3.13 (1.2)
asydecr = 0.65; % Eq. 3.13 (0.7)
albefa = 0.1; % Eq. 3.6 && 3.7
een = ones(n,1);
zeron = zeros(n,1);
% Calculation of the asymptotes low and upp :
if iter < 2.5
low = xval - asyinit*(xmax-xmin);
upp = xval + asyinit*(xmax-xmin);
else
zzz = (xval-xold1).*(xold1-xold2);
factor = een;
factor(find(zzz > 0)) = asyincr;
factor(find(zzz < 0)) = asydecr;
low = xval - factor.*(xold1 - low);
upp = xval + factor.*(upp - xold1);
lowmin = xval - 10*(xmax-xmin);
lowmax = xval - 0.01*(xmax-xmin);
uppmin = xval + 0.01*(xmax-xmin);
uppmax = xval + 10*(xmax-xmin);
low = max(low,lowmin);
low = min(low,lowmax);
upp = min(upp,uppmax);
upp = max(upp,uppmin);
end
% Calculation of the bounds alfa and beta :
zzz = low + albefa*(xval-low);
alfa = max(zzz,xmin);
zzz = upp - albefa*(upp-xval);
beta = min(zzz,xmax);
% Calculations of p0, q0, P, Q and b.
ux1 = upp-xval;
ux2 = ux1.*ux1;
ux3 = ux2.*ux1;
xl1 = xval-low;
xl2 = xl1.*xl1;
xl3 = xl2.*xl1;
ul1 = upp-low;
ulinv1 = een./ul1;
uxinv1 = een./ux1;
xlinv1 = een./xl1;
uxinv3 = een./ux3;
xlinv3 = een./xl3;
diap = (ux3.*xl1)./(2*ul1);
diaq = (ux1.*xl3)./(2*ul1);
p0 = zeron;
p0(find(df0dx > 0)) = df0dx(find(df0dx > 0));
p0 = p0 + 0.001*abs(df0dx) + feps*ulinv1;
p0 = p0.*ux2;
q0 = zeron;
q0(find(df0dx < 0)) = -df0dx(find(df0dx < 0));
q0 = q0 + 0.001*abs(df0dx) + feps*ulinv1;
q0 = q0.*xl2;
dg0dx2 = 2*(p0./ux3 + q0./xl3);
del0 = df0dx2 - dg0dx2;
delpos0 = zeron;
delpos0(find(del0 > 0)) = del0(find(del0 > 0));
p0 = p0 + delpos0.*diap;
q0 = q0 + delpos0.*diaq;
%%%%%%%%%%% the first section without coefficient of formulas 4.3 and 4.4
P = zeros(m,n);
P(find(dfdx > 0)) = dfdx(find(dfdx > 0));
%%%P = P * diag(ux2);
P = P * spdiags(ux2,0,n,n);
%%%%%%%%%%% the second section without coefficient of formulas 4.3 and 4.4
Q = zeros(m,n);
Q(find(dfdx < 0)) = -dfdx(find(dfdx < 0));
%%%Q = Q * diag(xl2);
Q = Q * spdiags(xl2,0,n,n);
%%%dgdx2 = 2*(P*diag(uxinv3) + Q*diag(xlinv3));
dgdx2 = P*spdiags(uxinv3,0,n,n)+Q*spdiags(xlinv3,0,n,n);
dgdx2 = 2*dgdx2;
sizedgdx2 = size(dgdx2);
sizedfdx2 = size(dfdx2);
del = dfdx2 - dgdx2;
delpos = zeros(m,n);
delpos(find(del > 0)) = del(find(del > 0));
%%%P = P + delpos*diag(diap);
P = P + delpos*spdiags(diap,0,n,n);
%%%Q = Q + delpos*diag(diaq);
Q = Q + delpos*spdiags(diaq,0,n,n);
b = P*uxinv1 + Q*xlinv1 - fval ; %% formula 4.2
%% Solving the subproblem by a primal-dual Newton method
[xmma,ymma,zmma,lam,xsi,eta,mu,zet,s] = ...
subsolv(m,n,epsimin,low,upp,alfa,beta,p0,q0,P,Q,a0,a,b,c,d);
| MATLAB |
2D | hpfem/hermes-examples | 2d-benchmarks-general/moving-front-space-adapt/definitions.h | .h | 2,110 | 75 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double x0, double x1, double y0, double y1,
double* t_ptr, double s, double c)
: ExactSolutionScalar<double>(mesh), x0(x0), x1(x1), y0(y0), y1(y1), t_ptr(t_ptr), s(s), c(c) {};
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
double x0, x1, y0, y1, *t_ptr, s, c;
};
/* Custom function f */
class CustomFunction: public Hermes2DFunction<double>
{
public:
CustomFunction(double x0, double x1, double y0, double y1,
double s, double c)
: Hermes2DFunction<double>(), x0(x0), x1(x1), y0(y0), y1(y1), s(s), c(c) {};
virtual double value(double x, double y, double t) const;
virtual Ord value(Ord x, Ord y) const;
double x0, x1, y0, y1, s, c, *t_ptr;
};
class CustomVectorFormVol : public VectorFormVol<double>
{
public:
CustomVectorFormVol(int i = 0, std::string area = HERMES_ANY,
Hermes::Hermes2DFunction<double>* coeff = nullptr,
GeomType gt = HERMES_PLANAR);
CustomVectorFormVol(int i, std::vector<std::string> areas,
Hermes::Hermes2DFunction<double>* coeff = nullptr,
GeomType gt = HERMES_PLANAR);
~CustomVectorFormVol();
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
virtual VectorFormVol<double>* clone() const;
private:
Hermes::Hermes2DFunction<double>* coeff;
GeomType gt;
};
class CustomWeakFormPoisson : public WeakFormsH1::DefaultWeakFormPoisson<double>
{
public:
CustomWeakFormPoisson(std::string area = HERMES_ANY,
Hermes1DFunction<double>* coeff = nullptr,
Hermes2DFunction<double>* f = nullptr,
GeomType gt = HERMES_PLANAR);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-general/moving-front-space-adapt/plot_graph.py | .py | 334 | 18 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.title("DOF history")
pylab.xlabel("Physical time (s)")
pylab.ylabel("Number of degrees of freedom")
data = numpy.loadtxt("dof_history.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="number of DOF")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-general/moving-front-space-adapt/plot_graphs.py | .py | 548 | 26 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.title("DOF history")
pylab.xlabel("Physical time")
pylab.ylabel("Number of degrees of freedom")
data = numpy.loadtxt("dof_history_hp.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="hp-FEM")
data = numpy.loadtxt("dof_history_h2.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="h-FEM (p=2)")
data = numpy.loadtxt("dof_history_h1.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="h-FEM (p=1)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-general/moving-front-space-adapt/main.cpp | .cpp | 9,423 | 246 | #include "definitions.h"
using namespace RefinementSelectors;
// This benchmark can be used to test adaptivity algorithms for transient
// PDE. It has an exact solution that exhibits a moving front of arbitrary
// steepness "s". Adaptivity is done in space only, i.e., the time step is
// not changed during computation. Arbitrary RK method can be used for time
// integration.
//
// PDE: time-dependent heat transfer equation, du/dt = Laplace u + f.
//
// Domain: square (0, 10) \times (-5, 5).
//
// BC: Zero Dirichlet.
//
// IC: Zero.
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Time step.
const double time_step = 0.1;
// Time interval length.
const double T_FINAL = 10.0;
// Adaptivity
// Every UNREF_FREQth time step the mesh is derefined.
const int UNREF_FREQ = 1;
// 1... mesh reset to basemesh and poly degrees to P_INIT.
// 2... one ref. layer shaved off, poly degrees reset to P_INIT.
// 3... one ref. layer shaved off, poly degrees decreased by one.
const int UNREF_METHOD = 3;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
// Newton's method
// Stopping criterion for Newton on fine mesh.
const double NEWTON_TOL = 1e-5;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 20;
// Choose one of the following time-integration methods, or define your own Butcher's table. The last number
// in the name of each method is its order. The one before last, if present, is the number of stages.
// Explicit methods:
// Explicit_RK_1, Explicit_RK_2, Explicit_RK_3, Explicit_RK_4.
// Implicit methods:
// Implicit_RK_1, Implicit_Crank_Nicolson_2_2, Implicit_SIRK_2_2, Implicit_ESIRK_2_2, Implicit_SDIRK_2_2,
// Implicit_Lobatto_IIIA_2_2, Implicit_Lobatto_IIIB_2_2, Implicit_Lobatto_IIIC_2_2, Implicit_Lobatto_IIIA_3_4,
// Implicit_Lobatto_IIIB_3_4, Implicit_Lobatto_IIIC_3_4, Implicit_Radau_IIA_3_5, Implicit_SDIRK_5_4.
// Embedded explicit methods:
// Explicit_HEUN_EULER_2_12_embedded, Explicit_BOGACKI_SHAMPINE_4_23_embedded, Explicit_FEHLBERG_6_45_embedded,
// Explicit_CASH_KARP_6_45_embedded, Explicit_DORMAND_PRINCE_7_45_embedded.
// Embedded implicit methods:
// Implicit_SDIRK_CASH_3_23_embedded, Implicit_ESDIRK_TRBDF2_3_23_embedded, Implicit_ESDIRK_TRX2_3_23_embedded,
// Implicit_SDIRK_BILLINGTON_3_23_embedded, Implicit_SDIRK_CASH_5_24_embedded, Implicit_SDIRK_CASH_5_34_embedded,
// Implicit_DIRK_ISMAIL_7_45_embedded.
ButcherTableType butcher_table_type = Implicit_RK_1;
// Problem parameters.
double x_0 = 0.0;
double x_1 = 10.0;
double y_0 = -5.0;
double y_1 = 5.0;
// Steepness of the moving front.
double s = 20.0;
double c = 1000.0;
// Current time.
double current_time = 0.0;
int main(int argc, char* argv[])
{
// Choose a Butcher's table or define your own.
ButcherTable bt(butcher_table_type);
if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size());
if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size());
// Load the mesh.
MeshSharedPtr mesh(new Mesh), basemesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", basemesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) basemesh->refine_all_elements(0, true);
mesh->copy(basemesh);
// Exact solution.
CustomExactSolution exact_sln(mesh, x_0, x_1, y_0, y_1, ¤t_time, s, c);
// Initialize boundary conditions.
DefaultEssentialBCConst<double> bc_essential("Bdy", 0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof_coarse = space->get_num_dofs();
// Initialize the weak formulation
CustomFunction f(x_0, x_1, y_0, y_1, s, c);
WeakFormSharedPtr<double> wf(new CustomWeakFormPoisson(HERMES_ANY, new Hermes::Hermes1DFunction<double>(-1.0), &f));
// Previous and next time level solution.
MeshFunctionSharedPtr<double> sln_time_prev(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> sln_time_new(new Solution<double>(mesh));
// Create a refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Visualize initial condition.
char title[100];
Views::ScalarView sview("Initial condition", new Views::WinGeom(0, 0, 440, 350));
Views::OrderView oview("Initial mesh", new Views::WinGeom(445, 0, 410, 350));
sview.show(sln_time_prev);
oview.show(space);
// Graph for dof history.
SimpleGraph dof_history_graph;
// Time stepping loop.
int ts = 1;
do
{
// Periodic global derefinement.
if (ts > 1 && ts % UNREF_FREQ == 0)
{
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
switch (UNREF_METHOD) {
case 1: mesh->copy(basemesh);
space->set_uniform_order(P_INIT);
break;
case 2: mesh->unrefine_all_elements();
space->set_uniform_order(P_INIT);
break;
case 3: mesh->unrefine_all_elements();
space->adjust_element_order(-1, -1, P_INIT, P_INIT);
break;
}
space->assign_dofs();
ndof_coarse = space->get_num_dofs();
}
// Spatial adaptivity loop. Note: sln_time_prev must not be changed
// during spatial adaptivity.
bool done = false; int as = 1;
double err_est;
do {
Hermes::Mixins::Loggable::Static::info("Time step %d, adaptivity step %d:", ts, as);
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
// Initialize Runge-Kutta time stepping.
RungeKutta<double> runge_kutta(wf, ref_space, &bt);
// Perform one Runge-Kutta time step according to the selected Butcher's table.
Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).",
current_time, time_step, bt.get_size());
bool freeze_jacobian = true;
bool block_diagonal_jacobian = true;
bool verbose = true;
try
{
runge_kutta.set_time(current_time);
runge_kutta.set_time_step(time_step);
runge_kutta.rk_time_step_newton(sln_time_prev, sln_time_new);
}
catch (Exceptions::Exception& e)
{
e.print_msg();
}
// Project the fine mesh solution onto the coarse mesh.
MeshFunctionSharedPtr<double> sln_coarse(new Solution<double>);
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh for error estimation.");
OGProjection<double> ogProjection;
ogProjection.project_global(space, sln_time_new, sln_coarse);
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
adaptivity.set_space(space);
errorCalculator.calculate_errors(sln_coarse, sln_time_new);
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_ref: %d, err_est_rel: %g%%",
space->get_num_dofs(), ref_space->get_num_dofs(), err_est_rel_total);
// If err_est too large, adapt the mesh.
if (err_est_rel_total < ERR_STOP) done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
done = adaptivity.adapt(&selector);
as++;
}
} while (done == false);
// Visualize the solution and mesh.
char title[100];
sprintf(title, "Solution, time %g", current_time);
sview.set_title(title);
sview.show_mesh(false);
sview.show(sln_time_new);
sprintf(title, "Mesh, time %g", current_time);
oview.set_title(title);
oview.show(space);
// Copy last reference solution into sln_time_prev->
sln_time_prev->copy(sln_time_new);
// Add entry to DOF convergence graph.
dof_history_graph.add_values(current_time, space->get_num_dofs());
dof_history_graph.save("dof_history.dat");
// Increase current time and counter of time steps.
current_time += time_step;
ts++;
} while (current_time < T_FINAL);
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/moving-front-space-adapt/definitions.cpp | .cpp | 5,928 | 148 | #include "definitions.h"
double CustomExactSolution::value(double x, double y) const
{
double S = s;
double C = c;
double t = *t_ptr;
return ((x - x0)*(x - x1)*(y - y0)*(y - y1)*Hermes::atan(t)*(M_PI / 2. - Hermes::atan(S*(-t + Hermes::sqrt(x*x + y*y))))) / C;
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double S = s;
double C = c;
double t = *t_ptr;
dx = ((y - y0)*(y - y1)*Hermes::atan(t)*(M_PI*(2 * x - x0 - x1) + (2 * S*x*(x - x0)*(x - x1)) /
(Hermes::sqrt(x*x + y*y)*(-1 + 2 * S*S*t*Hermes::sqrt(x*x + y*y) - S*S*(t*t + x*x + y*y))) +
(4 * x - 2 * (x0 + x1))*Hermes::atan(S*(t - Hermes::sqrt(x*x + y*y))))) / (2.*C);
dy = ((x - x0)*(x - x1)*Hermes::atan(t)*((2 * S*y*(y - y0)*(y - y1)) / (Hermes::sqrt(x*x + y*y)*(-1 + 2 * S*S*t*Hermes::sqrt(x*x + y*y) - S*S*(t*t + x*x + y*y))) +
M_PI*(2 * y - y0 - y1) + (4 * y - 2 * (y0 + y1))*Hermes::atan(S*(t - Hermes::sqrt(x*x + y*y))))) / (2.*C);
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(20);
}
double CustomFunction::value(double x, double y, double t) const
{
double S = s;
double C = c;
// Generated by Mathematica.
double f = (2 * S*x*(((x - x0)*(y - y0)) / C + ((x - x1)*(y - y0)) / C)*(y - y1)*Hermes::atan(t)) / (Hermes::sqrt(x*x + y*y)*(1
+ S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2))) +
(S*(x - x0)*(x - x1)*(y - y0)*(y - y1)*Hermes::atan(t)) / (C*(1 + S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2))) -
((x - x0)*(x - x1)*((2 * Hermes::pow(S, 3)*x*x*(-t + Hermes::sqrt(x*x + y*y))) / ((x*x + y*y)*Hermes::pow(1 + S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2), 2)) +
(S*x*x) / (Hermes::pow(x*x + y*y, 1.5)*(1 + S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2))) -
S / (Hermes::sqrt(x*x + y*y)*(1 + S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2))))*(y - y0)*(y - y1)*Hermes::atan(t)) / C -
((x - x0)*(x - x1)*(y - y0)*((-2 * S*y*Hermes::atan(t)) / (Hermes::sqrt(x*x + y*y)*(1 + S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2))) +
((2 * Hermes::pow(S, 3)*y*y*(-t + Hermes::sqrt(x*x + y*y))) / ((x*x + y*y)*Hermes::pow(1 + S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2), 2)) +
(S*y*y) / (Hermes::pow(x*x + y*y, 1.5)*(1 + S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2))) -
S / (Hermes::sqrt(x*x + y*y)*(1 + S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2))))*(y - y1)*Hermes::atan(t))) / C -
(2 * (x - x0)*(x - x1)*(-((S*y*(y - y1)*Hermes::atan(t)) / (Hermes::sqrt(x*x + y*y)*(1 + S*S*Hermes::pow(-t + Hermes::sqrt(x*x + y*y), 2)))) +
Hermes::atan(t)*(M_PI / 2. - Hermes::atan(S*(-t + Hermes::sqrt(x*x + y*y)))))) / C +
((x - x0)*(x - x1)*(y - y0)*(y - y1)*(M_PI / 2. - Hermes::atan(S*(-t + Hermes::sqrt(x*x + y*y))))) / (C*(1 + t*t)) -
(2 * (y - y0)*(y - y1)*Hermes::atan(t)*(M_PI / 2. - Hermes::atan(S*(-t + Hermes::sqrt(x*x + y*y))))) / C;
return f;
}
Ord CustomFunction::value(Ord x, Ord y) const
{
return Ord(20);
}
CustomVectorFormVol::CustomVectorFormVol(int i, std::string area,
Hermes::Hermes2DFunction<double>* coeff,
GeomType gt)
: VectorFormVol<double>(i), coeff(coeff), gt(gt)
{
this->set_area(area);
// If coeff is nullptr, initialize it to be constant 1.0.
if (coeff == nullptr) this->coeff = new Hermes::Hermes2DFunction<double>(1.0);
}
CustomVectorFormVol::CustomVectorFormVol(int i, std::vector<std::string> areas,
Hermes::Hermes2DFunction<double>* coeff,
GeomType gt)
: VectorFormVol<double>(i), coeff(coeff), gt(gt)
{
this->set_areas(areas);
// If coeff is nullptr, initialize it to be constant 1.0.
if (coeff == nullptr) this->coeff = new Hermes::Hermes2DFunction<double>(1.0);
}
CustomVectorFormVol::~CustomVectorFormVol()
{
// FIXME: Should be deleted here only if it was created here.
//if (coeff != nullptr) delete coeff;
};
double CustomVectorFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0;
if (gt == HERMES_PLANAR) {
for (int i = 0; i < n; i++) {
result += wt[i] * static_cast<CustomFunction*>(coeff)->value(e->x[i], e->y[i], this->get_current_stage_time()) * v->val[i];
}
}
else {
if (gt == HERMES_AXISYM_X) {
for (int i = 0; i < n; i++) {
result += wt[i] * e->y[i] * static_cast<CustomFunction*>(coeff)->value(e->x[i], e->y[i], this->get_current_stage_time()) * v->val[i];
}
}
else {
for (int i = 0; i < n; i++) {
result += wt[i] * e->x[i] * static_cast<CustomFunction*>(coeff)->value(e->x[i], e->y[i], this->get_current_stage_time()) * v->val[i];
}
}
}
return result;
}
Ord CustomVectorFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (gt == HERMES_PLANAR) {
for (int i = 0; i < n; i++) {
result += wt[i] * coeff->value(e->x[i], e->y[i]) * v->val[i];
}
}
else {
if (gt == HERMES_AXISYM_X) {
for (int i = 0; i < n; i++) {
result += wt[i] * e->y[i] * coeff->value(e->x[i], e->y[i]) * v->val[i];
}
}
else {
for (int i = 0; i < n; i++) {
result += wt[i] * e->x[i] * coeff->value(e->x[i], e->y[i]) * v->val[i];
}
}
}
return result;
}
VectorFormVol<double>* CustomVectorFormVol::clone() const
{
return new CustomVectorFormVol(*this);
}
CustomWeakFormPoisson::CustomWeakFormPoisson(std::string area,
Hermes1DFunction<double>* coeff, Hermes2DFunction<double>* f,
GeomType gt) : WeakFormsH1::DefaultWeakFormPoisson<double>()
{
// Jacobian.
// NOTE: The flag HERMES_NONSYM is important here.
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0, area, coeff, HERMES_NONSYM, gt));
// Residual.
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(0, area, coeff, gt));
add_vector_form(new CustomVectorFormVol(0, area, f, gt));
}; | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-iso/definitions.h | .h | 846 | 38 | #include "hermes2d.h"
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh) : ExactSolutionScalar<double>(mesh)
{
}
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual double value(double x, double y) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh); }
};
/* Custom function f */
class CustomFunction: public Hermes::Hermes2DFunction<double>
{
public:
CustomFunction() : Hermes::Hermes2DFunction<double>()
{
}
virtual double value(double x, double y) const;
virtual Ord value(Ord x, Ord y) const;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-iso/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-iso/main.cpp | .cpp | 6,720 | 189 | #include "definitions.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::RefinementSelectors;
using namespace Hermes::Hermes2D::Views;
// This example shows that it makes sense to use anisotropic polynomial
// degrees in quadrilateral elements. The exact solution to this Poisson
// problem is u(x,y) = sin(x), defined in the square (0, pi)x(0, pi).
//
// PDE: -Laplace u - f = 0.
//
// Known exact solution, see class CustomExactSolution in definitions.cpp.
//
// Domain: square domain (0, pi) x (0, pi), mesh file square_quad.mesh->
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
int P_INIT = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-4;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square_quad.mesh", mesh);
// Avoid zero ndof situation.
if (P_INIT == 1) {
if (is_hp(CAND_LIST)) P_INIT++;
else mesh->refine_element_id(0, 0);
}
// Define exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh));
// Initialize the weak formulation.
Hermes1DFunction<double> lambda(1.0);
CustomFunction f;
WeakFormSharedPtr<double> wf(new DefaultWeakFormPoisson<double>(HERMES_ANY, &lambda, &f));
// Initialize boundary conditions.
DefaultEssentialBCConst<double> bc_essential("Bdy", 0.0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Set it to adaptivity.
adaptivity.set_space(space);
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.set_linearizer_criterion(LinearizerCriterionFixed(2));
sview.show_mesh(false);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 400, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
Adapt<double> adaptivity(space, &errorCalculator, &stoppingCriterion);
errorCalculator.calculate_errors(sln, exact_sln, false);
double err_exact_rel = errorCalculator.get_total_error_squared() * 100;
errorCalculator.calculate_errors(sln, ref_sln);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-iso/definitions.cpp | .cpp | 574 | 27 | #include "definitions.h"
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
dx = Hermes::cos(x)*Hermes::sin(y);
dy = Hermes::sin(x)*Hermes::cos(y);
}
double CustomExactSolution::value(double x, double y) const
{
return Hermes::sin(x)*Hermes::sin(y);
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(7);
}
double CustomFunction::value(double x, double y) const
{
return -2 * Hermes::sin(x)*Hermes::sin(y);
}
Ord CustomFunction::value(Ord x, Ord y) const
{
return Ord(7);
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/layer-interior/definitions.h | .h | 977 | 42 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double slope)
: ExactSolutionScalar<double>(mesh), slope(slope) {};
virtual double value (double x, double y) const;
virtual void derivatives (double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, slope); }
double slope;
};
/* Custom function f */
class CustomFunction: public Hermes::Hermes2DFunction<double>
{
public:
CustomFunction(double slope)
: Hermes::Hermes2DFunction<double>(), slope(slope) {};
virtual double value(double x, double y) const;
virtual Ord value(Ord x, Ord y) const;
double slope;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-general/layer-interior/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-general/layer-interior/main.cpp | .cpp | 7,090 | 203 | #include "definitions.h"
using namespace RefinementSelectors;
using namespace Views;
// This is another example that allows you to compare h- and hp-adaptivity from the point of view
// of both CPU time requirements and discrete problem size, look at the quality of the a-posteriori
// error estimator used by Hermes (exact error is provided), etc. You can also change
// the parameter MESH_REGULARITY to see the influence of hanging nodes on the adaptive process.
// The problem is made harder for adaptive algorithms by increasing the parameter SLOPE.
//
// PDE: -Laplace u + f = 0
//
// Known exact solution.
//
// Domain: unit square (0, 1) x (0, 1), see the file square.mesh->
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.6;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-5;
// Problem parameters.
// Slope of the layer.
double slope = 60;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
// Quadrilaterals.
mloader.load("square_quad.mesh", mesh);
// Triangles.
// mloader.load("square_tri.mesh", mesh);
MeshView m;
m.show(mesh);
m.save_screenshot("initialmesh.bmp", true);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Define exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, slope));
// Define custom function f.
CustomFunction f(slope);
// Initialize the weak formulation.
Hermes::Hermes1DFunction<double> lambda(1.0);
WeakFormSharedPtr<double> wf(new DefaultWeakFormPoisson<double>(HERMES_ANY, &lambda, &f));
// Initialize boundary conditions
DefaultEssentialBCNonConst<double> bc_essential("Bdy", exact_sln);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
ScalarView s;
// Adaptivity loop:
int as = 1; bool done = false;
try
{
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
newton.solve();
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
adaptivity.set_space(space);
errorCalculator.calculate_errors(sln, exact_sln, false);
double err_exact_rel = errorCalculator.get_total_error_squared() * 100;
errorCalculator.calculate_errors(sln, ref_sln, true);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(ref_sln);
sview.save_numbered_screenshot("solution%i.bmp", as, true);
oview.show(ref_space);
oview.set_b_orders(true);
oview.save_numbered_screenshot("space%i.bmp", as, true);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/layer-interior/definitions.cpp | .cpp | 1,315 | 37 | #include "definitions.h"
double CustomExactSolution::value(double x, double y) const
{
return Hermes::atan(slope * (Hermes::sqrt(Hermes::sqr(x - 1.25) + Hermes::sqr(y + 0.25)) - M_PI / 3));
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double t = Hermes::sqrt(Hermes::sqr(x - 1.25) + Hermes::sqr(y + 0.25));
double u = t * (Hermes::sqr(slope) * Hermes::sqr(t - M_PI / 3) + 1);
dx = slope * (x - 1.25) / u;
dy = slope * (y + 0.25) / u;
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(20);
}
double CustomFunction::value(double x, double y) const
{
double t2 = Hermes::sqr(y + 0.25) + Hermes::sqr(x - 1.25);
double t = Hermes::sqrt(t2);
double u = (Hermes::sqr(M_PI - 3.0*t) * Hermes::sqr(slope) + 9.0);
return (27.0 / 2.0 * Hermes::sqr(2.0*y + 0.5) * (M_PI - 3.0*t) * Hermes::pow(slope, 3.0) / (Hermes::sqr(u) * t2)
+ 27.0 / 2.0 * Hermes::sqr(2.0*x - 2.5) * (M_PI - 3.0*t) * Hermes::pow(slope, 3.0) / (Hermes::sqr(u) * t2)
- 9.0 / 4.0 * Hermes::sqr(2.0*y + 0.5) * slope / (u * Hermes::pow(t, 3.0))
- 9.0 / 4.0 * Hermes::sqr(2.0*x - 2.5) * slope / (u * Hermes::pow(t, 3.0)) + 18.0 * slope / (u * t)
);
}
Ord CustomFunction::value(Ord x, Ord y) const
{
return Ord(20);
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-aniso-x/definitions.h | .h | 1,019 | 47 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh) : ExactSolutionScalar<double>(mesh)
{
}
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual double value(double x, double y) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh); }
};
/* Custom function f */
class CustomFunction: public Hermes::Hermes2DFunction<double>
{
public:
CustomFunction() : Hermes::Hermes2DFunction<double>()
{
}
virtual double value(double x, double y) const;
virtual Ord value(Ord x, Ord y) const;
};
/* Weak forms */
class CustomWeakFormPoisson : public WeakForm<double>
{
public:
CustomWeakFormPoisson(std::string bdy_marker_right);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-aniso-x/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-aniso-x/main.cpp | .cpp | 6,293 | 174 | #include "definitions.h"
using namespace RefinementSelectors;
// This example shows that it makes sense to use anisotropic polynomial
// degrees in quadrilateral elements. The exact solution to this Poisson
// problem is u(x,y) = sin(x), defined in the square (0, pi)x(0, pi).
//
// PDE: -Laplace u - f = 0.
//
// Known exact solution, see functions fn() and fndd().
//
// Domain: square domain (0, pi) x (0, pi), mesh file square_quad.mesh->
//
// BC: Dirichlet and Neumann, given by exact solution.
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
int P_INIT = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
// Define exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh));
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormPoisson("Right"));
// Initialize boundary conditions.
DefaultEssentialBCConst<double> bc_essential("Left", 0.0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Set it to adaptivity.
adaptivity.set_space(space);
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 400, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
errorCalculator.calculate_errors(sln, exact_sln, false);
double err_exact_rel_total = errorCalculator.get_total_error_squared() * 100;
errorCalculator.calculate_errors(sln, ref_sln, true);
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel_total, err_exact_rel_total);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel_total);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel_total);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel_total);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel_total);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel_total < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-aniso-x/definitions.cpp | .cpp | 975 | 38 | #include "definitions.h"
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
dx = Hermes::cos(x);
dy = 0;
}
double CustomExactSolution::value(double x, double y) const
{
return Hermes::sin(x);
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(7);
}
double CustomFunction::value(double x, double y) const
{
return -Hermes::sin(x);
}
Ord CustomFunction::value(Ord x, Ord y) const
{
return Ord(7);
}
CustomWeakFormPoisson::CustomWeakFormPoisson(std::string bdy_marker_right) : WeakForm<double>(1)
{
// Jacobian.
add_matrix_form(new DefaultJacobianDiffusion<double>(0, 0));
// Residual.
add_vector_form(new DefaultResidualDiffusion<double>(0));
add_vector_form(new DefaultVectorFormVol<double>(0, HERMES_ANY, new CustomFunction));
add_vector_form_surf(new DefaultVectorFormSurf<double>(0, bdy_marker_right, new Hermes::Hermes2DFunction<double>(1.0)));
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-aniso-y/definitions.h | .h | 1,015 | 46 | #include "hermes2d.h"
using namespace Hermes::Hermes2D;
using namespace Hermes;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh) : ExactSolutionScalar<double>(mesh)
{
}
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual double value(double x, double y) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh); }
};
/* Custom function f */
class CustomFunction: public Hermes::Hermes2DFunction<double>
{
public:
CustomFunction() : Hermes::Hermes2DFunction<double>()
{
}
virtual double value(double x, double y) const;
virtual Ord value(Ord x, Ord y) const;
};
/* Weak forms */
class CustomWeakFormPoisson : public WeakForm<double>
{
public:
CustomWeakFormPoisson(std::string bdy_marker_top);
}; | Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-aniso-y/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-aniso-y/main.cpp | .cpp | 6,207 | 174 | #include "definitions.h"
using namespace RefinementSelectors;
// This example shows that it makes sense to use anisotropic polynomial
// degrees in quadrilateral elements. The exact solution to this Poisson
// problem is u(x,y) = sin(y), defined in the square (0, pi)x(0, pi).
//
// PDE: -Laplace u = f.
//
// Known exact solution, see functions fn() and fndd().
//
// Domain: square domain (0, pi) x (0, pi), mesh file square_quad.mesh->
//
// BC: Dirichlet and Neumann, given by exact solution.
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
int P_INIT = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
// Define exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh));
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormPoisson("Top"));
// Initialize boundary conditions.
DefaultEssentialBCConst<double> bc_essential("Bottom", 0.0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Set it to adaptivity.
adaptivity.set_space(space);
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 400, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate exact error.
errorCalculator.calculate_errors(sln, exact_sln, false);
double err_exact_rel = errorCalculator.get_total_error_squared() * 100;
errorCalculator.calculate_errors(sln, ref_sln, true);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/smooth-aniso-y/definitions.cpp | .cpp | 971 | 38 | #include "definitions.h"
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
dx = 0;
dy = Hermes::cos(y);
}
double CustomExactSolution::value(double x, double y) const
{
return Hermes::sin(y);
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(7);
}
double CustomFunction::value(double x, double y) const
{
return -Hermes::sin(y);
}
Ord CustomFunction::value(Ord x, Ord y) const
{
return Ord(7);
}
CustomWeakFormPoisson::CustomWeakFormPoisson(std::string bdy_marker_top) : WeakForm<double>(1)
{
// Jacobian.
add_matrix_form(new DefaultJacobianDiffusion<double>(0, 0));
// Residual.
add_vector_form(new DefaultResidualDiffusion<double>(0));
add_vector_form(new DefaultVectorFormVol<double>(0, HERMES_ANY, new CustomFunction));
add_vector_form_surf(new DefaultVectorFormSurf<double>(0, bdy_marker_top, new Hermes::Hermes2DFunction<double>(1.0)));
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/nonsym-check/definitions.h | .h | 1,643 | 63 | #include "hermes2d.h"
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh) : ExactSolutionScalar<double>(mesh)
{
}
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual double value(double x, double y) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const;
};
/* Weak forms */
class CustomJacobian : public MatrixFormVol<double>
{
public:
CustomJacobian(int i, int j) : MatrixFormVol<double>(i, j)
{
}
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
};
class CustomResidual : public VectorFormVol<double>
{
public:
CustomResidual(int i) : VectorFormVol<double>(i)
{
}
virtual double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
VectorFormVol<double>* clone() const;
};
class CustomWeakForm : public WeakForm<double>
{
public:
CustomWeakForm(std::string marker_bdy_right);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-general/nonsym-check/main.cpp | .cpp | 6,282 | 176 | #include "definitions.h"
using namespace RefinementSelectors;
//
// This example uses a nonsymmetric equation and its purpose is to
// check that nonsymmetric problems are solved correctly.
//
// PDE: -Laplace u + du/dx - (sin(x) + cos(x)) = 0.
//
// Known exact solution u(x,y) = sin(x).
//
// Domain: square domain (0, pi) x (0, pi), mesh file square_quad.mesh->
//
// BC: Zero Dirichlet on left edge, zero Neumann on top and bottom edges,
// nonzero Neumann on the right edge (all matching exact solution).
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
int P_INIT = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
// Define exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh));
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm("Right"));
// Initialize boundary conditions.
DefaultEssentialBCConst<double> bc_essential("Left", 0.0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Set the space to adaptivity.
adaptivity.set_space(space);
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
errorCalculator.calculate_errors(sln, exact_sln, false);
double err_exact_rel = errorCalculator.get_total_error_squared() * 100;
errorCalculator.calculate_errors(sln, ref_sln, true);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/nonsym-check/definitions.cpp | .cpp | 2,007 | 74 | #include "definitions.h"
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
dx = Hermes::cos(x);
dy = 0;
}
double CustomExactSolution::value(double x, double y) const
{
return sin(x);
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(20);
}
MeshFunction<double>* CustomExactSolution::clone() const
{
return new CustomExactSolution(this->mesh);
}
double CustomJacobian::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * u->dx[i] * v->val[i];
return result;
}
Ord CustomJacobian::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return Ord(20);
}
MatrixFormVol<double>* CustomJacobian::clone() const
{
return new CustomJacobian(*this);
}
double CustomResidual::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * (u_ext[0]->dx[i] - Hermes::sin(e->x[i]) - Hermes::cos(e->x[i])) * v->val[i];
return result;
}
Ord CustomResidual::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return Ord(20);
}
VectorFormVol<double>* CustomResidual::clone() const
{
return new CustomResidual(*this);
}
CustomWeakForm::CustomWeakForm(std::string marker_bdy_right) : WeakForm<double>(1)
{
// Jacobian.
add_matrix_form(new DefaultJacobianDiffusion<double>(0, 0));
add_matrix_form(new CustomJacobian(0, 0));
// Residual.
add_vector_form(new DefaultResidualDiffusion<double>(0));
add_vector_form(new CustomResidual(0));
add_vector_form_surf(new DefaultVectorFormSurf<double>(0, marker_bdy_right, new Hermes::Hermes2DFunction<double>(1.0)));
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/lshape/definitions.h | .h | 573 | 24 | #include "hermes2d.h"
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh) : ExactSolutionScalar<double>(mesh)
{
}
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh); }
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-general/lshape/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-general/lshape/plot_graph_comparison.py | .py | 1,358 | 56 | # This is a utility that produces comparison plots
# of DOF and CPU convergence. To use it, your directory
# must contain Hermes convergence files
# conv_dof_exact_h1.dat, conv_dof_exact_h2.dat
# and conv_dof_exact_hp.dat
# import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact_h1.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="h-FEM (p=1)")
data = numpy.loadtxt("conv_dof_exact_h2.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="h-FEM (p=2)")
data = numpy.loadtxt("conv_dof_exact_hp.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="hp-FEM")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact_h1.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="h-FEM (p=1)")
data = numpy.loadtxt("conv_cpu_exact_h2.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="h-FEM (p=2)")
data = numpy.loadtxt("conv_cpu_exact_hp.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="hp-FEM")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-general/lshape/main.cpp | .cpp | 6,681 | 183 | #include "definitions.h"
using namespace RefinementSelectors;
// This is a standard benchmark for adaptive FEM algorithms. The exact solution is a harmonic
// function in an L-shaped domain and it contains singular gradient at the re-entrant corner.
//
// PDE: -Laplace u = 0.
//
// Known exact solution, see functions fn() and fndd().
//
// Domain: L-shape domain. Classical version is in the file "lshape-standard.mesh", version
// with a circular edge in "lshape-round.mesh". Choose the one you like to use
// and copy it into "domain.mesh". This is the mesh file that is loaded into Hermes.
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-4;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("lshape.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
//mesh->refine_towards_vertex(3, 5);
// Define exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh));
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new DefaultWeakFormLaplace<double>);
// Initialize boundary conditions
DefaultEssentialBCNonConst<double> bc_essential("Bdy", exact_sln);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Set the space to adaptivity.
adaptivity.set_space(space);
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 410, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate exact error.
errorCalculator.calculate_errors(sln, exact_sln, false);
double err_exact_rel = errorCalculator.get_total_error_squared() * 100;
// Calculate element errors and total error estimate.
errorCalculator.calculate_errors(sln, ref_sln, true);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/lshape/definitions.cpp | .cpp | 720 | 22 | #include "definitions.h"
double CustomExactSolution::value(double x, double y) const
{
double r = Hermes::sqrt(x*x + y*y);
double a = Hermes::atan2(x, y);
return Hermes::pow(r, 2.0 / 3.0) * Hermes::sin(2.0*a / 3.0 + M_PI / 3);
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double t1 = 2.0 / 3.0*Hermes::atan2(x, y) + M_PI / 3;
double t2 = Hermes::pow(x*x + y*y, 1.0 / 3.0);
double t3 = x*x * ((y*y) / (x*x) + 1);
dx = 2.0 / 3.0*x*Hermes::sin(t1) / (t2*t2) + 2.0 / 3.0*y*t2*Hermes::cos(t1) / t3;
dy = 2.0 / 3.0*y*Hermes::sin(t1) / (t2*t2) - 2.0 / 3.0*x*t2*Hermes::cos(t1) / t3;
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(20);
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/layer-boundary/definitions.h | .h | 1,216 | 68 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Exact solution */
class CustomExactFunction
{
public:
CustomExactFunction(double K) : K(K) {};
double uhat(double x);
double duhat_dx(double x);
double dduhat_dxx(double x);
protected:
double K;
};
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double K);
virtual double value (double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
~CustomExactSolution();
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, K); }
CustomExactFunction* cef;
double K;
};
/* Custom function */
class CustomFunction: public Hermes::Hermes2DFunction<double>
{
public:
CustomFunction(double coeff1);
virtual double value(double x, double y) const;
virtual Ord value(Ord x, Ord y) const;
~CustomFunction();
CustomExactFunction* cef;
double coeff1;
};
/* Weak forms */
class CustomWeakForm : public WeakForm<double>
{
public:
CustomWeakForm(CustomFunction* f);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-general/layer-boundary/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-general/layer-boundary/main.cpp | .cpp | 6,693 | 187 | #include "definitions.h"
using namespace RefinementSelectors;
// This singularly perturbed problem exhibits a thin boundary layer. The
// exact solution facilitates convergence studies.
//
// PDE: -Laplace u + K*K*u - K*K + g(x,y) = 0.
//
// Domain: Square (-1,1)^2.
//
// BC: Homogeneous Dirichlet.
//
// Exact solution: v(x,y) = U(x)U(y) where U(t) = 1 - (exp(K*x) + exp(-K*x))/(exp(K) + exp(-K)) is
// the exact solution to the 1D singularly perturbed problem -u'' + K*K*u = K*K* in (-1,1)
// equipped with zero Dirichlet BC.
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
const int P_INIT = 1;
// Number of initial mesh refinements (the original mesh is just one element).
const int INIT_REF_NUM = 0;
// Number of initial mesh refinements towards the boundary.
const int INIT_REF_NUM_BDY = 5;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.5;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-5;
// Problem parameters.
const double K = 1e2;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary("Bdy", INIT_REF_NUM_BDY);
// Define exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, K));
// Define right side vector.
CustomFunction f(K);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(&f));
// Initialize boundary conditions.
DefaultEssentialBCConst<double> bc_essential("Bdy", 0.0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 400, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
adaptivity.set_space(space);
// Calculate exact error.
errorCalculator.calculate_errors(sln, exact_sln, false);
double err_exact_rel = errorCalculator.get_total_error_squared() * 100;
errorCalculator.calculate_errors(sln, ref_sln, true);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
done = (err_est_rel < ERR_STOP ? true : adaptivity.adapt(&selector));
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-general/layer-boundary/definitions.cpp | .cpp | 2,111 | 76 | #include "definitions.h"
double CustomExactFunction::uhat(double x)
{
return 1. - (exp(K*x) + exp(-K*x)) / (exp(K) + exp(-K));
}
double CustomExactFunction::duhat_dx(double x)
{
return -K * (exp(K*x) - exp(-K*x)) / (exp(K) + exp(-K));
}
double CustomExactFunction::dduhat_dxx(double x)
{
return -K*K * (exp(K*x) + exp(-K*x)) / (exp(K) + exp(-K));
}
CustomExactSolution::CustomExactSolution(MeshSharedPtr mesh, double K) : ExactSolutionScalar<double>(mesh), K(K)
{
cef = new CustomExactFunction(K);
}
CustomExactSolution::~CustomExactSolution()
{
delete cef;
}
double CustomExactSolution::value(double x, double y) const
{
return cef->uhat(x) * cef->uhat(y);
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
dx = cef->duhat_dx(x) * cef->uhat(y);
dy = cef->uhat(x) * cef->duhat_dx(y);
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(20);
}
CustomFunction::CustomFunction(double coeff1) : Hermes::Hermes2DFunction<double>(), coeff1(coeff1)
{
cef = new CustomExactFunction(coeff1);
}
CustomFunction::~CustomFunction()
{
delete cef;
}
double CustomFunction::value(double x, double y) const
{
return -(-(cef->dduhat_dxx(x) * cef->uhat(y) + cef->uhat(x) * cef->dduhat_dxx(y))
+ coeff1 * coeff1 * cef->uhat(x) * cef->uhat(y));
}
Ord CustomFunction::value(Ord x, Ord y) const
{
return Ord(5);
}
CustomWeakForm::CustomWeakForm(CustomFunction* f) : WeakForm<double>(1)
{
// Jacobian.
add_matrix_form(new Hermes::Hermes2D::WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0));
add_matrix_form(new Hermes::Hermes2D::WeakFormsH1::DefaultMatrixFormVol<double>(0, 0, HERMES_ANY,
new Hermes::Hermes2DFunction<double>(f->coeff1*f->coeff1)));
// Residual.
add_vector_form(new Hermes::Hermes2D::WeakFormsH1::DefaultResidualDiffusion<double>(0));
add_vector_form(new Hermes::Hermes2D::WeakFormsH1::DefaultResidualVol<double>(0, HERMES_ANY,
new Hermes::Hermes2DFunction<double>(f->coeff1*f->coeff1)));
add_vector_form(new Hermes::Hermes2D::WeakFormsH1::DefaultVectorFormVol<double>(0, HERMES_ANY, f));
} | C++ |
2D | hpfem/hermes-examples | 1d/system/definitions.h | .h | 3,522 | 151 | #include "hermes2d.h"
using namespace Hermes::Hermes2D;
/* Custom function that is used in the exact solution and in right-hand side */
class CustomExactFunction1
{
public:
CustomExactFunction1() {};
double val(double x);
double dx(double x);
double ddxx(double x);
};
class CustomExactFunction2
{
public:
CustomExactFunction2(double K) : K(K) {};
double val(double x);
double dx(double x);
double ddxx(double x);
double K;
};
/* Right-hand side */
class CustomRightHandSide1: public Hermes::Hermes2DFunction<double>
{
public:
CustomRightHandSide1(double K, double d_u, double sigma);
virtual double value(double x, double y) const;
virtual Hermes::Ord ord (Hermes::Ord x, Hermes::Ord y) const;
~CustomRightHandSide1();
CustomExactFunction1* cef1;
CustomExactFunction2* cef2;
double d_u, sigma;
};
class CustomRightHandSide2: public Hermes::Hermes2DFunction<double>
{
public:
CustomRightHandSide2(double K, double d_v);
virtual double value(double x, double y) const;
virtual Hermes::Ord ord (Hermes::Ord x, Hermes::Ord y) const;
~CustomRightHandSide2();
CustomExactFunction1* cef1;
CustomExactFunction2* cef2;
double d_v;
};
/* Exact solution */
class ExactSolutionFitzHughNagumo1 : public ExactSolutionScalar<double>
{
public:
ExactSolutionFitzHughNagumo1(MeshSharedPtr mesh);
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Hermes::Ord ord (double x, double y) const;
~ExactSolutionFitzHughNagumo1();
CustomExactFunction1* cef1;
virtual MeshFunction<double>* clone() const;
};
class ExactSolutionFitzHughNagumo2 : public ExactSolutionScalar<double>
{
public:
ExactSolutionFitzHughNagumo2(MeshSharedPtr mesh, double K);
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Hermes::Ord ord (double x, double y) const;
~ExactSolutionFitzHughNagumo2();
CustomExactFunction2* cef2;
virtual MeshFunction<double>* clone() const;
double K;
};
/* Weak forms */
class CustomResidual1 : public VectorFormVol<double>
{
public:
CustomResidual1(double d_u, double sigma, CustomRightHandSide1* g1)
: VectorFormVol<double>(0), d_u(d_u), sigma(sigma), g1(g1) {};
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const;
virtual Hermes::Ord ord(int n, double *wt, Func<Hermes::Ord> *u_ext[], Func<Hermes::Ord> *v,
GeomVol<Hermes::Ord> *e, Func<Hermes::Ord>* *ext) const;
virtual VectorFormVol<double>* clone() const;
private:
double d_u;
double sigma;
CustomRightHandSide1* g1;
};
class CustomResidual2 : public VectorFormVol<double>
{
public:
CustomResidual2(double d_v, CustomRightHandSide2* g2)
: VectorFormVol<double>(1), d_v(d_v), g2(g2) {};
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const;
virtual Hermes::Ord ord(int n, double *wt, Func<Hermes::Ord> *u_ext[], Func<Hermes::Ord> *v,
GeomVol<Hermes::Ord> *e, Func<Hermes::Ord>* *ext) const;
virtual VectorFormVol<double>* clone() const;
private:
double d_v;
CustomRightHandSide2* g2;
};
class CustomWeakForm : public WeakForm<double>
{
public:
CustomWeakForm(CustomRightHandSide1* g1, CustomRightHandSide2* g2);
};
| Unknown |
2D | hpfem/hermes-examples | 1d/system/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 1d/system/main.cpp | .cpp | 10,848 | 276 | #include "definitions.h"
using namespace RefinementSelectors;
// This example is an analogy to the 2D tutorial example P04-adapt/03-system.
// It explains how to use the multimesh adaptive hp-FEM for 1D problems whose
// solution components behave very differently, so that using the same mesh
// for both is a waste of DOFs.
//
// PDE: Linearized FitzHugh-Nagumo equation
// -d_u^2 u'' - f(u) + \sigma v - g1 = 0,
// -d_v^2 v'' - u + v - g2 = 0.
// In the original equation, f(u) = \lambda u - u^3 - \kappa. For
// simplicity, here we just take f(u) = u.
//
// Domain: Interval (-1, 1).
//
// BC: Both solution components are zero on the boundary.
//
// Exact solution: The functions g1 and g2 were calculated so that
// the exact solution is:
// U(x) = cos(M_PI*x/2)
// V(x) = 1 - (exp(K*x) + exp(-K*x)) / (exp(K) + exp(-K))
// Note: V(x) is the exact solution of the 1D singularly perturbed equation
// -u'' + K*K*u = K*K in (-1, 1) with zero Dirichlet BC.
//
// The following parameters can be changed: In particular, compare hp- and
// h-adaptivity via the CAND_LIST option, and compare the multi-mesh vs.
// single-mesh using the MULTI parameter.
// Should exact solution be used and exact error calculated?
#define WITH_EXACT_SOLUTION
// Initial polynomial degree for u.
const int P_INIT_U = 1;
// Initial polynomial degree for v.
const int P_INIT_V = 1;
// Number of initial boundary refinements
const int INIT_REF_BDY = 5;
// MULTI = true ... use multi-mesh,
// MULTI = false ... use single-mesh->
// Note: In the single mesh option, the meshes are
// forced to be geometrically the same but the
// polynomial degrees can still vary.
const bool MULTI = true;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
// Problem parameters.
const double D_u = 1;
const double D_v = 1;
const double SIGMA = 1;
const double LAMBDA = 1;
const double KAPPA = 1;
const double K = 100.;
int main(int argc, char* argv[])
{
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Load the mesh.
MeshSharedPtr u_mesh(new Mesh), v_mesh(new Mesh);
MeshReaderH1DXML mloader;
mloader.load("domain.xml", u_mesh);
u_mesh->refine_all_elements();
if (MULTI == false)
{
u_mesh->refine_towards_boundary("Left", INIT_REF_BDY);
// Minus one for the sake of mesh symmetry.
if (INIT_REF_BDY > 1) u_mesh->refine_towards_boundary("Right", INIT_REF_BDY - 1);
}
// Create initial mesh (master mesh).
v_mesh->copy(u_mesh);
// Initial mesh refinements in the v_mesh towards the boundary.
if (MULTI == true)
{
v_mesh->refine_towards_boundary("Left", INIT_REF_BDY);
// Minus one for the sake of mesh symmetry.
if (INIT_REF_BDY > 1) v_mesh->refine_towards_boundary("Right", INIT_REF_BDY - 1);
}
#ifdef WITH_EXACT_SOLUTION
// Set exact solutions.
MeshFunctionSharedPtr<double> exact_u(new ExactSolutionFitzHughNagumo1(u_mesh));
MeshFunctionSharedPtr<double> exact_v(new ExactSolutionFitzHughNagumo2(v_mesh, K));
#endif
// Define right-hand sides.
CustomRightHandSide1 g1(K, D_u, SIGMA);
CustomRightHandSide2 g2(K, D_v);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(&g1, &g2));
// Initialize boundary conditions
DefaultEssentialBCConst<double> bc_u(std::vector<std::string>({ "Left", "Right" }), 0.0);
EssentialBCs<double> bcs_u(&bc_u);
DefaultEssentialBCConst<double> bc_v(std::vector<std::string>({ "Left", "Right" }), 0.0);
EssentialBCs<double> bcs_v(&bc_v);
// Create H1 spaces with default shapeset for both displacement components.
SpaceSharedPtr<double> u_space(new H1Space<double>(u_mesh, &bcs_u, P_INIT_U));
SpaceSharedPtr<double> v_space(new H1Space<double>(MULTI ? v_mesh : u_mesh, &bcs_v, P_INIT_V));
// Initialize coarse and reference mesh solutions.
MeshFunctionSharedPtr<double> u_sln(new Solution<double>), v_sln(new Solution<double>), u_ref_sln(new Solution<double>), v_ref_sln(new Solution<double>);
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
Views::ScalarView s_view_0("Solution[0]", new Views::WinGeom(0, 0, 440, 350));
s_view_0.show_mesh(false);
Views::OrderView o_view_0("Mesh[0]", new Views::WinGeom(450, 0, 420, 350));
Views::ScalarView s_view_1("Solution[1]", new Views::WinGeom(880, 0, 440, 350));
s_view_1.show_mesh(false);
Views::OrderView o_view_1("Mesh[1]", new Views::WinGeom(1330, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est;
#ifdef WITH_EXACT_SOLUTION
SimpleGraph graph_dof_exact, graph_cpu_exact;
#endif
// Adaptivity loop:
int as = 1;
bool done = false;
do
{
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);
// Construct globally refined reference mesh and setup reference space.
// FIXME: This should be increase in the x-direction only.
int order_increase = 1;
// FIXME: This should be '2' but that leads to a segfault.
int refinement_type = 0;
Mesh::ReferenceMeshCreator refMeshCreator1(u_mesh);
MeshSharedPtr ref_u_mesh = refMeshCreator1.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator1(u_space, ref_u_mesh);
SpaceSharedPtr<double> ref_u_space = refSpaceCreator1.create_ref_space();
Mesh::ReferenceMeshCreator refMeshCreator2(v_mesh);
MeshSharedPtr ref_v_mesh = refMeshCreator2.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator2(v_space, ref_v_mesh);
SpaceSharedPtr<double> ref_v_space = refSpaceCreator2.create_ref_space();
std::vector<SpaceSharedPtr<double> > ref_spaces({ ref_u_space, ref_v_space });
int ndof_ref = Space<double>::get_num_dofs(ref_spaces);
// Initialize reference problem.
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
DiscreteProblem<double> dp(wf, ref_spaces);
NewtonSolver<double> newton(&dp);
newton.set_verbose_output(true);
// Time measurement.
cpu_time.tick();
// Perform Newton's iteration.
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the Solution<double> sln->
Solution<double>::vector_to_solutions(newton.get_sln_vector(), ref_spaces,
std::vector<MeshFunctionSharedPtr<double> >({ u_ref_sln, v_ref_sln }));
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting reference solutions on coarse meshes.");
OGProjection<double>::project_global({ u_space, v_space },
std::vector<MeshFunctionSharedPtr<double> >({ u_ref_sln, v_ref_sln }),
std::vector<MeshFunctionSharedPtr<double> >({ u_sln, v_sln }));
cpu_time.tick();
// View the coarse mesh solution and polynomial orders.
s_view_0.show(u_ref_sln);
o_view_0.show(u_space);
s_view_1.show(v_ref_sln);
o_view_1.show(v_space);
// Calculate element errors.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
adaptivity.set_spaces({ u_space, v_space });
#ifdef WITH_EXACT_SOLUTION
errorCalculator.calculate_errors({ u_sln, v_sln }, { exact_u, exact_v }, false);
double err_exact_rel_total = errorCalculator.get_total_error_squared() * 100;
#endif
errorCalculator.calculate_errors({ u_sln, v_sln }, { u_ref_sln, v_ref_sln }, true);
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
// Time measurement.
cpu_time.tick();
// Report results.
#ifdef WITH_EXACT_SOLUTION
Hermes::Mixins::Loggable::Static::info("ndof_coarse[0]: %d, ndof_fine[0]: %d",
u_space->get_num_dofs(), ref_u_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("ndof_coarse[1]: %d, ndof_fine[1]: %d",
v_space->get_num_dofs(), ref_v_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("ndof_coarse_total: %d, ndof_fine_total: %d",
Space<double>::get_num_dofs({ u_space, v_space }),
Space<double>::get_num_dofs(ref_spaces));
Hermes::Mixins::Loggable::Static::info("err_est_rel_total: %g%%, err_est_exact_total: %g%%", err_est_rel_total, err_exact_rel_total);
#else
Hermes::Mixins::Loggable::Static::info("ndof_coarse[0]: %d, ndof_fine[0]: %d", u_space->get_num_dofs(), u_ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel[0]: %g%%", err_est_rel[0] * 100);
Hermes::Mixins::Loggable::Static::info("ndof_coarse[1]: %d, ndof_fine[1]: %d", v_space->get_num_dofs(), v_ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel[1]: %g%%", err_est_rel[1] * 100);
Hermes::Mixins::Loggable::Static::info("ndof_coarse_total: %d, ndof_fine_total: %d",
Space<double>::get_num_dofs({ u_space, v_space }),
Space<double>::get_num_dofs(*ref_spaces));
Hermes::Mixins::Loggable::Static::info("err_est_rel_total: %g%%", err_est_rel_total);
#endif
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(Space<double>::get_num_dofs({ u_space, v_space }),
err_est_rel_total);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(cpu_time.accumulated(), err_est_rel_total);
graph_cpu_est.save("conv_cpu_est.dat");
#ifdef WITH_EXACT_SOLUTION
graph_dof_exact.add_values(Space<double>::get_num_dofs({ u_space, v_space }),
err_exact_rel_total);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(cpu_time.accumulated(), err_exact_rel_total);
graph_cpu_exact.save("conv_cpu_exact.dat");
#endif
// If err_est too large, adapt the mesh.
if (err_est_rel_total < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
done = adaptivity.adapt({ &selector, &selector });
}
// Increase counter.
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 1d/system/generate_equation_data.py | .py | 1,375 | 68 | from sympy import (var, exp, pprint, Eq, Symbol, Function, cos, pi, simplify,
ccode, latex)
var("x y")
d_u = Symbol("D_u")
d_v = Symbol("D_v")
sigma = Symbol("SIGMA")
lam = Symbol("LAMBDA")
kappa = Symbol("KAPPA")
k = Symbol("K")
def eq1(u, v, f):
return -d_u*d_u*(u.diff(x, 2) + u.diff(y, 2)) - f(u) + sigma*v
def eq2(u, v):
return -d_v*d_v*(v.diff(x, 2) + v.diff(y, 2)) - u + v
u = Function("u")
v = Function("v")
print "Reaction-Diffusion Equations:"
def f(u):
return lam*u-u**3-kappa
pprint(eq1(u(x, y), v(x, y), f))
pprint(eq2(u(x, y), v(x, y)))
print "\nSolution:"
u_hat = 1 - (exp(k*x)+exp(-k*x)) / (exp(k)+exp(-k))
pprint(Eq(Function("u_hat")(x), u_hat))
#test the Boundary Conditions:
assert u_hat.subs(x, -1) == 0
assert u_hat.subs(x, 1) == 0
u = cos(x*pi/2)*cos(y*pi/2)
v = u_hat*u_hat.subs(x, y)
print "u:"
pprint(u)
print "u:", ccode(u)
print "d u/d x:", ccode(u.diff(x))
print "d u/d y:", ccode(u.diff(y))
print "v:"
pprint(v)
print "v:", ccode(v)
print "d v/d x:", ccode(v.diff(x))
print "d v/d y:", ccode(v.diff(y))
print "-"*80
print "RHS, for f(u)=u:"
# delete this redefinition to get nonlinear f(u):
def f(u):
return u
e1 = eq1(u, v, f)
e2 = eq2(u, v)
print "g1:"
pprint(e1)
print "g2:"
pprint(e2)
print
print "latex:"
print latex(e1)
print latex(e2)
print
print "C code:"
print "g1 =", ccode(e1)
print "g2 =", ccode(e2)
| Python |
2D | hpfem/hermes-examples | 1d/system/definitions.cpp | .cpp | 6,267 | 236 | #include "definitions.h"
double CustomExactFunction1::val(double x)
{
return cos(M_PI*x / 2);
}
double CustomExactFunction1::dx(double x)
{
return -sin(M_PI*x / 2)*(M_PI / 2.);
}
double CustomExactFunction1::ddxx(double x)
{
return -cos(M_PI*x / 2)*(M_PI / 2.)*(M_PI / 2.);
}
double CustomExactFunction2::val(double x)
{
return 1. - (exp(K*x) + exp(-K*x)) / (exp(K) + exp(-K));
}
double CustomExactFunction2::dx(double x)
{
return -K*(exp(K*x) - exp(-K*x)) / (exp(K) + exp(-K));
}
double CustomExactFunction2::ddxx(double x)
{
return -K*K*(exp(K*x) + exp(-K*x)) / (exp(K) + exp(-K));
}
CustomRightHandSide1::CustomRightHandSide1(double K, double d_u, double sigma)
: Hermes::Hermes2DFunction<double>(), d_u(d_u), sigma(sigma)
{
cef1 = new CustomExactFunction1();
cef2 = new CustomExactFunction2(K);
}
double CustomRightHandSide1::value(double x, double y) const
{
double Laplace_u = cef1->ddxx(x);
double u = cef1->val(x);
double v = cef2->val(x);
return -d_u * d_u * Laplace_u - u + sigma * v;
}
Hermes::Ord CustomRightHandSide1::ord(Hermes::Ord x, Hermes::Ord y) const
{
return Hermes::Ord(10);
}
CustomRightHandSide1::~CustomRightHandSide1()
{
delete cef1;
delete cef2;
}
CustomRightHandSide2::CustomRightHandSide2(double K, double d_v)
: Hermes::Hermes2DFunction<double>(), d_v(d_v)
{
cef1 = new CustomExactFunction1();
cef2 = new CustomExactFunction2(K);
}
double CustomRightHandSide2::value(double x, double y) const
{
double Laplace_v = cef2->ddxx(x);
double u = cef1->val(x);
double v = cef2->val(x);
return -d_v*d_v * Laplace_v - u + v;
}
Hermes::Ord CustomRightHandSide2::ord(Hermes::Ord x, Hermes::Ord y) const
{
return Hermes::Ord(10);
}
CustomRightHandSide2::~CustomRightHandSide2()
{
delete cef1;
delete cef2;
}
ExactSolutionFitzHughNagumo1::ExactSolutionFitzHughNagumo1(MeshSharedPtr mesh)
: ExactSolutionScalar<double>(mesh)
{
cef1 = new CustomExactFunction1();
}
double ExactSolutionFitzHughNagumo1::value(double x, double y) const
{
return cef1->val(x);
}
void ExactSolutionFitzHughNagumo1::derivatives(double x, double y, double& dx, double& dy) const
{
dx = cef1->dx(x);
dy = 0;
}
Hermes::Ord ExactSolutionFitzHughNagumo1::ord(double x, double y) const
{
return Hermes::Ord(10);
}
ExactSolutionFitzHughNagumo1::~ExactSolutionFitzHughNagumo1()
{
delete cef1;
}
MeshFunction<double>* ExactSolutionFitzHughNagumo1::clone() const
{
return new ExactSolutionFitzHughNagumo1(this->mesh);
}
ExactSolutionFitzHughNagumo2::ExactSolutionFitzHughNagumo2(MeshSharedPtr mesh, double K)
: ExactSolutionScalar<double>(mesh), K(K)
{
cef2 = new CustomExactFunction2(K);
}
double ExactSolutionFitzHughNagumo2::value(double x, double y) const
{
return cef2->val(x);
}
void ExactSolutionFitzHughNagumo2::derivatives(double x, double y, double& dx, double& dy) const
{
dx = cef2->dx(x);
dy = 0;
}
Hermes::Ord ExactSolutionFitzHughNagumo2::ord(double x, double y) const
{
return Hermes::Ord(10);
}
ExactSolutionFitzHughNagumo2::~ExactSolutionFitzHughNagumo2()
{
delete cef2;
}
MeshFunction<double>* ExactSolutionFitzHughNagumo2::clone() const
{
return new ExactSolutionFitzHughNagumo2(this->mesh, K);
}
double CustomResidual1::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (d_u*d_u * u_ext[0]->dx[i] * v->dx[i]
- u_ext[0]->val[i] * v->val[i]
+ sigma*u_ext[1]->val[i] * v->val[i]
- g1->value(e->x[i], 0)*v->val[i]
);
}
return result;
}
Hermes::Ord CustomResidual1::ord(int n, double *wt, Func<Hermes::Ord> *u_ext[], Func<Hermes::Ord> *v,
GeomVol<Hermes::Ord> *e, Func<Hermes::Ord>* *ext) const
{
Hermes::Ord result = Hermes::Ord(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (d_u*d_u * u_ext[0]->dx[i] * v->dx[i]
- u_ext[0]->val[i] * v->val[i]
+ sigma*u_ext[1]->val[i] * v->val[i]
- g1->ord(e->x[i], Hermes::Ord(0))*v->val[i]
);
}
return result;
}
VectorFormVol<double>* CustomResidual1::clone() const
{
return new CustomResidual1(*this);
}
double CustomResidual2::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (d_v*d_v * u_ext[1]->dx[i] * v->dx[i]
- u_ext[0]->val[i] * v->val[i]
+ u_ext[1]->val[i] * v->val[i]
- g2->value(e->x[i], 0)*v->val[i]
);
}
return result;
}
Hermes::Ord CustomResidual2::ord(int n, double *wt, Func<Hermes::Ord> *u_ext[], Func<Hermes::Ord> *v,
GeomVol<Hermes::Ord> *e, Func<Hermes::Ord>* *ext) const
{
Hermes::Ord result = Hermes::Ord(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (d_v*d_v * u_ext[1]->dx[i] * v->dx[i]
- u_ext[0]->val[i] * v->val[i]
+ u_ext[1]->val[i] * v->val[i]
- g2->ord(e->x[i], Hermes::Ord(0))*v->val[i]
);
}
return result;
}
VectorFormVol<double>* CustomResidual2::clone() const
{
return new CustomResidual2(*this);
}
CustomWeakForm::CustomWeakForm(CustomRightHandSide1* g1, CustomRightHandSide2* g2) : WeakForm<double>(2)
{
// Jacobian.
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0, Hermes::HERMES_ANY, new Hermes::Hermes1DFunction<double>(g1->d_u * g1->d_u)));
add_matrix_form(new WeakFormsH1::DefaultMatrixFormVol<double>(0, 0, Hermes::HERMES_ANY, new Hermes::Hermes2DFunction<double>(-1.0)));
add_matrix_form(new WeakFormsH1::DefaultMatrixFormVol<double>(0, 1, Hermes::HERMES_ANY, new Hermes::Hermes2DFunction<double>(g1->sigma), HERMES_NONSYM));
add_matrix_form(new WeakFormsH1::DefaultMatrixFormVol<double>(1, 0, Hermes::HERMES_ANY, new Hermes::Hermes2DFunction<double>(-1.0), HERMES_NONSYM));
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(1, 1, Hermes::HERMES_ANY, new Hermes::Hermes1DFunction<double>(g2->d_v * g2->d_v)));
add_matrix_form(new WeakFormsH1::DefaultMatrixFormVol<double>(1, 1, Hermes::HERMES_ANY, new Hermes::Hermes2DFunction<double>(1.0)));
// Residual.
add_vector_form(new CustomResidual1(g1->d_u, g1->sigma, g1));
add_vector_form(new CustomResidual2(g2->d_v, g2));
} | C++ |
2D | hpfem/hermes-examples | 1d/poisson/definitions.h | .h | 432 | 15 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
/* Weak forms */
class CustomWeakFormPoisson : public Hermes::Hermes2D::WeakForm<double>
{
public:
CustomWeakFormPoisson(std::string mat_al, Hermes::Hermes1DFunction<double>* lambda_al,
std::string mat_cu, Hermes::Hermes1DFunction<double>* lambda_cu,
Hermes::Hermes2DFunction<double>* src_term);
};
| Unknown |
2D | hpfem/hermes-examples | 1d/poisson/main.cpp | .cpp | 3,640 | 109 | #include "definitions.h"
using namespace Hermes::Hermes2D;
// This example is analogous to P01-linear/03-poisson.
//
// PDE: Poisson equation -(LAMBDA u')' - VOLUME_HEAT_SRC = 0.
//
// Boundary conditions: Dirichlet u(x) = FIXED_BDY_TEMP on the boundary.
//
// Geometry: Interval (0, 2*pi).
//
// The following parameters can be changed:
// Set to "false" to suppress Hermes OpenGL visualization.
const bool HERMES_VISUALIZATION = true;
// Set to "true" to enable VTK output.
const bool VTK_VISUALIZATION = false;
// Uniform polynomial degree of mesh elements.
const int P_INIT = 5;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 3;
// Problem parameters.
// Thermal cond. of Al for temperatures around 20 deg Celsius.
const double LAMBDA_AL = 236.0;
// Thermal cond. of Cu for temperatures around 20 deg Celsius.
const double LAMBDA_CU = 386.0;
// Volume heat sources generated (for example) by electric current.
const double VOLUME_HEAT_SRC = 5e3;
// Fixed temperature on the boundary.
const double FIXED_BDY_TEMP = 20.0;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH1DXML mloader;
mloader.load("domain.xml", mesh);
// Perform initial mesh refinements (optional).
// Split elements vertically.
int refinement_type = 2;
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements(refinement_type);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormPoisson("Al", new Hermes::Hermes1DFunction<double>(LAMBDA_AL), "Cu",
new Hermes::Hermes1DFunction<double>(LAMBDA_CU),
new Hermes::Hermes2DFunction<double>(-VOLUME_HEAT_SRC)));
// Initialize essential boundary conditions.
DefaultEssentialBCConst<double> bc_essential(std::vector<std::string>({ "Left", "Right" }),
FIXED_BDY_TEMP);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof = space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);
// Show the mesh and poly degrees.
Views::OrderView oview("Mesh", new Views::WinGeom(0, 0, 900, 250));
if (HERMES_VISUALIZATION) oview.show(space);
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, space);
// Perform Newton's iteration and translate the resulting coefficient vector into a Solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
NewtonSolver<double> newton(&dp);
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
Solution<double>::vector_to_solution(newton.get_sln_vector(), space, sln);
// Get info about time spent during assembling in its respective parts.
//dp.get_all_profiling_output(std::cout);
// VTK output.
if (VTK_VISUALIZATION)
{
// Output solution in VTK format.
Views::Linearizer lin(FileExport);
bool mode_3D = true;
lin.save_solution_vtk(sln, "sln.vtk", "Temperature", mode_3D);
Hermes::Mixins::Loggable::Static::info("Solution in VTK format saved to file %s.", "sln.vtk");
// Output mesh and element orders in VTK format.
Views::Orderizer ord;
ord.save_orders_vtk(space, "ord.vtk");
Hermes::Mixins::Loggable::Static::info("Element orders in VTK format saved to file %s.", "ord.vtk");
}
// Visualize the solution.
if (HERMES_VISUALIZATION)
{
Views::ScalarView view("Solution", new Views::WinGeom(0, 300, 900, 350));
view.show(sln);
Views::View::wait();
}
return 0;
} | C++ |
2D | hpfem/hermes-examples | 1d/poisson/definitions.cpp | .cpp | 909 | 17 | #include "definitions.h"
/* Weak forms */
CustomWeakFormPoisson::CustomWeakFormPoisson(std::string mat_al, Hermes::Hermes1DFunction<double>* lambda_al,
std::string mat_cu, Hermes::Hermes1DFunction<double>* lambda_cu,
Hermes::Hermes2DFunction<double>* src_term) : Hermes::Hermes2D::WeakForm<double>(1)
{
// Jacobian forms.
add_matrix_form(new Hermes::Hermes2D::WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0, mat_al, lambda_al));
add_matrix_form(new Hermes::Hermes2D::WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0, mat_cu, lambda_cu));
// Residual forms.
add_vector_form(new Hermes::Hermes2D::WeakFormsH1::DefaultResidualDiffusion<double>(0, mat_al, lambda_al));
add_vector_form(new Hermes::Hermes2D::WeakFormsH1::DefaultResidualDiffusion<double>(0, mat_cu, lambda_cu));
add_vector_form(new Hermes::Hermes2D::WeakFormsH1::DefaultVectorFormVol<double>(0, HERMES_ANY, src_term));
}; | C++ |
2D | hpfem/hermes-examples | 1d/moving-front/definitions.h | .h | 2,139 | 76 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double x0, double x1, double y0, double y1,
double* t_ptr, double s, double c)
: ExactSolutionScalar<double>(mesh), x0(x0), x1(x1), y0(y0), y1(y1), t_ptr(t_ptr), s(s), c(c) {};
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
double x0, x1, y0, y1, *t_ptr, s, c;
};
/* Custom function f */
class CustomFunction: public Hermes::Hermes2DFunction<double>
{
public:
CustomFunction(double x0, double x1, double y0, double y1,
double s, double c)
: Hermes::Hermes2DFunction<double>(), x0(x0), x1(x1), y0(y0), y1(y1), s(s), c(c) {};
virtual double value(double x, double y, double t) const;
virtual Ord value(Ord x, Ord y) const;
double x0, x1, y0, y1, s, c, *t_ptr;
};
class CustomVectorFormVol : public VectorFormVol<double>
{
public:
CustomVectorFormVol(int i = 0,
Hermes::Hermes2DFunction<double>* coeff = nullptr, std::string area = HERMES_ANY,
GeomType gt = HERMES_PLANAR);
CustomVectorFormVol(int i,
Hermes::Hermes2DFunction<double>* coeff, std::vector<std::string> areas,
GeomType gt = HERMES_PLANAR);
~CustomVectorFormVol();
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
virtual VectorFormVol<double>* clone() const;
private:
Hermes::Hermes2DFunction<double>* coeff;
GeomType gt;
};
class CustomWeakFormPoisson : public WeakFormsH1::DefaultWeakFormPoisson<double>
{
public:
CustomWeakFormPoisson(
Hermes::Hermes1DFunction<double>* coeff = nullptr,
Hermes::Hermes2DFunction<double>* f = nullptr,
std::string area = HERMES_ANY,
GeomType gt = HERMES_PLANAR);
};
| Unknown |
2D | hpfem/hermes-examples | 1d/moving-front/plot_graph.py | .py | 334 | 18 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.title("DOF history")
pylab.xlabel("Physical time (s)")
pylab.ylabel("Number of degrees of freedom")
data = numpy.loadtxt("dof_history.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="number of DOF")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 1d/moving-front/plot_graphs.py | .py | 548 | 26 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.title("DOF history")
pylab.xlabel("Physical time")
pylab.ylabel("Number of degrees of freedom")
data = numpy.loadtxt("dof_history_hp.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="hp-FEM")
data = numpy.loadtxt("dof_history_h2.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="h-FEM (p=2)")
data = numpy.loadtxt("dof_history_h1.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="h-FEM (p=1)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 1d/moving-front/main.cpp | .cpp | 10,123 | 263 | #include "definitions.h"
using namespace RefinementSelectors;
// This examples is an analogy to the 2D benchmark moving-front-space-adapt.
// It has an exact solution that contains a moving front with arbitrary
// steepness S. The mesh changes dynamically in time. Arbitrary RK method
// can be used for time integration.
//
// PDE: time-dependent heat transfer equation, du/dt = u'' + f.
//
// Domain: Interval (0, 10).
//
// BC: Zero Dirichlet.
//
// IC: Zero.
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// Initial polynomial degree of mesh elements.
const int P_INIT = 1;
// Time step.
const double time_step = 0.01;
// Time interval length.
const double T_FINAL = 10.0;
// Adaptivity
// Every UNREF_FREQth time step the mesh is derefined.
const int UNREF_FREQ = 1;
// 1... mesh reset to basemesh and poly degrees to P_INIT.
// 2... one ref. layer shaved off, poly degrees reset to P_INIT.
// 3... one ref. layer shaved off, poly degrees decreased by one.
const int UNREF_METHOD = 3;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
// Newton's method
// Stopping criterion for Newton on fine mesh.
const double NEWTON_TOL = 1e-5;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 20;
// Choose one of the following time-integration methods, or define your own Butcher's table. The last number
// in the name of each method is its order. The one before last, if present, is the number of stages.
// Explicit methods:
// Explicit_RK_1, Explicit_RK_2, Explicit_RK_3, Explicit_RK_4.
// Implicit methods:
// Implicit_RK_1, Implicit_Crank_Nicolson_2_2, Implicit_SIRK_2_2, Implicit_ESIRK_2_2, Implicit_SDIRK_2_2,
// Implicit_Lobatto_IIIA_2_2, Implicit_Lobatto_IIIB_2_2, Implicit_Lobatto_IIIC_2_2, Implicit_Lobatto_IIIA_3_4,
// Implicit_Lobatto_IIIB_3_4, Implicit_Lobatto_IIIC_3_4, Implicit_Radau_IIA_3_5, Implicit_SDIRK_5_4.
// Embedded explicit methods:
// Explicit_HEUN_EULER_2_12_embedded, Explicit_BOGACKI_SHAMPINE_4_23_embedded, Explicit_FEHLBERG_6_45_embedded,
// Explicit_CASH_KARP_6_45_embedded, Explicit_DORMAND_PRINCE_7_45_embedded.
// Embedded implicit methods:
// Implicit_SDIRK_CASH_3_23_embedded, Implicit_ESDIRK_TRBDF2_3_23_embedded, Implicit_ESDIRK_TRX2_3_23_embedded,
// Implicit_SDIRK_BILLINGTON_3_23_embedded, Implicit_SDIRK_CASH_5_24_embedded, Implicit_SDIRK_CASH_5_34_embedded,
// Implicit_DIRK_ISMAIL_7_45_embedded.
ButcherTableType butcher_table_type = Implicit_Crank_Nicolson_2_2;
// Problem parameters.
double x_0 = 0.0;
double x_1 = 10.0;
double y_0 = -5.0;
double y_1 = 5.0;
// Steepness of the moving front.
double s = 20.0;
double c = 1000.0;
// Current time.
double current_time = 0.0;
int main(int argc, char* argv[])
{
// Choose a Butcher's table or define your own.
ButcherTable bt(butcher_table_type);
if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size());
if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size());
// Load the mesh.
MeshSharedPtr mesh(new Mesh), basemesh(new Mesh);
MeshReaderH1DXML mloader;
try
{
mloader.load("domain.xml", basemesh);
}
catch (Hermes::Exceptions::MeshLoadFailureException& e)
{
e.print_msg();
return -1;
}
// Perform initial mesh refinements.
int refinement_type = 2; // Split elements vertically.
for (int i = 0; i < INIT_REF_NUM; i++) basemesh->refine_all_elements(refinement_type, true);
mesh->copy(basemesh);
// Exact solution.
CustomExactSolution exact_sln(mesh, x_0, x_1, y_0, y_1, ¤t_time, s, c);
// Initialize boundary conditions.
DefaultEssentialBCConst<double> bc_essential(std::vector<std::string>({ "Left", "Right" }), 0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof_coarse = space->get_num_dofs();
// Initialize the weak formulation
CustomFunction f(x_0, x_1, y_0, y_1, s, c);
WeakFormSharedPtr<double> wf(new CustomWeakFormPoisson(new Hermes::Hermes1DFunction<double>(-1.0), &f));
// Previous and next time level solution.
MeshFunctionSharedPtr<double> sln_time_prev(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> sln_time_new(new Solution<double>(mesh));
// Create a refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Visualize initial condition.
char title[100];
Views::ScalarView sview("Initial condition", new Views::WinGeom(0, 0, 1200, 200));
Views::OrderView oview("Initial mesh", new Views::WinGeom(0, 260, 1200, 200));
sview.show(sln_time_prev);
oview.show(space);
// Graph for dof history.
SimpleGraph dof_history_graph;
// Time stepping loop.
int ts = 1;
do
{
// Periodic global derefinement.
if (ts > 1 && ts % UNREF_FREQ == 0)
{
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
switch (UNREF_METHOD) {
case 1: mesh->copy(basemesh);
space->set_uniform_order(P_INIT);
break;
case 2: mesh->unrefine_all_elements();
space->set_uniform_order(P_INIT);
break;
case 3: mesh->unrefine_all_elements();
space->adjust_element_order(-1, -1, P_INIT, P_INIT);
break;
default: throw Hermes::Exceptions::Exception("Wrong global derefinement method.");
}
space->assign_dofs();
ndof_coarse = space->get_num_dofs();
}
// Spatial adaptivity loop. Note: sln_time_prev must not be changed
// during spatial adaptivity.
bool done = false; int as = 1;
double err_est;
do {
Hermes::Mixins::Loggable::Static::info("Time step %d, adaptivity step %d:", ts, as);
// Construct globally refined reference mesh and setup reference space.
// FIXME: This should be increase in the x-direction only.
int order_increase = 1;
// FIXME: This should be '2' but that leads to a segfault.
int refinement_type = 0;
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
// Initialize Runge-Kutta time stepping.
RungeKutta<double> runge_kutta(wf, ref_space, &bt);
// Perform one Runge-Kutta time step according to the selected Butcher's table.
Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).",
current_time, time_step, bt.get_size());
bool freeze_jacobian = true;
bool block_diagonal_jacobian = false;
bool verbose = true;
try
{
runge_kutta.set_time(current_time);
runge_kutta.set_verbose_output(true);
runge_kutta.set_time_step(time_step);
runge_kutta.set_newton_max_allowed_iterations(NEWTON_MAX_ITER);
runge_kutta.set_newton_tolerance(NEWTON_TOL);
runge_kutta.rk_time_step_newton(sln_time_prev, sln_time_new);
}
catch (Exceptions::Exception& e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Runge-Kutta time step failed");
}
// Project the fine mesh solution onto the coarse mesh.
MeshFunctionSharedPtr<double> sln_coarse(new Solution<double>);
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh for error estimation.");
OGProjection<double>::project_global(space, sln_time_new, sln_coarse);
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
adaptivity.set_space(space);
errorCalculator.calculate_errors(sln_coarse, sln_time_new);
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_ref: %d, err_est_rel: %g%%",
space->get_num_dofs(), ref_space->get_num_dofs(), err_est_rel_total);
// If err_est too large, adapt the mesh.
if (err_est_rel_total < ERR_STOP) done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
done = adaptivity.adapt(&selector);
// Increase the counter of performed adaptivity steps.
as++;
}
} while (done == false);
// Visualize the solution and mesh.
char title[100];
sprintf(title, "Solution, time %g", current_time);
sview.set_title(title);
sview.show_mesh(false);
sview.show(sln_time_new);
sprintf(title, "Mesh, time %g", current_time);
oview.set_title(title);
oview.show(space);
// Copy last reference solution into sln_time_prev->
sln_time_prev->copy(sln_time_new);
dof_history_graph.add_values(current_time, space->get_num_dofs());
dof_history_graph.save("dof_history.dat");
// Increase current time and counter of time steps.
current_time += time_step;
ts++;
} while (current_time < T_FINAL);
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 1d/moving-front/definitions.cpp | .cpp | 4,454 | 129 | #include "definitions.h"
double CustomExactSolution::value(double x, double y) const
{
double S = s;
double C = c;
double t = *t_ptr;
return (x - x0) * (x - x1) * Hermes::atan(t) * (M_PI / 2. - Hermes::atan(S*(x - t))) / C;
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double S = s;
double C = c;
double t = *t_ptr;
dx = -S*(x - x0)*(x - x1)*Hermes::atan(t) / (C*(Hermes::pow(S, 2)*Hermes::pow(-t + x, 2) + 1)) + (x - x0)*(-Hermes::atan(S*(-t + x)) + M_PI / 2)*Hermes::atan(t) / C + (x - x1)*(-Hermes::atan(S*(-t + x)) + M_PI / 2)*Hermes::atan(t) / C;
dy = 0;
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(20);
}
double CustomFunction::value(double x, double y, double t) const
{
double S = s;
double C = c;
// Generated by Sympy.
double f = -Hermes::pow(S, 3)*(-2 * t + 2 * x)*(x - x0)*(x - x1)*Hermes::atan(t) / (C*Hermes::pow(Hermes::pow(S, 2)*Hermes::pow(-t + x, 2) + 1, 2)) + S*(x - x0)*(x - x1)*Hermes::atan(t) / (C*(Hermes::pow(S, 2)*Hermes::pow(-t + x, 2) + 1)) + 2 * S*(x - x0)*Hermes::atan(t) / (C*(Hermes::pow(S, 2)*Hermes::pow(-t + x, 2) + 1)) + 2 * S*(x - x1)*Hermes::atan(t) / (C*(Hermes::pow(S, 2)*Hermes::pow(-t + x, 2) + 1)) - 2 * (-Hermes::atan(S*(-t + x)) + M_PI / 2)*Hermes::atan(t) / C + (x - x0)*(x - x1)*(-Hermes::atan(S*(-t + x)) + M_PI / 2) / (C*(Hermes::pow(t, 2) + 1));
return -f;
}
Ord CustomFunction::value(Ord x, Ord y) const
{
return Ord(20);
}
CustomVectorFormVol::CustomVectorFormVol(int i,
Hermes::Hermes2DFunction<double>* coeff, std::string area, GeomType gt)
: VectorFormVol<double>(i), coeff(coeff), gt(gt)
{
this->set_area(area);
// If coeff is nullptr, initialize it to be constant 1.0.
if (coeff == nullptr) this->coeff = new Hermes::Hermes2DFunction<double>(1.0);
}
CustomVectorFormVol::CustomVectorFormVol(int i, Hermes::Hermes2DFunction<double>* coeff, std::vector<std::string> areas, GeomType gt)
: VectorFormVol<double>(i), coeff(coeff), gt(gt)
{
this->set_areas(areas);
// If coeff is nullptr, initialize it to be constant 1.0.
if (coeff == nullptr) this->coeff = new Hermes::Hermes2DFunction<double>(1.0);
}
CustomVectorFormVol::~CustomVectorFormVol()
{
// FIXME: Should be deleted here only if it was created here.
//if (coeff != nullptr) delete coeff;
};
double CustomVectorFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0;
if (gt == HERMES_PLANAR) {
for (int i = 0; i < n; i++) {
result += wt[i] * static_cast<CustomFunction*>(coeff)->value(e->x[i], e->y[i], this->get_current_stage_time()) * v->val[i];
}
}
else {
if (gt == HERMES_AXISYM_X) {
for (int i = 0; i < n; i++) {
result += wt[i] * e->y[i] * static_cast<CustomFunction*>(coeff)->value(e->x[i], e->y[i], this->get_current_stage_time()) * v->val[i];
}
}
else {
for (int i = 0; i < n; i++) {
result += wt[i] * e->x[i] * static_cast<CustomFunction*>(coeff)->value(e->x[i], e->y[i], this->get_current_stage_time()) * v->val[i];
}
}
}
return result;
}
Ord CustomVectorFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (gt == HERMES_PLANAR) {
for (int i = 0; i < n; i++) {
result += wt[i] * coeff->value(e->x[i], e->y[i]) * v->val[i];
}
}
else {
if (gt == HERMES_AXISYM_X) {
for (int i = 0; i < n; i++) {
result += wt[i] * e->y[i] * coeff->value(e->x[i], e->y[i]) * v->val[i];
}
}
else {
for (int i = 0; i < n; i++) {
result += wt[i] * e->x[i] * coeff->value(e->x[i], e->y[i]) * v->val[i];
}
}
}
return result;
}
VectorFormVol<double>* CustomVectorFormVol::clone() const
{
return new CustomVectorFormVol(*this);
}
CustomWeakFormPoisson::CustomWeakFormPoisson(
Hermes::Hermes1DFunction<double>* coeff, Hermes::Hermes2DFunction<double>* f, std::string area,
GeomType gt) : WeakFormsH1::DefaultWeakFormPoisson<double>()
{
// Jacobian.
// NOTE: The flag HERMES_NONSYM is important here.
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0, area, coeff, HERMES_NONSYM, gt));
// Residual.
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(0, area, coeff, gt));
add_vector_form(new CustomVectorFormVol(0, f, area, gt));
}; | C++ |
2D | hpfem/hermes-examples | 1d/layer-boundary/definitions.h | .h | 1,228 | 68 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Exact solution */
class CustomExactFunction
{
public:
CustomExactFunction(double K) : K(K) {};
double uhat(double x);
double duhat_dx(double x);
double dduhat_dxx(double x);
protected:
double K;
};
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double K);
virtual double value (double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(this->mesh, this->K); }
~CustomExactSolution();
CustomExactFunction* cef;
double K;
};
/* Custom function */
class CustomFunction: public Hermes::Hermes2DFunction<double>
{
public:
CustomFunction(double coeff1);
virtual double value(double x, double y) const;
virtual Ord value(Ord x, Ord y) const;
~CustomFunction();
CustomExactFunction* cef;
double coeff1;
};
/* Weak forms */
class CustomWeakForm : public WeakForm<double>
{
public:
CustomWeakForm(CustomFunction* f);
};
| Unknown |
2D | hpfem/hermes-examples | 1d/layer-boundary/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 1d/layer-boundary/main.cpp | .cpp | 8,090 | 213 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the 1D version of the benchmark layer-boundary. It is a
// singularly perturbed problem that exhibits a thin boundary layer.
// Known exact solution facilitates convergence studies.
//
// PDE: -u'' + K*K*u - K*K + g(x) = 0.
//
// Domain: Interval (-1, 1).
//
// BC: Homogeneous Dirichlet.
//
// Exact solution: U(x) = 1 - (exp(K*x) + exp(-K*x))/(exp(K) + exp(-K)).
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
const int P_INIT = 1;
// Number of initial mesh refinements (the original mesh is just one element).
const int INIT_REF_NUM = 0;
// Number of initial mesh refinements towards the boundary.
const int INIT_REF_NUM_BDY = 5;
/// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.5;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates. Possible values are
// H2D_P_ISO, H2D_P_ANISO, H2D_H_ISO, H2D_H_ANISO, H2D_HP_ISO,
// H2D_HP_ANISO_H, H2D_HP_ANISO_P, H2D_HP_ANISO.
const CandList CAND_LIST = H2D_HP_ANISO;
// Maximum allowed level of hanging nodes:
// MESH_REGULARITY = -1 ... arbitrary level hangning nodes (default),
// MESH_REGULARITY = 1 ... at most one-level hanging nodes,
// MESH_REGULARITY = 2 ... at most two-level hanging nodes, etc.
// Note that regular meshes are not supported, this is due to
// their notoriously bad performance.
const int MESH_REGULARITY = -1;
// This parameter influences the selection of
// candidates in hp-adaptivity. Default value is 1.0.
const double CONV_EXP = 0.5;
// Stopping criterion for adaptivity (rel. error tolerance between the
// reference mesh and coarse mesh solution in percent).
const double ERR_STOP = 1e-3;
// Adaptivity process stops when the number of degrees of freedom grows
// over this limit. This is to prevent h-adaptivity to go on forever.
const int NDOF_STOP = 1000;
// Matrix solver: SOLVER_AMESOS, SOLVER_AZTECOO, SOLVER_MUMPS,
// SOLVER_PETSC, SOLVER_SUPERLU, SOLVER_UMFPACK.
Hermes::MatrixSolverType matrix_solver = Hermes::SOLVER_UMFPACK;
// Problem parameters.
const double K = 1e2;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH1DXML mloader;
mloader.load("domain.xml", mesh);
// Perform initial mesh refinement.
// Split elements vertically.
int refinement_type = 2;
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements(refinement_type);
mesh->refine_towards_boundary("Left", INIT_REF_NUM_BDY);
mesh->refine_towards_boundary("Right", INIT_REF_NUM_BDY);
// Define exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, K));
// Define right side vector.
CustomFunction f(K);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(&f));
// Initialize boundary conditions.
DefaultEssentialBCConst<double> bc_essential(std::vector<std::string>({ "Left", "Right" }), 0.0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 600, 360));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(0, 420, 600, 270));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space.
// FIXME: This should be increase in the x-direction only.
int order_increase = 1;
// FIXME: This should be '2' but that leads to a segfault.
int refinement_type = 0;
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
// Calculate exact error.
errorCalculator.calculate_errors(sln, exact_sln, false);
double err_exact_rel = errorCalculator.get_total_error_squared() * 100;
errorCalculator.calculate_errors(sln, ref_sln);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
Adapt<double> adaptivity(space, &errorCalculator, &stoppingCriterion);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP || space->get_num_dofs() >= NDOF_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 1d/layer-boundary/definitions.cpp | .cpp | 2,009 | 75 | #include "definitions.h"
double CustomExactFunction::uhat(double x)
{
return 1. - (exp(K*x) + exp(-K*x)) / (exp(K) + exp(-K));
}
double CustomExactFunction::duhat_dx(double x)
{
return -K * (exp(K*x) - exp(-K*x)) / (exp(K) + exp(-K));
}
double CustomExactFunction::dduhat_dxx(double x)
{
return -K*K * (exp(K*x) + exp(-K*x)) / (exp(K) + exp(-K));
}
CustomExactSolution::CustomExactSolution(MeshSharedPtr mesh, double K) : ExactSolutionScalar<double>(mesh), K(K)
{
cef = new CustomExactFunction(K);
}
CustomExactSolution::~CustomExactSolution()
{
delete cef;
}
double CustomExactSolution::value(double x, double y) const
{
return cef->uhat(x) * cef->uhat(y);
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
dx = cef->duhat_dx(x) * cef->uhat(y);
dy = 0;
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(20);
}
CustomFunction::CustomFunction(double coeff1) : Hermes::Hermes2DFunction<double>(), coeff1(coeff1)
{
cef = new CustomExactFunction(coeff1);
}
CustomFunction::~CustomFunction()
{
delete cef;
}
double CustomFunction::value(double x, double y) const
{
return -(-cef->dduhat_dxx(x) + coeff1 * coeff1 * cef->uhat(x));
}
Ord CustomFunction::value(Ord x, Ord y) const
{
return Ord(5);
}
CustomWeakForm::CustomWeakForm(CustomFunction* f) : WeakForm<double>(1)
{
// Jacobian.
add_matrix_form(new Hermes::Hermes2D::WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0));
add_matrix_form(new Hermes::Hermes2D::WeakFormsH1::DefaultMatrixFormVol<double>(0, 0, HERMES_ANY,
new Hermes::Hermes2DFunction<double>(f->coeff1*f->coeff1)));
// Residual.
add_vector_form(new Hermes::Hermes2D::WeakFormsH1::DefaultResidualDiffusion<double>(0));
add_vector_form(new Hermes::Hermes2D::WeakFormsH1::DefaultResidualVol<double>(0, HERMES_ANY,
new Hermes::Hermes2DFunction<double>(f->coeff1*f->coeff1)));
add_vector_form(new Hermes::Hermes2D::WeakFormsH1::DefaultVectorFormVol<double>(0, HERMES_ANY, f));
} | C++ |
2D | hpfem/hermes-examples | doc/conf.py | .py | 11,204 | 383 | # -*- coding: utf-8 -*-
#
# Hermes2D documentation build configuration file, created by
# sphinx-quickstart on Fri Oct 30 19:23:04 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
sys.path.append(os.path.abspath(os.path.join("..", "python")))
sys.path.append(os.path.abspath('exts'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'math_dollar', 'youtube', 'popup', 'sourcecode', 'latexcode']
latex_preamble = r"""
\usepackage{dsfont}
\usepackage{braket}
\usepackage{slashed}
\usepackage{fancyvrb}
\usepackage{color}
\usepackage{float}
\usepackage{bm}
\let\origfigure=\figure
\renewenvironment{figure}[6]{
\origfigure[H]}
{\endlist}
\def\degrees{^\circ}
\def\d{{\rm d}}
\def\L{{\mathcal L}}
\def\H{{\mathcal H}}
\def\M{{\mathcal M}}
\def\matrix{}
\def\fslash#1{#1 \!\!\!/}
\def\F{{\bf F}}
\def\R{{\bf R}}
\def\J{{\bf J}}
\def\x{{\bf x}}
\def\y{{\bf y}}
\def\h{{\rm h}}
\def\a{{\rm a}}
\newcommand{\bfx}{\mbox{\boldmath $x$}}
\newcommand{\bfy}{\mbox{\boldmath $y$}}
\newcommand{\bfz}{\mbox{\boldmath $z$}}
\newcommand{\bfv}{\mbox{\boldmath $v$}}
\newcommand{\bfu}{\mbox{\boldmath $u$}}
\newcommand{\bfF}{\mbox{\boldmath $F$}}
\newcommand{\bfJ}{\mbox{\boldmath $J$}}
\newcommand{\bfU}{\mbox{\boldmath $U$}}
\newcommand{\bfY}{\mbox{\boldmath $Y$}}
\newcommand{\bfR}{\mbox{\boldmath $R$}}
\newcommand{\bfg}{\mbox{\boldmath $g$}}
\newcommand{\bfc}{\mbox{\boldmath $c$}}
\newcommand{\bfxi}{\mbox{\boldmath $\xi$}}
\newcommand{\bfw}{\mbox{\boldmath $w$}}
\newcommand{\bfE}{\mbox{\boldmath $E$}}
\newcommand{\bfS}{\mbox{\boldmath $S$}}
\newcommand{\bfb}{\mbox{\boldmath $b$}}
\newcommand{\bfH}{\mbox{\boldmath $H$}}
\def\Hcurl{{\bfH({\rm curl})}}
\def\Hdiv{{\bfH({\rm div})}}
\newcommand{\dd}[2]{\frac{\partial #1}{\partial #2}}
\newcommand{\dx}{\;\mbox{d}\bfx}
%\def\back{\!\!\!\!\!\!\!\!\!\!}
\def\PY{}
\def\PYZcb{}
\def\PYZob{}
\def\PYZus{}
\def\PYZbs{}
\def\PYZpc{}
\def\PYZti{}
\def\PYZsh{}
\def\back{}
\def\col#1#2{\left(\matrix{#1#2}\right)}
\def\row#1#2{\left(\matrix{#1#2}\right)}
\def\mat#1{\begin{pmatrix}#1\end{pmatrix}}
\def\matd#1#2{\left(\matrix{#1\back0\cr0\back#2}\right)}
\def\p#1#2{{\partial#1\over\partial#2}}
\def\cg#1#2#3#4#5#6{({#1},\,{#2},\,{#3},\,{#4}\,|\,{#5},\,{#6})}
\def\half{{\textstyle{1\over2}}}
\def\jsym#1#2#3#4#5#6{\left\{\matrix{
{#1}{#2}{#3}
{#4}{#5}{#6}
}\right\}}
\def\diag{\hbox{diag}}
\font\dsrom=dsrom10
\def\one{\hbox{\dsrom 1}}
\def\res{\mathop{\mathrm{Res}}}
\def\mathnot#1{\text{"$#1$"}}
%See Character Table for cmmib10:
%http://www.math.union.edu/~dpvc/jsmath/download/extra-fonts/cmmib10/cmmib10.html
\font\mib=cmmib10
\def\balpha{\hbox{\mib\char"0B}}
\def\bbeta{\hbox{\mib\char"0C}}
\def\bgamma{\hbox{\mib\char"0D}}
\def\bdelta{\hbox{\mib\char"0E}}
\def\bepsilon{\hbox{\mib\char"0F}}
\def\bzeta{\hbox{\mib\char"10}}
\def\boldeta{\hbox{\mib\char"11}}
\def\btheta{\hbox{\mib\char"12}}
\def\biota{\hbox{\mib\char"13}}
\def\bkappa{\hbox{\mib\char"14}}
\def\blambda{\hbox{\mib\char"15}}
\def\bmu{\hbox{\mib\char"16}}
\def\bnu{\hbox{\mib\char"17}}
\def\bxi{\hbox{\mib\char"18}}
\def\bpi{\hbox{\mib\char"19}}
\def\brho{\hbox{\mib\char"1A}}
\def\bsigma{\hbox{\mib\char"1B}}
\def\btau{\hbox{\mib\char"1C}}
\def\bupsilon{\hbox{\mib\char"1D}}
\def\bphi{\hbox{\mib\char"1E}}
\def\bchi{\hbox{\mib\char"1F}}
\def\bpsi{\hbox{\mib\char"20}}
\def\bomega{\hbox{\mib\char"21}}
\def\bvarepsilon{\hbox{\mib\char"22}}
\def\bvartheta{\hbox{\mib\char"23}}
\def\bvarpi{\hbox{\mib\char"24}}
\def\bvarrho{\hbox{\mib\char"25}}
\def\bvarphi{\hbox{\mib\char"27}}
%how to use:
%$$\alpha\balpha$$
%$$\beta\bbeta$$
%$$\gamma\bgamma$$
%$$\delta\bdelta$$
%$$\epsilon\bepsilon$$
%$$\zeta\bzeta$$
%$$\eta\boldeta$$
%$$\theta\btheta$$
%$$\iota\biota$$
%$$\kappa\bkappa$$
%$$\lambda\blambda$$
%$$\mu\bmu$$
%$$\nu\bnu$$
%$$\xi\bxi$$
%$$\pi\bpi$$
%$$\rho\brho$$
%$$\sigma\bsigma$$
%$$\tau\btau$$
%$$\upsilon\bupsilon$$
%$$\phi\bphi$$
%$$\chi\bchi$$
%$$\psi\bpsi$$
%$$\omega\bomega$$
%
%$$\varepsilon\bvarepsilon$$
%$$\vartheta\bvartheta$$
%$$\varpi\bvarpi$$
%$$\varrho\bvarrho$$
%$$\varphi\bvarphi$$
%small font
\font\mibsmall=cmmib7
\def\bsigmasmall{\hbox{\mibsmall\char"1B}}
\def\Tr{\hbox{Tr}\,}
\def\Arg{\hbox{Arg}}
\def\atan{\hbox{atan}}
"""
pngmath_latex_preamble = latex_preamble
latex_elements = {"preamble": latex_preamble}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Hermes'
copyright = u'2009-2011, hp-FEM group at UNR'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.5'
# The full version, including alpha/beta/rc tags.
release = '0.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'bodyfont': 'verdana, helvetica, arial, sans-serif',
'bgcolor': '#FFFFFF',
'textcolor': '#000000',
'linkcolor': '#3D5C7A',
'rightsidebar': False,
'sidebarbgcolor': '#F8F8F8',
'sidebartextcolor': '#000000',
'sidebarlinkcolor': '#3D5C7A',
'headfont': '"trebuchet ms", verdana, helvetica, arial, sans-serif',
'headbgcolor': '#FFFFFF',
'headtextcolor': '#7590AE',
'headlinkcolor': '#3D5C7A',
'codebgcolor': '#F5F5F5',
'codetextcolor': '#000000',
'relbarbgcolor': '#1553ef',
'relbartextcolor': '#000000',
'relbarlinkcolor': '#FFFFFF',
'footerbgcolor': '#FFFFFF',
'footertextcolor': '#000000'
}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = 'Hermes Examples Guide'
# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = 'Content'
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = '.html'
# Output file base name for HTML help builder.
htmlhelp_basename = 'Hermes2Ddoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Hermes2D.tex', u'Hermes2D Documentation',
u'hp-FEM group at UNR', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
| Python |
2D | hpfem/hermes-examples | doc/src/hermes2d/benchmarks-general/benchmark-lshape/plot_graph_cpu.py | .py | 558 | 26 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("CPU time")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_cpu_exact_h1.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1)")
data = numpy.loadtxt("conv_cpu_exact_h2.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2)")
data = numpy.loadtxt("conv_cpu_exact_hp.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | doc/src/hermes2d/benchmarks-general/benchmark-lshape/plot_graph_dof.py | .py | 568 | 26 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_dof_exact_h1.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1)")
data = numpy.loadtxt("conv_dof_exact_h2.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2)")
data = numpy.loadtxt("conv_dof_exact_hp.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | doc/src/hermes2d/benchmarks-general/benchmark-layer-interior/plot_graph_cpu.py | .py | 558 | 26 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("CPU time")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_cpu_exact_h1.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1)")
data = numpy.loadtxt("conv_cpu_exact_h2.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2)")
data = numpy.loadtxt("conv_cpu_exact_hp.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | doc/src/hermes2d/benchmarks-general/benchmark-layer-interior/plot_graph_dof.py | .py | 568 | 26 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_dof_exact_h1.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1)")
data = numpy.loadtxt("conv_dof_exact_h2.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2)")
data = numpy.loadtxt("conv_dof_exact_hp.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | doc/src/hermes2d/benchmarks-general/benchmark-layer-boundary/plot_compar_h2.py | .py | 888 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_dof_exact_h2_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2, iso)")
data = numpy.loadtxt("conv_dof_exact_h2_aniso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2, aniso)")
legend()
# initialize new window
pylab.figure()
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_cpu_exact_h2_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2, iso)")
data = numpy.loadtxt("conv_cpu_exact_h2_aniso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2, aniso)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | doc/src/hermes2d/benchmarks-general/benchmark-layer-boundary/plot_compar_h1.py | .py | 888 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_dof_exact_h1_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1, iso)")
data = numpy.loadtxt("conv_dof_exact_h1_aniso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1, aniso)")
legend()
# initialize new window
pylab.figure()
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_cpu_exact_h1_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1, iso)")
data = numpy.loadtxt("conv_cpu_exact_h1_aniso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1, aniso)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | doc/src/hermes2d/benchmarks-general/benchmark-layer-boundary/plot_compar_hp.py | .py | 1,134 | 50 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_dof_exact_hp_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (iso)")
data = numpy.loadtxt("conv_dof_exact_hp_anisoh.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (aniso h)")
data = numpy.loadtxt("conv_dof_exact_hp_aniso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (aniso hp)")
legend()
# initialize new window
pylab.figure()
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_cpu_exact_hp_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (iso)")
data = numpy.loadtxt("conv_cpu_exact_hp_anisoh.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (aniso h)")
data = numpy.loadtxt("conv_cpu_exact_hp_aniso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (aniso hp)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | doc/src/hermes2d/benchmarks-general/benchmark-layer-boundary/plot_compar_iso.py | .py | 1,122 | 50 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_dof_exact_h1_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1, iso)")
data = numpy.loadtxt("conv_dof_exact_h2_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2, iso)")
data = numpy.loadtxt("conv_dof_exact_hp_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (iso)")
legend()
# initialize new window
pylab.figure()
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_cpu_exact_h1_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=1, iso)")
data = numpy.loadtxt("conv_cpu_exact_h2_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="h-FEM (p=2, iso)")
data = numpy.loadtxt("conv_cpu_exact_hp_iso.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (iso)")
legend()
# finalize
show()
| Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.