Compare commits

...

10 Commits

Author SHA1 Message Date
1554ed0ef5 refactor + add colors 2025-05-17 20:22:42 +03:00
Kirill
7c27a20994 feat(main.kt): Alfa1 2025-05-12 15:05:10 +03:00
Kirill
b4232eee5e feat(Main.kt): beta 3 2025-05-12 14:56:52 +03:00
Kirill
e0fbe8c605 feat(Main.kt): Beta 2 2025-05-12 13:02:47 +03:00
Kirill
91bf0fdfa8 feat(Lab3): Beta 2025-05-12 09:30:37 +03:00
Kirill
16cfa6744d fix(Lab_2): White screen after selecting file
Fix problem with white screeen after selected file
2025-05-04 16:42:10 +03:00
Kirill
f18d6f1025 fix(lab_2): worked
All worked 2-nd lab
2025-05-04 16:26:52 +03:00
Kirill
be5701e4de feat(lab_2): preALlfa work wersion 2025-05-01 18:38:29 +03:00
Remizov Kirirll
65aeef7f2b Added all Matrix filters 2025-03-17 18:05:05 +03:00
Remizov Kirirll
f671d526f0 Added all pointed filters 2025-03-16 18:43:04 +03:00
38 changed files with 2291 additions and 4 deletions

45
Lab3/.gitignore vendored Normal file
View File

@ -0,0 +1,45 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Kotlin ###
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

3
Lab3/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

17
Lab3/.idea/gradle.xml generated Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

6
Lab3/.idea/kotlinc.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="2.0.21" />
</component>
</project>

7
Lab3/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
Lab3/.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

52
Lab3/build.gradle.kts Normal file
View File

@ -0,0 +1,52 @@
plugins {
kotlin("jvm") version "2.0.21"
application
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
val lwjglVersion = "3.3.3"
val lwjglNatives = "natives-linux" // Для NixOS используем стандартные Linux-нативы
dependencies {
testImplementation(kotlin("test"))
implementation(platform("org.lwjgl:lwjgl-bom:$lwjglVersion"))
// Основные LWJGL модули
implementation("org.lwjgl:lwjgl")
implementation("org.lwjgl:lwjgl-glfw")
implementation("org.lwjgl:lwjgl-opengl")
// Дополнительные модули
implementation("org.lwjgl:lwjgl-stb")
implementation("org.lwjgl:lwjgl-nanovg")
implementation("org.lwjgl:lwjgl-nfd")
implementation("org.lwjgl:lwjgl-openal")
implementation("org.joml:joml:1.10.5")
// Нативные библиотеки
runtimeOnly("org.lwjgl:lwjgl::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-glfw::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-opengl::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-stb::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-nanovg::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-nfd::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-openal::$lwjglNatives")
}
tasks.test {
useJUnitPlatform()
}
application {
mainClass.set("org.exampl.MainKt") // Укажите главный класс
}
kotlin {
jvmToolchain(21)
}

1
Lab3/gradle.properties Normal file
View File

@ -0,0 +1 @@
kotlin.code.style=official

BIN
Lab3/gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Sun May 11 12:45:28 MSK 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
Lab3/gradlew vendored Executable file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
Lab3/gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

5
Lab3/settings.gradle.kts Normal file
View File

@ -0,0 +1,5 @@
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "Lab3"

32
Lab3/shell.nix Normal file
View File

@ -0,0 +1,32 @@
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
buildInputs = [
pkgs.jdk21
pkgs.gradle
pkgs.libGL
pkgs.glfw
pkgs.xorg.libX11
pkgs.xorg.libXcursor
pkgs.xorg.libXrandr
pkgs.xorg.libXi
pkgs.mesa
];
shellHook = ''
export JAVA_HOME="${pkgs.jdk21}"
export PATH="${pkgs.gradle}/bin:$PATH"
export LD_LIBRARY_PATH="${
pkgs.lib.makeLibraryPath [
pkgs.libGL
pkgs.glfw
pkgs.xorg.libX11
pkgs.xorg.libXcursor
pkgs.xorg.libXrandr
pkgs.xorg.libXi
pkgs.mesa
]
}:$LD_LIBRARY_PATH"
'';
}

View File

