row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
10,144
|
Can u give me instruction in details how to set up firebase for my react native project?
|
affb68f39a89cefd05c9116728ac3719
|
{
"intermediate": 0.6830042600631714,
"beginner": 0.11079984903335571,
"expert": 0.2061959207057953
}
|
10,145
|
make some attachment points on which new edges-vertices can be snapped. spread all these attachment points all over canvas through the center of 3d matrix model. make this mvc menu appear and disappear when pointing throughou these attachmen point grid, to be able to press that addedge button and draw a new line to extend the actual wireframe. output only full properre modified and optimized code, without any shortages and cutoffs. analyze all possible functions extremely careful and if need optimize or adapt them appropriately and accordingly, by not ruinning the transformation animations and deviations. (if need make your own version of absolutely new code but with the same similar functionalities.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
1c5c01f17796e08c7f47e808659cd3d0
|
{
"intermediate": 0.30002614855766296,
"beginner": 0.36309120059013367,
"expert": 0.33688271045684814
}
|
10,146
|
im not usin androidx and i added some lines in block android. here:
apply plugin: "com.android.application"
apply plugin: "com.facebook.react"
import com.android.build.OutputFile
def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()
def expoDebuggableVariants = ['debug']
// Override `debuggableVariants` for expo-updates debugging
if (System.getenv('EX_UPDATES_NATIVE_DEBUG') == "1") {
react {
expoDebuggableVariants = []
}
}
/**
* This is the configuration block to customize your React Native Android app.
* By default you don't need to apply any configuration, just uncomment the lines you need.
*/
react {
entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android", "absolute"].execute(null, rootDir).text.trim())
reactNativeDir = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile()
hermesCommand = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/sdks/hermesc/%OS-BIN%/hermesc"
debuggableVariants = expoDebuggableVariants
/* Folders */
// The root of your project, i.e. where "package.json" lives. Default is '..'
// root = file("../")
// The folder where the react-native NPM package is. Default is ../node_modules/react-native
// reactNativeDir = file("../node_modules/react-native")
// The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen
// codegenDir = file("../node_modules/react-native-codegen")
// The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
// cliFile = file("../node_modules/react-native/cli.js")
/* Variants */
// The list of variants to that are debuggable. For those we're going to
// skip the bundling of the JS bundle and the assets. By default is just 'debug'.
// If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
// debuggableVariants = ["liteDebug", "prodDebug"]
/* Bundling */
// A list containing the node command and its flags. Default is just 'node'.
// nodeExecutableAndArgs = ["node"]
//
// The command to run when bundling. By default is 'bundle'
// bundleCommand = "ram-bundle"
//
// The path to the CLI configuration file. Default is empty.
// bundleConfig = file(../rn-cli.config.js)
//
// The name of the generated asset file containing your JS bundle
// bundleAssetName = "MyApplication.android.bundle"
//
// The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
// entryFile = file("../js/MyApplication.android.js")
//
// A list of extra flags to pass to the 'bundle' commands.
// See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
// extraPackagerArgs = []
/* Hermes Commands */
// The hermes compiler command to run. By default it is 'hermesc'
// hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
//
// The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
// hermesFlags = ["-O", "-output-source-map"]
}
// Override `hermesEnabled` by `expo.jsEngine`
ext {
hermesEnabled = (findProperty('expo.jsEngine') ?: "hermes") == "hermes"
}
/**
* Set this to true to create four separate APKs instead of one,
* one for each native architecture. This is useful if you don't
* use App Bundles (https://developer.android.com/guide/app-bundle/)
* and want to have separate APKs to upload to the Play Store.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Set this to true to Run Proguard on Release builds to minify the Java bytecode.
*/
def enableProguardInReleaseBuilds = (findProperty('android.enableProguardInReleaseBuilds') ?: false).toBoolean()
/**
* The preferred build flavor of JavaScriptCore (JSC)
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Private function to get the list of Native Architectures you want to build.
* This reads the value from reactNativeArchitectures in your gradle.properties
* file and works together with the --active-arch-only flag of react-native run-android.
*/
def reactNativeArchitectures() {
def value = project.getProperties().get("reactNativeArchitectures")
return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}
android {
compile 'com.google.firebase:firebase-core:16.0.6'
compile 'com.google.firebase:firebase-auth:16.0.2'
compile 'com.google.firebase:firebase-database:16.0.6'
ndkVersion rootProject.ext.ndkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
namespace 'com.whiterose.whiteroseapp'
defaultConfig {
applicationId 'com.whiterose.whiteroseapp'
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include (*reactNativeArchitectures())
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
shrinkResources (findProperty('android.enableShrinkResourcesInReleaseBuilds')?.toBoolean() ?: false)
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
// Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
defaultConfig.versionCode * 1000 + versionCodes.get(abi)
}
}
}
}
// Apply static values from `gradle.properties` to the `android.packagingOptions`
// Accepts values in comma delimited lists, example:
// android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini
["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop ->
// Split option: 'foo,bar' -> ['foo', 'bar']
def options = (findProperty("android.packagingOptions.$prop") ?: "").split(",");
// Trim all elements in place.
for (i in 0..<options.size()) options[i] = options[i].trim();
// `[] - ""` is essentially `[""].filter(Boolean)` removing all empty strings.
options -= ""
if (options.length > 0) {
println "android.packagingOptions.$prop += $options ($options.length)"
// Ex: android.packagingOptions.pickFirsts += '**/SCCS/**'
options.each {
android.packagingOptions[prop] += it
}
}
}
dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")
def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";
def frescoVersion = rootProject.ext.frescoVersion
// If your app supports Android versions before Ice Cream Sandwich (API level 14)
if (isGifEnabled || isWebpEnabled) {
implementation("com.facebook.fresco:fresco:${frescoVersion}")
implementation("com.facebook.fresco:imagepipeline-okhttp3:${frescoVersion}")
}
if (isGifEnabled) {
// For animated gif support
implementation("com.facebook.fresco:animated-gif:${frescoVersion}")
}
if (isWebpEnabled) {
// For webp support
implementation("com.facebook.fresco:webpsupport:${frescoVersion}")
if (isWebpAnimatedEnabled) {
// Animated webp support
implementation("com.facebook.fresco:animated-webp:${frescoVersion}")
}
}
implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0")
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}")
if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
} else {
implementation jscFlavor
}
}
apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
applyNativeModulesAppBuildGradle(project)
is it correcr?
|
ab334fb470502f13257ade628aac7257
|
{
"intermediate": 0.33279454708099365,
"beginner": 0.4263016879558563,
"expert": 0.24090375006198883
}
|
10,147
|
i tried to set up firebase in my android app, downloaded google-services.json, added it to the same folder where android folder is. what should i do next? or its wrong?
|
f0f0bb790ee3feef0e29f397d6db68f9
|
{
"intermediate": 0.5367705821990967,
"beginner": 0.20660530030727386,
"expert": 0.2566240429878235
}
|
10,148
|
make some attachment points on which new edges-vertices can be snapped. spread all these attachment points all over canvas through the center of 3d matrix model. make this mvc menu appear and disappear when pointing throughou these attachmen point grid, to be able to press that addedge button and draw a new line to extend the actual wireframe. output only full properre modified and optimized code, without any shortages and cutoffs. analyze all possible functions extremely careful and if need optimize or adapt them appropriately and accordingly, by not ruinning the transformation animations and deviations. (if need make your own version of absolutely new code but with the same similar functionalities.):
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<meta name=“viewport” content=“width=device-width, initial-scale=1.0”>
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class=“vmc-menu” id=“vmc-menu”>
<label>Vertex X: <input type=“number” id=“vmc-vertex-x” step=“0.1”></label>
<label>Vertex Y: <input type=“number” id=“vmc-vertex-y” step=“0.1”></label>
<label>Vertex Z: <input type=“number” id=“vmc-vertex-z” step=“0.1”></label>
<button id=“add-edge”>Add Edge</button>
<button id=“remove-edge”>Remove Edge</button>
</div>
<div class=“red-dot” id=“red-dot”></div>
<script>
const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
eebbeb40f677e7e15073b6edf69fab77
|
{
"intermediate": 0.3349653482437134,
"beginner": 0.3765048086643219,
"expert": 0.2885299026966095
}
|
10,149
|
make some attachment points on which new edges-vertices can be snapped. spread all these attachment points all over canvas through the center of 3d matrix model. make this mvc menu appear and disappear when pointing throughou these attachmen point grid, to be able to press that addedge button and draw a new line to extend the actual wireframe. output only full properre modified and optimized code, without any shortages and cutoffs. analyze all possible functions extremely careful and if need optimize or adapt them appropriately and accordingly, by not ruinning the transformation animations and deviations. (if need make your own version of absolutely new code but with the same similar functionalities.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
z-index:2;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const redDot = document.getElementById('red-dot');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
const updateMouseMove = (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
}
canvas.addEventListener('mousemove', updateMouseMove);
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
const updateVertexValue = (event, indexToUpdate) => {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
};
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
31a95239c54ad2d0d6aec2ebec4b91c8
|
{
"intermediate": 0.27943044900894165,
"beginner": 0.3430544435977936,
"expert": 0.37751510739326477
}
|
10,150
|
make some attachment points on which new edges-vertices can be snapped. spread all these attachment points all over canvas through the center of 3d matrix model. make this mvc menu appear and disappear when pointing throughou these attachmen point grid, to be able to press that addedge button and draw a new line to extend the actual wireframe. output only full properre modified and optimized code, without any shortages and cutoffs. analyze all possible functions extremely careful and if need optimize or adapt them appropriately and accordingly, by not ruinning the transformation animations and deviations. (if need make your own version of absolutely new code but with the same similar functionalities.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
z-index:2;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const redDot = document.getElementById('red-dot');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
const updateMouseMove = (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
}
canvas.addEventListener('mousemove', updateMouseMove);
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
const updateVertexValue = (event, indexToUpdate) => {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
};
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
3493bf373fcc14ac8b80c14f82ac0d89
|
{
"intermediate": 0.27943044900894165,
"beginner": 0.3430544435977936,
"expert": 0.37751510739326477
}
|
10,151
|
Change that:
@everywhere function mutate(selected_players, position_vectors_list, probability)
selected_players_matrix = copy(selected_players)
function select_random_player(idx_list, selected_players)
while true
random_idx = rand(idx_list)
if ismissing(selected_players) || !(random_idx in selected_players)
return random_idx
end
end
end
for i in 1:size(selected_players_matrix)[1]
for pos_idx in 1:length(position_vectors_list)
if rand() <= probability
selected_players_matrix[i, pos_idx] = select_random_player(position_vectors_list[pos_idx],
selected_players_matrix[i, :])
end
end
end
return selected_players_matrix
end
so it would fit a DataFrame with 1 column containing vectors.
|
72baf2fd18f146445ec3b7e70b084839
|
{
"intermediate": 0.3977644741535187,
"beginner": 0.3365747332572937,
"expert": 0.26566076278686523
}
|
10,152
|
написать программу на с++, чтобы сортировка вставками и сортировка bogosort
Входные данные программы - файл с целыми числами, в количестве 10 штук в отдельных строках (numbers.txt).
Выходные данные программы - файл с теми же 10 отсортированными числами в отдельных строках (otsorted_numbers.txt). В консоль выводится количество итераций и затраченное время на сортировку.
|
1ce0cad23a9aaa7faceb723f307acd95
|
{
"intermediate": 0.30306944251060486,
"beginner": 0.4216355085372925,
"expert": 0.27529507875442505
}
|
10,153
|
i need to set up firebase to my android app react native, i added some lines to build.gradle file. is it right?
apply plugin: "com.android.application"
apply plugin: "com.facebook.react"
import com.android.build.OutputFile
def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()
def expoDebuggableVariants = ['debug']
// Override `debuggableVariants` for expo-updates debugging
if (System.getenv('EX_UPDATES_NATIVE_DEBUG') == "1") {
react {
expoDebuggableVariants = []
}
}
/**
* This is the configuration block to customize your React Native Android app.
* By default you don't need to apply any configuration, just uncomment the lines you need.
*/
react {
entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android", "absolute"].execute(null, rootDir).text.trim())
reactNativeDir = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile()
hermesCommand = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/sdks/hermesc/%OS-BIN%/hermesc"
debuggableVariants = expoDebuggableVariants
/* Folders */
// The root of your project, i.e. where "package.json" lives. Default is '..'
// root = file("../")
// The folder where the react-native NPM package is. Default is ../node_modules/react-native
// reactNativeDir = file("../node_modules/react-native")
// The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen
// codegenDir = file("../node_modules/react-native-codegen")
// The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
// cliFile = file("../node_modules/react-native/cli.js")
/* Variants */
// The list of variants to that are debuggable. For those we're going to
// skip the bundling of the JS bundle and the assets. By default is just 'debug'.
// If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
// debuggableVariants = ["liteDebug", "prodDebug"]
/* Bundling */
// A list containing the node command and its flags. Default is just 'node'.
// nodeExecutableAndArgs = ["node"]
//
// The command to run when bundling. By default is 'bundle'
// bundleCommand = "ram-bundle"
//
// The path to the CLI configuration file. Default is empty.
// bundleConfig = file(../rn-cli.config.js)
//
// The name of the generated asset file containing your JS bundle
// bundleAssetName = "MyApplication.android.bundle"
//
// The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
// entryFile = file("../js/MyApplication.android.js")
//
// A list of extra flags to pass to the 'bundle' commands.
// See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
// extraPackagerArgs = []
/* Hermes Commands */
// The hermes compiler command to run. By default it is 'hermesc'
// hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
//
// The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
// hermesFlags = ["-O", "-output-source-map"]
}
// Override `hermesEnabled` by `expo.jsEngine`
ext {
hermesEnabled = (findProperty('expo.jsEngine') ?: "hermes") == "hermes"
}
/**
* Set this to true to create four separate APKs instead of one,
* one for each native architecture. This is useful if you don't
* use App Bundles (https://developer.android.com/guide/app-bundle/)
* and want to have separate APKs to upload to the Play Store.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Set this to true to Run Proguard on Release builds to minify the Java bytecode.
*/
def enableProguardInReleaseBuilds = (findProperty('android.enableProguardInReleaseBuilds') ?: false).toBoolean()
/**
* The preferred build flavor of JavaScriptCore (JSC)
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Private function to get the list of Native Architectures you want to build.
* This reads the value from reactNativeArchitectures in your gradle.properties
* file and works together with the --active-arch-only flag of react-native run-android.
*/
def reactNativeArchitectures() {
def value = project.getProperties().get("reactNativeArchitectures")
return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}
android {
//IM NOT SURE
compile 'com.google.firebase:firebase-core:16.0.6'
compile 'com.google.firebase:firebase-auth:16.0.2'
compile 'com.google.firebase:firebase-database:16.0.6'
ndkVersion rootProject.ext.ndkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
namespace 'com.whiterose.whiteroseapp'
defaultConfig {
applicationId 'com.whiterose.whiteroseapp'
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include (*reactNativeArchitectures())
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
shrinkResources (findProperty('android.enableShrinkResourcesInReleaseBuilds')?.toBoolean() ?: false)
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
// Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
defaultConfig.versionCode * 1000 + versionCodes.get(abi)
}
}
}
}
// Apply static values from `gradle.properties` to the `android.packagingOptions`
// Accepts values in comma delimited lists, example:
// android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini
["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop ->
// Split option: 'foo,bar' -> ['foo', 'bar']
def options = (findProperty("android.packagingOptions.$prop") ?: "").split(",");
// Trim all elements in place.
for (i in 0..<options.size()) options[i] = options[i].trim();
// `[] - ""` is essentially `[""].filter(Boolean)` removing all empty strings.
options -= ""
if (options.length > 0) {
println "android.packagingOptions.$prop += $options ($options.length)"
// Ex: android.packagingOptions.pickFirsts += '**/SCCS/**'
options.each {
android.packagingOptions[prop] += it
}
}
}
dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")
implementation platform('com.google.firebase:firebase-bom:29.0.0')
implementation 'com.google.firebase:firebase-core'
implementation 'com.google.firebase:firebase-auth'
implementation 'com.google.firebase:firebase-database'
def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";
def frescoVersion = rootProject.ext.frescoVersion
// If your app supports Android versions before Ice Cream Sandwich (API level 14)
if (isGifEnabled || isWebpEnabled) {
implementation("com.facebook.fresco:fresco:${frescoVersion}")
implementation("com.facebook.fresco:imagepipeline-okhttp3:${frescoVersion}")
}
if (isGifEnabled) {
// For animated gif support
implementation("com.facebook.fresco:animated-gif:${frescoVersion}")
}
if (isWebpEnabled) {
// For webp support
implementation("com.facebook.fresco:webpsupport:${frescoVersion}")
if (isWebpAnimatedEnabled) {
// Animated webp support
implementation("com.facebook.fresco:animated-webp:${frescoVersion}")
}
}
implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0")
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}")
if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
} else {
implementation jscFlavor
}
}
apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'
|
ff4136d1bd4e59d6998cf7cc5c7dc383
|
{
"intermediate": 0.42581695318222046,
"beginner": 0.35849106311798096,
"expert": 0.21569198369979858
}
|
10,154
|
Project:
AI Toolchain is a collection of tools for quickly building and deploying machine learning models for various use cases. Currently, the toolchain includes a text translation model, and more models may be added in the future. It abstracts the dirty details of how a model works similar to Huggingface and gives a clean API that you can orchestrate at aenter code here BFF level.
Features to be implemented
Abstract the layer of deployment for AI Tools. Anyone should be easily add a new model to the stack without thinking about deployments. We should be able to deploy AI Tools in such a way where each model (every model can be packaged as a container) should be independently scalable. As a user, I should be able to access APIs associated with any model.
Acceptance Criteria
Document to add a new model and test it on local
Document to deploy a new model
Document to accesss APIs asscoiated with model
|
ee6f876dd9d5be47f1451ddbf3ed50d8
|
{
"intermediate": 0.6029272079467773,
"beginner": 0.17916300892829895,
"expert": 0.21790972352027893
}
|
10,155
|
Using HTMX and the Fetch API, how would I fetch items from the Facebook Pages Feed API?
|
6804055da34972b93856cf96b464b2f3
|
{
"intermediate": 0.8316466808319092,
"beginner": 0.05487546697258949,
"expert": 0.11347782611846924
}
|
10,156
|
crete a coherrent plan like 1-a 1-b for this ecommerce app reuiğrements: Postgresql
n-tier architecture
For all Spring API endpoints Postman and SwaggerUI will be used
React for Front-End
There will be users and admin
There will be screens for log-in and register
To be able to buy a product user needs to have an account
There will be a class for shipping with fake addresses
Users can list their previous shoppings
There will be stocks for products and when a user buys a products the stock will decrease
There will be a language toggle at te top of the page Turkish or English
If a user makes more than one wrong logins the system will be locked
Admin can add product to the system
There are two roles user(n) and admin(n). In the role management system many to many
ıf a user is not registired he will need to register first with thier mail address and password. After registration an activation mail will be sent
User can add a product to the basket
After a product bought, there will be a receipt sent to the users mail adress.
You can see how many products are there in the product page
While a user buy a product ask if I allow the creditcard info to be stored in the database. If a user choose to click the box the credit card data will be stored in the database
User-Credit card = OneToMany
User will be able to toggle the language clicking the buttons on top of the page. For this Resource Bundle (ValidationMessages.properties and ValidationMessages_tr.properties)
Logging for wrong log in attempts in database
|
bbe25da6ee5710d0a9398189b0fbe0e6
|
{
"intermediate": 0.8018503785133362,
"beginner": 0.11788848042488098,
"expert": 0.08026114851236343
}
|
10,157
|
make some attachment points on which new edges-vertices can be snapped. spread all these attachment points all over canvas through the center of 3d matrix model. make this mvc menu appear and disappear when pointing throughou these attachmen point grid, to be able to press that addedge button and draw a new line to extend the actual wireframe. output only full properre modified and optimized code, without any shortages and cutoffs. analyze all possible functions extremely careful and if need optimize or adapt them appropriately and accordingly, by not ruinning the transformation animations and deviations. (if need make your own version of absolutely new code but with the same similar functionalities.):
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<meta name=“viewport” content=“width=device-width, initial-scale=1.0”>
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class=“vmc-menu” id=“vmc-menu”>
<label>Vertex X: <input type=“number” id=“vmc-vertex-x” step=“0.1”></label>
<label>Vertex Y: <input type=“number” id=“vmc-vertex-y” step=“0.1”></label>
<label>Vertex Z: <input type=“number” id=“vmc-vertex-z” step=“0.1”></label>
<button id=“add-edge”>Add Edge</button>
<button id=“remove-edge”>Remove Edge</button>
</div>
<div class=“red-dot” id=“red-dot”></div>
<script>
const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
14c55b7f40fb08f63bf0539475bf6c16
|
{
"intermediate": 0.3349653482437134,
"beginner": 0.3765048086643219,
"expert": 0.2885299026966095
}
|
10,158
|
I want to create a brand new, extremely useful and innovative uptime and status management service with a huge range of features and things that set it apart from competition, for web only. IT SHOULD NOT BE GENERIC. It will be fully open source on GitHub. Based on this, please create a. a unique, memorable name for the service and the repo, b. a description for the repo and c. a full possible file structure for the GitHub repo that will host the service. Don’t leave any folder or file out, include EVERYTHING, down to each individual file. Do not leave any folders empty.
|
abf6a64bd2e04d3a12ae63c4584d4740
|
{
"intermediate": 0.30697423219680786,
"beginner": 0.33593788743019104,
"expert": 0.3570878207683563
}
|
10,159
|
let dist be a
|
�
|
×
|
�
|
{\displaystyle |V|\times |V|} массив минимальных расстояний, инициализированный как
∞\infty (бесконечность)
let next be a
|
�
|
×
|
�
|
{\displaystyle |V|\times |V|} массив индексов вершин, инициализированный null
procedure FloydWarshallWithPathReconstruction() is
for each edge (u, v) do
dist[u][v] ← w(u, v) // Вес ребра (u, v)
next[u][v] ← v
for each vertex v do
dist[v][v] ← 0
next[v][v] ← v
for k from 1 to |V| do // стандартная реализация алгоритма Флойда–Уоршелла
for i from 1 to |V|
for j from 1 to |V|
if dist[i][j] > dist[i][k] + dist[k][j] then
dist[i][j] ← dist[i][k] + dist[k][j]
next[i][j] ← next[i][k]
procedure Path(u, v)
if next[u][v] = null then
return []
path = [u]
while u ≠ v
u ← next[u][v]
path.append(u)
return path Вот всевдокод алгоритма поиска кратчайшего расстояния флойд воршала. МОжешь написать этот алгоритм на языке R
|
dd8a45784aafcee1f85b8e348422be36
|
{
"intermediate": 0.2873055934906006,
"beginner": 0.43276333808898926,
"expert": 0.27993112802505493
}
|
10,160
|
Hi,
Change the following code to this operation of sorting wit bitonicSort, The kernels to be written should sort the contents of the file datSeq1M.bin in 10 iteration
steps. In iteration 1, 1024 subsequences of 1024 integer values are to be sorted in parallel. In
iteration 2, 512 subsequences of 2048 integer values are to be sorted in parallel based on the
merging of the previously sorted halves. And so on and so forth, until iteration 10 is reached,
where 2 previously sorted subsequences of 512K values are merged, yielding the whole sorted
sequence.
Assume that the values of the whole sequence, when stored in memory, are organized as the
elements of 1024 X 1024 matrix. The threads in a block thread process successive matrix rows
This is the code that has to be changed:
/**
* Hugo Leal (93059) and Luísa Amaral (93001), June 2022
* Matrices are processed by rows
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <libgen.h>
#include <unistd.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include "common.h"
#include <cuda_runtime.h>
/* allusion to internal functions */
static void calculateDeterminantCPU(double *matrix, double *determinant, int size);
__global__ void calculateDeterminantGPUKernel(double *mat, double *determinants, int n);
static double get_delta_time(void);
static void printUsage(char *cmdName);
int parseArgs(int argc, char* argv[], char *filenames[]);
/**
* main program
*/
int main(int argc, char **argv)
{
printf("%s Starting...\n", argv[0]);
if (sizeof(unsigned int) != (size_t)4)
return 1; // it fails with prejudice if an integer does not have 4 bytes
/* set up the device */
int dev = 0;
cudaDeviceProp deviceProp;
CHECK(cudaGetDeviceProperties(&deviceProp, dev));
printf("Using Device %d: %s\n", dev, deviceProp.name);
CHECK(cudaSetDevice(dev));
int nArgs = (int)(argc - 1) / 2 + 50; /* size of the array of file names */
char *fileNames[nArgs]; /* Stores the provided file names */
memset(fileNames, 0, nArgs); /* Initializes the array with zeros */
parseArgs(argc, argv, fileNames); /* parse command line arguments */
int num, size;
size_t matSize, matAreaSize;
size_t numDet;
double *mat; /* stores the matrices coeficients on host side */
double *mat_device; /* stores the matrices coeficients on device side */
double *det; /* used to initialize determinants data on host side */
double *det_device; /* stores the determinants on device side */
double *det_cpu; /* stores the determinants calculated with CPU kernel */
double *new_det; /* stores the determinants from device side*/
/* Open file */
FILE *f;
f = fopen(fileNames[0], "rb");
if (!f)
{
printf("Error opening file %s\n", fileNames[0]);
exit(EXIT_FAILURE);
}
printf("File '%s'\n", fileNames[0]); //only the first file is parsed
if(!fread(&num, sizeof(int), 1, f)) // num of matrices in file
{
printf("Error reading from file %s\n", fileNames[0]);
exit(EXIT_FAILURE);
}
printf("Number of matrices to be read = %d\n", num);
if(!fread(&size, sizeof(int), 1, f)) // size of each matrix
{
printf("Error reading from file %s\n", fileNames[0]);
exit(EXIT_FAILURE);
}
printf("Matrices order = %d\n\n", size);
/* create memory areas in host and device memory where the coefficients will be stored */
matSize = (size_t)size * (size_t)size * sizeof(double);
matAreaSize = (size_t)num * matSize;
numDet = (size_t)num * sizeof(double);
if ((matAreaSize + numDet) > (size_t)1.3e9)
{
fprintf(stderr, "The GeForce GTX 1660 Ti cannot handle more than 5GB of memory!\n");
exit(1);
}
mat = (double *)malloc(matAreaSize);
det = (double *)malloc(numDet);
CHECK(cudaMalloc((void **)&mat_device, matAreaSize));
CHECK(cudaMalloc((void **)&det_device, numDet));
/* initialize the host data */
for (int j = 0; j < num * size * size; j++)
{
char bytes[8];
if(!fread(&bytes, sizeof(double), 1, f))
{
printf("Error reading from file %s\n", fileNames[0]);
exit(EXIT_FAILURE);
}
double d = *((double *)bytes);
mat[j] = d;
}
fclose(f);
for(int j= 0; j < num; j++) {
det[j] = 1;
}
/* copy the host data to the device memory */
(void) get_delta_time ();
CHECK (cudaMemcpy (mat_device, mat, matAreaSize, cudaMemcpyHostToDevice));
CHECK (cudaMemcpy (det_device, det, numDet, cudaMemcpyHostToDevice));
printf ("The transfer of %ld bytes from the host to the device took %.3e seconds\n",
(long) matAreaSize + (long) numDet, get_delta_time ());
/* run the computational kernel */
unsigned int gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ;
blockDimX = size;
blockDimY = 1;
blockDimZ = 1;
gridDimX = num;
gridDimY = 1;
gridDimZ = 1;
dim3 grid (gridDimX, gridDimY, gridDimZ);
dim3 block (blockDimX, blockDimY, blockDimZ);
(void) get_delta_time ();
calculateDeterminantGPUKernel<<<grid, block>>>(mat_device, det_device, size);
CHECK (cudaDeviceSynchronize ()); // wait for kernel to finish
CHECK (cudaGetLastError ()); // check for kernel errors
printf("The CUDA kernel <<<(%d,%d,%d), (%d,%d,%d)>>> took %.3e seconds to run\n",
gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, get_delta_time ());
/* copy kernel result back to host side */
new_det = (double *) malloc (numDet);
(void) get_delta_time ();
CHECK (cudaMemcpy (new_det, det_device, numDet, cudaMemcpyDeviceToHost));
printf ("The transfer of %ld bytes from the device to the host took %.3e seconds\n",
(long) numDet, get_delta_time ());
/* free device global memory */
CHECK(cudaFree(mat_device));
CHECK(cudaFree(det_device));
/* reset the device */
CHECK(cudaDeviceReset());
/* compute the determinants on the CPU */
det_cpu = (double *)malloc(numDet);
(void) get_delta_time ();
for(int i = 0; i < num; i++)
{
det_cpu[i] = 1;
calculateDeterminantCPU(mat + (i*size*size), &det_cpu[i], size);
}
printf("The single threaded cpu kernel took %.3e seconds to run \n",get_delta_time ());
for(int i = 0; i < num; i++) {
printf("\nDeterminant of matrix %d GPU: %.3E CPU: %.3E\n", i+1, new_det[i], det_cpu[i]);
}
free(mat);
free(det);
free(new_det);
exit(EXIT_SUCCESS);
return 0;
}
/**
* \brief Method calculateDeterminantGPUKernel.
*
* Its role is to calculate the determinants of the matrix using a GPU
*
*
* \param mat pointer to the matrix coefficients
* \param determinants pointer to struct that holds the calculated determinants
* \param n order of matrix
*/
__global__ void calculateDeterminantGPUKernel(double *mat, double *determinants, int n)
{
int bkx = blockIdx.x + gridDim.x * blockIdx.y + gridDim.x * gridDim.y * blockIdx.z;
int pos = bkx * n * n; // point to the first coefficient of the current matrix
mat += pos;
bool reverseSignal = false;
double aux;
int idx;
idx = threadIdx.x + blockDim.x * threadIdx.y + blockDim.x * blockDim.y * threadIdx.z;
double det;
for (int i = 0; i <= idx; i++) // each loop has a smaller matrix to process (submatrix)
{
// in case of a 0 in a diagonal
if (mat[(i * n + i)] == 0) // test diagonal cell in current row
{
bool allNull = true;
for (int j = i + 1; j < n; j++)
{
if (mat[(i + j*n)] != 0)
{
// swap rows
aux = mat[i*n+idx];
mat[i*n+idx] = mat[j*n + idx];
mat[j*n + idx] = aux;
__syncthreads();
reverseSignal = !reverseSignal;
allNull = false;
}
}
// if the matrix contains a full column of zeros, anywhere in the matrix, the determinant will be 0
if (allNull)
{
determinants[bkx] = 0;
break;
}
}
double mul;
for (int k = i + 1; k < n; k++)
{
mul = (mat[(k + n*i)] / mat[(i + i * n)]);
__syncthreads();
mat[(k + n*idx)] -= mul * mat[i + n*idx];
}
if(i == idx) {
// calculate the determinant by multiplying the diagonal elements
det = mat[idx*n + idx];
determinants[bkx] *= det;
if (reverseSignal)
{
determinants[bkx] *= -1;
reverseSignal = false;
}
}
}
}
/**
* \brief Method calculateDeterminantCPU.
*
* Its role is to calculate the determinant of a matrix
*
*
* \param matrix pointer to the memory region with the matrix coefficients
* \param determinant pointer that holds the calculated determinant
* \param size order of the matrix
*/
static void calculateDeterminantCPU(double *matrix, double *determinant, int size)
{
bool reverseSignal = false;
for (int i = 0; i < size - 1; i++)
{
if (matrix[i * size + i] == 0)
{
bool allNull = true;
for (int j = i + 1; j < size; j++)
{
if (matrix[j * size + i] != 0)
{
// swap rows
int aux;
for (int k = 0; k < size; k++)
{
aux = matrix[(i-1) * size + k];
matrix[(i-1) * size + k] = matrix[(j-1) * size + k];
matrix[(j-1) * size + k] = aux;
}
reverseSignal = !reverseSignal;
allNull = false;
}
}
// if the matrix contains a full column of zeros, anywhere in the matrix, the determinant will be 0
if (allNull)
{
*determinant = 0;
return;
}
}
double aux;
for (int k = i + 1; k < size; k++)
{
aux = (matrix[i * size + k] / matrix[i * size + i]);
for (int j = 0; j < size; j++)
{
matrix[j * size + k] -= aux * matrix[j * size + i];
}
}
}
double prod = 1;
for (int i = 0; i < size; i++)
{
prod *= matrix[i * size + i];
}
if(reverseSignal) {
prod *= -1;
}
*determinant = prod;
}
/**
* \brief parseArgs function.
*
* \param argc number of words of the command line
* \param argv list of words of the command line
* \param filenames pointer to store names of files
*
* \return status of operation
*/
int parseArgs(int argc, char* argv[], char *filenames[])
{
/* process command line options */
int opt; /* selected option */
// char *fName = "no name"; /* file name (initialized to "no name" by default) */
int cnt = 0;
do
{
switch ((opt = getopt(argc, argv, "f:n:h")))
{
case 'f': /* file name */
if (optarg[0] == '-')
{
fprintf(stderr, "%s: file name is missing\n", basename(argv[0]));
printUsage(basename(argv[0]));
return EXIT_FAILURE;
}
filenames[cnt] = optarg;
cnt++;
break;
case 'h': /* help mode */
printUsage(basename(argv[0]));
return EXIT_SUCCESS;
case '?': /* invalid option */
fprintf(stderr, "%s: invalid option\n", basename(argv[0]));
printUsage(basename(argv[0]));
return EXIT_FAILURE;
case -1:
break;
}
} while (opt != -1);
if (argc == 1)
{
fprintf(stderr, "%s: invalid format\n", basename(argv[0]));
printUsage(basename(argv[0]));
return EXIT_FAILURE;
}
/* that's all */
return EXIT_SUCCESS;
} /* end of parseArgs */
/**
* \brief Print command usage.
*
* A message specifying how the program should be called is printed.
*
* \param cmdName string with the name of the command
*/
void printUsage(char *cmdName)
{
fprintf(stderr, "\nSynopsis: %s OPTIONS [filename / positive number]\n"
" OPTIONS:\n"
" -h --- print this help\n"
" -f --- filename\n",
cmdName);
}
static double get_delta_time(void)
{
static struct timespec t0,t1;
t0 = t1;
if(clock_gettime(CLOCK_MONOTONIC,&t1) != 0)
{
perror("clock_gettime");
exit(1);
}
return (double)(t1.tv_sec - t0.tv_sec) + 1.0e-9 * (double)(t1.tv_nsec - t0.tv_nsec);
}
|
7b179a6b85804cd1cca1bf5ebeb96a6c
|
{
"intermediate": 0.4926374554634094,
"beginner": 0.34291818737983704,
"expert": 0.16444431245326996
}
|
10,161
|
i need to create function that allows me to add users in db firebase react native
|
91d0c2d1c9efb9161a87220d5a733722
|
{
"intermediate": 0.7324174642562866,
"beginner": 0.14496323466300964,
"expert": 0.12261933833360672
}
|
10,162
|
Thanks. Unfortunately the hotkey did not work when CTRL ALT F10 was pressed, although the hotkey itself was activated. Could you debug and edit the code so it will operate as expected?
|
8b872297aebe0e7d7d34072b43add6e1
|
{
"intermediate": 0.5146004557609558,
"beginner": 0.23020769655704498,
"expert": 0.2551918923854828
}
|
10,163
|
I want to create a brand new, extremely useful and innovative uptime and status management service with a huge range of features and things that set it apart from competition. The service is in the form of a self hosted web app. IT SHOULD NOT BE GENERIC. It will be fully open source on GitHub. Based on this, please create a. a unique, memorable name for the service and the repo, b. a description for the repo and c. a full possible file structure for the GitHub repo that will host the service. Don’t leave any folder or file out, include EVERYTHING, down to each individual file. Do not leave any folders empty.
|
74f982760717ca1dcc334641dfa89070
|
{
"intermediate": 0.350423663854599,
"beginner": 0.30937591195106506,
"expert": 0.3402003347873688
}
|
10,164
|
I want to create a brand new, extremely useful and innovative uptime and status management service with a huge range of features and things that set it apart from competition. The service is in the form of a self hosted web app. IT SHOULD NOT BE GENERIC. It will be fully open source on GitHub. Based on this, please create a. a unique, memorable name for the service and the repo, b. a description for the repo and c. a full possible file structure for the GitHub repo that will host the service. Don’t leave any folder or file out, include EVERYTHING, down to each individual file. Do not leave any folders empty.
|
6250c4cca8c01205074cf0a605451d13
|
{
"intermediate": 0.3539215624332428,
"beginner": 0.305996298789978,
"expert": 0.34008219838142395
}
|
10,165
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
markets = binance_futures.load_markets()
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_time()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 44640)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 44640)
def order_execution(symbol, signal, step_size, leverage):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Round the price variable
try:
price = round_step_size(price, step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
return
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Set take profit and stop loss prices
# Set take profit and stop loss prices
if signal == 'buy':
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
take_profit_price = round_step_size(price * (1 + take_profit_percentage / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - stop_loss_percentage / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
take_profit_price = None
stop_loss_price = None
else:
take_profit_price = None
stop_loss_price = None
else:
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
take_profit_price = round_step_size(price * (1 - take_profit_percentage / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + stop_loss_percentage / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
take_profit_price = None
stop_loss_price = None
else:
take_profit_price = None
stop_loss_price = None
# Place order
order_params = {
"side": "BUY" if signal == "buy" else "SELL",
"type": order_type,
"positionSide": position_side,
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"reduceOnly": False,
"newOrderRespType": "RESULT",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": 100
}
try:
order_params['symbol'] = symbol
response = binance_futures.fapiPrivatePostOrder(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(0.1)
|
eebd2c228454a0baec7c4f00dd0c1417
|
{
"intermediate": 0.5031484961509705,
"beginner": 0.33535489439964294,
"expert": 0.1614965945482254
}
|
10,166
|
Hello
|
6b5d3499ea49f448ec07216e1ccad054
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
10,167
|
I want to create a brand new, extremely useful and innovative uptime and status management service with a huge range of features and things that set it apart from competition. The service is in the form of a self hosted web app. IT SHOULD NOT BE GENERIC. It will be fully open source on GitHub. Based on this, please create a. a unique, memorable name for the service and the repo, b. a description for the repo and c. a full possible file structure for the GitHub repo that will host the service. Don’t leave any folder or file out, include EVERYTHING, down to each individual file. Do not leave any folders empty.
|
b70758acc721ce78c46e31dab32caa7d
|
{
"intermediate": 0.3539215624332428,
"beginner": 0.305996298789978,
"expert": 0.34008219838142395
}
|
10,168
|
I want to create a brand new, extremely useful and innovative uptime and status management service with a huge range of features and things that set it apart from competition. The service is in the form of a self hosted web app. IT SHOULD NOT BE GENERIC. It will be fully open source on GitHub. Based on this, please create a. a unique, memorable name for the service and the repo, b. a description for the repo and c. a full possible file structure for the GitHub repo that will host the service. Don’t leave any folder or file out, include EVERYTHING, down to each individual file. Do not leave any folders empty.
|
98bfdf3cf3e1480eb975278f9a85ee2e
|
{
"intermediate": 0.3539215624332428,
"beginner": 0.305996298789978,
"expert": 0.34008219838142395
}
|
10,169
|
Quadratic equation in Python program
|
4bfdc9b42a83e3a1e7343412d772fd7b
|
{
"intermediate": 0.33946433663368225,
"beginner": 0.27719637751579285,
"expert": 0.3833392560482025
}
|
10,170
|
%%cu
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <libgen.h>
#include <unistd.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include "/content/common.h"
#include <cuda_runtime.h>
#define ROWS 1024
#define COLS 1024
#define ITERATIONS 10
__global__ void bitonicSortKernel(int *mat, int iteration, bool dir)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int offset = idx * COLS;
int i, j, k;
int temp;
for (i = 1 << (iteration - 1); i > 0; i = i >> 1)
{
for (j = i; j > 0; j = j >> 1)
{
for (k = 0; k < (COLS >> 1); ++k)
{
int ixj = k ^ j;
if ((k & i) == 0 && (ixj > k) && (dir == (mat[offset + k] > mat[offset + ixj])))
{
// Swap elements
temp = mat[offset + k];
mat[offset + k] = mat[offset + ixj];
mat[offset + ixj] = temp;
}
}
__syncthreads();
}
}
}
bool isSorted(int* data, int size) {
for (int i = 0; i < size - 1; i++) {
if (data[i] > data[i + 1])
return false;
}
return true;
}
int main(int argc, char **argv)
{
printf("%s Starting…\n", argv[0]);
int *mat;
mat = (int *)malloc(sizeof(int) * ROWS * COLS);
// Read the input data from file
FILE* inputFile = fopen("/content/datSeq1M.bin", "rb");
fseek(inputFile, sizeof(int), SEEK_SET); // Skip the first integer
fread(mat, sizeof(int), ROWS * COLS, inputFile);
fclose(inputFile);
int *mat_device;
CHECK(cudaMalloc((void**)&mat_device, sizeof(int) * ROWS * COLS));
CHECK(cudaMemcpy(mat_device, mat, sizeof(int) * ROWS * COLS, cudaMemcpyHostToDevice));
dim3 grid(ROWS / COLS, 1, 1);
dim3 block(COLS, 1, 1);
int numPairs = ROWS;
for (int i = 0; i < ITERATIONS; ++i)
{
for (int j = 0; j < i; ++j)
{
bool dir = (numPairs & 0x01) == 0;
bitonicSortKernel<<<grid, block>>>(mat_device, i - j + 1, dir);
CHECK (cudaDeviceSynchronize ()); // wait for kernel to finish
CHECK (cudaGetLastError ()); // check for kernel errors
}
numPairs = numPairs >> 1;
}
CHECK(cudaMemcpy(mat, mat_device, sizeof(int) * ROWS * COLS, cudaMemcpyDeviceToHost));
CHECK(cudaFree(mat_device));
// Print the sorted data
for (int i = 0; i < 20; i++) {
printf("%d ", mat[i]);
if( i == 10 ) break;
}
printf("\n");
// Check if the array is sorted
bool isOrdered = isSorted(mat, ROWS * COLS);
// Print the result of the ordering check
if (isOrdered) {
printf("The array is ordered.\n");
} else {
printf("The array is not ordered.\n");
}
free(mat);
return 0;
}
This isnt ordering the array, please fix it by keeping on mind this:
The kernels to be written should sort the contents of the file datSeq1M.bin in 10 iteration
steps. In iteration 1, 1024 subsequences of 1024 integer values are to be sorted in parallel. In
iteration 2, 512 subsequences of 2048 integer values are to be sorted in parallel based on the
merging of the previously sorted halves. And so on and so forth, until iteration 10 is reached,
where 2 previously sorted subsequences of 512K values are merged, yielding the whole sorted
sequence.
Assume that the values of the whole sequence, when stored in memory, are organized as the
elements of 1024 X 1024 matrix. The threads in a block thread process successive matrix rows
|
dcbc0c3f9f675cc80a5c3332416bcec6
|
{
"intermediate": 0.34069371223449707,
"beginner": 0.4748927056789398,
"expert": 0.1844135820865631
}
|
10,171
|
Write a program code that will analyze all transactions on the site https://bscscan.com/token/0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e in the Transfers tab and if these transactions have method signatures
Lock Tokens 0x6167aa61
Add Liquidity ETH 0xf305d719
Lock 0x07279357 return true
Token on Binance Smart Chain. Use APIKey
|
9d3597f44362424428486c539a9d0f09
|
{
"intermediate": 0.5888190865516663,
"beginner": 0.137002095580101,
"expert": 0.2741788327693939
}
|
10,172
|
export default class ClustersClientControllers {
xWidthInMs = timeFrame * clustersCountUI
DOMBorderOffset = 0
abnormalDensities = 200
clusters = []
currentMin = 0
tempCluster = {}
tempCurrentMin
totals = []
tempTotal = {}
root: ClientController
canvasHeight = 0
canvasWidth = 0
tradesArr: any = []
public bestPrices: any = null
clustersCtx
orderFeedCtx
public cameraPrice = null
public zoom = 10
clusterCellWidth
virtualServerTime = null
tradesFilterBySymbol = {}
constructor(root) {
this.root = root
window['clusters'] = this
this.restoreClusterSettings()
}
renderTrades = () => {
this.clearOrderFeed();
reduce(this.tradesArr, (prev, cur, index) => {
this.renderTrade(prev, cur, this.tradesArr.length - (index as any))
prev = cur
return prev
})
}
renderTrade = (prev, item, index) => {
//const anomalyQty = this.root.instruments[this.root.selectedSymbol].anomalies.anomaly_qty;
//if (size < 1) return;
const ctx = this.orderFeedCtx
let xPos = (this.canvasWidth - (index * (bubbleSize * 1.5))) - bubbleSize;
const offsetFromTop = this.root.tradingDriverController.upperPrice - item.price_micro;
const y = ((offsetFromTop / this.root.tradingDriverController.getZoomedStepMicro()) - 1) * rowHeight
const label = abbreviateNumber(item.quantity * item.price_float)
const {width: textWidth} = ctx.measureText(label);
const itemUsdt = item.quantity * item.price_float;
const tradeFilter = this.getTradeFilterBySymbol(this.getSymbol())
const maxUsdtBubbleAmount = tradeFilter * 30;
const maxPixelBubbleAmount = 35;
const realBubbleSize = (itemUsdt / maxUsdtBubbleAmount) * maxPixelBubbleAmount
const size = clamp(realBubbleSize, (textWidth/2)+3, maxPixelBubbleAmount)
const bubbleX = xPos;
const bubbleY = y + 8;
ctx.beginPath();
let bigRatio = (realBubbleSize / maxPixelBubbleAmount) / 3;
bigRatio = bigRatio > 0.95 ? 0.95 : bigRatio;
ctx.fillStyle = item.side === "Sell" ? deepGreen.lighten(bigRatio).toString() : deepRed.lighten(bigRatio).toString()
ctx.strokeStyle = 'black';
ctx.arc(xPos, bubbleY, size, 0, 2 * Math.PI)
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#FFFFFF"
ctx.fillText(label, bubbleX - (textWidth / 2), (bubbleY + (rowHeight / 2)) - 2)
}
переписать полностью на функциональный компонент. полностью весь код, ВЕСЬ КОД ПОЛНОСТЬЮ НАПИШИ
|
ac6f958ae4a4c3ee44b1dd5f8eb2ea5e
|
{
"intermediate": 0.20567764341831207,
"beginner": 0.5781365633010864,
"expert": 0.21618583798408508
}
|
10,173
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class MainClass
{
public static void Main()
{
// Создание и инициализация экземпляра класса, который будет сериализован
MyClass myObject = new MyClass();
myObject.Name = "Объект";
myObject.Number = 42;
myObject.StringArray = new string[] { "один", "два", "три" };
myObject.DataList = new SortedList<int, string>();
myObject.DataList.Add(1, "Значение 1");
myObject.DataList.Add(2, "Значение 2");
myObject.InnerObject = new InnerClass();
myObject.InnerObject.Value1 = 10;
myObject.InnerObject.Value2 = 3.14;
myObject.Image = new Bitmap("image.bmp");
// Сериализация объекта в XML с использованием XMLWriter
string xmlWithWriter = SerializeWithXmlWriter(myObject);
Console.WriteLine("Сериализация с использованием XMLWriter:");
Console.WriteLine(xmlWithWriter);
Console.WriteLine();
// Десериализация XML обратно в объект с использованием XMLReader
MyClass deserializedObjectWithReader = DeserializeWithXmlReader(xmlWithWriter);
Console.WriteLine("Десериализация с использованием XMLReader:");
Console.WriteLine("Имя: " + deserializedObjectWithReader.Name);
Console.WriteLine("Число: " + deserializedObjectWithReader.Number);
Console.WriteLine("Строки: " + string.Join(", ", deserializedObjectWithReader.StringArray));
Console.WriteLine("Список данных:");
foreach (KeyValuePair<int, string> kvp in deserializedObjectWithReader.DataList)
{
Console.WriteLine($" {kvp.Key}: {kvp.Value}");
}
Console.WriteLine("Вложенный объект:");
Console.WriteLine(" Значение 1: " + deserializedObjectWithReader.InnerObject.Value1);
Console.WriteLine(" Значение 2: " + deserializedObjectWithReader.InnerObject.Value2);
Console.WriteLine("Изображение: " + deserializedObjectWithReader.Image);
Console.WriteLine();
// Сериализация объекта в XML с использованием XMLSerializer
string xmlWithSerializer = SerializeWithXmlSerializer(myObject);
Console.WriteLine("Сериализация с использованием XMLSerializer:");
Console.WriteLine(xmlWithSerializer);
Console.WriteLine();
// Десериализация XML обратно в объект с использованием XMLSerializer
MyClass deserializedObjectWithSerializer = DeserializeWithXmlSerializer(xmlWithSerializer);
Console.WriteLine("Десериализация с использованием XMLSerializer:");
Console.WriteLine("Имя: " + deserializedObjectWithSerializer.Name);
Console.WriteLine("Число: " + deserializedObjectWithSerializer.Number);
Console.WriteLine("Строки: " + string.Join(", ", deserializedObjectWithSerializer.StringArray));
Console.WriteLine("Список данных:");
foreach (KeyValuePair<int, string> kvp in deserializedObjectWithSerializer.DataList)
{
Console.WriteLine($" {kvp.Key}: {kvp.Value}");
}
Console.WriteLine("Вложенный объект:");
Console.WriteLine(" Значение 1: " + deserializedObjectWithSerializer.InnerObject.Value1);
Console.WriteLine(" Значение 2: " + deserializedObjectWithSerializer.InnerObject.Value2);
Console.WriteLine("Изображение: " + deserializedObjectWithSerializer.Image);
}
// Класс, который будет сериализован
[Serializable]
public class MyClass
{
public string Name { get; set; }
public int Number { get; set; }
public string[] StringArray { get; set; }
public SortedList<int, string> DataList { get; set; }
public InnerClass InnerObject { get; set; }
[XmlAttribute]
public Bitmap Image { get; set; }
}
// Вложенный класс
[Serializable]
public class InnerClass
{
public int Value1 { get; set; }
public double Value2 { get; set; }
}
// Сериализация с использованием XMLWriter
public static string SerializeWithXmlWriter(object obj)
{
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
};
using (StringWriter sw = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("Root");
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(writer, obj);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
return sw.ToString();
}
}
// Десериализация с использованием XMLReader
public static MyClass DeserializeWithXmlReader(string xml)
{
using (StringReader sr = new StringReader(xml))
using (XmlReader reader = XmlReader.Create(sr))
{
reader.ReadStartElement("Root");
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
MyClass obj = (MyClass)serializer.Deserialize(reader);
reader.ReadEndElement();
return obj;
}
}
// Сериализация с использованием XMLSerializer
public static string SerializeWithXmlSerializer(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, obj);
return sw.ToString();
}
}
// Десериализация с использованием XMLSerializer
public static MyClass DeserializeWithXmlSerializer(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
using (StringReader sr = new StringReader(xml))
{
MyClass obj = (MyClass)serializer.Deserialize(sr);
return obj;
}
}
}
Данный код выдает ошибку "Невозможно сериализовать член VVP5.MainClass+MyClass.DataList типа System.Collections.Generic.SortedList`2". Как ее решить?
|
e2beb19a49d265853b5da580d97bab99
|
{
"intermediate": 0.25376197695732117,
"beginner": 0.5496215224266052,
"expert": 0.19661647081375122
}
|
10,174
|
import requests
API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
TOKEN_CONTRACT = '0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e'
def get_transaction_list(api_key, contract_address, start_block=28269140, end_block=29812249, page=1, offset=150):
url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={contract_address}&startblock={start_block}&endblock={end_block}&page={page}&offset={offset}&apikey={api_key}'
response = requests.get(url)
if response.status_code == 200:
result = response.json()
return result['result']
else:
return None
def get_all_transaction_hashes(api_key, contract_address):
all_hashes = []
page = 1
while True:
transactions = get_transaction_list(api_key, contract_address, page=page)
if transactions:
hashes = [tx['hash'] for tx in transactions]
all_hashes.extend(hashes)
if len(transactions) < 100:
break
page += 1
else:
print('Error getting transactions')
break
return all_hashes
all_transaction_hashes = get_all_transaction_hashes(API_KEY, TOKEN_CONTRACT)
for txn_hash in all_transaction_hashes:
print(txn_hash)
Change the code above to only return those Txn Hash whose method id is 0xf305d719
Use the following function for this
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == 'd719'
|
de761154d4d6476be733017f60e11514
|
{
"intermediate": 0.4072084128856659,
"beginner": 0.39999207854270935,
"expert": 0.19279947876930237
}
|
10,175
|
live camera Streaming without preview ( running app in background?)with rtmp url android studio
|
5297b8336a3944ee78e8c9bfdd6914fd
|
{
"intermediate": 0.5480551719665527,
"beginner": 0.236154243350029,
"expert": 0.21579061448574066
}
|
10,176
|
I would like to change this formula so that it counts the number of times B3:B15 is 0 =SUM(IF($C$3:$C$15=H3, $B$3:$B$15, 0))
|
b3be8eba03c03691b1d195efc6a8a0f6
|
{
"intermediate": 0.35305047035217285,
"beginner": 0.29204532504081726,
"expert": 0.3549042046070099
}
|
10,177
|
in the following table CREATE TABLE App_User(
userID INT AUTO_INCREMENT,
username VARCHAR(255) NOT NULL UNIQUE,
password_ VARCHAR(255) NOT NULL,
role_status ENUM('student','educator','library_operator','adminstrator') NOT NULL,
schoolID INT,
full_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
phone_number VARCHAR(255) NOT NULL,
DOB DATE,
no_books_allowed ENUM('1','2','not applicable'),
active_status BOOLEAN DEFAULT FALSE,
approval_by_operator BOOLEAN DEFAULT FALSE,
PRIMARY KEY (userID),
FOREIGN KEY (schoolID) REFERENCES School(schoolID) how can the password be only visible to the user what command should I add
|
9df3178845d5e0192161e39054b717c1
|
{
"intermediate": 0.3360104560852051,
"beginner": 0.2846043109893799,
"expert": 0.37938523292541504
}
|
10,178
|
import requests
API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
TOKEN_CONTRACT = '0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e'
def get_transaction_list(api_key, contract_address, start_block=28269140, end_block=29812249, page=1, offset=150):
url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={contract_address}&startblock={start_block}&endblock={end_block}&page={page}&offset={offset}&apikey={api_key}'
response = requests.get(url)
if response.status_code == 200:
result = response.json()
return result['result']
else:
return None
def get_all_transaction_hashes(api_key, contract_address):
all_hashes = []
page = 1
while True:
transactions = get_transaction_list(api_key, contract_address, page=page)
if transactions:
hashes = [tx['hash'] for tx in transactions]
all_hashes.extend(hashes)
if len(transactions) < 100:
break
page += 1
else:
print('Error getting transactions')
break
return all_hashes
all_transaction_hashes = get_all_transaction_hashes(API_KEY, TOKEN_CONTRACT)
for txn_hash in all_transaction_hashes:
print(txn_hash)
Change the above code to return Txn Hash whose id method is Add Liquidity ETH
|
3da6f54cd0d6a1f078e666088e2a8953
|
{
"intermediate": 0.443386971950531,
"beginner": 0.35014858841896057,
"expert": 0.20646438002586365
}
|
10,179
|
hi
|
9233cdcca8870248403cd5718ca6ff7a
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,180
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <libgen.h>
#include <unistd.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include “common.h”
#include <cuda_runtime.h>
/ allusion to internal functions /
static void calculateDeterminantCPU(double matrix, double determinant, int size);
global void calculateDeterminantGPUKernel(double mat, double determinants, int n);
static double get_delta_time(void);
static void printUsage(char cmdName);
int parseArgs(int argc, char argv[], char filenames[]);
/
main program
/
int main(int argc, char argv)
{
printf(“%s Starting…\n”, argv[0]);
if (sizeof(unsigned int) != (size_t)4)
return 1; // it fails with prejudice if an integer does not have 4 bytes
/ set up the device /
int dev = 0;
cudaDeviceProp deviceProp;
CHECK(cudaGetDeviceProperties(&deviceProp, dev));
printf(“Using Device %d: %s\n”, dev, deviceProp.name);
CHECK(cudaSetDevice(dev));
int nArgs = (int)(argc - 1) / 2 + 50; / size of the array of file names /
char fileNames[nArgs]; / Stores the provided file names /
memset(fileNames, 0, nArgs); / Initializes the array with zeros /
parseArgs(argc, argv, fileNames); / parse command line arguments /
int num, size;
size_t matSize, matAreaSize;
size_t numDet;
double mat; / stores the matrices coeficients on host side /
double mat_device; / stores the matrices coeficients on device side /
double det; / used to initialize determinants data on host side /
double det_device; / stores the determinants on device side /
double det_cpu; / stores the determinants calculated with CPU kernel /
double new_det; / stores the determinants from device side/
/ Open file /
FILE f;
f = fopen(fileNames[0], “rb”);
if (!f)
{
printf(“Error opening file %s\n”, fileNames[0]);
exit(EXIT_FAILURE);
}
printf(“File ‘%s’\n”, fileNames[0]); //only the first file is parsed
if(!fread(&num, sizeof(int), 1, f)) // num of matrices in file
{
printf(“Error reading from file %s\n”, fileNames[0]);
exit(EXIT_FAILURE);
}
printf(“Number of matrices to be read = %d\n”, num);
if(!fread(&size, sizeof(int), 1, f)) // size of each matrix
{
printf(“Error reading from file %s\n”, fileNames[0]);
exit(EXIT_FAILURE);
}
printf(“Matrices order = %d\n\n”, size);
/ create memory areas in host and device memory where the coefficients will be stored /
matSize = (size_t)size * (size_t)size * sizeof(double);
matAreaSize = (size_t)num * matSize;
numDet = (size_t)num * sizeof(double);
if ((matAreaSize + numDet) > (size_t)1.3e9)
{
fprintf(stderr, “The GeForce GTX 1660 Ti cannot handle more than 5GB of memory!\n”);
exit(1);
}
mat = (double )malloc(matAreaSize);
det = (double )malloc(numDet);
CHECK(cudaMalloc((void )&mat_device, matAreaSize));
CHECK(cudaMalloc((void )&det_device, numDet));
/ initialize the host data /
for (int j = 0; j < num * size * size; j++)
{
char bytes[8];
if(!fread(&bytes, sizeof(double), 1, f))
{
printf(“Error reading from file %s\n”, fileNames[0]);
exit(EXIT_FAILURE);
}
double d = ((double )bytes);
mat[j] = d;
}
fclose(f);
for(int j= 0; j < num; j++) {
det[j] = 1;
}
/ copy the host data to the device memory /
(void) get_delta_time ();
CHECK (cudaMemcpy (mat_device, mat, matAreaSize, cudaMemcpyHostToDevice));
CHECK (cudaMemcpy (det_device, det, numDet, cudaMemcpyHostToDevice));
printf (“The transfer of %ld bytes from the host to the device took %.3e seconds\n”,
(long) matAreaSize + (long) numDet, get_delta_time ());
/ run the computational kernel /
unsigned int gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ;
blockDimX = size;
blockDimY = 1;
blockDimZ = 1;
gridDimX = num;
gridDimY = 1;
gridDimZ = 1;
dim3 grid (gridDimX, gridDimY, gridDimZ);
dim3 block (blockDimX, blockDimY, blockDimZ);
(void) get_delta_time ();
calculateDeterminantGPUKernel<<<grid, block>>>(mat_device, det_device, size);
CHECK (cudaDeviceSynchronize ()); // wait for kernel to finish
CHECK (cudaGetLastError ()); // check for kernel errors
printf(“The CUDA kernel <<<(%d,%d,%d), (%d,%d,%d)>>> took %.3e seconds to run\n”,
gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, get_delta_time ());
/ copy kernel result back to host side /
new_det = (double ) malloc (numDet);
(void) get_delta_time ();
CHECK (cudaMemcpy (new_det, det_device, numDet, cudaMemcpyDeviceToHost));
printf (“The transfer of %ld bytes from the device to the host took %.3e seconds\n”,
(long) numDet, get_delta_time ());
/ free device global memory /
CHECK(cudaFree(mat_device));
CHECK(cudaFree(det_device));
/ reset the device /
CHECK(cudaDeviceReset());
/ compute the determinants on the CPU /
det_cpu = (double )malloc(numDet);
(void) get_delta_time ();
for(int i = 0; i < num; i++)
{
det_cpu[i] = 1;
calculateDeterminantCPU(mat + (isizesize), &det_cpu[i], size);
}
printf(“The single threaded cpu kernel took %.3e seconds to run \n”,get_delta_time ());
for(int i = 0; i < num; i++) {
printf(“\nDeterminant of matrix %d GPU: %.3E CPU: %.3E\n”, i+1, new_det[i], det_cpu[i]);
}
free(mat);
free(det);
free(new_det);
exit(EXIT_SUCCESS);
return 0;
}
/
\brief Method calculateDeterminantGPUKernel.
Its role is to calculate the determinants of the matrix using a GPU
\param mat pointer to the matrix coefficients
\param determinants pointer to struct that holds the calculated determinants
\param n order of matrix
/
global void calculateDeterminantGPUKernel(double mat, double determinants, int n)
{
int bkx = blockIdx.x + gridDim.x * blockIdx.y + gridDim.x * gridDim.y * blockIdx.z;
int pos = bkx * n * n; // point to the first coefficient of the current matrix
mat += pos;
bool reverseSignal = false;
double aux;
int idx;
idx = threadIdx.x + blockDim.x * threadIdx.y + blockDim.x * blockDim.y * threadIdx.z;
double det;
for (int i = 0; i <= idx; i++) // each loop has a smaller matrix to process (submatrix)
{
// in case of a 0 in a diagonal
if (mat[(i * n + i)] == 0) // test diagonal cell in current row
{
bool allNull = true;
for (int j = i + 1; j < n; j++)
{
if (mat[(i + jn)] != 0)
{
// swap rows
aux = mat[in+idx];
mat[in+idx] = mat[jn + idx];
mat[jn + idx] = aux;
__syncthreads();
reverseSignal = !reverseSignal;
allNull = false;
}
}
// if the matrix contains a full column of zeros, anywhere in the matrix, the determinant will be 0
if (allNull)
{
determinants[bkx] = 0;
break;
}
}
double mul;
for (int k = i + 1; k < n; k++)
{
mul = (mat[(k + ni)] / mat[(i + i * n)]);
__syncthreads();
mat[(k + nidx)] -= mul * mat[i + nidx];
}
if(i == idx) {
// calculate the determinant by multiplying the diagonal elements
det = mat[idxn + idx];
determinants[bkx] = det;
if (reverseSignal)
{
determinants[bkx] = -1;
reverseSignal = false;
}
}
}
}
/
\brief Method calculateDeterminantCPU.
Its role is to calculate the determinant of a matrix
\param matrix pointer to the memory region with the matrix coefficients
\param determinant pointer that holds the calculated determinant
\param size order of the matrix
/
static void calculateDeterminantCPU(double matrix, double determinant, int size)
{
bool reverseSignal = false;
for (int i = 0; i < size - 1; i++)
{
if (matrix[i * size + i] == 0)
{
bool allNull = true;
for (int j = i + 1; j < size; j++)
{
if (matrix[j * size + i] != 0)
{
// swap rows
int aux;
for (int k = 0; k < size; k++)
{
aux = matrix[(i-1) * size + k];
matrix[(i-1) * size + k] = matrix[(j-1) * size + k];
matrix[(j-1) * size + k] = aux;
}
reverseSignal = !reverseSignal;
allNull = false;
}
}
// if the matrix contains a full column of zeros, anywhere in the matrix, the determinant will be 0
if (allNull)
{
determinant = 0;
return;
}
}
double aux;
for (int k = i + 1; k < size; k++)
{
aux = (matrix[i * size + k] / matrix[i * size + i]);
for (int j = 0; j < size; j++)
{
matrix[j * size + k] -= aux * matrix[j * size + i];
}
}
}
double prod = 1;
for (int i = 0; i < size; i++)
{
prod = matrix[i * size + i];
}
if(reverseSignal) {
prod = -1;
}
determinant = prod;
}
/
\brief parseArgs function.
\param argc number of words of the command line
\param argv list of words of the command line
\param filenames pointer to store names of files
\return status of operation
/
int parseArgs(int argc, char argv[], char filenames[])
{
/ process command line options /
int opt; / selected option /
// char fName = “no name”; / file name (initialized to “no name” by default) /
int cnt = 0;
do
{
switch ((opt = getopt(argc, argv, “f:n:h”)))
{
case ‘f’: / file name /
if (optarg[0] == ‘-’)
{
fprintf(stderr, “%s: file name is missing\n”, basename(argv[0]));
printUsage(basename(argv[0]));
return EXIT_FAILURE;
}
filenames[cnt] = optarg;
cnt++;
break;
case ‘h’: / help mode /
printUsage(basename(argv[0]));
return EXIT_SUCCESS;
case ‘?’: / invalid option /
fprintf(stderr, “%s: invalid option\n”, basename(argv[0]));
printUsage(basename(argv[0]));
return EXIT_FAILURE;
case -1:
break;
}
} while (opt != -1);
if (argc == 1)
{
fprintf(stderr, “%s: invalid format\n”, basename(argv[0]));
printUsage(basename(argv[0]));
return EXIT_FAILURE;
}
/ that’s all /
return EXIT_SUCCESS;
} / end of parseArgs /
/
\brief Print command usage.
* A message specifying how the program should be called is printed.
\param cmdName string with the name of the command
*/
void printUsage(char *cmdName)
{
fprintf(stderr, “\nSynopsis: %s OPTIONS [filename / positive number]\n”
" OPTIONS:\n"
" -h — print this help\n"
" -f — filename\n",
cmdName);
}
static double get_delta_time(void)
{
static struct timespec t0,t1;
t0 = t1;
if(clock_gettime(CLOCK_MONOTONIC,&t1) != 0)
{
perror(“clock_gettime”);
exit(1);
}
return (double)(t1.tv_sec - t0.tv_sec) + 1.0e-9 * (double)(t1.tv_nsec - t0.tv_nsec);
}
change this code to do bitonic sort with this discription:
The kernels to be written should sort the contents of the file datSeq1M.bin in 10 iteration
steps. In iteration 1, 1024 subsequences of 1024 integer values are to be sorted in parallel. In
iteration 2, 512 subsequences of 2048 integer values are to be sorted in parallel based on the
merging of the previously sorted halves. And so on and so forth, until iteration 10 is reached,
where 2 previously sorted subsequences of 512K values are merged, yielding the whole sorted
sequence.
Assume that the values of the whole sequence, when stored in memory, are organized as the
elements of 1024 X 1024 matrix. The threads in a block thread process successive matrix rows
Give me the full code solution
|
6f24b28213c8b2ffec3bfa40ae0d6ab2
|
{
"intermediate": 0.3950643837451935,
"beginner": 0.3443002998828888,
"expert": 0.26063528656959534
}
|
10,181
|
timestamp market pair ask bid open_spread close_spread open_spread_more_0.0 open_spread_more_0.1 open_spread_more_0.2 open_spread_more_0.3 open_spread_more_0.4 open_spread_more_0.5 open_spread_more_0.6 open_spread_more_0.7 open_spread_more_0.8 open_spread_more_0.9 open_spread_more_1.0
25449 2023-06-03 17:48:38.480 s LINA/USDT 0.018650 0.018644 0.214 -0.300 True True True NaN NaN NaN NaN NaN NaN NaN NaN
31550 2023-06-03 17:54:42.960 f LINA/USDT 0.018730 0.018720 0.214 -0.305 True True True NaN NaN NaN NaN NaN NaN NaN NaN
35834 2023-06-03 17:58:39.100 f LINA/USDT 0.018660 0.018650 0.236 -0.312 True True True NaN NaN NaN NaN NaN NaN NaN NaN
102704 2023-06-03 19:04:22.338 f LINA/USDT 0.018650 0.018640 0.220 -0.339 True True True NaN NaN NaN NaN NaN NaN NaN NaN
102764 2023-06-03 19:04:25.368 f LINA/USDT 0.018680 0.018670 0.262 -0.376 True True True NaN NaN NaN NaN NaN NaN NaN NaN
102768 2023-06-03 19:04:25.569 f LINA/USDT 0.018680 0.018670 0.220 -0.344 True True True NaN NaN NaN NaN NaN NaN NaN NaN
102769 2023-06-03 19:04:25.608 s LINA/USDT 0.018632 0.018625 0.204 -0.295 True True True NaN NaN NaN NaN NaN NaN NaN NaN
102770 2023-06-03 19:04:25.670 f LINA/USDT 0.018690 0.018680 0.257 -0.349 True True True NaN NaN NaN NaN NaN NaN NaN NaN
102771 2023-06-03 19:04:25.707 s LINA/USDT 0.018632 0.018626 0.257 -0.344 True True True NaN NaN NaN NaN NaN NaN NaN NaN
102772 2023-06-03 19:04:25.770 f LINA/USDT 0.018700 0.018690 0.310 -0.397 True True True True NaN NaN NaN NaN NaN NaN NaN
102773 2023-06-03 19:04:25.809 s LINA/USDT 0.018640 0.018635 0.268 -0.349 True True True NaN NaN NaN NaN NaN NaN NaN NaN
102774 2023-06-03 19:04:25.871 f LINA/USDT 0.018700 0.018690 0.268 -0.349 True True True NaN NaN NaN. Эти данные выведены командой df_lina[df_lina['open_spread_more_0.2'] == True]. Напиши код на питоне, который анализируя индекс записи собирает статистику последовательного постоянства, например после индекса 25449 следующий индекс 31550 - это значит что записи между ними не попали в выборку и последовательная встречаемость равна 1, однако записи с 102768 по 102774 свидетельствуют о частоте последовательной встречаемости равной 7, таким образом 25449 - 1 раз, 31550 - 1 раз, 35834 - 1 раз, 102704 - 1 раз, с 102768 по 102774 - 7 раз, а это значит что индекс последовательной встречаемости равен (1 + 1 + 1 + 1 + 7) = 2,2.
|
c5fd01237c822b88e1726bd255eb5e84
|
{
"intermediate": 0.2969798147678375,
"beginner": 0.3585561215877533,
"expert": 0.3444640338420868
}
|
10,182
|
hello
|
2761546fafe579bf61c0c58400cc7efd
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
10,183
|
in this VBA code below, is it possible to limit the number of words to 10 fot the reults displayed by this line: "" & eventsSheet.Range("C" & i).Value & vbNewLine & _
Sub EventsOverdue()
Dim eventsSheet As Worksheet
Dim lastRow As Long
Dim DateToCheck As Date
Dim i As Long
Dim MatchCount As Integer
Dim Matches As String
Set eventsSheet = ThisWorkbook.Sheets("Events")
lastRow = eventsSheet.Range("B" & Rows.count).End(xlUp).Row
DateToCheck = Date - 1 ' find dates starting from yesterday
Dim EndDate As Date
EndDate = Date - 90 ' find dates up to 90 days before yesterday
MatchCount = 0
For i = 2 To lastRow
If eventsSheet.Range("B" & i).Value <= DateToCheck Then 'And eventsSheet.Range("B" & i).Value <= EndDate Then
MatchCount = MatchCount + 1
Matches = Matches & vbNewLine & _
"Date: " & eventsSheet.Range("B" & i).Value & vbNewLine & _
"" & eventsSheet.Range("C" & i).Value & vbNewLine & _
"" & eventsSheet.Range("D" & i).Value & vbNewLine
End If
Next i
If MatchCount > 0 Then
MsgBox "Overdue Events: " & MatchCount & vbNewLine & Matches
End If
End Sub
|
0f44444cdb74eb7505df65d73372f7ca
|
{
"intermediate": 0.44086185097694397,
"beginner": 0.3919150233268738,
"expert": 0.16722308099269867
}
|
10,184
|
Работа работает не правильно, помоги её исправить
frame(name(bird),
isa(animal),
[travel(flies),feathers],
[]).
frame(name(penguin),
isa(bird),
[color(brown)],
[travel(walks)]).
frame(name(canary),
isa(bird),
[color(yellow),call(sing)],
[size(small)]).
frame(name(tweety),
isa(canary),
[],
[color(white)]).
get(Prop,Object):- % если задано конкретное свойство - ищем только в самом объекте
frame(name(Object),,List_of_properties,),
member(Prop,List_of_properties).
get(Prop,Object):- % иначе ищем сначала в списке свойств объекта, затем в списке по умолчанию, не учитывая наследование
frame(name(Object),,List_of_properties,List_of_defaults),
+ member(Prop,List_of_properties), % проверяем, что свойство не задано явно
member(Prop,List_of_defaults).
get(Prop,Object):- % если не нашли свойство в данном объекте, ищем у его родителя, но не учитываем наследование, если свойство задано явно
frame(name(Object),isa(Parent),,_),
+ get(Prop,Object), % проверяем, что свойство не найдено в текущем объекте
get(Prop,Parent).
|
873a3158f7f2ef0904f102a2ef4f4991
|
{
"intermediate": 0.30066806077957153,
"beginner": 0.3861617147922516,
"expert": 0.3131702244281769
}
|
10,185
|
Test
|
9a401f505e9c6567ada78478cd5b2d10
|
{
"intermediate": 0.34329941868782043,
"beginner": 0.33079785108566284,
"expert": 0.32590270042419434
}
|
10,186
|
Как развернуть это приложение не на локальном сервере а на repl.it
from fastapi import FastAPI, WebSocket, Request, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import json
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
message_counter = 0
message_list = []
@app.get("/", response_class=HTMLResponse)
async def get_home(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
global message_counter
await websocket.accept()
while True:
try:
data = await websocket.receive_text()
message = json.loads(data)
message_counter += 1
message_with_number = f"{message_counter}. {message}"
message_list.append(message_with_number)
await websocket.send_text(json.dumps(message_list))
except WebSocketDisconnect:
break
@app.post('/clear_messages')
async def clear_messages():
global message_list, message_counter
message_list = []
message_counter = 0
return {'message': 'Messages cleared'}
if name == "main":
import uvicorn
uvicorn.run("main:app", host="localhost", port=8000) const messageListElement = document.getElementById("messageList");
const messageForm = document.getElementById("messageForm");
const messageTextArea = document.getElementById("message");
const ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = handleMessage;
messageForm.onsubmit = (e) => {
e.preventDefault();
const message = messageTextArea.value;
ws.send(JSON.stringify(message));
messageTextArea.value = "";
};
function handleMessage(e) {
const messages = JSON.parse(e.data);
messageListElement.innerHTML = "";
for (const message of messages) {
const listItem = document.createElement("li");
listItem.textContent = message;
messageListElement.appendChild(listItem);
}
}
window.addEventListener('beforeunload', async function() {
await fetch('/clear_messages', { method: 'POST' });
});
window.addEventListener('unload', async function() {
await fetch('/clear_messages', { method: 'POST' });
});
|
47140aefcc74fd57e7dfd860f47ce5ff
|
{
"intermediate": 0.3626270890235901,
"beginner": 0.4261976480484009,
"expert": 0.211175337433815
}
|
10,187
|
%%cu
#include <cuda_runtime.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <libgen.h>
#include <unistd.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#include <time.h>
#define FILE_NAME "/content/datSeq1M.bin"
#define NUM_ITERATIONS 10
#define SEQ_LENGTH 1024
#define NUM_SEQUENCES (1 << (NUM_ITERATIONS))
#define BLOCK_SIZE 256
__global__ void bitonic_sort_step(int *values, const int stage, const int step) {
unsigned int tId = threadIdx.x;
unsigned int pId = tId + blockIdx.x * blockDim.x;
unsigned int partner = pId ^ step;
if (pId < partner) {
if ((tId & stage) == 0) {
if (values[pId] > values[partner]) {
int tmp = values[pId];
values[pId] = values[partner];
values[partner] = tmp;
}
} else {
if (values[pId] < values[partner]) {
int tmp = values[pId];
values[pId] = values[partner];
values[partner] = tmp;
}
}
}
}
__global__ void bitonic_merge(int *values, int stage, int step) {
int length = 1 << (stage + 1);
int index = threadIdx.x + blockIdx.x * blockDim.x;
int base = (index / length) * length;
int partner = base + length / 2 + (index % (length / 2));
if (index < partner) {
if ((index & (length / 2)) == 0) {
if (values[index] > values[partner]) {
int tmp = values[index];
values[index] = values[partner];
values[partner] = tmp;
}
} else {
if (values[index] < values[partner]) {
int tmp = values[index];
values[index] = values[partner];
values[partner] = tmp;
}
}
}
}
void bitonic_sort(int *values, int sequence_length) {
for (int stage = 0; stage < (int)log2f(sequence_length); ++stage) {
for (int step = sequence_length / 2; step > 0; step /= 2) {
unsigned int numBlocks = (sequence_length + BLOCK_SIZE - 1) / BLOCK_SIZE;
bitonic_sort_step<<<numBlocks, BLOCK_SIZE>>>(values, stage, step);
cudaDeviceSynchronize();
}
}
}
void read_sequence(int *data) {
FILE *fp = fopen(FILE_NAME, "rb");
fseek(fp, sizeof(int), SEEK_SET); // Skip the first integer
if (fp == NULL) {
fprintf(stderr, "Failed to open the input file\n");
exit(1);
}
for (int i = 0; i < NUM_SEQUENCES * SEQ_LENGTH; i++) {
if (fread(&data[i], sizeof(int), 1, fp) != 1) {
fprintf(stderr, "Failed to read the input file\n");
exit(1);
}
}
fclose(fp);
}
bool isSorted(int* data, int size) {
for (int i = 0; i < size - 1; i++) {
if (data[i] > data[i + 1])
return false;
}
return true;
}
int main() {
int *data = (int *)malloc(NUM_SEQUENCES * SEQ_LENGTH * sizeof(int));
int *d_data;
// Read sequences from the file
read_sequence(data);
// Allocate memory on GPU
cudaMalloc((void **)&d_data, NUM_SEQUENCES * SEQ_LENGTH * sizeof(int));
cudaMemcpy(d_data, data, NUM_SEQUENCES * SEQ_LENGTH * sizeof(int), cudaMemcpyHostToDevice);
// Perform sorting iterations
for (int i = 0; i < NUM_ITERATIONS; ++i) {
int seq_length = SEQ_LENGTH << i;
printf("Iteration %d: Sorting %d sequences of length %d\n", i + 1, NUM_SEQUENCES >> i, seq_length);
bitonic_sort(d_data, seq_length);
}
cudaMemcpy(data, d_data, NUM_SEQUENCES * SEQ_LENGTH * sizeof(int), cudaMemcpyDeviceToHost);
cudaFree(d_data);
// Write output to a file
FILE *fp = fopen("sorted_output.bin", "wb");
fwrite(data, sizeof(int), SEQ_LENGTH * NUM_SEQUENCES, fp);
fclose(fp);
// Print the sorted data
for (int i = 0; i < 20; i++) {
printf("%d ", data[i]);
if( i == 10 ) break;
}
// Check if the array is sorted
bool isOrdered = isSorted(data, NUM_SEQUENCES * SEQ_LENGTH);
// Print the result of the ordering check
if (isOrdered) {
printf("The array is ordered.\n");
} else {
printf("The array is not ordered.\n");
}
free(data);
return 0;
}
This isnt ordering the input file
|
6615386bdadb0ffa04ee695bd1819ff2
|
{
"intermediate": 0.37041231989860535,
"beginner": 0.41460755467414856,
"expert": 0.2149801105260849
}
|
10,188
|
I have a mongodb database that i need you to write an api for in C#.
|
ecdc318ac9b4721926d5378606ff2476
|
{
"intermediate": 0.8309003114700317,
"beginner": 0.08154666423797607,
"expert": 0.08755309134721756
}
|
10,189
|
i want to start a business,write me a strategy
|
22d66147c791bee01fcab36e6b3beabc
|
{
"intermediate": 0.3553257882595062,
"beginner": 0.24671714007854462,
"expert": 0.39795711636543274
}
|
10,190
|
this is the main of my application "import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'login_logic.dart';
import 'signup_logic.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Bienvenue à Attendance Manager!',
builder: EasyLoading.init(),
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginSignupPage(),
);
}
}
class LoginSignupPage extends StatefulWidget {
@override
_LoginSignupPageState createState() => _LoginSignupPageState();
}
class _LoginSignupPageState extends State<LoginSignupPage> {
bool _isLoginForm = true;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _usernameController = TextEditingController();
String _selectedRole = 'Admin';
List<String> _roleOptions = ['Admin', 'Etudiant', 'Enseignant'];
final TextEditingController _matriculeController = TextEditingController();
void _toggleFormMode() {
setState(() {
_isLoginForm = !_isLoginForm;
});
}
final loginLogic = LoginLogic();
void _login() async {
print('_login method called');
try {
final response = await loginLogic.login(
_usernameController.text,
_passwordController.text,
);
await loginLogic.handleResponse(context, response);
} catch (e) {
// Handle any network or server errors
}
}
final _signupLogic = SignupLogic();
Future<void> _signup() async {
try {
final response = await _signupLogic.registerUser(
context,
_emailController.text,
_usernameController.text,
_passwordController.text,
_selectedRole,
_matriculeController.text,
);
if (response.statusCode == 200 || response.statusCode == 201) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Compte créé avec succès'),
actions: <Widget>[
ElevatedButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
print('Registration success');
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Erreur'),
content: Text('Veuillez remplir tous les champs et réessayez'),
actions: <Widget>[
ElevatedButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
print('Received signup response with status code: ${response.statusCode}');
}
} catch (e) {
// handle network or server errors
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_isLoginForm ? 'Se connecter' : 'Créer un compte'),
),
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(height: 48.0),
if (_isLoginForm)
TextFormField(
controller: _usernameController,
decoration: InputDecoration(
labelText: "Nom d'utilisateur",
hintText: "Entrez votre nom d'utilisateur",
),
),
if (!_isLoginForm)
TextFormField(
controller: _emailController,
decoration: InputDecoration(
labelText: 'Email',
hintText: 'Entrez votre addresse e-mail',
),
),
SizedBox(height: 16.0),
TextFormField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Mot de passe',
hintText: 'Entrez votre mot de passe',
),
),
SizedBox(height: 16.0),
if (!_isLoginForm)
TextFormField(
controller: _usernameController,
decoration: InputDecoration(
labelText: "nom d'utilisateur",
hintText: "Entrez votre nom d'utilisateur",
),
),
SizedBox(height: 16.0),
if (!_isLoginForm)
DropdownButtonFormField<String>(
decoration: InputDecoration(
labelText: 'Role',
hintText: 'Sélectionnez votre rôle',
),
value: _selectedRole,
onChanged: (String? value) {
setState(() {
_selectedRole = value!;
});
},
items: _roleOptions.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
SizedBox(height: 16.0),
if (!_isLoginForm)
TextFormField(
controller: _matriculeController,
decoration: InputDecoration(
labelText: 'Matricule',
hintText: 'Entrez votre matricule',
),
),
SizedBox(height: 48.0),
ElevatedButton(
child: Text(_isLoginForm ? 'Se connecter' : 'Créer un compte'),
onPressed: () {
print('Login button pressed');
if (_isLoginForm) {
_login();
} else {
_signup();
}
},
),
TextButton(
child: Text(_isLoginForm
? 'Ou créer un compte'
: 'Vouz avez un compte? vous pouvez vous connecter'),
onPressed: _toggleFormMode,
),
],
),
),
),
);
}
}" using this "
import 'dart:convert';
import 'package:attendance_app/profile_admin_screen.dart';
import 'package:attendance_app/profile_enseignant_screen.dart';
import 'package:attendance_app/profile_etudiant_screen.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'constants.dart';
class LoginLogic {
static const String _jwtKey = 'watchme';
static String get jwtKey => _jwtKey;
static final _storage = FlutterSecureStorage();
static FlutterSecureStorage get storage => _storage;
Future<http.Response> login(String email, String password) async {
if (email.isEmpty && password.isEmpty) {
return Future.error('Veuillez remplir les champs de l\'identifiant et du mot de passe');
} else if (email.isEmpty) {
return Future.error('Veuillez remplir le champ de l\'identifiant');
} else if (password.isEmpty) {
return Future.error('Veuillez remplir le champ du mot de passe');
}
print('Starting login request with email: $email and password: $password');
final data = {
'userName': email,
'password': password,
};
final jsonData = jsonEncode(data);
try {
final response = await http.post(
Uri.parse('$endpointUrl/login'),
headers: {'Content-Type': 'application/json'},
body: jsonData,
).timeout(Duration(seconds: 5));
print('Received login response with status code: ${response.statusCode}');
return response;
} on TimeoutException catch (e) {
return Future.error('La requête a expiré');
} catch (e) {
return Future.error('Échec de la connexion');
}
}
Future<void> handleResponse(BuildContext context, http.Response response) async {
if (response.statusCode == 200) {
final responseBody = json.decode(response.body);
final token = responseBody['token'];
try {
await _storage.write(key: _jwtKey, value: token);
} catch (e) {
print('Error writing token to storage: $e');
}
print('Token generated and written to storage: $token');
String? role = await getUserRole();
if (role != null) {
if (role.toLowerCase() == 'etudiant') {
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => ProfileEtudiantScreen()));
} else if (role.toLowerCase() == 'enseignant') {
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => ProfileEnseignantScreen()));
} else if (role.toLowerCase() == 'administrateur') {
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => ProfileAdminScreen()));
} else {
print('Invalid role: $role');
}
} else {
print('Role not found in response');
}
} else if (response.statusCode == 401) {
final responseBody = json.decode(response.body);
var message = responseBody['message'];
if (message == null) {
message = 'Une erreur s\'est produite lors de la connexion.';
} else if (message == 'Veuillez remplir les champs de l\'identifiant et du mot de passe') {
message = 'Veuillez remplir les champs de l\'identifiant et du mot de passe';
} else if (message == 'Veuillez remplir le champ de l\'identifiant') {
message = 'Veuillez remplir le champ de l\'identifiant';
} else if (message == 'Veuillez remplir le champ du mot de passe') {
message = 'Veuillez remplir le champ du mot de passe';
}
print('Response message: $message');
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Erreur'),
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('OK'),
),
],
),
);
} else {
print('Response status code: ${response.statusCode}');
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Erreur'),
content: Text('Une erreur s\'est produite lors de la connexion.'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('OK'),
),
],
),
);
}
}
static Future<String?> getToken() async {
try {
final token = await _storage.read(key: _jwtKey);
return token;
} catch (e) {
print('Error reading token from storage: $e');
return null;
}
}
Future<String?> getUserRole() async {
final token = await getToken();
if (token != null) {
try {
final response = await http.get(
Uri.parse('$endpointUrl/getusernamerole'),
headers: {'Authorization': 'Bearer $token'},
);
if (response.statusCode == 200) {
final responseBody = json.decode(response.body);
final role = responseBody['role'];
return role;
} else {
print('Failed to retrieve user role');
return null;
}
} catch (e) {
print('Error fetching user role: $e');
return null;
}
} else {
print('No token found');
return null;
}
}
}
" and this "import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'constants.dart' as Constants;
class SignupLogic {
Future<http.Response> registerUser(BuildContext context,String email, String username, String password, String role, String matricule) async {
final url = Uri.parse('${Constants.endpointUrl}/register');
final headers = <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
};
final body = jsonEncode(<String, String>{
'email': email,
'username': username,
'password': password,
'role': role,
'matricule': matricule,
});
final response = await http.post(url, headers: headers, body: body);
print('Received Registration response with status code: ${response.statusCode}');
if (response.statusCode == 201) {
Navigator.pushNamedAndRemoveUntil(context, '/', (route) => false);
return response;
} else {
// Handle errors
print('Received Registration response with status code: ${response.statusCode}');
return response;
}
}
}
", I want to encapsulate as maximum as possible the login and signup logics in their files while keeping the main less dense, can you suggest the most efficient, concise implementations of the 3 pieces of code while providing me with the full versions of those 3 files ?
|
1273f68d8bee46bc55801c281a60760a
|
{
"intermediate": 0.41544318199157715,
"beginner": 0.48936721682548523,
"expert": 0.09518957883119583
}
|
10,191
|
hi
|
34e1720f7092c2cb74b1934bf4a0d984
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,192
|
This is some JavaScript code that fetches a torrent file and then posts it on a remote server, with a php endpoint, using the right form:
|
8c4026dda5ec43c98ae2d4fa10f57aaa
|
{
"intermediate": 0.36421728134155273,
"beginner": 0.33556461334228516,
"expert": 0.30021804571151733
}
|
10,193
|
i want you to review this code below and fix the issues
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import community
# Read the data from CSV file
data = pd.read_csv("cleaned_data.csv")
# Select the first 15 users as main users
main_users = data["User"][:15]
# Create an undirected graph
G = nx.Graph()
# Add main users as nodes to the graph
for user in main_users:
G.add_node(user, main_user=True)
# Add followers and following relationships as edges to the graph
for i in range(len(data)):
user = data.iloc[i]["User"]
followers = data.iloc[i]["Followers"].split(",")
following = data.iloc[i]["Following"].split(",")
if followers[0] != 'nan' and followers[0] != '':
for follower in followers:
G.add_edge(follower, user, relationship='follower') # Add follower relationship edge
if not G.has_node(follower):
G.add_node(follower, main_user=False)
else:
G.add_node(f"user_{i}", main_user=False)
if following[0] != 'nan' and following[0] != '':
for follow in following:
G.add_edge(user, follow, relationship='following') # Add following relationship edge
if not G.has_node(follow):
G.add_node(follow, main_user=False)
else:
G.add_node(f"user_{i+len(data)}", main_user=False)
# Remove the 'nan' node if it exists
if 'nan' in G:
G.remove_node('nan')
# Convert the directed graph to an undirected graph
G_undirected = G.to_undirected()
# Perform community detection using Louvain algorithm on the undirected graph
partition = community.best_partition(G_undirected)
# Rest of the code remains the same...
# Convert the partition into a dictionary format
partition_dict = {}
for node, community_id in partition.items():
partition_dict[node] = community_id
# Visualize subgraphs by community
graphs_data = []
for community_num in set(partition.values()):
subgraph_nodes = [node for node in G.nodes if partition[node] == community_num]
subgraph = G.subgraph(subgraph_nodes)
graphs_data.append(subgraph)
plt.figure(figsize=(30, 20))
pos = nx.circular_layout(G)
node_colors = ['red' if 'main_user' in G.nodes[node] and G.nodes[node]['main_user'] else 'skyblue' for node in G.nodes]
edge_colors = ['red' if G.edges[edge]['relationship'] == 'follower' else 'gray' for edge in G.edges]
for subgraph in graphs_data:
nx.draw_networkx(subgraph, pos, with_labels=True, node_color=node_colors, edge_color=edge_colors, node_size=24000, font_size=12)
# Add text with graph information
plt.text(1.1, 0.9, f"Nodes: {G.number_of_nodes()}", transform=plt.gca().transAxes, fontsize=14)
plt.text(1.1, 0.85, f"Edges: {G.number_of_edges()}", transform=plt.gca().transAxes, fontsize=14)
plt.text(1.1, 0.8, f"Connected Users: {len(main_users)}", transform=plt.gca().transAxes, fontsize=14)
plt.text(1.1, 0.75, f"Main User: {', '.join(main_users)}", transform=plt.gca().transAxes, fontsize=14)
plt.tight_layout()
plt.savefig("graph.png")
plt.close()
eigenvector_centrality = nx.eigenvector_centrality(G, max_iter=1000)
# Remove the temporary nodes and edges
from networkx.algorithms.community import greedy_modularity_communities
# Perform community detection using greedy modularity
communities = greedy_modularity_communities(G)
# Convert the communities to a partition dictionary
partition = {}
for i, comm in enumerate(communities):
for node in comm:
partition[node] = i
# Remove the 'nan' node from the partition dictionary
partition.pop('nan', None)
# Visualize subgraphs by community
graphs_data = []
for community_num in set(partition_dict.values()):
subgraph_nodes = [node for node in G.nodes if partition_dict[node] == community_num]
subgraph = G.subgraph(subgraph_nodes)
plt.figure(figsize=(25, 15))
pos = nx.kamada_kawai_layout(subgraph)
node_colors = ['red' if 'main_user' in subgraph.nodes[node] and subgraph.nodes[node]['main_user'] else 'skyblue' for node in subgraph.nodes]
nx.draw_networkx(subgraph, pos, with_labels=True, node_color=node_colors, edge_color='gray', node_size=19000, font_size=11)
# Add text with subgraph information
plt.text(0.95, 0.95, f"Community: {community_num}", transform=plt.gca().transAxes, fontsize=14, ha='right', va='top')
plt.text(0.95, 0.9, f"Nodes: {subgraph.number_of_nodes()}", transform=plt.gca().transAxes, fontsize=14, ha='right', va='top')
plt.text(0.95, 0.85, f"Edges: {subgraph.number_of_edges()}", transform=plt.gca().transAxes, fontsize=14, ha='right', va='top')
plt.text(0.95, 0.8, f"Connected Users: {len(main_users)}", transform=plt.gca().transAxes, fontsize=14, ha='right', va='top')
plt.text(0.95, 0.75, f"Main User: {', '.join(main_users)}", transform=plt.gca().transAxes, fontsize=14, ha='right', va='top')
plt.tight_layout()
plt.savefig(f"graph_community_{community_num}.png")
plt.close()
graph_data = {
'Community': community_num,
'Nodes': subgraph.number_of_nodes(),
'Edges': subgraph.number_of_edges(),
'Density': nx.density(subgraph),
}
graphs_data.append(graph_data)
# Calculate graph metrics
density = nx.density(G)
number_of_edges = G.number_of_edges()
unique_edges = G.size(weight="weight")
eigenvector_centrality_top_10 = sorted([(node, eigenvector_centrality[node]) for node in main_users if node in eigenvector_centrality.keys()], key=lambda x: x[1], reverse=True)[:10]
# Print graph metrics
print("Graph Density:", density)
print("Number of Edges:", number_of_edges)
print("Unique Edges:", unique_edges)
print("Eigenvector Centrality (Top 10 nodes):", eigenvector_centrality_top_10)
# Save graphs and metrics data to CSV files
graphs_df = pd.DataFrame(graphs_data)
graphs_df.to_csv('graphs_data.csv', index=False)
metrics_data = {
'Graph Density': density,
'Number of Edges': number_of_edges,
'Unique Edges': unique_edges,
'Eigenvector Centrality (Top 10 nodes)': eigenvector_centrality_top_10,
}
metrics_df = pd.DataFrame([metrics_data])
metrics_df.to_csv('metrics_data.csv', index=False)
|
dcbdaa833c0f4731cf3e6babb0b276ed
|
{
"intermediate": 0.4289364218711853,
"beginner": 0.343490868806839,
"expert": 0.2275727242231369
}
|
10,194
|
How to use stable diffusion for generation of a background for an object?
|
4634527c5ef2199ddb043f1734a1d719
|
{
"intermediate": 0.28247153759002686,
"beginner": 0.11808305978775024,
"expert": 0.5994454026222229
}
|
10,195
|
I'm using Vuetify 2 and avataaars.io urls to create a custom avatar builder. Please provide me with a sample code. I want all the avataaars categories ('topTypes', 'facialHairTypes', etc.) to be shown as vuetify tabs, and all the category options ('NoHair', 'Eyepatch', etc.) to be shown in each tab as image items inside the item-group components (3 items for a row). Each time the user changes an option I want the main avatar image to get updated. After avatar is build I want it to be stored in local storage and every time the app is restarted I want all the corresponding item-group elements to be preselected, according to the options of the stored avatar. Rather than using many urls, write a function that would update just one url. Also, make the option images computed, so that the user could see how each option would change the avatar.
|
f825efd4ca5836f29a7fae5803f03876
|
{
"intermediate": 0.5204957127571106,
"beginner": 0.19724257290363312,
"expert": 0.2822616398334503
}
|
10,196
|
I'm using Vuetify 2 and avataaars.io urls to create a custom avatar builder. Please provide me with a sample code. I want all the avataaars categories ('topTypes', 'facialHairTypes', etc.) to be shown as vuetify tabs, and all the category options ('NoHair', 'Eyepatch', etc.) to be shown in each tab as image items inside the item-group components (3 items for a row). Each time the user changes an option I want the main avatar image to get updated. After avatar is build I want it to be stored in local storage and every time the app is restarted I want all the corresponding item-group elements to be preselected, according to the options of the stored avatar. Rather than using many urls, write a function that would update just one url. Also, make the option images computed, so that the user could see how each option would change the avatar
|
579a921ec169d778fbb58c16234fba24
|
{
"intermediate": 0.5268853306770325,
"beginner": 0.18473230302333832,
"expert": 0.28838229179382324
}
|
10,197
|
I'm using Vuetify 2 and avataaars.io urls to create a custom avatar builder. Please provide me with a sample code. I want all the avataaars categories ('topTypes', 'facialHairTypes', etc.) to be shown as vuetify tabs, and all the category options ('NoHair', 'Eyepatch', etc.) to be shown in each tab as image items inside the item-group components (3 items for a row). Each time the user changes an option I want the main avatar image to get updated. After avatar is build I want it to be stored in local storage and every time the app is restarted I want all the corresponding item-group elements to be preselected, according to the options of the stored avatar. Rather than using many urls, write a function that would update just one url. Also, make the option images computed, so that the user could see how each option would change the avatar
|
13f719e61b791db2992c7463bc9d972b
|
{
"intermediate": 0.5268853306770325,
"beginner": 0.18473230302333832,
"expert": 0.28838229179382324
}
|
10,198
|
将下面这段javascript代码按照功能意思将函数名和变量名修改成有意义的名字,让我更好的理解,按照小驼峰格式,不要删除变量,保留原来的代码格式
function expandExpression(_0x3fdd79, _0x293ede, _0x35d695, _0x32ffde) {
_0x35d695 = _0x35d695 || {}, _0x32ffde = _0x32ffde || {};
if (!_0x3fdd79.jsconfuserDetected) {
return;
}
let _0x51d4aa = {},
_0x46226f;
if (_0x293ede.isFunctionDeclaration()) _0x46226f = utility.getBinding(_0x293ede.get('id'));else {
_0x46226f = utility.getBinding(_0x293ede);
if (!_0x46226f) {
return;
}
if (_0x46226f.path.isVariableDeclarator()) {
if (_0x51d4aa.data = _0x3fdd79.d.expander.get(_0x46226f)) {
return _0x51d4aa.data;
}
if ((_0x51d4aa.id = _0x46226f.path.get('init')).isIdentifier()) {
_0x51d4aa.data = expandExpression(_0x3fdd79, _0x51d4aa.id, _0x35d695, _0x32ffde);
if (_0x51d4aa.data) {
if (!_0x46226f.constant) {
_log('# warning: derived expander is not constant:', _summarize(_0x46226f.path)), _0x46226f.constantViolations.forEach(_0x4c2267 => _log(' ', _summarize(_0x4c2267))), _abort();
}
return _0x3fdd79.opts.test && _log('# got derived expander.', _summarize(_0x46226f.path), 'for', _summarize(_0x51d4aa.data.path)), _0x3fdd79.d.expander.set(_0x46226f, _0x51d4aa.data), _0x51d4aa.data;
}
}
return;
} else {
if (!_0x46226f.path.isFunctionDeclaration()) {
return;
}
}
}
if (_0x51d4aa.data = _0x3fdd79.d.expander.get(_0x46226f)) return _0x51d4aa.data;
if (_0x32ffde.shallow) {
return;
}
let _0x5dbf9e = _0x46226f.path.get('params'),
_0x3a6c02 = _0x46226f.path.get('body.body');
const _0x379c81 = {};
_0x379c81.value = false;
if (_0x3fdd79.d.secondTable && _0x5dbf9e.length === 5 && utility.isAssignmentPattern(_0x5dbf9e[3], (_0x5a1b51, _0x41fa0d) => _0x5a1b51.isIdentifier() && (_0x51d4aa.decoder = {
'id': _0x41fa0d
}, _0x41fa0d).isIdentifier()) && utility.isAssignmentPattern(_0x5dbf9e[4], (_0x36a1c2, _0x1a1673) => _0x36a1c2.isIdentifier() && utility.getBinding(_0x1a1673) === _0x3fdd79.d.secondTable.cache) && _0x3a6c02.length === 2 && _0x3a6c02[0].isIfStatement() && _0x3a6c02[1].isReturnStatement() && (_0x51d4aa.v = _0x3a6c02[1].get('argument')).isConditionalExpression() && (_0x51d4aa.alt = _0x51d4aa.v.get('alternate')) && utility.isLogicalExpression(_0x51d4aa.alt, (_0xdfc392, _0x186c40, _0x2b3d68) => _0x2b3d68 === '||' && utility.isMemberExpression(_0xdfc392, (_0x97cb64, _0x16a762, _0x9c9a71) => utility.getBinding(_0x97cb64) === _0x3fdd79.d.secondTable.cache && utility.getBinding(_0x16a762) === utility.getBinding(_0x5dbf9e[0])) && utility.isSequenceExpression(_0x186c40, _0x46ba62 => _0x46ba62.length === 2 && utility.isAssignmentExpression(_0x46ba62[1], (_0x4b492f, _0x142f74, _0x351868) => _0x351868 === '=' && utility.isMemberExpression(_0x4b492f, (_0x2002ca, _0x5ac6d6, _0x4f4ac3) => utility.getBinding(_0x2002ca) === _0x3fdd79.d.secondTable.cache && utility.getBinding(_0x5ac6d6) === utility.getBinding(_0x5dbf9e[0])))))) {
_log('# got second-expander:', _summarize(_0x46226f.path)), _0x51d4aa.decoder.bd = utility.getBinding(_0x51d4aa.decoder.id);
!_0x51d4aa.decoder.bd && (_log('# error: no binding of decoder \'' + _0x51d4aa.decoder.id + '\''), _abort());
_log(' decoder:', _summarize(_0x51d4aa.decoder.bd.path));
if (!_0x51d4aa.decoder.bd.path.isFunctionDeclaration) {
_log('# error: decoder must be FunctionDeclaration. got', _0x51d4aa.decoder.bd.path.type), _abort();
}
return initializeCode(_0x3fdd79, _0x51d4aa.decoder.bd.path, {
'name': 'decoder'
}), addMetacode(_0x3fdd79, _0x51d4aa.decoder.bd.path, 'remove second-expander decoder'), initializeCode(_0x3fdd79, _0x46226f.path, {
'name': 'second-expander'
}), addMetacode(_0x3fdd79, _0x46226f.path, 'remove second-expander'), _0x51d4aa.data = {
'bd': _0x46226f,
'path': _0x46226f.path,
'expand': _0x3fdd79.sandbox[_0x46226f.identifier.name],
'decoder': _0x51d4aa.decoder,
'name': 'second-expander'
}, _0x3fdd79.d.expander.set(_0x46226f, _0x51d4aa.data), _0x51d4aa.data;
} else {
if (_0x3fdd79.d.extraTable && (_0x51d4aa.body = _0x46226f.path.get('body.body')) && _0x51d4aa.body.length > 0 && ((_0x51d4aa.rs = _0x51d4aa.body[_0x51d4aa.body.length - 1]).isReturnStatement() || utility.isIfStatement(_0x51d4aa.rs, (_0x569549, _0x49feab, _0x766426) => _0x569549.isBooleanLiteral(_0x379c81) && _0x766426.isBlockStatement() && (_0x51d4aa.body = _0x766426.get('body')) && _0x51d4aa.body.length > 0 && (_0x51d4aa.rs = _0x51d4aa.body[_0x51d4aa.body.length - 1]).isReturnStatement())) && (_0x51d4aa.arg = _0x51d4aa.rs.get('argument')) && utility.isMemberExpression(_0x51d4aa.arg, (_0x43b5f0, _0x3a31bb) => utility.getBinding(_0x43b5f0) === _0x3fdd79.d.extraTable.bd)) {
let _0x38cb1e = _0x46226f.path.get('id');
_log('# got extra-expander:', _summarize(_0x46226f.path)), initializeCode(_0x3fdd79, _0x46226f.path, {
'name': 'extra-expander'
}), addMetacode(_0x3fdd79, _0x46226f.path, 'remove extra-expander');
const _0x4cd180 = {};
return _0x4cd180.bd = _0x46226f, _0x4cd180.path = _0x46226f.path, _0x4cd180.expand = _0x3fdd79.sandbox[_0x46226f.identifier.name], _0x4cd180.name = 'extra-expander', _0x51d4aa.data = _0x4cd180, _0x3fdd79.d.expander.set(_0x46226f, _0x51d4aa.data), _0x51d4aa.data;
} else {
if (_0x3fdd79.d.objectExpander && _0x46226f === _0x3fdd79.d.objectExpander.bd) {
_log('parsing object-expander at', _0x35d695.name);
let _0x5525c2 = new Map();
_0x46226f.path.get('body.body').forEach(_0x59a236 => {
_0x3fdd79.opts.test && _log(' ' + _summarize(_0x59a236)), utility.isSwitchStatement(_0x59a236, (_0x427943, _0x3cc0c2) => {
_0x3cc0c2.forEach(_0x409e48 => {
utility.isSwitchCase(_0x409e48, (_0x5337af, _0x8fe485) => {
let _0x266583 = _0x8fe485[0],
_0x2b826c,
_0x26d3a6;
_0x3fdd79.opts.test && _log(' case', _summarize(_0x5337af) + ':', _gencode(_0x266583));
try {
_0x2b826c = utility.evalLiteralExpression(_0x5337af);
} catch (_0x4e3504) {
_log(_0x4e3504.name + ':', _0x4e3504.message), _log('# error: SwitchCase.test is not literal:', _summarize(_0x266583)), _abort();
}
if (!_0x266583) _log('# error: SwtchCase has no consequent:', _summarize(_0x266583)), _abort();else {
if (utility.isReturnStatement(_0x266583, _0x41225d => utility.isLogicalExpression(_0x41225d, (_0x345bce, _0x2c6fe3, _0x3a0fa0) => _0x3a0fa0 === '||' && utility.isMemberExpression(_0x345bce, (_0x487745, _0x4306e8, _0x3f00ed, _0x203040) => _0x26d3a6 = _0x203040))) || utility.isExpressionStatement(_0x266583, _0x1aac8 => utility.isAssignmentExpression(_0x1aac8, (_0xc04f5c, _0x1c4236, _0x563186) => _0x563186 === '=' && _0x1c4236.isStringLiteral() && (_0x26d3a6 = _0x1c4236.node.value)))) {
_0x3fdd79.opts.test && _log(' ' + _0x2b826c, ':', _0x26d3a6), _0x5525c2.set(_0x2b826c, _0x26d3a6);
} else {
_log('# error: unexpected SwticCase.consequent[0]:', _gencode(_0x266583)), _abort();
}
}
});
});
});
}), _log('# got object-expander:', _summarize(_0x46226f.path)), _log(' globals:', Array.from(_0x5525c2).map(_0x4abc6b => _0x4abc6b[1]).sort().join(', '));
let _0x4fc8ba = {
'bd': _0x46226f,
'path': _0x46226f.path,
'expand': function (_0x361fca) {
return _0x5525c2.get(_0x361fca);
},
'name': 'object-expander'
};
_0x3fdd79.d.expander.set(_0x46226f, _0x4fc8ba), addMetacode(_0x3fdd79, _0x46226f.path, 'remove object-expander');
} else {
if ((_0x51d4aa.body = _0x46226f.path.get('body.body')) && utility.isSwitchStatement(_0x51d4aa.body[_0x51d4aa.body.length - 1], (_0x2d833c, _0x4a6232) => (_0x51d4aa.ope = utility.getBinding(_0x2d833c)) && utility.isVariableDeclarator(_0x51d4aa.ope.path, (_0x49ea99, _0x3afa9d) => !_0x3afa9d.node) && _0x4a6232.every(_0x29647e => utility.isSwitchCase(_0x29647e, (_0x402a36, _0x5daef8) => utility.isReturnStatement(_0x5daef8[0], _0x48722a => utility.isBinaryExpression(_0x48722a, (_0x18faf7, _0x375069, _0x2fb4ed) => ['+', '-', '*', '/'].includes(_0x2fb4ed))))))) {
let _0x549ba2 = 'calculator';
_log('# got', _0x549ba2 + ':', _summarize(_0x46226f.path)), _log(' operator specifier:', _summarize(_0x51d4aa.ope.path)), _0x51d4aa.ope.referencePaths.forEach(_0x1afe40 => {
if (_0x51d4aa.directive) {
return;
}
let _0x841446 = utility.findAncestor(_0x1afe40, _0x1f02ad => !['BinaryExpression', 'AssignmentExpression', 'SequenceExpression', 'ReturnStatement', 'IfStatement', 'BlockStatement'].includes(_0x1f02ad.type));
if (_0x841446.isFunctionDeclaration()) {
_0x5b5126(_0x3fdd79, _0x841446);
let _0x4a38d3 = _0x1afe40.parentPath,
_0xc5f75d = _0x4a38d3.parentPath,
_0x28aaf1 = _0xc5f75d.parentPath;
const _0x482ea7 = {};
_0x482ea7.value = 0;
if (utility.isBinaryExpression(_0x4a38d3, (_0x528c74, _0x15c3af, _0x35d6e3) => _0x35d6e3 === '+' && _0x528c74 === _0x1afe40 && utility.isSequenceExpression(_0x15c3af, _0x324f08 => utility.isAssignmentExpression(_0x324f08[0], (_0x1abc26, _0x438b91) => _0x1abc26.isIdentifier({
'name': _0x1afe40.node.name
}) && (_0x51d4aa.right = _0x438b91)) && _0x324f08[1] && _0x324f08[1].isNumericLiteral(_0x482ea7)))) {
utility.isAssignmentExpression(_0xc5f75d, (_0x33669c, _0x1a8d6f, _0x3be335) => utility.bothReferToSame(_0x33669c, _0x51d4aa.right) && _0x1a8d6f === _0x4a38d3) && _0x28aaf1.key === 'argument' && _0x28aaf1.parentPath.isReturnStatement() && utility.isSequenceExpression(_0x28aaf1, _0x92723e => _0x92723e[0] === _0xc5f75d && utility.bothReferToSame(_0x92723e[1], _0x51d4aa.right)) && (_0x51d4aa.dir = utility.getBinding(_0x841446.get('id')), _log(' operator directive:', _summarize(_0x841446)));
}
}
}), initializeCode(_0x3fdd79, _0x51d4aa.ope.path, {
'name': 'calculator operator specifier'
}), _0x3fdd79.d.expander.set(_0x51d4aa.ope, {
'bd': _0x51d4aa.ope,
'path': _0x51d4aa.ope.path,
'expand': _0x3fdd79.sandbox[_0x51d4aa.ope.identifier.name],
'name': 'calculator operator specifier'
});
if (_0x51d4aa.dir) {
initializeCode(_0x3fdd79, _0x51d4aa.dir.path, {
'name': 'calculator operator directive'
}), _0x3fdd79.d.expander.set(_0x51d4aa.dir, {
'bd': _0x51d4aa.dir,
'path': _0x51d4aa.dir.path,
'expand': _0x3fdd79.sandbox[_0x51d4aa.dir.identifier.name],
'name': 'calculator operator directive',
'noReturn': true
});
}
const _0x4deaf7 = {};
_0x4deaf7.name = _0x549ba2, initializeCode(_0x3fdd79, _0x46226f.path, _0x4deaf7);
const _0x41d736 = {};
_0x41d736.bd = _0x46226f, _0x41d736.path = _0x46226f.path, _0x41d736.expand = _0x3fdd79.sandbox[_0x46226f.identifier.name], _0x41d736.name = _0x549ba2, _0x51d4aa.data = _0x41d736, _0x3fdd79.d.expander.set(_0x46226f, _0x51d4aa.data);
const _0x43d575 = {};
return _0x43d575.bd = _0x46226f, _0x43d575.operator = _0x51d4aa.ope, _0x43d575.directive = _0x51d4aa.dir, _0x3fdd79.d.calculator = _0x43d575, _0x51d4aa.data;
} else {
if (_0x51d4aa.data = processBossExpander(_0x3fdd79, _0x46226f, _0x35d695)) return _0x51d4aa.data;
}
}
}
}
}
|
b27a564842fcaf6deeb815dec914fae5
|
{
"intermediate": 0.34686118364334106,
"beginner": 0.43738165497779846,
"expert": 0.21575716137886047
}
|
10,199
|
hello
|
114f2769291b4672fe0058ae3128db7d
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
10,200
|
write me python code for excel to as a pdf.
|
6892103fabb476bfb5c6498741ab2e92
|
{
"intermediate": 0.39694392681121826,
"beginner": 0.23082157969474792,
"expert": 0.3722345232963562
}
|
10,201
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::CleanupCommandBuffers()
{
vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
}
void Renderer::CleanupCommandPool()
{
// Clean up Vulkan command pool
CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool
vkDestroyCommandPool(device, commandPool, nullptr);
}
void Renderer::CleanupDevice()
{
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
void Renderer::CleanupFramebuffers()
{
for (auto framebuffer : framebuffers)
{
if (framebuffer != VK_NULL_HANDLE)
{
vkDestroyFramebuffer(device, framebuffer, nullptr);
framebuffer = VK_NULL_HANDLE;
}
}
framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer
}
void Renderer::CleanupImageViews()
{
for (auto imageView : swapChainImageViews)
{
vkDestroyImageView(device, imageView, nullptr);
}
swapChainImageViews.clear();
}
void Renderer::CleanupInstance()
{
// Destroy the Vulkan instance
vkDestroyInstance(instance, nullptr);
}
void Renderer::CleanupRenderPass()
{
vkDestroyRenderPass(device, renderPass, nullptr);
}
void Renderer::CleanupSwapchain()
{
// Clean up Vulkan swapchain
if (swapchain != VK_NULL_HANDLE)
{
vkDestroySwapchainKHR(device, swapchain, nullptr);
swapchain = VK_NULL_HANDLE;
}
}
void Renderer::CleanupSyncObjects()
{
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (renderFinishedSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
if (imageAvailableSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
if (inFlightFences[i] != VK_NULL_HANDLE)
vkDestroyFence(device, inFlightFences[i], nullptr);
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
A portion of GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
Mesh.h:
#pragma once
#include <vector>
#include <vulkan/vulkan.h>
#include <glm/glm.hpp>
#include "BufferUtils.h"
struct Vertex
{
glm::vec3 position;
glm::vec3 color;
};
class Mesh
{
public:
Mesh();
~Mesh();
void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
const std::vector<Vertex>& GetVertices() const;
const std::vector<uint32_t>& GetIndices() const;
VkBuffer GetVertexBuffer() const;
VkBuffer GetIndexBuffer() const;
void SetVertices(const std::vector<Vertex>& vertices);
void SetIndices(const std::vector<uint32_t>& indices);
std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const;
std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const;
private:
VkDevice device;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
VkBuffer indexBuffer;
VkDeviceMemory indexBufferMemory;
};
A portion of Mesh.cpp:
Mesh::Mesh()
: device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE)
{
}
Mesh::~Mesh()
{
Cleanup();
}
void Mesh::Cleanup()
{
if (device != VK_NULL_HANDLE)
{
if (vertexBuffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(device, vertexBuffer, nullptr);
vkFreeMemory(device, vertexBufferMemory, nullptr);
vertexBuffer = VK_NULL_HANDLE;
vertexBufferMemory = VK_NULL_HANDLE;
}
if (indexBuffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(device, indexBuffer, nullptr);
vkFreeMemory(device, indexBufferMemory, nullptr);
indexBuffer = VK_NULL_HANDLE;
indexBufferMemory = VK_NULL_HANDLE;
}
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
A portion of Material.cpp:
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
void Cleanup();
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
A portion of Texture.cpp:
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
Cleanup();
}
void Texture::Cleanup()
{
if (!initialized) {
return;
}
if (sampler != VK_NULL_HANDLE) {
vkDestroySampler(device, sampler, nullptr);
sampler = VK_NULL_HANDLE;
}
if (imageView != VK_NULL_HANDLE) {
vkDestroyImageView(device, imageView, nullptr);
imageView = VK_NULL_HANDLE;
}
if (image != VK_NULL_HANDLE) {
vkDestroyImage(device, image, nullptr);
image = VK_NULL_HANDLE;
}
if (imageMemory != VK_NULL_HANDLE) {
vkFreeMemory(device, imageMemory, nullptr);
imageMemory = VK_NULL_HANDLE;
}
initialized = false;
}
I am getting the following error in Renderer::CleanupDevice:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1b470d69e90, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0xca0b160000000085, type = VK_OBJECT_TYPE_PIPELINE; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1b470d69e90[], VkPipeline 0xca0b160000000085[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1b470d69e90, type: 3, name: NULL
[1] 0xca0b160000000085, type: 19, name: NULL
Do you know what might be causing it and how to change the code to fix it?
|
a07744d6ae30b0f7647a2b2797f2b132
|
{
"intermediate": 0.279109388589859,
"beginner": 0.4491756856441498,
"expert": 0.27171486616134644
}
|
10,202
|
Create a batch script for Windows 10 that can create shortcuts in the current folder of all the fildes inside the subfolders. The name of the shortcut should be the name of the subfolder plus the name of the file. Thoses names can contain Unicode characters, so make it sure it works for this case too.
|
7ffdff24db0a6abb9fa232f2127a4088
|
{
"intermediate": 0.360517680644989,
"beginner": 0.21390123665332794,
"expert": 0.42558106780052185
}
|
10,203
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::CleanupCommandBuffers()
{
vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
}
void Renderer::CleanupCommandPool()
{
// Clean up Vulkan command pool
CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool
vkDestroyCommandPool(device, commandPool, nullptr);
}
void Renderer::CleanupDevice()
{
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
void Renderer::CleanupFramebuffers()
{
for (auto framebuffer : framebuffers)
{
if (framebuffer != VK_NULL_HANDLE)
{
vkDestroyFramebuffer(device, framebuffer, nullptr);
framebuffer = VK_NULL_HANDLE;
}
}
framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer
}
void Renderer::CleanupImageViews()
{
for (auto imageView : swapChainImageViews)
{
vkDestroyImageView(device, imageView, nullptr);
}
swapChainImageViews.clear();
}
void Renderer::CleanupInstance()
{
// Destroy the Vulkan instance
vkDestroyInstance(instance, nullptr);
}
void Renderer::CleanupRenderPass()
{
vkDestroyRenderPass(device, renderPass, nullptr);
}
void Renderer::CleanupSwapchain()
{
// Clean up Vulkan swapchain
if (swapchain != VK_NULL_HANDLE)
{
vkDestroySwapchainKHR(device, swapchain, nullptr);
swapchain = VK_NULL_HANDLE;
}
}
void Renderer::CleanupSyncObjects()
{
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (renderFinishedSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
if (imageAvailableSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
if (inFlightFences[i] != VK_NULL_HANDLE)
vkDestroyFence(device, inFlightFences[i], nullptr);
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
A portion of GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
A portion of Material.cpp:
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
void Cleanup();
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
A portion of Texture.cpp:
void Texture::Cleanup()
{
if (!initialized) {
return;
}
if (sampler != VK_NULL_HANDLE) {
vkDestroySampler(device, sampler, nullptr);
sampler = VK_NULL_HANDLE;
}
if (imageView != VK_NULL_HANDLE) {
vkDestroyImageView(device, imageView, nullptr);
imageView = VK_NULL_HANDLE;
}
if (image != VK_NULL_HANDLE) {
vkDestroyImage(device, image, nullptr);
image = VK_NULL_HANDLE;
}
if (imageMemory != VK_NULL_HANDLE) {
vkFreeMemory(device, imageMemory, nullptr);
imageMemory = VK_NULL_HANDLE;
}
initialized = false;
}
Pipeline.h:
#pragma once
#include <vulkan/vulkan.h>
#include <vector>
#include <array>
#include <stdexcept>
#include "Shader.h"
class Pipeline
{
public:
Pipeline();
~Pipeline();
void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions,
const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions,
VkExtent2D swapchainExtent,
const std::vector<Shader*>& shaders,
VkRenderPass renderPass,
VkPipelineLayout pipelineLayout,
VkDevice device);
void Cleanup();
VkPipeline GetPipeline() const;
bool IsInitialized() const;
private:
VkDevice device;
VkPipeline pipeline;
bool initialized;
void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages);
};
A portion of code from Pipeline.cpp:
Pipeline::Pipeline()
: device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE), initialized(false)
{
}
Pipeline::~Pipeline()
{
Cleanup();
}
void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions,
const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions,
VkExtent2D swapchainExtent,
const std::vector<Shader*>& shaders,
VkRenderPass renderPass,
VkPipelineLayout pipelineLayout,
VkDevice device)
{
this->device = device;
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size());
vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data();
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size());
vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data();
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport{};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = static_cast<float>(swapchainExtent.width);
viewport.height = static_cast<float>(swapchainExtent.height);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{};
scissor.offset = { 0, 0 };
scissor.extent = swapchainExtent;
VkPipelineViewportStateCreateInfo viewportState{};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachment.blendEnable = VK_FALSE;
VkPipelineColorBlendStateCreateInfo colorBlending{};
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment;
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
std::vector<VkPipelineShaderStageCreateInfo> shaderStages;
CreateShaderStages(shaders, shaderStages);
VkGraphicsPipelineCreateInfo pipelineCreateInfo{};
pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
pipelineCreateInfo.pStages = shaderStages.data();
pipelineCreateInfo.pVertexInputState = &vertexInputInfo;
pipelineCreateInfo.pInputAssemblyState = &inputAssembly;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pRasterizationState = &rasterizer;
pipelineCreateInfo.pMultisampleState = &multisampling;
pipelineCreateInfo.pColorBlendState = &colorBlending;
pipelineCreateInfo.layout = pipelineLayout;
pipelineCreateInfo.renderPass = renderPass;
pipelineCreateInfo.subpass = 0;
if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create graphics pipeline.");
}
initialized = true;
}
I am getting the following error in Pipeline::CreateGraphicsPipeline:
VUID-VkPipelineLayoutCreateInfo-pSetLayouts-06561(ERROR / SPEC): msgNum: -2012114744 - Validation Error: [ VUID-VkPipelineLayoutCreateInfo-pSetLayouts-06561 ] Object 0: handle = 0x208787c0ce0, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x881190c8 | vkCreatePipelineLayout(): pSetLayouts[0] is VK_NULL_HANDLE, but VK_EXT_graphics_pipeline_library is not enabled. The Vulkan spec states: Elements of pSetLayouts must be valid VkDescriptorSetLayout objects (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkPipelineLayoutCreateInfo-pSetLayouts-06561)
Objects: 1
[0] 0x208787c0ce0, type: 3, name: NULL
Do you know what might be causing it and how to change the code to fix it?
|
8c1ef06e878a03ff1110dbeb42c0ee1e
|
{
"intermediate": 0.279109388589859,
"beginner": 0.4491756856441498,
"expert": 0.27171486616134644
}
|
10,204
|
hi i need you to code a program for me
|
0d2780db0d725f186a7822897f702d37
|
{
"intermediate": 0.2675270140171051,
"beginner": 0.2319832146167755,
"expert": 0.5004897713661194
}
|
10,205
|
import numpy as np
import pandas as pd
import yfinance as yf
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
# Function to fetch historical stock data
def fetch_stock_data(ticker, start_date, end_date):
stock_data = yf.download(ticker, start=start_date, end=end_date)
return stock_data
# Function to compute the Relative Strength Index (RSI)
def compute_rsi(close_prices):
price_diff = close_prices.diff()
positive_diff = price_diff.where(price_diff > 0, 0)
negative_diff = -price_diff.where(price_diff < 0, 0)
average_gain = positive_diff.rolling(window=14).mean()
average_loss = negative_diff.rolling(window=14).mean()
relative_strength = average_gain / average_loss
rsi = 100 - (100 / (1 + relative_strength))
return rsi
# Function to compute the Stochastic Oscillator
def compute_stochastic_oscillator(high_prices, low_prices, close_prices):
highest_high = high_prices.rolling(window=14).max()
lowest_low = low_prices.rolling(window=14).min()
percent_k = ((close_prices - lowest_low) / (highest_high - lowest_low)) * 100
percent_d = percent_k.rolling(window=3).mean()
return percent_k, percent_d
# Function to compute technical indicators
def compute_indicators(stock_data):
stock_data['MA_5'] = stock_data['Adj Close'].rolling(window=5).mean().shift()
stock_data['MA_15'] = stock_data['Adj Close'].rolling(window=15).mean().shift()
stock_data['RSI'] = compute_rsi(stock_data['Adj Close'])
stock_data['%K'], stock_data['%D'] = compute_stochastic_oscillator(stock_data['High'], stock_data['Low'], stock_data['Close'])
return stock_data
# Function to compute feature scores and rank stocks
def rank_stocks(start_date, end_date):
# Fetch historical data for all available tickers
all_tickers = yf.download('^GSPC', start=start_date, end=end_date)
all_tickers = pd.DataFrame(all_tickers['Adj Close'])
all_tickers = all_tickers.columns
feature_scores = []
for ticker in all_tickers:
stock_data = fetch_stock_data(ticker, start_date, end_date)
stock_data = compute_indicators(stock_data)
features = stock_data[['MA_5', 'MA_15', 'RSI', '%K', '%D']].tail(1).values
# Standardize the features
scaler = StandardScaler()
standardized_features = scaler.fit_transform(features)
# Evaluate features using ANOVA F-value
kbest = SelectKBest(f_classif, k=5)
kbest.fit(standardized_features, np.ones((1,)))
feature_scores.append((ticker, kbest.scores_.sum()))
# Sort stocks by feature scores
ranked_stocks = sorted(feature_scores, key=lambda x: x[1], reverse=True)[:10]
return ranked_stocks
if __name__ == "__main__":
# Specify the date range for stock data
start_date = "2019-01-01"
end_date = "2023-06-03"
# Rank stocks based on technical indicators
ranked_stocks = rank_stocks(start_date, end_date)
# Print results
print("Top 10 stocks based on technical indicators:")
for rank, stock in enumerate(ranked_stocks, start=1):
print(f"{rank}. {stock[0]} (Score: {stock[1]})")
what is wrong with my code
|
88802ffd37933eaf2114695d4ceaee1a
|
{
"intermediate": 0.39908117055892944,
"beginner": 0.35289493203163147,
"expert": 0.24802392721176147
}
|
10,206
|
Create a MQL4 indicator code to display three LWMAs with different colors of the periods: 3, 6 and 9 with the names MA1, MA2, MA3. Create an array with the price values of all MAs and sort them and calculate the difference and display that difference number continuously on the chart. Compare the difference in pips with a extern input called "Max_MA_Range" and if the difference is less or equal to the Max_MA_Range, draw a range box around the area where the MAs are within the range of the difference. Draw a text saying "BREAKOUT" and send a notification to mobile when price closes outside of this box.
|
c815c860f344e3792611a084b75e4938
|
{
"intermediate": 0.5442438125610352,
"beginner": 0.1516222059726715,
"expert": 0.30413398146629333
}
|
10,207
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::CleanupCommandBuffers()
{
vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
}
void Renderer::CleanupCommandPool()
{
// Clean up Vulkan command pool
CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool
vkDestroyCommandPool(device, commandPool, nullptr);
}
void Renderer::CleanupDevice()
{
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
void Renderer::CleanupFramebuffers()
{
for (auto framebuffer : framebuffers)
{
if (framebuffer != VK_NULL_HANDLE)
{
vkDestroyFramebuffer(device, framebuffer, nullptr);
framebuffer = VK_NULL_HANDLE;
}
}
framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer
}
void Renderer::CleanupImageViews()
{
for (auto imageView : swapChainImageViews)
{
vkDestroyImageView(device, imageView, nullptr);
}
swapChainImageViews.clear();
}
void Renderer::CleanupInstance()
{
// Destroy the Vulkan instance
vkDestroyInstance(instance, nullptr);
}
void Renderer::CleanupRenderPass()
{
vkDestroyRenderPass(device, renderPass, nullptr);
}
void Renderer::CleanupSwapchain()
{
// Clean up Vulkan swapchain
if (swapchain != VK_NULL_HANDLE)
{
vkDestroySwapchainKHR(device, swapchain, nullptr);
swapchain = VK_NULL_HANDLE;
}
}
void Renderer::CleanupSyncObjects()
{
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (renderFinishedSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
if (imageAvailableSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
if (inFlightFences[i] != VK_NULL_HANDLE)
vkDestroyFence(device, inFlightFences[i], nullptr);
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
A portion of GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
A portion of Material.cpp:
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
void Cleanup();
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
A portion of Texture.cpp:
void Texture::Cleanup()
{
if (!initialized) {
return;
}
if (sampler != VK_NULL_HANDLE) {
vkDestroySampler(device, sampler, nullptr);
sampler = VK_NULL_HANDLE;
}
if (imageView != VK_NULL_HANDLE) {
vkDestroyImageView(device, imageView, nullptr);
imageView = VK_NULL_HANDLE;
}
if (image != VK_NULL_HANDLE) {
vkDestroyImage(device, image, nullptr);
image = VK_NULL_HANDLE;
}
if (imageMemory != VK_NULL_HANDLE) {
vkFreeMemory(device, imageMemory, nullptr);
imageMemory = VK_NULL_HANDLE;
}
initialized = false;
}
Pipeline.h:
#pragma once
#include <vulkan/vulkan.h>
#include <vector>
#include <array>
#include <stdexcept>
#include "Shader.h"
class Pipeline
{
public:
Pipeline();
~Pipeline();
void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions,
const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions,
VkExtent2D swapchainExtent,
const std::vector<Shader*>& shaders,
VkRenderPass renderPass,
VkPipelineLayout pipelineLayout,
VkDevice device);
void Cleanup();
VkPipeline GetPipeline() const;
bool IsInitialized() const;
private:
VkDevice device;
VkPipeline pipeline;
bool initialized;
void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages);
};
A portion of code from Pipeline.cpp:
Pipeline::Pipeline()
: device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE), initialized(false)
{
}
Pipeline::~Pipeline()
{
Cleanup();
}
void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions,
const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions,
VkExtent2D swapchainExtent,
const std::vector<Shader*>& shaders,
VkRenderPass renderPass,
VkPipelineLayout pipelineLayout,
VkDevice device)
{
this->device = device;
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size());
vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data();
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size());
vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data();
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport{};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = static_cast<float>(swapchainExtent.width);
viewport.height = static_cast<float>(swapchainExtent.height);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{};
scissor.offset = { 0, 0 };
scissor.extent = swapchainExtent;
VkPipelineViewportStateCreateInfo viewportState{};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachment.blendEnable = VK_FALSE;
VkPipelineColorBlendStateCreateInfo colorBlending{};
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment;
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
std::vector<VkPipelineShaderStageCreateInfo> shaderStages;
CreateShaderStages(shaders, shaderStages);
VkGraphicsPipelineCreateInfo pipelineCreateInfo{};
pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
pipelineCreateInfo.pStages = shaderStages.data();
pipelineCreateInfo.pVertexInputState = &vertexInputInfo;
pipelineCreateInfo.pInputAssemblyState = &inputAssembly;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pRasterizationState = &rasterizer;
pipelineCreateInfo.pMultisampleState = &multisampling;
pipelineCreateInfo.pColorBlendState = &colorBlending;
pipelineCreateInfo.layout = pipelineLayout;
pipelineCreateInfo.renderPass = renderPass;
pipelineCreateInfo.subpass = 0;
if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create graphics pipeline.");
}
initialized = true;
}
I am getting the following error in Pipeline::CreateGraphicsPipeline:
VUID-VkPipelineLayoutCreateInfo-pSetLayouts-06561(ERROR / SPEC): msgNum: -2012114744 - Validation Error: [ VUID-VkPipelineLayoutCreateInfo-pSetLayouts-06561 ] Object 0: handle = 0x208787c0ce0, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x881190c8 | vkCreatePipelineLayout(): pSetLayouts[0] is VK_NULL_HANDLE, but VK_EXT_graphics_pipeline_library is not enabled. The Vulkan spec states: Elements of pSetLayouts must be valid VkDescriptorSetLayout objects (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkPipelineLayoutCreateInfo-pSetLayouts-06561)
Objects: 1
[0] 0x208787c0ce0, type: 3, name: NULL
The error seems to have occured when trying to resolve an issue with cleaning up the DescriptorSets in the Material class. Something may have gone wrong in implementing that fix.
Do you know what might be causing it and how to change the code to fix it?
|
49ca662b8a23eee5c7b05765a2e0bfae
|
{
"intermediate": 0.279109388589859,
"beginner": 0.4491756856441498,
"expert": 0.27171486616134644
}
|
10,208
|
Explain why these two functions do not work. When I enter print(greatest(countries,"Death Rate",16)) I always get the #1 result, but I want to be able to get the Nth!
def remove_highest_dictionary(list_of_dicts, feature, times):
for i in range(times):
results = greatest(list_of_dicts, feature, 1)
highest_value = results[0]
new_list = []
for dictionary in list_of_dicts:
if dictionary[feature] != highest_value:
new_list.append(dictionary)
list_of_dicts = new_list
return list_of_dicts
def greatest(list_of_dicts, feature, rank):
highest = 0
holder = ""
for dictionary in list_of_dicts:
value = float(dictionary[feature])
if value > highest:
highest = value
holder = dictionary["Name"]
elif value == highest:
holder = holder + " and " + dictionary["Name"]
if rank == 1:
return highest, holder
else:
new_list = remove_highest_dictionary(list_of_dicts, feature, rank-1)
return greatest(new_list, feature, 1)
|
210b75dc6d421cf72cbdbdd52b4d8b91
|
{
"intermediate": 0.2838493883609772,
"beginner": 0.5573670268058777,
"expert": 0.15878355503082275
}
|
10,209
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
void Renderer::CreateGraphicsPipeline(Mesh* mesh, Material* material) {
vkDeviceWaitIdle(device);
if (pipeline)
{
pipeline->Cleanup();
}
// Create pipeline object and configure its properties
pipeline = std::make_shared<Pipeline>();
pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(),
mesh->GetVertexInputAttributeDescriptions(),
swapChainExtent,
{material->GetvertexShader().get(), material->GetfragmentShader().get()},
renderPass,
material->GetPipelineLayout(),
device);
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting the following error in Renderer::CleanupDevice:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1b1c8945040, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0x149d740000000087, type = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1b1c8945040[], VkDescriptorSetLayout 0x149d740000000087[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1b1c8945040, type: 3, name: NULL
[1] 0x149d740000000087, type: 20, name: NULL
I believe it relates to the handling of DescriptorSets in the Material class. I think I need to correctly link the DescriptorSets being passed into the Initialize method to the member variables so they can be properly destroyed. I am right in this thinking? If so, can you show me how?
|
7eba11cc9626d9f70e700d2d9475ffcd
|
{
"intermediate": 0.4465576410293579,
"beginner": 0.420981764793396,
"expert": 0.1324605941772461
}
|
10,210
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->samplerDescriptorSetLayout = samplerDescriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
void Renderer::CreateGraphicsPipeline(Mesh* mesh, Material* material) {
vkDeviceWaitIdle(device);
if (pipeline)
{
pipeline->Cleanup();
}
// Create pipeline object and configure its properties
pipeline = std::make_shared<Pipeline>();
pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(),
mesh->GetVertexInputAttributeDescriptions(),
swapChainExtent,
{material->GetvertexShader().get(), material->GetfragmentShader().get()},
renderPass,
material->GetPipelineLayout(),
device);
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting the following error in Renderer::CleanupDevice:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1c27d733290, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0x149d740000000087, type = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1c27d733290[], VkDescriptorSetLayout 0x149d740000000087[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1c27d733290, type: 3, name: NULL
[1] 0x149d740000000087, type: 20, name: NULL
Do you know what might be causeing this error and how to fix it?
|
e7f969cf907c9a857a2d9b312837c011
|
{
"intermediate": 0.4465576410293579,
"beginner": 0.420981764793396,
"expert": 0.1324605941772461
}
|
10,211
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->samplerDescriptorSetLayout = samplerDescriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
void Renderer::CreateGraphicsPipeline(Mesh* mesh, Material* material) {
vkDeviceWaitIdle(device);
if (pipeline)
{
pipeline->Cleanup();
}
// Create pipeline object and configure its properties
pipeline = std::make_shared<Pipeline>();
pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(),
mesh->GetVertexInputAttributeDescriptions(),
swapChainExtent,
{material->GetvertexShader().get(), material->GetfragmentShader().get()},
renderPass,
material->GetPipelineLayout(),
device);
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting the following error in Renderer::CleanupDevice:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1c27d733290, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0x149d740000000087, type = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1c27d733290[], VkDescriptorSetLayout 0x149d740000000087[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1c27d733290, type: 3, name: NULL
[1] 0x149d740000000087, type: 20, name: NULL
Do you know what might be causeing this error and how to fix it?
|
f59cf935ffc51d727db2b765149e2920
|
{
"intermediate": 0.4465576410293579,
"beginner": 0.420981764793396,
"expert": 0.1324605941772461
}
|
10,212
|
Linked list in cs50 2022 lecture 5 data structure
|
f68317f758938fabd04b16370d36236a
|
{
"intermediate": 0.28557199239730835,
"beginner": 0.2736935317516327,
"expert": 0.4407344460487366
}
|
10,213
|
answer = get_answer(question_text_area)
escaped = answer.encode('utf-8').decode('utf-8')
# Display answer
st.caption("Answer :")
st.markdown(escaped) 为什么中文显示不正确
|
b38e5f743587f612ec6c09e0156a91b7
|
{
"intermediate": 0.3167107403278351,
"beginner": 0.42745277285575867,
"expert": 0.25583645701408386
}
|
10,214
|
please revise the sentences for me.
|
19d26a553993a64f1a4854c4e3954439
|
{
"intermediate": 0.34042346477508545,
"beginner": 0.3565833568572998,
"expert": 0.3029932379722595
}
|
10,215
|
def createXY(dataset,n_past):
dataX = []
dataY = []
for i in range(n_past, len(dataset)):
dataX.append(dataset[i - n_past:i, 0:dataset.shape[1]])
dataY.append(dataset[i,5])
return np.array(dataX),np.array(dataY)
|
283dd5048ca092ac118604f9dbd4aa8a
|
{
"intermediate": 0.33480924367904663,
"beginner": 0.40116021037101746,
"expert": 0.2640305459499359
}
|
10,216
|
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.h(1)
circ.cx(1,0,ctrl_state=0)
circ.cx(1,2,ctrl_state=0)
qcirc=circ
now they have equal super position of 101> and 010>, now I want 101> have 75% probability and 010> have 25%, can you fix it for me?
|
95ef76b3bd946cf457b978c3e13689ae
|
{
"intermediate": 0.3396894633769989,
"beginner": 0.30304017663002014,
"expert": 0.35727033019065857
}
|
10,217
|
Can you write me a code that will ask me to put in a ticker symbol. once i put in the ticker symbol it will be put into one of either 2 column a red text column and a green text column. The green text column will be when the stock is currently rising. The red text column will be when the stock is dropping in price. In quotations next to the ticker will be the price of the stock at that current moment with an arrow point if it is either going up or down
|
031287b9dbc290b8b927bcf47a29f0b3
|
{
"intermediate": 0.3783106505870819,
"beginner": 0.18148867785930634,
"expert": 0.4402006268501282
}
|
10,218
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->samplerDescriptorSetLayout = samplerDescriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
void Renderer::CreateGraphicsPipeline(Mesh* mesh, Material* material) {
vkDeviceWaitIdle(device);
if (pipeline)
{
pipeline->Cleanup();
}
// Create pipeline object and configure its properties
pipeline = std::make_shared<Pipeline>();
pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(),
mesh->GetVertexInputAttributeDescriptions(),
swapChainExtent,
{material->GetvertexShader().get(), material->GetfragmentShader().get()},
renderPass,
material->GetPipelineLayout(),
device);
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting the following error in Renderer::CleanupDevice:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1c27d733290, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0x149d740000000087, type = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1c27d733290[], VkDescriptorSetLayout 0x149d740000000087[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1c27d733290, type: 3, name: NULL
[1] 0x149d740000000087, type: 20, name: NULL
Do you know what might be causeing this error and how to fix it?
|
1bd7fa64510d5b048ffd34e62564c793
|
{
"intermediate": 0.4465576410293579,
"beginner": 0.420981764793396,
"expert": 0.1324605941772461
}
|
10,219
|
Давай начнем с самого простого. В этом упражнении тебе необходимо получить отфильтрованные данные из таблицы в базе данных. Почему важно фильтровать данные именно в запросе, а не после этого в библиотеке Pandas? Потому что таблицы могут иметь огромный размер. Если ты попыташься получить всю таблицу, то не сможешь ее "переварить" – у тебя может не хватить оперативной памяти. Всегда помни об этом.
Первый способ фильтрации — выбрать только те столбцы, которые тебе действительно нужны. Второй способ — выбрать только те строки, которые тебе действительно нужны.
Подробное описание задания:
Помести базу данных в подкаталог data в корневом каталоге, используемом в рамках этого проекта.
Создай соединение с базой данных с помощью библиотеки sqlite3.
Получи схему таблицы pageviews с помощью pd.io.sql.read_sql и запроса PRAGMA table_info(pageviews);.
Получи только первые 10 строк таблицы pageviews, чтобы проверить, как она выглядит.
Получи подтаблицу с помощью только одного запроса, в котором:
используются только uid и datetime;
используются только данные пользователей (user_*), и не используются данные администраторов;
сортировка выполняется по uid в порядке возрастания;
столбец индекса — это datetime;
datetime преобразован в DatetimeIndex;
имя датафрейма — pageviews.
Закрой соединение с базой данных. import sqlite3
import pandas as pd
from google.colab import drive
drive.mount('/content/drive')
conn = sqlite3.connect('/content/drive/MyDrive/School21/day10/checking-logs.sqlite') pd.io.sql.read_sql('PRAGMA table_info(pageviews)', conn) pd.io.sql.read_sql('select * from pageviews limit 10', conn) pageviews = pd.io.sql.read_sql("select datetime, uid from pageviews where uid like 'user_%' order by uid", conn, index_col = 'datetime', parse_dates = {"datetime": "%Y-%m-%d %H:%M:%S.%f"})
pageviews conn.close() pageviews.info() <class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 987 entries, 2020-04-26 21:53:59.624136 to 2020-05-21 16:36:40.915488
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 uid 987 non-null object
dtypes: object(1)
memory usage: 15.4+ KB
|
8ef1099f9c1d1745b637a3d2568da420
|
{
"intermediate": 0.30003511905670166,
"beginner": 0.45826563239097595,
"expert": 0.2416992485523224
}
|
10,220
|
import firebase from 'firebase/compat/app';
import '@react-native-firebase/database';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: 'AIzaSyCxKc9YpoVlch4VXGKHlmEaIJaD6RypG7c',
authDomain: 'white-rose-1c834.firebaseapp.com',
databaseURL: 'https://white-rose-1c834-default-rtdb.firebaseio.com/',
projectId: 'white-rose-1c834',
storageBucket: "white-rose-1c834.appspot.com",
messagingSenderId: '443024309358',
appId: '1:443024309358:android:7f8f6200cf7f9d609e3a7f',
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
const db = firebaseApp.firestore();
const auth = firebase.auth();
export { auth, db };
ERROR TypeError: Cannot read property 'initializeApp' of undefined, js engine: hermes
ERROR Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called., js engine: hermes
|
ae8d0b09e0ccad2f1217a089b3160125
|
{
"intermediate": 0.6020795106887817,
"beginner": 0.2057643085718155,
"expert": 0.19215624034404755
}
|
10,221
|
hi please help me answer this questions. how can i grant users for the employees, suppliers, customers and
|
8d84b50b7a014f2007470798eb5b5dc2
|
{
"intermediate": 0.49587810039520264,
"beginner": 0.2759302258491516,
"expert": 0.22819170355796814
}
|
10,222
|
how effective is immuno therapy
|
01ff1c485b1458217d46fe8e1e612da4
|
{
"intermediate": 0.4488019049167633,
"beginner": 0.3450673520565033,
"expert": 0.206130713224411
}
|
10,223
|
i have an ethernet connection and a wifi connection. How do i launch 2 selenium browsers: one of which uses the wifi IP adress and the other uses my ethernet cable IP? Use python.
|
feaf1a185d3d18799484cdc9c8f1cd30
|
{
"intermediate": 0.5308553576469421,
"beginner": 0.22824408113956451,
"expert": 0.24090060591697693
}
|
10,224
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->samplerDescriptorSetLayout = samplerDescriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
void Renderer::CreateGraphicsPipeline(Mesh* mesh, Material* material) {
vkDeviceWaitIdle(device);
if (pipeline)
{
pipeline->Cleanup();
}
// Create pipeline object and configure its properties
pipeline = std::make_shared<Pipeline>();
pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(),
mesh->GetVertexInputAttributeDescriptions(),
swapChainExtent,
{material->GetvertexShader().get(), material->GetfragmentShader().get()},
renderPass,
material->GetPipelineLayout(),
device);
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting the following error in Renderer::CleanupDevice:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1c27d733290, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0x149d740000000087, type = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1c27d733290[], VkDescriptorSetLayout 0x149d740000000087[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1c27d733290, type: 3, name: NULL
[1] 0x149d740000000087, type: 20, name: NULL
Do you know what might be causing this error and how to fix it? Using breakpoints and debug mode I have checked and can confirm the Material class is destroying the descriptor sets before the command to destroy the device is being run.
|
17dc3f8481624e425c3288e4e97e16ed
|
{
"intermediate": 0.4465576410293579,
"beginner": 0.420981764793396,
"expert": 0.1324605941772461
}
|
10,225
|
Прошу прощения, возможно, произошла какая-то ошибка при передаче кода в форматировании. Попробуйте использовать следующий код:
import sqlite3
import pandas as pd
conn = sqlite3.connect(‘/content/drive/MyDrive/School21/day10/checking-logs.sqlite’)
# Вывод информации о таблице checker
pd.io.sql.read_sql(‘PRAGMA table_info(checker)’, conn)
# Вывод первых 10 строк таблицы checker
pd.io.sql.read_sql(‘select * from checker limit 10’, conn)
# Запрос для подсчета строки в pageviews, используя фильтры с условиями
sql_query = ‘’‘
SELECT COUNT(*) as cnt
FROM pageviews
WHERE uid IN (
SELECT uid
FROM checker
WHERE status = ‘ready’
AND numTrials = 1
AND labname IN (‘laba04’, ‘laba04s’, ‘laba05’, ‘laba05’, ‘laba06’, ‘laba06s’, ‘project1’)
)
’‘’
# Сохраняем результат в датафрейме checkers
checkers = pd.io.sql.read_sql(sql_query, conn)
# Выводим датафрейм checkers
print(checkers)
# Закрываем соединение с базой данных
conn.close()
Этот код должен работать без ошибки и выдавать таблицу checkers со значениями, вычисленными на основе заданных условий. Используя этот код Создай соединение с базой данных с помощью библиотеки sqlite3.
Создай новую таблицу datamart в базе данных, объединив таблицы pageviews и checker с помощью только одного запроса.
Таблица должна содержать следующие столбцы: uid, labname, first_commit_ts, first_view_ts.
first_commit_ts — это просто новое имя для столбца timestamp из таблицы checker; он показывает первый коммит конкретного лабораторного задания конкретного пользователя.
first_view_ts — первое посещение пользователем из таблицы pageviews, метка времени посещения пользователем ленты новостей.
По-прежнему нужно использовать фильтр status = 'ready'.
По-прежнему нужно использовать фильтр numTrials = 1.
Имена лабораторных заданий по-прежнему должны быть из следующего списка: laba04, laba04s, laba05, laba06, laba06s, project1.
Таблица должна содержать только пользователей (uid с user_*), а не администраторов.
first_commit_ts и first_view_ts должны быть распарсены как datetime64[ns].
Используя методы библиотеки Pandas, создай два датафрейма: test и control.
test должен включать пользователей, у которых имеются значения в first_view_ts.
control должен включать пользователей, у которых отсутствуют значения в first_view_ts.
Замени пропущенные значения в control средним значением first_view_ts пользователей из test (оно пригодится нам для анализа в будущем).
Сохрани обе таблицы в базе данных (вы будете использовать их в следующих упражнениях).
Закрой соединение.
|
295d1923b53303f465774c385fc04931
|
{
"intermediate": 0.3206818401813507,
"beginner": 0.46962860226631165,
"expert": 0.20968952775001526
}
|
10,226
|
how is the Cognitive Failures Questionnaire score calculated?
|
ddd68ff24eaad903d29a6a2aa25add2b
|
{
"intermediate": 0.33353710174560547,
"beginner": 0.42585209012031555,
"expert": 0.24061080813407898
}
|
10,227
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout* CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout* CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
A portion of Renderer.cpp:
VkDescriptorSetLayout* Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout* descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorSetLayout* Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout* descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
I have recently converted the DescriptorSetLayout functions to use pointers instead of instances to allow for better memory management. However, the code now requires me to initialize the descriptorSetLayout variables in order to work. How can I do this?
|
67d18436e107375990142c7abe53641c
|
{
"intermediate": 0.3505549430847168,
"beginner": 0.394856333732605,
"expert": 0.2545887529850006
}
|
10,228
|
using activiz library, how to display a slice of a 3d image on a 2d image viewer. considering SetResliceAxesDirectionCosines requires 9 parameters and can you tell me how to get imageDims. Also how do i use vtkExtractEdges class
|
f1437f2e5013296ccdeec1464c909866
|
{
"intermediate": 0.9061903357505798,
"beginner": 0.06169126182794571,
"expert": 0.03211837634444237
}
|
10,229
|
CREATE TABLE Student (
StudentID NUMBER(10) PRIMARY KEY
,YearStart NUMBER(4) NOT NULL
,YearEnd NUMBER(4)
);
CREATE TABLE Teacher (
TeacherID NUMBER(10) PRIMARY KEY
,IsCurrent NUMBER(1) NOT NULL CONSTRAINT check_IsCurrent CHECK (
IsCurrent BETWEEN 0
AND 1
) DISABLE
);
CREATE TABLE Person (
PersonID NUMBER(10) PRIMARY KEY
,FirstName VARCHAR2(255) NOT NULL
,LastName VARCHAR2(255) NOT NULL
,Gender CHAR(1) NOT NULL
,DateOfBirth DATE
);
CREATE TABLE Class (
ClassID NUMBER(10) PRIMARY KEY
,TeacherID NUMBER(10) NOT NULL
,ClassName VARCHAR2(255) NOT NULL
,YearOffered NUMBER(4) NOT NULL
,TermOffered NUMBER(1) NOT NULL CONSTRAINT check_TermOffered CHECK (
TermOffered BETWEEN 1
AND 2
) DISABLE
,CONSTRAINT FK_Class_teacherID FOREIGN KEY (TeacherID) REFERENCES Teacher(TeacherID)
);
CREATE TABLE Room (
RoomID NUMBER(10) PRIMARY KEY
,RoomNum NUMBER(4) NOT NULL
,Floor NUMBER(2) NOT NULL
,Building VARCHAR2(64) NOT NULL
);
CREATE TABLE ClassStudent (
ClassID NUMBER(10) NOT NULL
,StudentID NUMBER(10) NOT NULL
,FinalGrade NUMBER(1) CONSTRAINT check_FinalGrade CHECK (
FinalGrade BETWEEN 2
AND 6
) DISABLE
,CONSTRAINT PK_ClassStudent PRIMARY KEY (
ClassID
,StudentID
)
,CONSTRAINT FK_ClassStudent_classID FOREIGN KEY (ClassID) REFERENCES Class(ClassID)
,CONSTRAINT FK_ClassStudent_studentID FOREIGN KEY (StudentID) REFERENCES Student(StudentID)
);
CREATE TABLE Schedule (
ClassID NUMBER(10) NOT NULL
,RoomID NUMBER(10) NOT NULL
,FromTS VARCHAR2(16) NOT NULL
,ToTS VARCHAR2(16) NOT NULL
,CONSTRAINT PK_Schedule PRIMARY KEY (
ClassID
,RoomID
,FromTS
)
,CONSTRAINT FK_Schedule_classID FOREIGN KEY (ClassID) REFERENCES Class(ClassID)
,CONSTRAINT FK_Schedule_roomID FOREIGN KEY (RoomID) REFERENCES Room(RoomID)
); Да се изведат годината и семестъра, когато е била изучавана дисциплината „Big Data“ SQL kod
|
df336202b2dc22667ef18ae6176d8784
|
{
"intermediate": 0.3175669312477112,
"beginner": 0.3281058371067047,
"expert": 0.3543272316455841
}
|
10,230
|
hi
|
9f8f3390b82980569e13eba175811036
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,231
|
python webscraping how can i go through a page a download the src image attached to every div with the class "thumb"
|
cad30f59fba3a897c99e72a50fc8b317
|
{
"intermediate": 0.4872162342071533,
"beginner": 0.3036075234413147,
"expert": 0.2091762125492096
}
|
10,232
|
Write code about content based recommender system using python, please explain it per step
|
c4c300440675f771ffd1b718a54f6889
|
{
"intermediate": 0.20166932046413422,
"beginner": 0.09340910613536835,
"expert": 0.704921543598175
}
|
10,233
|
CREATE TABLE Student (
StudentID NUMBER(10) PRIMARY KEY
,YearStart NUMBER(4) NOT NULL
,YearEnd NUMBER(4)
);
CREATE TABLE Teacher (
TeacherID NUMBER(10) PRIMARY KEY
,IsCurrent NUMBER(1) NOT NULL CONSTRAINT check_IsCurrent CHECK (
IsCurrent BETWEEN 0
AND 1
) DISABLE
);
CREATE TABLE Person (
PersonID NUMBER(10) PRIMARY KEY
,FirstName VARCHAR2(255) NOT NULL
,LastName VARCHAR2(255) NOT NULL
,Gender CHAR(1) NOT NULL
,DateOfBirth DATE
);
CREATE TABLE Class (
ClassID NUMBER(10) PRIMARY KEY
,TeacherID NUMBER(10) NOT NULL
,ClassName VARCHAR2(255) NOT NULL
,YearOffered NUMBER(4) NOT NULL
,TermOffered NUMBER(1) NOT NULL CONSTRAINT check_TermOffered CHECK (
TermOffered BETWEEN 1
AND 2
) DISABLE
,CONSTRAINT FK_Class_teacherID FOREIGN KEY (TeacherID) REFERENCES Teacher(TeacherID)
);
CREATE TABLE Room (
RoomID NUMBER(10) PRIMARY KEY
,RoomNum NUMBER(4) NOT NULL
,Floor NUMBER(2) NOT NULL
,Building VARCHAR2(64) NOT NULL
);
CREATE TABLE ClassStudent (
ClassID NUMBER(10) NOT NULL
,StudentID NUMBER(10) NOT NULL
,FinalGrade NUMBER(1) CONSTRAINT check_FinalGrade CHECK (
FinalGrade BETWEEN 2
AND 6
) DISABLE
,CONSTRAINT PK_ClassStudent PRIMARY KEY (
ClassID
,StudentID
)
,CONSTRAINT FK_ClassStudent_classID FOREIGN KEY (ClassID) REFERENCES Class(ClassID)
,CONSTRAINT FK_ClassStudent_studentID FOREIGN KEY (StudentID) REFERENCES Student(StudentID)
);
CREATE TABLE Schedule (
ClassID NUMBER(10) NOT NULL
,RoomID NUMBER(10) NOT NULL
,FromTS VARCHAR2(16) NOT NULL
,ToTS VARCHAR2(16) NOT NULL
,CONSTRAINT PK_Schedule PRIMARY KEY (
ClassID
,RoomID
,FromTS
)
,CONSTRAINT FK_Schedule_classID FOREIGN KEY (ClassID) REFERENCES Class(ClassID)
,CONSTRAINT FK_Schedule_roomID FOREIGN KEY (RoomID) REFERENCES Room(RoomID)
); Да се изведе списък на имената на сградите и броя етажи за всяка от тях. Колоната с изчисления брой да се именува num_floors. Резултатът да се сортира по азбучен ред на името на сградата. SQL
|
86e204579a293342cc618472f659694a
|
{
"intermediate": 0.2741837203502655,
"beginner": 0.45387157797813416,
"expert": 0.27194473147392273
}
|
10,234
|
python webscraping how can i go through a page a download the src image attached to every div with the class "thumb"
this is an example of the div
<div class="thumb" style="width: 194px;"><div style="margin:19px auto;"><a href="/index.php?title=File:Dinghy.png" class="image"><img alt="" src="/images/thumb/3/39/Dinghy.png/164px-Dinghy.png" decoding="async" width="164" height="92" srcset="/images/thumb/3/39/Dinghy.png/246px-Dinghy.png 1.5x, /images/thumb/3/39/Dinghy.png/328px-Dinghy.png 2x" /></a></div></div>
|
f4b34a3df412d921a6841034c002fc79
|
{
"intermediate": 0.5772870779037476,
"beginner": 0.2229318767786026,
"expert": 0.19978110492229462
}
|
10,235
|
python webscraping how can i go through a page a download the src image attached to every div with the class "thumb"
|
692ab7bfc6034947a7e2198e6b4838a2
|
{
"intermediate": 0.4872162342071533,
"beginner": 0.3036075234413147,
"expert": 0.2091762125492096
}
|
10,236
|
scp -p what does?
|
f5d4c08537bcd01a2e4e5534522ee28e
|
{
"intermediate": 0.28383880853652954,
"beginner": 0.4496653378009796,
"expert": 0.26649585366249084
}
|
10,237
|
django template example
|
5d9164ffa427feb7ea543326ffe857de
|
{
"intermediate": 0.4509274363517761,
"beginner": 0.22996938228607178,
"expert": 0.3191032409667969
}
|
10,238
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout* CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout* CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout* descriptorSetLayout, VkDescriptorSetLayout* samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout* descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout* descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout* descriptorSetLayout, VkDescriptorSetLayout* samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = *descriptorSetLayout;
this->samplerDescriptorSetLayout = *samplerDescriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout* descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout* descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
//Shutdown();
}
void Engine::Run()
{
MainLoop();
Shutdown();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout* descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout* samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Shutdown(); // Make sure to call Shutdown() on the game objects
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
if (material) {
material->Cleanup();
delete material;
material = nullptr;
}
if (mesh) {
delete mesh;
mesh = nullptr;
}
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
I am getting an access violation error in Material::CreateDescriptorSet when trying to allocate descriptorsets. Here is the log output:
VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter(ERROR / SPEC): msgNum: -1275504685 - Validation Error: [ VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter ] Object 0: handle = 0x1f2f1e29a40, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0xb3f957d3 | Invalid VkDescriptorSetLayout Object 0xb3dc6ff590. The Vulkan spec states: If setLayoutCount is not 0, pSetLayouts must be a valid pointer to an array of setLayoutCount valid or VK_NULL_HANDLE VkDescriptorSetLayout handles (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter)
Objects: 1
[0] 0x1f2f1e29a40, type: 1, name: NULL
Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 0
Calling vkBeginCommandBufferà
vkBeginCommandBuffer calledà
VUID-VkDescriptorSetAllocateInfo-pSetLayouts-parameter(ERROR / SPEC): msgNum: 210066664 - Validation Error: [ VUID-VkDescriptorSetAllocateInfo-pSetLayouts-parameter ] Object 0: handle = 0x1f2f1e29a40, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0xc855ce8 | Invalid VkDescriptorSetLayout Object 0xcccccccccccccccc. The Vulkan spec states: pSetLayouts must be a valid pointer to an array of descriptorSetCount valid VkDescriptorSetLayout handles (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkDescriptorSetAllocateInfo-pSetLayouts-parameter)
Objects: 1
[0] 0x1f2f1e29a40, type: 1, name: NULL
What might be causing this issue and how can I fix it?
|
892fe0dd2bc37d02c9703b29cbebe4c3
|
{
"intermediate": 0.3505549430847168,
"beginner": 0.394856333732605,
"expert": 0.2545887529850006
}
|
10,239
|
# Load required libraries
library(dplyr)
library(tidyr)
library(brms)
# Set working directory and load data
files <- list.files(pattern = '.csv')
# Create function to read and process files
read_and_process_file <- function(file) {
df <- read.table(file, stringsAsFactors = FALSE, header = TRUE, sep = ',', quote = '"', na.strings = '', fill = TRUE)
return(df)
}
# Read and combine all CSV files into a single data frame
data <- lapply(files, read_and_process_file) %>% do.call(rbind, .)
# Remove NA rows and columns for 'key_resp.keys' and 'ish'
subset_data <- data[!is.na(data$key_resp.keys), ] %>% select(-which(colSums(!is.na(.)) == 0))
subset_dataish <- data[!is.na(data$ish), ] %>% select(-which(colSums(!is.na(.)) == 0)) %>% mutate(ish_integer = as.integer(gsub('\\D', '', ish)))
# Retrieve gradientSeen and observer_check information
gradientsSeen <- data %>% group_by(participant) %>% slice(1) %>% select(participant, gradients_seen = textbox.text)
observer_check <- table(subset_dataish$participant, subset_dataish$ish_integer == subset_dataish$textbox_2.text)
# Calculate the maximum time that participants spend working on the experiment
max_times <- data %>% group_by(participant) %>% summarise(max_globalClockTime = max(globalClockTime, na.rm = TRUE))
# Retrieve Cognitive Failures Questionnaire (CFQ) data
subset_datacfq <- data[!is.na(data$cfq), ]
sum_per_participant <- aggregate(textbox_3.text ~ participant, data = data, FUN = sum, na.rm = TRUE)
# Find the presentations that were double for all the participants
datadub <- subset_data %>% group_by(participant, image) %>% filter(duplicated(image) | duplicated(image, fromLast = TRUE)) %>% arrange(participant, image)
# Model disagreement
data1 <- datadub[seq(1, nrow(datadub), 2), ]
data2 <- datadub[seq(2, nrow(datadub), 2), ]
# Compute the correlation for each participant and store it in a matrix
ids <- unique(subset_data$participant)
cort <- matrix(NA, length(ids), 2, dimnames = list(NULL, c("correlation", "participant")))
cort[, 2] <- ids
for (i in 1:length(ids)) {
sub_data1 <- subset(data1, participant == ids[i])
sub_data2 <- subset(data2, participant == ids[i])
cort[i, 1] <- cor(sub_data1$key_resp.keys, sub_data2$key_resp.keys)
}
# Convert the matrix to a data.frame
cort_df <- as.data.frame(cort)
cort_df$participant <- as.factor(cort_df$participant)
cort_df$correlation <- as.numeric(cort_df$correlation)
# Calculate the mean and SD of the correlations and filter participants
mean_cor <- mean(cort_df$correlation)
sd_cor <- sd(cort_df$correlation)
threshold <- mean_cor - 2 * sd_cor
filtered_participants <- cort_df$participant[cort_df$correlation < threshold]
# Throw away observers with low correlation
subset_data <- subset(subset_data, !participant %in% filtered_participants)
# Create models
mgaus0 <- brm(key_resp.keys ~ -1 + (1 | participant), data = subset_data,
chains = 3, cores = 3, iter = 10000, warmup = 1000, thin = 2)
Please propose different models to model responses based on demographics such as age and gender. One of these models could use gaussian processes for age.
|
4af933b3bd39bff9da8e5ed0ef21702d
|
{
"intermediate": 0.5344998836517334,
"beginner": 0.3048667907714844,
"expert": 0.1606334000825882
}
|
10,240
|
Как в Visual Studio Code найти и заменить каждую строчку с любым локатором внутри, пример: page.click('selector') на page.locator('selector').click,
еще пример, есть: page.click(`li:has-text("${modelName}") button >> text="Перейти"`) должно замениться на page.locator(`li:has-text("${modelName}") button >> text="Перейти"`).click()
|
b3ef652af9ee945ee9016dfd8e46f37d
|
{
"intermediate": 0.3634379506111145,
"beginner": 0.3453570008277893,
"expert": 0.2912050783634186
}
|
10,241
|
can i get hostname form aspectj joinpoint ?
|
21486fe12423cca8136fb90ee0523d90
|
{
"intermediate": 0.47133395075798035,
"beginner": 0.19922958314418793,
"expert": 0.3294365406036377
}
|
10,242
|
I want to create an innovative, helpful and very unique project stored on a GitHub repository. Please come up with an idea for a project and then produce a FULL file structure for the repo of said project.
|
b0d148a9ef538e9c61d5aab4ae5c4bf1
|
{
"intermediate": 0.3626602590084076,
"beginner": 0.2872973382472992,
"expert": 0.3500423729419708
}
|
10,243
|
Фрукты
Пользователь вводит число K - количество фруктов. Затем он вводит K фруктов в формате: название фрукта и его количество. Добавьте все фрукты в словарь, где название фрукта - это ключ, а количество - значение.
|
2ef9b863c044eb46a6b9fadb5b4414a7
|
{
"intermediate": 0.32734498381614685,
"beginner": 0.30907270312309265,
"expert": 0.3635822832584381
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.