@ -0,0 +1,401 @@
package org.exampl
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL20.*
import org.lwjgl.opengl.GL30.*
import org.lwjgl.system.MemoryUtil.*
import java.nio.FloatBuffer
import kotlin.math.*
class AtomModelShader {
private var window: Long = 0
private var isRunning = false
private var shaderProgram = 0
private var vao = 0
private var vbo = 0
// Параметры камеры
private var cameraDistance = 15.0f
private var cameraAngleX = 30.0f
private var cameraAngleY = 45.0f
// Параметры атома
private val nucleusRadius = 1.2f
private val electronRadius = 0.4f
private val protonRadius = 0.5f // Протоны немного больше электронов
private val orbitRadii = floatArrayOf(4.0f, 6.0f, 8.0f)
private var rotationAngle = 0.0f
private var nucleusRotationAngle = 0.0f
private val electronSpeeds = floatArrayOf(1.0f, 1.3f, 0.8f)
private val protonSpeeds = floatArrayOf(0.7f, 1.1f, 0.9f)
fun run() {
init()
loop()
cleanup()
}
private fun loop() {
var lastTime = glfwGetTime()
while (isRunning && !glfwWindowShouldClose(window)) {
val currentTime = glfwGetTime()
val deltaTime = (currentTime - lastTime).toFloat()
lastTime = currentTime
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
// Обновление углов вращения
nucleusRotationAngle += 0.5f * deltaTime
rotationAngle += 0.6f * deltaTime
// Активация шейдера
glUseProgram(shaderProgram)
// Настройка камеры
val view = createViewMatrix()
val projection = createProjectionMatrix()
// Установка uniform-переменных
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "view"), false, view)
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projection"), false, projection)
glUniform3f(glGetUniformLocation(shaderProgram, "lightPos"), 10f, 10f, 10f)
glUniform3f(glGetUniformLocation(shaderProgram, "lightColor"), 1f, 1f, 1f)
glUniform3f(glGetUniformLocation(shaderProgram, "viewPos"),
0f, 0f, cameraDistance)
// Отрисовка ядра с вращением
drawNucleus()
// Отрисовка электронов и протонов
drawParticles()
glfwSwapBuffers(window)
glfwPollEvents()
}
}
private fun drawNucleus() {
val model = org.joml.Matrix4f()
.rotateY(nucleusRotationAngle)
.scale(nucleusRadius)
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), false, floatArrayToBuffer(model.get(FloatArray(16))))
glUniform3f(glGetUniformLocation(shaderProgram, "objectColor"), 1.0f, 1.0f, 0.0f)
glBindVertexArray(vao)
glDrawArrays(GL_TRIANGLES, 0, 32 * 32 * 6)
glBindVertexArray(0)
}
private fun drawParticles() {
// Красный цвет для электронов
val electronColor = floatArrayOf(1f, 0.0f, 0.0f)
// Синий цвет для протонов
val protonColor = floatArrayOf(0.0f, 0.0f, 1f)
// Отрисовка электронов (красные)
for (i in 0 until 3) {
val angle = rotationAngle * electronSpeeds[i]
val x = orbitRadii[i] * cos(angle.toDouble()).toFloat()
val z = orbitRadii[i] * sin(angle.toDouble()).toFloat()
val y = orbitRadii[i] * 0.3f * sin(angle.toDouble() * 1.5).toFloat()
val model = org.joml.Matrix4f()
.translate(x, y, z)
.scale(electronRadius)
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), false, floatArrayToBuffer(model.get(FloatArray(16))))
glUniform3f(glGetUniformLocation(shaderProgram, "objectColor"),
electronColor[0], electronColor[1], electronColor[2])
glBindVertexArray(vao)
glDrawArrays(GL_TRIANGLES, 0, 32 * 32 * 6)
glBindVertexArray(0)
}
// Отрисовка протонов (синие)
for (i in 0 until 3) {
val angle = rotationAngle * protonSpeeds[i] + PI.toFloat()
val x = (orbitRadii[i] + 1.5f) * cos(angle.toDouble()).toFloat()
val z = (orbitRadii[i] + 1.5f) * sin(angle.toDouble()).toFloat()
val y = (orbitRadii[i] + 1.5f) * 0.3f * cos(angle.toDouble() * 1.2).toFloat()
val model = org.joml.Matrix4f()
.translate(x, y, z)
.scale(protonRadius)
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), false, floatArrayToBuffer(model.get(FloatArray(16))))
glUniform3f(glGetUniformLocation(shaderProgram, "objectColor"),
protonColor[0], protonColor[1], protonColor[2])
glBindVertexArray(vao)
glDrawArrays(GL_TRIANGLES, 0, 32 * 32 * 6)
glBindVertexArray(0)
}
}
private fun init() {
if (!glfwInit()) throw IllegalStateException("Unable to initialize GLFW")
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE)
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)
window = glfwCreateWindow(1000, 800, "3D Atom Model with Shaders", NULL, NULL)
?: throw RuntimeException("Failed to create GLFW window")
glfwMakeContextCurrent(window)
GL.createCapabilities()
initShaders()
initBuffers()
glEnable(GL_DEPTH_TEST)
glClearColor(0.1f, 0.1f, 0.15f, 1.0f)
glfwSetFramebufferSizeCallback(window) { _, width, height ->
glViewport(0, 0, width, height)
}
glfwShowWindow(window)
isRunning = true
setupControls()
}
private fun initShaders() {
val vertexShader = """
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
out vec3 Normal;
out vec3 FragPos;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main() {
gl_Position = projection * view * model * vec4(aPos, 1.0);
FragPos = vec3(model * vec4(aPos, 1.0));
Normal = mat3(transpose(inverse(model))) * aNormal;
}
""".trimIndent()
val fragmentShader = """
#version 330 core
out vec4 FragColor;
in vec3 Normal;
in vec3 FragPos;
uniform vec3 objectColor;
uniform vec3 lightPos;
uniform vec3 lightColor;
uniform vec3 viewPos;
void main() {
// Ambient
float ambientStrength = 0.1;
vec3 ambient = ambientStrength * lightColor;
// Diffuse
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * lightColor;
// Specular
float specularStrength = 0.5;
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
vec3 specular = specularStrength * spec * lightColor;
vec3 result = (ambient + diffuse + specular) * objectColor;
FragColor = vec4(result, 1.0);
}
""".trimIndent()
shaderProgram = glCreateProgram()
val vs = compileShader(vertexShader, GL_VERTEX_SHADER)
val fs = compileShader(fragmentShader, GL_FRAGMENT_SHADER)
glAttachShader(shaderProgram, vs)
glAttachShader(shaderProgram, fs)
glLinkProgram(shaderProgram)
if (glGetProgrami(shaderProgram, GL_LINK_STATUS) == GL_FALSE) {
throw RuntimeException("Shader linking failed: ${glGetProgramInfoLog(shaderProgram)}")
}
glDeleteShader(vs)
glDeleteShader(fs)
}
private fun compileShader(source: String, type: Int): Int {
val shader = glCreateShader(type)
glShaderSource(shader, source)
glCompileShader(shader)
if (glGetShaderi(shader, GL_COMPILE_STATUS) == GL_FALSE) {
throw RuntimeException("Shader compilation failed: ${glGetShaderInfoLog(shader)}")
}
return shader
}
private fun initBuffers() {
vao = glGenVertexArrays()
vbo = glGenBuffers()
glBindVertexArray(vao)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
// Создаем сферу с треугольниками для более качественного отображения
val sphereData = createSolidSphereData(1.0f, 32, 32)
glBufferData(GL_ARRAY_BUFFER, sphereData, GL_STATIC_DRAW)
// Позиции вершин (0)
glVertexAttribPointer(0, 3, GL_FLOAT, false, 6 * Float.SIZE_BYTES, 0)
glEnableVertexAttribArray(0)
// Нормали (1)
glVertexAttribPointer(1, 3, GL_FLOAT, false, 6 * Float.SIZE_BYTES, 3 * Float.SIZE_BYTES.toLong())
glEnableVertexAttribArray(1)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindVertexArray(0)
}
private fun createSolidSphereData(radius: Float, sectors: Int, stacks: Int): FloatBuffer {
val vertices = mutableListOf<Float>()
val sectorStep = 2 * PI.toFloat() / sectors
val stackStep = PI.toFloat() / stacks
for (i in 0 until stacks) {
val stackAngle1 = PI.toFloat() / 2 - i * stackStep
val stackAngle2 = PI.toFloat() / 2 - (i + 1) * stackStep
val xy1 = radius * cos(stackAngle1)
val z1 = radius * sin(stackAngle1)
val xy2 = radius * cos(stackAngle2)
val z2 = radius * sin(stackAngle2)
for (j in 0 until sectors) {
val sectorAngle1 = j * sectorStep
val sectorAngle2 = (j + 1) * sectorStep
// Вершины для двух треугольников, образующих квад
val x1 = xy1 * cos(sectorAngle1)
val y1 = xy1 * sin(sectorAngle1)
val x2 = xy2 * cos(sectorAngle1)
val y2 = xy2 * sin(sectorAngle1)
val x3 = xy1 * cos(sectorAngle2)
val y3 = xy1 * sin(sectorAngle2)
val x4 = xy2 * cos(sectorAngle2)
val y4 = xy2 * sin(sectorAngle2)
// Первый треугольник (верхний)
addVertexWithNormal(vertices, x1, y1, z1, radius)
addVertexWithNormal(vertices, x2, y2, z2, radius)
addVertexWithNormal(vertices, x3, y3, z1, radius)
// Второй треугольник (нижний)
addVertexWithNormal(vertices, x2, y2, z2, radius)
addVertexWithNormal(vertices, x4, y4, z2, radius)
addVertexWithNormal(vertices, x3, y3, z1, radius)
}
}
val buffer = org.lwjgl.BufferUtils.createFloatBuffer(vertices.size)
vertices.forEach { buffer.put(it) }
buffer.flip()
return buffer
}
private fun addVertexWithNormal(vertices: MutableList<Float>, x: Float, y: Float, z: Float, radius: Float) {
// Позиция вершины
vertices.add(x)
vertices.add(y)
vertices.add(z)
// Нормаль (нормализованный вектор от центра к вершине)
vertices.add(x / radius)
vertices.add(y / radius)
vertices.add(z / radius)
}
private fun setupControls() {
glfwSetKeyCallback(window) { _, key, _, action, _ ->
when {
key == GLFW_KEY_ESCAPE && action == GLFW_PRESS -> glfwSetWindowShouldClose(window, true)
action == GLFW_PRESS || action == GLFW_REPEAT -> handleKeyPress(key)
}
}
glfwSetScrollCallback(window) { _, _, yOffset ->
cameraDistance = (cameraDistance - yOffset).coerceIn(5.0, 30.0).toFloat()
}
glfwSetCursorPosCallback(window) { _, xPos, yPos ->
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) {
cameraAngleY += xPos.toFloat() * 0.2f
cameraAngleX = (cameraAngleX + yPos.toFloat() * 0.1f).coerceIn(5f, 85f)
}
}
}
private fun handleKeyPress(key: Int) {
when (key) {
GLFW_KEY_W -> cameraAngleX -= 2f
GLFW_KEY_S -> cameraAngleX += 2f
GLFW_KEY_A -> cameraAngleY -= 2f
GLFW_KEY_D -> cameraAngleY += 2f
GLFW_KEY_Q -> cameraDistance += 0.5f
GLFW_KEY_E -> cameraDistance -= 0.5f
}
}
private fun createViewMatrix(): FloatBuffer {
val matrix = org.joml.Matrix4f()
matrix.rotateX(cameraAngleX * (PI.toFloat() / 180f))
matrix.rotateY(cameraAngleY * (PI.toFloat() / 180f))
matrix.translate(0f, 0f, -cameraDistance)
return floatArrayToBuffer(matrix.get(FloatArray(16)))
}
private fun createProjectionMatrix(): FloatBuffer {
val matrix = org.joml.Matrix4f()
matrix.perspective(45f * (PI.toFloat() / 180f), 1000f / 800f, 0.1f, 100f)
return floatArrayToBuffer(matrix.get(FloatArray(16)))
}
// Добавляем вспомогательную функцию для преобразования FloatArray в FloatBuffer
private fun floatArrayToBuffer(array: FloatArray): FloatBuffer {
val buffer = org.lwjgl.BufferUtils.createFloatBuffer(array.size)
buffer.put(array)
buffer.flip()
return buffer
}
private fun cleanup() {
glDeleteVertexArrays(vao)
glDeleteBuffers(vbo)
glDeleteProgram(shaderProgram)
glfwDestroyWindow(window)
glfwTerminate()
}
}
fun main() {
AtomModelShader().run()
}

View File

@ -1,5 +1,8 @@
package org.example.lab_1.Helpers;
import javafx.scene.control.ProgressBar;
import javafx.scene.image.*;
public class Helpers {
public static int CheckBit(int val, int min, int max){
if (val > max) {
@ -9,4 +12,126 @@ public class Helpers {
}
return val;
}
public static double NormolizeIdealOtr(double val) {
if (val > 1) {
return 1;
} else if (val < 0) {
return 0;
}
return val;
}
public static void sortArray(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
public static void MatrixFilter( ImageView imageView, double[][] matrix, String log) {
Image img = imageView.getImage();
if (img == null) {
return;
}
int w = (int) img.getWidth();
int h = (int) img.getHeight();
PixelReader reader = img.getPixelReader();
WritableImage Img = new WritableImage(w, h);
PixelWriter writer = Img.getPixelWriter();
for (int y = 1; y < h - 1; y++) {
for (int x = 1; x < w - 1; x++) {
int sumRed = 0;
int sumGreen = 0;
int sumBlue = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
int argb = reader.getArgb(x + dx, y + dy);
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
sumRed += (int) (r * matrix[dy + 1][dx + 1]);
sumGreen += (int) (g * matrix[dy + 1][dx + 1]);
sumBlue += (int) (b * matrix[dy + 1][dx + 1]);
}
}
int newRed = CheckBit(sumRed + 128, 0, 255);
int newGreen = CheckBit(sumGreen + 128, 0, 255);
int newBlue = CheckBit(sumBlue + 128, 0, 255);
int a = (reader.getArgb(x, y) >> 24) & 0xFF;
int newArgb = (a << 24) | (newRed << 16) | (newGreen << 8) | newBlue;
writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(Img);
System.out.println("Применен фильтр: " + log);
}
public static void DoubleMatrixFilter( ImageView imageView, double[][] gx, double[][] gy, String log) {
Image img = imageView.getImage();
if (img == null) {
return;
}
int w = (int) img.getWidth();
int h = (int) img.getHeight();
PixelReader reader = img.getPixelReader();
WritableImage Img = new WritableImage(w, h);
PixelWriter writer = Img.getPixelWriter();
for (int y = 1; y < h - 1; y++) {
for (int x = 1; x < w - 1; x++) {
int sumGxRed = 0, sumGxGreen = 0, sumGxBlue = 0;
int sumGyRed = 0, sumGyGreen = 0, sumGyBlue = 0;
// Применяем свертку с ядрами Gx и Gy
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
int argb = reader.getArgb(x + dx, y + dy);
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
sumGxRed += r * gx[dy + 1][dx + 1];
sumGxGreen += g * gx[dy + 1][dx + 1];
sumGxBlue += b * gx[dy + 1][dx + 1];
sumGyRed += r * gy[dy + 1][dx + 1];
sumGyGreen += g * gy[dy + 1][dx + 1];
sumGyBlue += b * gy[dy + 1][dx + 1];
}
}
int gradientRed = (int) Math.sqrt(sumGxRed * sumGxRed + sumGyRed * sumGyRed);
int gradientGreen = (int) Math.sqrt(sumGxGreen * sumGxGreen + sumGyGreen * sumGyGreen);
int gradientBlue = (int) Math.sqrt(sumGxBlue * sumGxBlue + sumGyBlue * sumGyBlue);
gradientRed = CheckBit(gradientRed, 0, 255);
gradientGreen = CheckBit(gradientGreen, 0, 255);
gradientBlue = CheckBit(gradientBlue, 0, 255);
int a = (reader.getArgb(x, y) >> 24) & 0xFF;
int newArgb = (a << 24) | (gradientRed << 16) | (gradientGreen << 8) | gradientBlue;
writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(Img);
System.out.println("Применен фильтр: " + log);
}
}

View File

@ -10,22 +10,35 @@ import javafx.scene.control.ProgressBar;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import static org.example.lab_1.Helpers.Helpers.CheckBit;
import static org.example.lab_1.Helpers.Helpers.NormolizeIdealOtr;
import static org.example.lab_1.Helpers.Helpers.sortArray;
import static org.example.lab_1.Helpers.Helpers.MatrixFilter;
import static org.example.lab_1.Helpers.Helpers.DoubleMatrixFilter;
public class ImageEditorController {
@FXML
private ImageView imageView;
private Image oldImg;
@FXML
private ProgressBar progressBar;
public void initialize() {
progressBar.setVisible(false);
String imageUrl = "https://s0.rbk.ru/v6_top_pics/media/img/7/15/756775857541157.jpg";
String imageUrl = "https://i.pinimg.com/originals/a9/1c/2e/a91c2ed53bdd4c8d236b82828ea99505.jpg";
Image defaultImage = new Image(imageUrl);
imageView.setImage(defaultImage);
}
public void returnToOldImage() {
if(imageView.getImage() == oldImg || oldImg == null){
return;
} else {
imageView.setImage(oldImg);
}
}
public void openFile() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Выберите изображение");
@ -41,6 +54,7 @@ public class ImageEditorController {
public void applyInversionFilter() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image image = imageView.getImage();
if (image == null) return;
@ -77,6 +91,7 @@ public class ImageEditorController {
public void GrayScaleFilter() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if(img == null){ return; }
@ -115,6 +130,7 @@ public class ImageEditorController {
public void Sepia() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if(img == null){ return; }
@ -137,7 +153,7 @@ public class ImageEditorController {
double grey = 0.299 * r + 0.587 * g + 0.144 * b;
int k = 32;
int k = 20;
double f;
r = CheckBit((int) grey+(2*k), 0, 255);
f = grey+(0.5*k);
@ -148,9 +164,486 @@ public class ImageEditorController {
Writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(SepiaImg);
System.out.println("Применён Sepia");
progressBar.setVisible(false);
}
public void GetYarc() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if (img == null) {
return;
}
int w = (int) img.getWidth();
int h = (int) img.getHeight();
WritableImage YarcImg = new WritableImage(w, h);
PixelReader Reader = img.getPixelReader();
PixelWriter Writer = YarcImg.getPixelWriter();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int argb = Reader.getArgb(x, y);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
double grey = 0.299 * r + 0.587 * g + 0.144 * b;
int k = 20;
r = Math.min(255, r + k);
g = Math.min(255, g + k);
b = Math.min(255, b + k);
int newArgb = (a << 24) | (r << 16) | (g << 8) | b;
Writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(YarcImg);
System.out.println("Применёно Увеличение яркости");
progressBar.setVisible(false);
}
public void Sdvig() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if(img == null){ return; }
int w = (int) img.getWidth();
int h = (int) img.getHeight();
WritableImage SdvigImg = new WritableImage(w, h);
PixelReader Reader = img.getPixelReader();
PixelWriter Writer = SdvigImg.getPixelWriter();
for(int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if(x < 50){
continue;
}
int argb = Reader.getArgb(x - 50, y);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
int newArgb = (a << 24) | (r << 16) | (g << 8) | b;
Writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(SdvigImg);
System.out.println("Применён Сдвиг");
progressBar.setVisible(false);
}
public void grayWorld() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if(img == null){ return; }
int w = (int) img.getWidth();
int h = (int) img.getHeight();
PixelReader pixelReader = img.getPixelReader();
double sumR = 0, sumG = 0, sumB = 0;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int argb = pixelReader.getArgb(x, y);
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
sumR += r;
sumG += g;
sumB += b;
}
}
double avgR = sumR / (w * h);
double avgG = sumG / (w * h);
double avgB = sumB / (w * h);
double avgGray = (avgR + avgG + avgB) / 3;
double scaleR = avgGray / avgR;
double scaleG = avgGray / avgG;
double scaleB = avgGray / avgB;
WritableImage GWImage = new WritableImage(w, h);
PixelWriter pixelWriter = GWImage.getPixelWriter();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int argb = pixelReader.getArgb(x, y);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
int newR = (int) Math.min(255, r * scaleR);
int newG = (int) Math.min(255, g * scaleG);
int newB = (int) Math.min(255, b * scaleB);
int newArgb = (a << 24) | (newR << 16) | (newG << 8) | newB;
pixelWriter.setArgb(x, y, newArgb);
}
}
imageView.setImage(GWImage);
System.out.println("Применен фильтр 'Серый мир'");
progressBar.setVisible(false);
}
public void autoLevels() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if(img == null) { return; }
int w = (int) img.getWidth();
int h = (int) img.getHeight();
PixelReader reader = img.getPixelReader();
int rMin = 127, rMax = 127, gMin = 127, gMax = 127, bMin = 127, bMax = 127;
for(int y = 0; y < h; y++) {
for (int x = 0; x < w; x++){
int argb = reader.getArgb(x, y);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
if(r < rMin) {
rMin = r;
} else if (r > rMax) {
rMax = r;
}
if(g < gMin) {
gMin = g;
} else if (g > gMax) {
gMax = g;
}
if(b < bMin) {
bMin = b;
} else if (b > bMax) {
bMax = b;
}
}
}
WritableImage autolevelImg = new WritableImage(w, h);
PixelWriter writer = autolevelImg.getPixelWriter();
for(int y = 0; y < h; y++) {
for (int x = 0; x < w; x++){
int argb = reader.getArgb(x, y);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
double _r = ((r - rMin) / (rMax - rMin)) * 255;
r = CheckBit((int) _r , 0 , 255);
double _g = ((g - gMin) / (gMax - gMin)) * 255;
g = CheckBit((int) _g , 0 , 255);
double _b = ((b - bMin) / (bMax - bMin)) * 255;
b = CheckBit((int) _b , 0 , 255);
int newArgb = (a << 24) | (r << 16) | (g << 8) | b;
writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(autolevelImg);
System.out.println("Применен фильтр 'Автолевел'");
progressBar.setVisible(false);
}
public void IDdealOtr() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if(img == null) { return; }
int w = (int) img.getWidth();
int h = (int) img.getHeight();
PixelReader reader = img.getPixelReader();
int rMax = 127, gMax = 127, bMax = 127;
for(int y = 0; y < h; y++) {
for (int x = 0; x < w; x++){
int argb = reader.getArgb(x, y);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
if(r > rMax) {
rMax = r;
}
if(g > gMax) {
gMax = g;
}
if(b > bMax) {
bMax = b;
}
}
}
WritableImage IdealOtrImg = new WritableImage(w, h);
PixelWriter writer = IdealOtrImg.getPixelWriter();
for(int y = 0; y < h; y++) {
for (int x = 0; x < w; x++){
int argb = reader.getArgb(x, y);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
double _r = NormolizeIdealOtr(r/rMax);
double _g = NormolizeIdealOtr(g/gMax);
double _b = NormolizeIdealOtr(b/bMax);
r = (int) _r * 255;
g = (int) _g * 255;
b = (int) _b * 255;
int newArgb = (a << 24) | (r << 16) | (g << 8) | b;
writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(IdealOtrImg);
System.out.println("Применен фильтр 'Идеальный отражатель'");
progressBar.setVisible(false);
}
public void MedianFilter() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if (img == null) {
return;
}
int w = (int) img.getWidth();
int h = (int) img.getHeight();
PixelReader reader = img.getPixelReader();
WritableImage medianImg = new WritableImage(w, h);
PixelWriter writer = medianImg.getPixelWriter();
for (int y = 1; y < h - 1; y++) {
for (int x = 1; x < w - 1; x++) {
int[] redValues = new int[9];
int[] greenValues = new int[9];
int[] blueValues = new int[9];
int index = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
int argb = reader.getArgb(x + dx, y + dy);
redValues[index] = (argb >> 16) & 0xFF; // Красный канал
greenValues[index] = (argb >> 8) & 0xFF; // Зеленый канал
blueValues[index] = argb & 0xFF; // Синий канал
index++;
}
}
sortArray(redValues);
sortArray(greenValues);
sortArray(blueValues);
int medianRed = redValues[4];
int medianGreen = greenValues[4];
int medianBlue = blueValues[4];
int a = (reader.getArgb(x, y) >> 24) & 0xFF;
int newArgb = (a << 24) | (medianRed << 16) | (medianGreen << 8) | medianBlue;
writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(medianImg);
System.out.println("Применен фильтр 'Медиана'");
progressBar.setVisible(false);
}
public void EmbossFilter() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
double[][] kernel = {
{0, 1, 0},
{1, 0, -1},
{0, -1, 0}
};
MatrixFilter(imageView, kernel, "Тиснение");
progressBar.setVisible(false);
}
public void goFilter() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
double[][] kernel = {
{1.0 / 3, 0, 0},
{1.0 / 3, 0, 0},
{1.0 / 3, 0, 0}
};
MatrixFilter(imageView, kernel, "Размытие в Движении");
progressBar.setVisible(false);
}
public void RazshirFilter() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if (img == null) {
return;
}
int w = (int) img.getWidth();
int h = (int) img.getHeight();
PixelReader reader = img.getPixelReader();
WritableImage dilationImg = new WritableImage(w, h);
PixelWriter writer = dilationImg.getPixelWriter();
for (int y = 1; y < h - 1; y++) {
for (int x = 1; x < w - 1; x++) {
int maxRed = 0;
int maxGreen = 0;
int maxBlue = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
int argb = reader.getArgb(x + dx, y + dy);
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
if (r > maxRed) maxRed = r;
if (g > maxGreen) maxGreen = g;
if (b > maxBlue) maxBlue = b;
}
}
int a = (reader.getArgb(x, y) >> 24) & 0xFF;
int newArgb = (a << 24) | (maxRed << 16) | (maxGreen << 8) | maxBlue;
writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(dilationImg);
System.out.println("Применен фильтр: Разширение");
progressBar.setVisible(false);
}
public void ErosionFilter() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
Image img = imageView.getImage();
if (img == null) {
return;
}
int w = (int) img.getWidth();
int h = (int) img.getHeight();
PixelReader reader = img.getPixelReader();
WritableImage erosionImg = new WritableImage(w, h);
PixelWriter writer = erosionImg.getPixelWriter();
for (int y = 1; y < h - 1; y++) {
for (int x = 1; x < w - 1; x++) {
int minRed = 255;
int minGreen = 255;
int minBlue = 255;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
int argb = reader.getArgb(x + dx, y + dy);
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
if (r < minRed) minRed = r;
if (g < minGreen) minGreen = g;
if (b < minBlue) minBlue = b;
}
}
int a = (reader.getArgb(x, y) >> 24) & 0xFF;
int newArgb = (a << 24) | (minRed << 16) | (minGreen << 8) | minBlue;
writer.setArgb(x, y, newArgb);
}
}
imageView.setImage(erosionImg);
System.out.println("Применен фильтр: Сужение");
progressBar.setVisible(false);
}
public void SobelFilter() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
double[][] dx = {
{-1, 0, 1},
{-2, 0, 2},
{-1, 0, 1}
};
double[][] dy = {
{-1, -2, -1},
{0, 0, 0},
{1, 2, 1}
};
DoubleMatrixFilter(imageView, dx, dy, "Фильтр Собеля");
progressBar.setVisible(false);
}
public void SharrFilter() {
progressBar.setVisible(true);
oldImg = imageView.getImage();
double[][] dx = {
{3, 10, 3},
{10, 0, -10},
{-3, -10, -3}
};
double[][] dy = {
{3, 0, -3},
{10, 0, -10},
{3, 0, -3}
};
DoubleMatrixFilter(imageView, dx, dy, "Фильтр Щарра");
progressBar.setVisible(false);
}
}

View File

@ -8,6 +8,7 @@
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Button?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.example.lab_1.ImageEditorController">
<top>
<MenuBar>
@ -19,9 +20,20 @@
<MenuItem text="Инверсия" onAction="#applyInversionFilter"/>
<MenuItem text="Оттенки серого" onAction="#GrayScaleFilter"/>
<MenuItem text="Сепия" onAction="#Sepia"/>
<MenuItem text="Увеличить яркость" onAction="#GetYarc"/>
<MenuItem text="Сдвиг" onAction="#Sdvig"/>
<MenuItem text="Серый мир" onAction="#grayWorld"/>
<MenuItem text="Автоуровни" onAction="#autoLevels"/>
<MenuItem text="Идеальный отражатель" onAction="#IDdealOtr" />
<MenuItem text="Медиана" onAction="#MedianFilter"/>
</Menu>
<Menu text="Матричные">
<!-- Пустое подменю -->
<MenuItem text="Тиснение" onAction="#EmbossFilter"/>
<MenuItem text="Разматие в движении" onAction="#goFilter" />
<MenuItem text="Разширение" onAction="#RazshirFilter" />
<MenuItem text="Сужение" onAction="#ErosionFilter"/>
<MenuItem text="Фильтр Собеля" onAction="#SobelFilter" />
<MenuItem text="Фильтр Щарра" onAction="#SharrFilter"/>
</Menu>
</Menu>
</MenuBar>
@ -32,4 +44,9 @@
<ProgressBar fx:id="progressBar" prefWidth="400"/>
</VBox>
</center>
<bottom>
<VBox alignment="CENTER" spacing="50" >
<Button onAction="#returnToOldImage">Вернуть к начальному состоянию</Button>
</VBox>
</bottom>
</BorderPane>

46
lab_2/.gitignore vendored Normal file
View File

@ -0,0 +1,46 @@
.gradle
shell.nix
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Kotlin ###
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

3
lab_2/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

17
lab_2/.idea/gradle.xml generated Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

6
lab_2/.idea/kotlinc.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="2.0.21" />
</component>
</project>

7
lab_2/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
lab_2/.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

53
lab_2/build.gradle.kts Normal file
View File

@ -0,0 +1,53 @@
import org.jetbrains.kotlin.gradle.utils.IMPLEMENTATION
plugins {
kotlin("jvm") version "2.0.21"
application
}
group = "org.exampl"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
val lwjglVersion = "3.3.3"
val lwjglNatives = "natives-linux" // Для NixOS используем стандартные Linux-нативы
dependencies {
testImplementation(kotlin("test"))
implementation(platform("org.lwjgl:lwjgl-bom:$lwjglVersion"))
implementation("org.lwjgl:lwjgl")
implementation("org.lwjgl:lwjgl-glfw")
implementation("org.lwjgl:lwjgl-opengl")
implementation("org.lwjgl:lwjgl-stb")
implementation("org.lwjgl:lwjgl-nanovg")
implementation("org.lwjgl:lwjgl-nfd")
implementation("org.lwjgl:lwjgl-openal")
runtimeOnly("org.lwjgl:lwjgl::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-glfw::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-opengl::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-stb::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-nanovg::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-nfd::$lwjglNatives")
runtimeOnly("org.lwjgl:lwjgl-openal::$lwjglNatives")
// JavaFX bindings
implementation("org.openjfx:javafx-controls:17")
implementation("org.openjfx:javafx-fxml:17")
implementation("org.openjfx:javafx-graphics:17")
}
application {
mainClass.set("org.exampl.MainKt")
}
tasks.test {
useJUnitPlatform()
}
kotlin {
jvmToolchain(21)
}

BIN
lab_2/cube_volume.raw Normal file

Binary file not shown.

1
lab_2/gradle.properties Normal file
View File

@ -0,0 +1 @@
kotlin.code.style=official

BIN
lab_2/gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Tue Apr 08 14:57:35 MSK 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
lab_2/gradlew vendored Executable file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
lab_2/gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,5 @@
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "lab_2"

View File

@ -0,0 +1,31 @@
package org.exampl
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
object Bin {
var X = 0
var Y = 0
var Z = 0
lateinit var array: ShortArray
fun readBIN(path: String) {
if (File(path).exists()) {
val buffer = ByteBuffer.wrap(File(path).readBytes()).order(ByteOrder.LITTLE_ENDIAN)
X = buffer.int
Y = buffer.int
Z = buffer.int
buffer.position(buffer.position() + 3 * Float.SIZE_BYTES) // Пропуск значений масштаба
val arraySize = X * Y * Z
array = ShortArray(arraySize)
for (i in 0 until arraySize) {
array[i] = buffer.short
}
}
}
}

View File

@ -0,0 +1,53 @@
package org.exampl
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.opengl.GL11.*
import javax.swing.JFileChooser
import javax.swing.filechooser.FileNameExtensionFilter
class Form1 {
private var loaded = false
var currentLayer = 0
private val bin = Bin
val view = View()
private var frameCount = 0
private var nextFPSUpdate = System.currentTimeMillis() + 1000
private fun displayFPS() {
if (System.currentTimeMillis() >= nextFPSUpdate) {
println("CT Visualizer (fps = $frameCount)")
nextFPSUpdate = System.currentTimeMillis() + 1000
frameCount = 0
}
frameCount++
}
private fun openFileDialog() {
val fileChooser = JFileChooser()
fileChooser.fileFilter = FileNameExtensionFilter("BIN Files", "bin")
val result = fileChooser.showOpenDialog(null)
if (result == JFileChooser.APPROVE_OPTION) {
val file = fileChooser.selectedFile
bin.readBIN(file.absolutePath)
view.setupView(800, 600) // Установите размеры окна
loaded = true
view.needReload = true // Убедимся, что текстура загружается сразу после выбора файла
}
}
fun run(window: Long) {
openFileDialog()
while (!glfwWindowShouldClose(window)) {
displayFPS()
glfwPollEvents()
if (loaded) {
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
view.drawQuads(currentLayer)
}
glfwSwapBuffers(window)
}
}
}

View File

@ -0,0 +1,56 @@
package org.exampl
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL11.*
import org.lwjgl.system.MemoryUtil.NULL
import kotlin.system.exitProcess
fun main() {
if (!glfwInit())
throw IllegalStateException("Unable to initialize GLFW")
glfwDefaultWindowHints()
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE)
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE)
val window = glfwCreateWindow(800, 600, "CT Visualizer", NULL, NULL)
if (window == NULL)
throw RuntimeException("Failed to create the GLFW window")
glfwSetFramebufferSizeCallback(window) { _: Long, width: Int, height: Int ->
glViewport(0, 0, width, height)
}
val form1 = Form1()
glfwSetKeyCallback(window) { _: Long, key: Int, _: Int, action: Int, _: Int ->
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
when (key) {
GLFW_KEY_LEFT -> {
if (form1.currentLayer > 0) {
form1.currentLayer--
form1.view.needReload = true
}
}
GLFW_KEY_RIGHT -> {
if (form1.currentLayer < Bin.Z - 1) {
form1.currentLayer++
form1.view.needReload = true
}
}
}
}
}
glfwMakeContextCurrent(window)
glfwSwapInterval(1)
glfwShowWindow(window)
GL.createCapabilities()
form1.run(window)
glfwTerminate()
exitProcess(0)
}

View File

@ -0,0 +1,49 @@
package org.exampl
import java.awt.Color
object TransferHelper {
private var min = -3100
private var max = 5000
fun setTF(newMin: Int, newMax: Int) {
min = newMin
max = newMax
}
fun transferFunction(value: Short): Color {
val k = value.toFloat().map(min.toFloat()..max.toFloat(), 0f..1f)
/*
0 -> black (0, 0, 0)
.25 -> blue (0, 0, f)
.5 -> green (0, f, 0)
.75 -> yellow (f, f, 0)
1 -> white (f, f, f)
*/
return when (k) {
in 0f..0.25f -> Color(0, 0, (k * 4 * 255).toInt())
in 0.25f..0.5f -> {
val g = k.map(0.25f..0.5f, 0f..255f).toInt()
Color(0, g, 255 - g)
}
in 0.5f..0.75f -> {
val r = k.map(0.5f..0.75f, 0f..255f).toInt()
Color(r, 255, 0)
}
in 0.75f..1f -> {
val b = k.map(0.75f..1f, 0f..255f).toInt()
Color(255, 255, b)
}
else -> throw IllegalArgumentException("$value not in range [$min..$max]")
}
}
fun Float.map(fromRange: ClosedRange<Float>, toRange: ClosedRange<Float>): Float {
if (fromRange.start == fromRange.endInclusive)
return (toRange.start + toRange.endInclusive) / 2
return (this - fromRange.start) * (toRange.endInclusive - toRange.start) /
(fromRange.endInclusive - fromRange.start) + toRange.start
}
}

View File

@ -0,0 +1,86 @@
package org.exampl
import org.lwjgl.opengl.GL11.*
import java.awt.image.BufferedImage
import java.nio.ByteBuffer
class View {
var needReload = false
fun setupView(width: Int, height: Int) {
glShadeModel(GL_SMOOTH)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, Bin.X.toDouble(), 0.0, Bin.Y.toDouble(), -1.0, 1.0)
glViewport(0, 0, width, height)
}
fun drawQuads(layerNumber: Int) {
if (needReload) {
generateTextureImage(layerNumber)
load2DTexture()
needReload = false
}
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, textureID)
glBegin(GL_QUADS)
glColor3f(1f, 1f, 1f)
glTexCoord2f(0f, 0f)
glVertex2f(0f, 0f)
glTexCoord2f(0f, 1f)
glVertex2f(0f, Bin.Y.toFloat())
glTexCoord2f(1f, 1f)
glVertex2f(Bin.X.toFloat(), Bin.Y.toFloat())
glTexCoord2f(1f, 0f)
glVertex2f(Bin.X.toFloat(), 0f)
glEnd()
glDisable(GL_TEXTURE_2D)
}
private lateinit var textureImage: BufferedImage
private var textureID: Int = 0
fun generateTextureImage(layerNumber: Int) {
textureImage = BufferedImage(Bin.X, Bin.Y, BufferedImage.TYPE_INT_ARGB)
for (x in 0 until Bin.X) {
for (y in 0 until Bin.Y) {
val pixelNumber = x + y * Bin.X + layerNumber * Bin.X * Bin.Y
val color = TransferHelper.transferFunction(Bin.array[pixelNumber])
textureImage.setRGB(x, y, color.rgb)
}
}
}
fun load2DTexture() {
textureID = glGenTextures()
glBindTexture(GL_TEXTURE_2D, textureID)
val pixels = IntArray(Bin.X * Bin.Y)
textureImage.getRGB(0, 0, Bin.X, Bin.Y, pixels, 0, Bin.X)
val pixelBuffer = ByteBuffer.allocateDirect(pixels.size * 4)
for (pixel in pixels) {
val r = (pixel shr 16) and 0xFF
val g = (pixel shr 8) and 0xFF
val b = pixel and 0xFF
val a = (pixel shr 24) and 0xFF
pixelBuffer.put(r.toByte()).put(g.toByte()).put(b.toByte()).put(a.toByte())
}
pixelBuffer.flip()
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Bin.X, Bin.Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelBuffer)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
}
}

BIN
lab_2/testdata.bin Normal file

Binary file not shown.