row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
7,929
Program the following Instructions with simple functional C# Code: Implement the guessing game with a menu system. The resting of the magic number should not be acknowledged, but not displayed. The user has to guess a number between 1-10. Have the Play make a single guess with "low" or "high" or "correct" messaging. After a guess, go back to the main menu. Guessing game 1. Reset magic number 2. Play 3. Quit Enter choice: Example output: Guessing game 1. Reset magic number 2. Play 3. Quit Enter choice: 1 Magic number reset Guessing game 1. Reset magic number 2. Play 3. Quit Enter choice: 2 Enter guess (1-10): 4 low Guessing game 1. Reset magic number 2. Play 3. Quit Enter choice: 3 bye
a1add46dd58aa41ef0d68740d0a001dd
{ "intermediate": 0.3675968647003174, "beginner": 0.404961496591568, "expert": 0.2274416834115982 }
7,930
Program the following in simple functional Python code: Implement the guessing game with a menu system. The resting of the magic number should not be acknowledged, but not displayed. The user has to guess a number between 1-10. Have the Play make a single guess with "low" or "high" or "correct" messaging. After a guess, go back to the main menu. Guessing game 1. Reset magic number 2. Play 3. Quit Enter choice: Example output: Guessing game 1. Reset magic number 2. Play 3. Quit Enter choice: 1 Magic number reset Guessing game 1. Reset magic number 2. Play 3. Quit Enter choice: 2 Enter guess (1-10): 4 low Guessing game 1. Reset magic number 2. Play 3. Quit Enter choice: 3 bye
a8f46eafe96f3e76921e670cce3d942b
{ "intermediate": 0.3997986912727356, "beginner": 0.36677244305610657, "expert": 0.23342891037464142 }
7,931
check if a line starts with certain characters in python
526950260c4d8cd22c250b34ca338755
{ "intermediate": 0.33806881308555603, "beginner": 0.34367018938064575, "expert": 0.31826093792915344 }
7,932
2.46-2.6 2.5 (non green)\n2.65 (green) $4000-8000 there is 3 string, make a python programme of using regular expression, to find the largest number of each string
d920967716e7ae17c76ebd78ad6d9231
{ "intermediate": 0.3303207457065582, "beginner": 0.2421121597290039, "expert": 0.4275670647621155 }
7,933
This is my ide program for a highsum gui game. "import GUIExample.GameTableFrame; import Model.*; import GUIExample.LoginDialog; public class GUIExample { private Dealer dealer; private Player player; private GameTableFrame app; public GUIExample() { } public void run() { dealer.shuffleCards(); app = new GameTableFrame(dealer, player); app.setVisible(true); // Replace app.run(); with this line } public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); GUIExample example = new GUIExample(); example.dealer = new Dealer(); example.player = new Player(login, password, 10000); example.run(); } } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.EventQueue; import javax.swing.*; public class HighSumGUI { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum() { // Override the ‘run’ method to display and update the GameTableFrame @Override public void run() { Dealer dealer = getDealer(); Player player = getPlayer(); GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); gameTableFrame.setVisible(true); // Use a loop to continuously update and start new games as desired by the user boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); int response = JOptionPane.showConfirmDialog( gameTableFrame, "Do you want to play another game?", "New Game", JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } gameTableFrame.dispose(); } }; highSum.init(login, password); highSum.run(); } } }); } } package Controller; import Model.Dealer; import Model.Player; import View.ViewController; public class GameController { private Dealer dealer; private Player player; private ViewController view; private int chipsOnTable; private boolean playerQuit; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } public boolean getPlayerQuitStatus() { return playerQuit; } public void run() { boolean carryOn= true; while(carryOn) { runOneRound(); char r = this.view.getPlayerNextGame(); if(r=='n') { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for(int round = 1;round<=4;round++) { this.view.displaySingleLine(); this.view.displayDealerDealCardsAndGameRound(round); this.view.displaySingleLine(); if (round == 1) { //round 1 deal extra card this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } else { this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } this.view.displayPlayerCardsOnHand(this.dealer); this.view.displayBlankLine(); this.view.displayPlayerCardsOnHand(player); this.view.displayPlayerTotalCardValue(player); int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard()); if(whoCanCall==1) {//dealer call int chipsToBet = this.view. getDealerCallBetChips(); //ask player want to follow? char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet); if(r=='y') { this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } }else {//player call if(round==1) {//round 1 player cannot quit int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayBetOntable(this.chipsOnTable); }else { char r = this.view.getPlayerCallOrQuit(); if(r=='c') { int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } } } } //check who win if(playerQuit) { this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) { this.view.displayPlayerWin(this.player); this.player.addChips(chipsOnTable); this.chipsOnTable=0; this.view.displayPlayerNameAndLeftOverChips(this.player); }else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) { this.view.displayDealerWin(); this.view.displayPlayerNameAndLeftOverChips(this.player); }else { this.view.displayTie(); this.player.addChips(chipsOnTable/2); this.view.displayPlayerNameAndLeftOverChips(this.player); } //put all the cards back to the deck dealer.addCardsBackToDeck(dealer.getCardsOnHand()); dealer.addCardsBackToDeck(player.getCardsOnHand()); dealer.clearCardsOnHand(); player.clearCardsOnHand(); } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.BorderLayout; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GameTableFrame extends JFrame { private GameTablePanel gameTablePanel; private Dealer dealer; private Player player; private JLabel shufflingLabel; private JButton playButton; private JButton quitButton; public GameTableFrame(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; gameTablePanel = new GameTablePanel(dealer, player); shufflingLabel = new JLabel("Shuffling"); shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER); playButton = new JButton("Play"); quitButton = new JButton("Quit"); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); HighSum highSum = new HighSum(); highSum.init(player.getLoginName(), "some_default_password"); highSum.run(); updateScreen(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); // Create the main panel that contains both the game board and the buttons JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); mainPanel.add(gameTablePanel, BorderLayout.CENTER); mainPanel.add(buttonsPanel, BorderLayout.SOUTH); mainPanel.add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); add(mainPanel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } // This method updates the screen after each game public void updateScreen() { gameTablePanel.updateTable(dealer, player); } } package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; public GameTablePanel(Dealer dealer, Player player) { setLayout(new BorderLayout()); setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); this.dealer = dealer; this.player = player; } public void updateTable(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; repaint(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Draw dealer’s cards int dealerX = 50; int dealerY = 100; g.drawString("Dealer", dealerX, dealerY - 20); dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true); // Draw player’s cards int playerX = 50; int playerY = getHeight() - 200; g.drawString("Player", playerX, playerY - 20); playerX = drawPlayerHand(g, player, playerX, playerY, false); // Draw chips on the table g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Chips on the table: ", playerX + 50, playerY); } private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) { int i = 0; for (Card c : p.getCardsOnHand()) { if (isDealer && i == 0) { new ImageIcon("images/back.png").paintIcon(this, g, x, y); } else { c.paintIcon(this, g, x, y); } x += 100; i++; } return x; } } package GUIExample; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoginDialog extends JDialog { private JTextField loginField; private JPasswordField passwordField; private JButton loginButton; private boolean loggedIn = false; public LoginDialog(JFrame parent) { super(parent, "Login", true); loginField = new JTextField(20); passwordField = new JPasswordField(20); loginButton = new JButton("Login"); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loggedIn = true; dispose(); } }); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 2)); panel.add(new JLabel("Login:")); panel.add(loginField); panel.add(new JLabel("Password:")); panel.add(passwordField); panel.add(loginButton); add(panel); pack(); setLocationRelativeTo(parent); } public String getLogin() { return loginField.getText(); } public String getPassword() { return new String(passwordField.getPassword()); } public boolean isLoggedIn() { return loggedIn; } } package Helper; public class Keyboard { public static String readString(String prompt) { System.out.print(prompt); return new java.util.Scanner(System.in).nextLine(); } public static int readInt(String prompt) { int input = 0; boolean valid = false; while (!valid) { try { input = Integer.parseInt(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter an integer ***"); } } return input; } public static double readDouble(String prompt) { double input = 0; boolean valid = false; while (!valid) { try { input = Double.parseDouble(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a double ***"); } } return input; } public static float readFloat(String prompt) { float input = 0; boolean valid = false; while (!valid) { try { input = Float.parseFloat(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a float ***"); } } return input; } public static long readLong(String prompt) { long input = 0; boolean valid = false; while (!valid) { try { input = Long.parseLong(readString(prompt)); valid = true; } catch (NumberFormatException e) { e.printStackTrace(); System.out.println("*** Please enter a long ***"); } } return input; } public static char readChar(String prompt,char[] choices) { boolean validChoice = false; char r = ' '; while(!validChoice) { r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":"); if(!validateChoice(choices,r)) { System.out.println("Invalid input"); }else { validChoice = true; } } return r; } private static String charArrayToString(char[] charArray) { String s = "["; for(int i=0;i<charArray.length;i++) { s+=charArray[i]; if(i!=charArray.length-1) { s+=","; } } s += "]"; return s; } private static boolean validateChoice(char[] choices, char choice) { boolean validChoice = false; for(int i=0;i<choices.length;i++) { if(choices[i]==choice) { validChoice = true; break; } } return validChoice; } public static char readChar(String prompt) { char input = 0; boolean valid = false; while (!valid) { String temp = readString(prompt); if (temp.length() != 1) { System.out.println("*** Please enter a character ***"); } else { input = temp.charAt(0); valid = true; } } return input; } public static boolean readBoolean(String prompt) { boolean valid = false; while (!valid) { String input = readString(prompt); if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true") || input.equalsIgnoreCase("t")) { return true; } else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false") || input.equalsIgnoreCase("f")) { return false; } else { System.out.println("*** Please enter Yes/No or True/False ***"); } } return false; } public static java.util.Date readDate(String prompt) { java.util.Date date = null; boolean valid = false; while (!valid) { try { String input = readString(prompt).trim(); if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) { int day = Integer.parseInt(input.substring(0, 2)); int month = Integer.parseInt(input.substring(3, 5)); int year = Integer.parseInt(input.substring(6, 10)); java.util.Calendar cal = java.util.Calendar.getInstance(); cal.setLenient(false); cal.set(year, month - 1, day, 0, 0, 0); date = cal.getTime(); valid = true; } else { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } catch (IllegalArgumentException e) { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } return date; } private static String quit = "0"; public static int getUserOption(String title, String[] menu) { displayMenu(title, menu); int choice = Keyboard.readInt("Enter Choice --> "); while (choice > menu.length || choice < 0) { choice = Keyboard.readInt("Invalid Choice, Re-enter --> "); } return choice; } private static void displayMenu(String title, String[] menu) { line(80, "="); System.out.println(title.toUpperCase()); line(80, "-"); for (int i = 0; i < menu.length; i++) { System.out.println("[" + (i + 1) + "] " + menu[i]); } System.out.println("[" + quit + "] Quit"); line(80, "-"); } public static void line(int len, String c) { System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c)); } } package Helper; import java.security.MessageDigest; public class Utility { public static String getHash(String base) { String message=""; try{ MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) hexString.append('0'); hexString.append(hex); } message = hexString.toString(); } catch(Exception ex){ throw new RuntimeException(ex); } return message; } public static void printLine(int num) { printLine(num,'-'); } public static void printDoubleLine(int num) { printLine(num,'='); } public static void printLine(int num,char pattern) { for(int i =0;i<num;i++) { System.out.print(pattern); } System.out.println(""); } } package Model; import javax.swing.*; public class Card extends ImageIcon { private String suit; private String name; private int value; private int rank; private boolean faceDown; public Card(String suit, String name, int value, int rank) { super("images/" + suit + name + ".png"); this.suit = suit; this.name = name; this.value = value; this.rank = rank; this.faceDown = false; } public boolean isFaceDown() { return this.faceDown; } public void setFaceDown(boolean faceDown) { this.faceDown = faceDown; } public String getSuit() { return this.suit; } public String getName() { return this.name; } public int getValue() { return this.value; } public int getRank() { return this.rank; } public String toString() { if (this.faceDown) { return "<HIDDEN CARD>"; } else { return "<" + this.suit + " " + this.name + ">"; } } public String display() { return "<"+this.suit+" "+this.name+" "+this.rank+">"; } } //card rank // D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import java.util.*; public class Dealer extends Player { private Deck deck; public Dealer() { super("Dealer", "", 0); deck = new Deck(); } public void shuffleCards() { System.out.println("Dealer shuffle deck"); deck.shuffle(); } public void dealCardTo(Player player) { Card card = deck.dealCard(); // take a card out from the deck player.addCard(card); // pass the card into the player } public void addCardsBackToDeck(ArrayList<Card> cards) { deck.appendCard(cards); } //return 1 if card1 rank higher, else return 2 public int determineWhichCardRankHigher(Card card1, Card card2) { if(card1.getRank()>card2.getRank()) { return 1; }else { return 2; } } } package Model; import java.util.*; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = { "Diamond", "Club","Heart","Spade", }; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, "Ace", 1,1+i); cards.add(card); int c = 5; for (int n = 2; n <= 10; n++) { Card oCard = new Card(suit, "" + n, n,c+i); cards.add(oCard); c+=4; } Card jackCard = new Card(suit, "Jack", 10,41+i); cards.add(jackCard); Card queenCard = new Card(suit, "Queen", 10,45+i); cards.add(queenCard); Card kingCard = new Card(suit, "King", 10,49+i); cards.add(kingCard); } } public Card dealCard() { return cards.remove(0); } //add back one card public void appendCard(Card card) { cards.add(card); } //add back arraylist of cards public void appendCard(ArrayList<Card> cards) { for(Card card: cards) { this.cards.add(card); } } public void shuffle() { Random random = new Random(); for(int i=0;i<10000;i++) { int indexA = random.nextInt(cards.size()); int indexB = random.nextInt(cards.size()); Card cardA = cards.get(indexA); Card cardB = cards.get(indexB); cards.set(indexA, cardB); cards.set(indexB, cardA); } } //for internal use only private void showCards() { for (Card card : cards) { System.out.println(card); } } //for internal use only private void displayCards() { for (Card card : cards) { System.out.println(card.display()); } } public static void main(String[] args) { Deck deck = new Deck(); //deck.shuffle(); /*Card card1 = deck.dealCard(); Card card2 = deck.dealCard(); Card card3 = deck.dealCard(); deck.showCards(); ArrayList<Card> cards = new ArrayList<Card>(); cards.add(card1); cards.add(card2); cards.add(card3); deck.appendCard(cards); System.out.println();*/ deck.displayCards(); } } //card rank //D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import Controller.*; import View.*; import GUIExample.LoginDialog; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; private int chipsOnTable; public HighSum() { } public void init(String login, String password) { // Create all the required objects this.dealer = new Dealer(); this.player = new Player(login, password, 50); this.view = new ViewController(); // Bring them together this.gc = new GameController(this.dealer, this.player, this.view); } private Player checkWinner() { if(player.getTotalCardsValue() > dealer.getTotalCardsValue()) return player; else if(player.getTotalCardsValue() < dealer.getTotalCardsValue()) return dealer; else return null; } public Dealer getDealer() { return dealer; } public Player getPlayer() { return player; } public void run() { // Setup the game table GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); // Starts the game! boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); if (!gc.getPlayerQuitStatus()) { int response = JOptionPane.showConfirmDialog( gameTableFrame, "Do you want to play another game?", "New Game", JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } else { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); gameTableFrame.dispose(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for (int round = 1; round <= 4; round++) { // Code remains same until here // Check if the player wants to follow or quit char r; int chipsToBet; if (round == 1) { chipsToBet = this.view.getPlayerCallBetChip(this.player); } else { chipsToBet = this.view.getDealerCallBetChips(); } } Player winner = checkWinner(); if(playerQuit){ this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } } /* public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum(); highSum.init(login, password); highSum.run(); } }*/ } package Model; import java.util.*; public class Player extends User{ private int chips; protected ArrayList<Card> cardsOnHand; public Player(String loginName, String password, int chips) { super(loginName, password); this.chips = chips; this.cardsOnHand = new ArrayList<Card>(); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips+=amount;//no error check } public void deductChips(int amount) { this.chips-=amount;//no error check } public void addCard(Card card) { this.cardsOnHand.add(card); } public ArrayList<Card> getCardsOnHand() { return this.cardsOnHand; } public int getTotalCardsValue() { int total = 0; for(Card card: this.cardsOnHand) { total+=card.getValue(); } return total; } public Card getLastCard() { return this.cardsOnHand.get(this.cardsOnHand.size()-1); } public void clearCardsOnHand() { this.cardsOnHand.clear(); } //Think of the action that a player can take //implement more related methods here public static void main(String[] args) { // TODO Auto-generated method stub Player player = new Player("IcePeak","A",100); System.out.println(player.getChips()); player.deductChips(10); System.out.println(player.getChips()); player.addChips(20); System.out.println(player.getChips()); } } package Model; import Helper.*; abstract public class User { private String loginName; private String hashPassword; public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return this.loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } } package View; import Helper.*; import Model.*; //all input and output should be done view ViewController //so that it is easier to implement GUI later public class ViewController { public void displayExitGame() { System.out.println("Thank you for playing HighSum game"); } public void displayBetOntable(int bet) { System.out.println("Bet on table : "+bet); } public void displayPlayerWin(Player player) { System.out.println(player.getLoginName()+" Wins!"); } public void displayDealerWin() { System.out.println("Dealer Wins!"); } public void displayTie() { System.out.println("It is a tie!."); } public void displayPlayerQuit() { System.out.println("You have quit the current game."); } public void displayPlayerCardsOnHand(Player player) { System.out.println(player.getLoginName()); if(player instanceof Dealer) { for (int i = 0; i < player.getCardsOnHand().size(); i++) { if (i == 0) { System.out.print("<HIDDEN CARD> "); } else { System.out.print(player.getCardsOnHand().get(i).toString() + " "); } } } else { for (Card card : player.getCardsOnHand()) { System.out.print(card + " "); } } System.out.println(); } public void displayBlankLine() { System.out.println(); } public void displayPlayerTotalCardValue(Player player) { System.out.println("Value:"+player.getTotalCardsValue()); } public void displayDealerDealCardsAndGameRound(int round) { System.out.println("Dealer dealing cards - ROUND "+round); } public void displayGameStart() { System.out.println("Game starts - Dealer shuffle deck"); } public void displayPlayerNameAndChips(Player player) { System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips"); } public void displayPlayerNameAndLeftOverChips(Player player) { System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips"); } public void displayGameTitle() { System.out.println("HighSum GAME"); } public void displaySingleLine() { for(int i=0;i<30;i++) { System.out.print("-"); } System.out.println(); } public void displayDoubleLine() { for(int i=0;i<30;i++) { System.out.print("="); } System.out.println(); } public char getPlayerCallOrQuit() { char[] choices = {'c','q'}; char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices); return r; } public char getPlayerFollowOrNot(Player player, int dealerBet) { boolean validChoice = false; char[] choices = {'y','n'}; char r = 'n'; while(!validChoice) { r = Keyboard.readChar("Do you want to follow?",choices); //check if player has enff chips to follow if(r=='y' && player.getChips()<dealerBet) { System.out.println("You do not have enough chips to follow"); displayPlayerNameAndChips(player); }else { validChoice = true; } } return r; } public char getPlayerNextGame() { char[] choices = {'y','n'}; char r = Keyboard.readChar("Next game?",choices); return r; } public int getPlayerCallBetChip(Player player) { boolean validBetAmount = false; int chipsToBet = 0; while(!validBetAmount) { chipsToBet = Keyboard.readInt("Player call, state bet:"); if(chipsToBet<0) { System.out.println("Chips cannot be negative"); }else if(chipsToBet>player.getChips()) { System.out.println("You do not have enough chips"); }else { validBetAmount = true; } } return chipsToBet; } public int getDealerCallBetChips() { System.out.println("Dealer call, state bet: 10"); return 10; } } " These are the requirements: "On completion of this assignment a student should be able to write a Java application that: • Makes use of Java API "Swing" and "AWT" packages • Handles generated events • Makes use of layout manager to organize the GUI components • Know how to apply and design a program using object-oriented concepts 2. Task Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI). 2.1 Login The game starts by the player logging into the game. 2.2 Play Game The game starts after the player click on “Login”. First, the dealer will shuffles the deck. (You may include animation in this frame to simulate “shuffle” effect as enhancement.) Then the dealer deals two cards from the top of the deck to the player and itself. Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game. Assume the player states 10 as the bet chips. The player’s chip will be deducted by 10. The chips on table will be updated to 20 and the dealer deals cards for next round. Assume the dealer’s last card is higher than the player’s last card. The dealer Call the game and the player gets to choose to Follow or Quit the game. If the player follows the game, 10 chips will be deducted from the player’s balance chips. (Asumme the dealer place 10 chips.) The games carry on for maximum of four rounds. In the last round, the player with the highest total sum wins the game. And the game continues until the player exits the game. Error Handling Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips. You should look out for other possible exceptions and handle them too." There are errors: " Description Resource Path Location Type GameTableFrame cannot be resolved to a type HighSum.java /A3Skeleton/src/Model line 47 Java Problem GameTableFrame cannot be resolved to a type HighSum.java /A3Skeleton/src/Model line 47 Java Problem JOptionPane cannot be resolved HighSum.java /A3Skeleton/src/Model line 57 Java Problem JOptionPane cannot be resolved to a variable HighSum.java /A3Skeleton/src/Model line 61 Java Problem JOptionPane cannot be resolved to a variable HighSum.java /A3Skeleton/src/Model line 64 Java Problem The method addWindowListener(WindowListener) in the type Window is not applicable for the arguments (new WindowAdapter(){}) GameTableFrame.java /A3Skeleton/src/GUIExample line 30 Java Problem WindowAdapter cannot be resolved to a type GameTableFrame.java /A3Skeleton/src/GUIExample line 30 Java Problem WindowEvent cannot be resolved to a type GameTableFrame.java /A3Skeleton/src/GUIExample line 32 Java Problem "
43acba593ea1327b453257cdc9269327
{ "intermediate": 0.2889218032360077, "beginner": 0.6018312573432922, "expert": 0.10924690216779709 }
7,934
provide for some filters for text-compare night background mode effects that can be used to improve the design in general and contrastisity.: as for element "<p>" style: "p { margin:20px; }" and a text color and background used style: "#night-mode-toggle:checked ~ body, #night-mode-toggle:checked ~ header, #night-mode-toggle:checked ~ .language-option, #night-mode-toggle:checked section { background-color: #1b2827; color: #fada38; }"
f5bc5ef197c1bacc5d7559831a427aa0
{ "intermediate": 0.3786078095436096, "beginner": 0.22488640248775482, "expert": 0.39650580286979675 }
7,935
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 some of the relevant header and source file 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; }; 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); private: bool shutdownInProgress; 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(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; 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(); CreateSwapchain(); CreateRenderPass(); CreateCommandPool(); CreateFramebuffers(); CreateSyncObjects(); } void Renderer::Shutdown() { if (device == VK_NULL_HANDLE || shutdownInProgress) { // If the device is already VK_NULL_HANDLE, it means the cleanup has run before return; } shutdownInProgress = true; // Indicate that the cleanup is in progress std::cout << "Waiting for device idle…" << std::endl; vkDeviceWaitIdle(device); // Wait for rendering to complete std::cout << "Cleaning up framebuffers…" << std::endl; CleanupFramebuffers(); std::cout << "Cleaning up renderpass…" << std::endl; CleanupRenderPass(); std::cout << "Cleaning up syncobject…" << std::endl; CleanupSyncObjects(); std::cout << "Cleaning up commandbuffers…" << std::endl; CleanupCommandBuffers(); // Free command buffers before destroying the command pool CleanupCommandPool(); CleanupImageViews(); CleanupSwapchain(); CleanupDevice(); // Make sure that CleanupDevice is called before DestroySurface DestroySurface(); // Move this line after CleanupDevice CleanupInstance(); } 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]; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); 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); 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; // 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()) { 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{}; // 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() { // 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); 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 = 0; 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); 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; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &uboLayoutBinding; 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; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 1; poolInfo.pPoolSizes = &poolSize; 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) { // 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; } Pipeline.cpp: #include "Pipeline.h" Pipeline::Pipeline() : device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE) { } Pipeline::~Pipeline() { Cleanup(); } void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device) { this->device = device; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(swapchainExtent.width); viewport.height = static_cast<float>(swapchainExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; // … VkPipelineMultisampleStateCreateInfo multisampling{}; // … VkPipelineColorBlendAttachmentState colorBlendAttachment{}; // … VkPipelineColorBlendStateCreateInfo colorBlending{}; // … std::vector<VkPipelineShaderStageCreateInfo> shaderStages; CreateShaderStages(shaders, shaderStages); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssembly; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizer; pipelineCreateInfo.pMultisampleState = &multisampling; pipelineCreateInfo.pColorBlendState = &colorBlending; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } } void Pipeline::Cleanup() { if (pipeline != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; } } VkPipeline Pipeline::GetPipeline() const { return pipeline; } void Pipeline::CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages) { for (auto shader : shaders) { shaderStages.push_back(shader->GetPipelineShaderStageCreateInfo()); } } It seems to be throwing unresolved external symbol errors related to the CreateGraphicsPipeline method. The method seems to be defined and called correctly so I'm not sure what the issue is.
5280d76d87c9576200682736cb2df4f8
{ "intermediate": 0.363829106092453, "beginner": 0.3310404419898987, "expert": 0.3051304817199707 }
7,936
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 some of the relevant header and source file 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; }; 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); private: bool shutdownInProgress; 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(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; 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(); CreateSwapchain(); CreateRenderPass(); CreateCommandPool(); CreateFramebuffers(); CreateSyncObjects(); } void Renderer::Shutdown() { if (device == VK_NULL_HANDLE || shutdownInProgress) { // If the device is already VK_NULL_HANDLE, it means the cleanup has run before return; } shutdownInProgress = true; // Indicate that the cleanup is in progress std::cout << "Waiting for device idle…" << std::endl; vkDeviceWaitIdle(device); // Wait for rendering to complete std::cout << "Cleaning up framebuffers…" << std::endl; CleanupFramebuffers(); std::cout << "Cleaning up renderpass…" << std::endl; CleanupRenderPass(); std::cout << "Cleaning up syncobject…" << std::endl; CleanupSyncObjects(); std::cout << "Cleaning up commandbuffers…" << std::endl; CleanupCommandBuffers(); // Free command buffers before destroying the command pool CleanupCommandPool(); CleanupImageViews(); CleanupSwapchain(); CleanupDevice(); // Make sure that CleanupDevice is called before DestroySurface DestroySurface(); // Move this line after CleanupDevice CleanupInstance(); } 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]; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); 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); 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; // 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()) { 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{}; // 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() { // 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); 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 = 0; 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); 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; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &uboLayoutBinding; 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; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 1; poolInfo.pPoolSizes = &poolSize; 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) { // 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; } Pipeline.cpp: #include "Pipeline.h" Pipeline::Pipeline() : device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE) { } Pipeline::~Pipeline() { Cleanup(); } void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device) { this->device = device; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(swapchainExtent.width); viewport.height = static_cast<float>(swapchainExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; // … VkPipelineMultisampleStateCreateInfo multisampling{}; // … VkPipelineColorBlendAttachmentState colorBlendAttachment{}; // … VkPipelineColorBlendStateCreateInfo colorBlending{}; // … std::vector<VkPipelineShaderStageCreateInfo> shaderStages; CreateShaderStages(shaders, shaderStages); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssembly; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizer; pipelineCreateInfo.pMultisampleState = &multisampling; pipelineCreateInfo.pColorBlendState = &colorBlending; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } } void Pipeline::Cleanup() { if (pipeline != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; } } VkPipeline Pipeline::GetPipeline() const { return pipeline; } void Pipeline::CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages) { for (auto shader : shaders) { shaderStages.push_back(shader->GetPipelineShaderStageCreateInfo()); } } I get the following error: Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol "public: class std::vector<struct VkVertexInputBindingDescription,class std::allocator<struct VkVertexInputBindingDescription> > __cdecl Mesh::GetVertexInputBindingDescriptions(void)const " (?GetVertexInputBindingDescriptions@Mesh@@QEBA?AV?$vector@UVkVertexInputBindingDescription@@V?$allocator@UVkVertexInputBindingDescription@@@std@@@std@@XZ) referenced in function "public: void __cdecl Renderer::CreateGraphicsPipeline(class Mesh *,class Material *)" (?CreateGraphicsPipeline@Renderer@@QEAAXPEAVMesh@@PEAVMaterial@@@Z) GPTTest C:\Users\Anthony\source\repos\GPTTest\GPTTest\Renderer.obj 1 I'm not sure what the issue is.
4c9817e0aeca73c81f6dc0c20c49dc53
{ "intermediate": 0.363829106092453, "beginner": 0.3310404419898987, "expert": 0.3051304817199707 }
7,937
"import zipfile import shutil import os import re from functions.sendMail import sendMail, sendErrorMail from functions.createLogger import createLogger sourceDir = "." unzipDir = "unzip/convertedData" regexZip = re.compile('(.*zip$)') regexPdf = re.compile('(.*pdf$)') logger = createLogger() os.makedirs('pdf') try: for file in os.listdir(sourceDir): if os.path.isfile(os.path.join(sourceDir, file)): if regexZip.match(file): with zipfile.ZipFile(file, 'r') as zip_ref: zip_ref.extractall("unzip") if os.path.exists(f'sent/{file}'): logger.warning(f'{file} Replaced') shutil.copy(file, "sent/") os.remove(file) if os.path.exists(unzipDir): for file in os.listdir(unzipDir): if os.path.isfile(os.path.join(unzipDir, file)): if regexPdf.match(file): if os.path.exists(f'pdf/{file}'): logger.warning(f'{file} Replaced') shutil.copy(f"unzip/convertedData/{file}", "pdf/") sendMail(file) logger.info(f'{file} Mail sent') else: logger.info('No submission found') if os.path.exists('pdf'): shutil.rmtree('pdf') if os.path.exists('unzip'): shutil.rmtree('unzip') except Exception as e: if os.path.exists('pdf'): shutil.rmtree('pdf') if os.path.exists('unzip'): shutil.rmtree('unzip') sendErrorMail(e) logger.error(e)" explain this code what is doing
1eff67239e54262969d9b43614fc8c9c
{ "intermediate": 0.3483935594558716, "beginner": 0.3989012837409973, "expert": 0.2527051270008087 }
7,938
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 some of the relevant header and source file 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; }; 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); private: bool shutdownInProgress; 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(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Mesh.cpp: #include "Mesh.h" Mesh::Mesh() : device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE) { } Mesh::~Mesh() { Cleanup(); } void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->vertices = vertices; this->indices = indices; this->device = device; Initialize(device, physicalDevice, commandPool, graphicsQueue); // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … } void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … // Declare and initialize stagingBuffer and bufferSize here VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize); vkDestroyBuffer(device, stagingBuffer, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr); bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingIndexBuffer; VkDeviceMemory stagingIndexBufferMemory; BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingIndexBuffer, stagingIndexBufferMemory); vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingIndexBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize); vkDestroyBuffer(device, stagingIndexBuffer, nullptr); vkFreeMemory(device, stagingIndexBufferMemory, nullptr); } void Mesh::Cleanup() { if (device != VK_NULL_HANDLE) { if (vertexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, vertexBuffer, nullptr); vkFreeMemory(device, vertexBufferMemory, nullptr); vertexBuffer = VK_NULL_HANDLE; vertexBufferMemory = VK_NULL_HANDLE; } if (indexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, indexBuffer, nullptr); vkFreeMemory(device, indexBufferMemory, nullptr); indexBuffer = VK_NULL_HANDLE; indexBufferMemory = VK_NULL_HANDLE; } } } const std::vector<Vertex>& Mesh::GetVertices() const { return vertices; } const std::vector<uint32_t>& Mesh::GetIndices() const { return indices; } VkBuffer Mesh::GetVertexBuffer() const { return vertexBuffer; } VkBuffer Mesh::GetIndexBuffer() const { return indexBuffer; } void Mesh::SetVertices(const std::vector<Vertex>& vertices) { this->vertices = vertices; } void Mesh::SetIndices(const std::vector<uint32_t>& indices) { this->indices = indices; } GetVertexInputBindingDescriptions and GetVertexInputAttributeDescriptions methods are currently missing from the Mesha class. Can you help write the associated code for these methods?
15eb4c523124083451157f605afe2dee
{ "intermediate": 0.363829106092453, "beginner": 0.3310404419898987, "expert": 0.3051304817199707 }
7,939
Take a look at this `canvas.lua` module, `canvas:draw()` function specifically:
bc71a1e25dd14b2fd6d5737449b1c9ad
{ "intermediate": 0.39871060848236084, "beginner": 0.30572980642318726, "expert": 0.2955596148967743 }
7,940
ошибка: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'addEventListener') код: import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false; controls.enableDamping = true; controls.dampingFactor = 0.05; const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb'; loader.load(url, function (gltf) { const model = gltf.scene; model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry; const texturePoint = new THREE.TextureLoader().load('texture3.png'); const sizeVariation = 0.001; const geometryPoint = new THREE.BufferGeometry(); const positions = geometry.getAttribute('position').array; const randomSize = []; for (let i = 0; i < positions.length; i += 3) { const startSize = 0.006; const size = startSize + (Math.random() * sizeVariation); randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z] } // let startSize = 0.06; const materialPoint = new THREE.PointsMaterial({ size: 0.03, sizeAttenuation: true, map: texturePoint, alphaTest: 0.01, transparent: true, color: new THREE.Color(1., 1., 1.), opacity: 1. }); const sizes = new Float32Array(randomSize); geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const randomPosition = []; for (let i = 0; i < positions.length; i += 3) { randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0); } const randomPositionCopy = [...randomPosition]; let increment = 0.002; geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); const points = new THREE.Points(geometryPoint, materialPoint); geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); function updateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < positions[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > positions[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - positions[i]) < 0.002) { randomPosition[i] = positions[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } function reverseUpdateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) { randomPosition[i] = randomPositionCopy[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } let time = 0; let sinPosition; let sinPosition2; let cosPosition; let randSignArray = []; let sign; let ratio = 1.0; for(let i = 0; i<randomPosition.length; i++) { sign = Math.random() < 0.5 ? -1.0 : 1.0; randSignArray[i] = sign; } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); window.addEventListener('wheel', function(event) { if (event.deltaY > 0) { updateArray(increment); if(ratio > 0.0) { ratio -= 0.01; } } else { reverseUpdateArray(increment); ratio += 0.01; } }); scene.add(points); points.rotateX(Math.PI/2.0); } }); camera.position.z = 3; // ________________________________________________________________________________________________________________________________________________ // Создаем переменные для точки и радиуса let point = new THREE.Vector3(0, 0, 0); let radius = 1; // Создаем функцию для генерации случайной точки внутри заданного радиуса function generateRandomPointInRadius(radius) { let angle1 = Math.random() * 2 * Math.PI; let angle2 = Math.random() * 2 * Math.PI; let x = radius * Math.sin(angle1) * Math.cos(angle2); let y = radius * Math.sin(angle1) * Math.sin(angle2); let z = radius * Math.cos(angle1); return new THREE.Vector3(x, y, z); } // Инициализируем переменные для генерации случайной точки let randomPoint = generateRandomPointInRadius(radius); let dist = point.distanceTo(randomPoint); let t = 0; // Создаем функцию для анимации точки function animatePoint() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } point.copy(newPos); } // Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); pointMesh.position.set(point.x, point.y, point.z); scene.add(pointMesh); // ________________________________________________________________________________________________________________________________________________ // ________________________________________________________________________________________________________________________________________________ const planeGeometry = new THREE.PlaneGeometry(5, 5, 1, 1); const planeTexture = new THREE.TextureLoader().load('gradient-1.png'); planeTexture.minFilter = THREE.LinearFilter; planeTexture.magFilter = THREE.LinearFilter; planeTexture.wrapS = THREE.ClampToEdgeWrapping; planeTexture.wrapT = THREE.ClampToEdgeWrapping; const planeMaterialGradient = new THREE.MeshBasicMaterial({map: planeTexture}); const planeMeshGradient = new THREE.Mesh(planeGeometry, planeMaterialGradient); planeMeshGradient.rotation.z = -Math.PI/2; planeMeshGradient.position.set(0,0,-10). controls.addEventListener('change', function() { planeMeshGradient.position.copy(camera.position); planeMeshGradient.quaternion.copy(camera.quaternion); }); scene.add(planeMeshGradient); function animate() { requestAnimationFrame(animate); animatePoint(); pointMesh.position.set(point.x, point.y, point.z); controls.update(); renderer.render(scene, camera); } animate(); });
67a49e098f86e1e08d8ba9921c9098e8
{ "intermediate": 0.34623831510543823, "beginner": 0.44540977478027344, "expert": 0.20835188031196594 }
7,941
$4000-8000 regular expression, expected result ['4000','8000']
99bbe37d365a022fb523847cd2da1410
{ "intermediate": 0.2922684848308563, "beginner": 0.4096863269805908, "expert": 0.29804518818855286 }
7,942
can hlp crete a style for <h2> "<h2>Climate Change</h2> ": around bg and text used in: "p { margin: 15px 5px; --x-blend-mode: Overlay; color: #F3EFEF; background-color: #182C2B; padding:5px 15px; border-radius:10px 10px; opacity:0.5; }" bg: "#night-mode-toggle:checked ~ body, #night-mode-toggle:checked ~ header, #night-mode-toggle:checked ~ .language-option, #night-mode-toggle:checked section { background-color: #1B2827; color: #F3EFEF; }"
51293e47cffb01f7c350907c70e7eb9a
{ "intermediate": 0.3559258282184601, "beginner": 0.30659157037734985, "expert": 0.3374825716018677 }
7,943
create a bot that predicts uprising cryptos and sells losing cryptos to buy the rising ones
1bd93e5f0eec78d328d0a75a2d987b25
{ "intermediate": 0.11449741572141647, "beginner": 0.05899813771247864, "expert": 0.8265044093132019 }
7,944
Uncaught TypeError: THREE.ImageUtils.loadTexture is not a function код: import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false; controls.enableDamping = true; controls.dampingFactor = 0.05; const shaderCode = document.getElementById("fragShader").innerHTML; const textureURL = "gradient-1.png"; THREE.ImageUtils.crossOrigin = ''; const texture = THREE.ImageUtils.loadTexture(textureURL); const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb'; loader.load(url, function (gltf) { const model = gltf.scene; model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry; const texturePoint = new THREE.TextureLoader().load('texture3.png'); const sizeVariation = 0.001; const geometryPoint = new THREE.BufferGeometry(); const positions = geometry.getAttribute('position').array; const randomSize = []; for (let i = 0; i < positions.length; i += 3) { const startSize = 0.006; const size = startSize + (Math.random() * sizeVariation); randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z] } // let startSize = 0.06; const materialPoint = new THREE.PointsMaterial({ size: 0.03, sizeAttenuation: true, map: texturePoint, alphaTest: 0.01, transparent: true, color: new THREE.Color(1., 1., 1.), opacity: 1. }); const sizes = new Float32Array(randomSize); geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const randomPosition = []; for (let i = 0; i < positions.length; i += 3) { randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0); } const randomPositionCopy = [...randomPosition]; let increment = 0.002; geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); const points = new THREE.Points(geometryPoint, materialPoint); geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); function updateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < positions[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > positions[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - positions[i]) < 0.002) { randomPosition[i] = positions[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } function reverseUpdateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) { randomPosition[i] = randomPositionCopy[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } let time = 0; let sinPosition; let sinPosition2; let cosPosition; let randSignArray = []; let sign; let ratio = 1.0; for(let i = 0; i<randomPosition.length; i++) { sign = Math.random() < 0.5 ? -1.0 : 1.0; randSignArray[i] = sign; } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); window.addEventListener('wheel', function(event) { if (event.deltaY > 0) { updateArray(increment); if(ratio > 0.0) { ratio -= 0.01; } } else { reverseUpdateArray(increment); ratio += 0.01; } }); scene.add(points); points.rotateX(Math.PI/2.0); } }); camera.position.z = 3; // ________________________________________________________________________________________________________________________________________________ // Создаем переменные для точки и радиуса let point = new THREE.Vector3(0, 0, 0); let radius = 1; // Создаем функцию для генерации случайной точки внутри заданного радиуса function generateRandomPointInRadius(radius) { let angle1 = Math.random() * 2 * Math.PI; let angle2 = Math.random() * 2 * Math.PI; let x = radius * Math.sin(angle1) * Math.cos(angle2); let y = radius * Math.sin(angle1) * Math.sin(angle2); let z = radius * Math.cos(angle1); return new THREE.Vector3(x, y, z); } // Инициализируем переменные для генерации случайной точки let randomPoint = generateRandomPointInRadius(radius); let dist = point.distanceTo(randomPoint); let t = 0; // Создаем функцию для анимации точки function animatePoint() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } point.copy(newPos); } // Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); pointMesh.position.set(point.x, point.y, point.z); scene.add(pointMesh); // ________________________________________________________________________________________________________________________________________________ // ________________________________________________________________________________________________________________________________________________ const planeGeometry = new THREE.PlaneGeometry(100, 100); const planeMaterial = new THREE.ShaderMaterial({uniforms:uniforms, fragmentShader:shaderCode}); const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); scene.add(planeMesh); let uniforms = { speed:{type:'f', value: speed}, mouseCoord: {type:'v3', value: new THREE.Vector3()}, tex: { type:'t', value:texture }, res: { type:'v2', value:new THREE.Vector2(window.innerWidth,window.innerHeight)} }; controls.addEventListener('change', function() { planeMesh.quaternion.copy(camera.quaternion); }); function animate() { requestAnimationFrame(animate); animatePoint(); pointMesh.position.set(point.x, point.y, point.z); controls.update(); uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; renderer.render(scene, camera); } animate(); });
86461d834fd94b565f85079a033595bd
{ "intermediate": 0.2585221827030182, "beginner": 0.5335099697113037, "expert": 0.20796780288219452 }
7,945
regular expression: current case: ' '
cb24c7309db4cc0c140783a50bb64f8b
{ "intermediate": 0.3705267310142517, "beginner": 0.2968021035194397, "expert": 0.3326711356639862 }
7,946
make a regular expression the case: ‘$100-10000 $4000-8000 $1-150’ excepted result: “[‘100’,‘1000’],[‘4000’,‘8000’]”, etc …
e7848d8df2e3d331f0a2dfa6bfd92891
{ "intermediate": 0.36430907249450684, "beginner": 0.28512611985206604, "expert": 0.3505648374557495 }
7,947
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 some of the relevant header and source file 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; }; 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); private: bool shutdownInProgress; 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(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Pipeline.cpp: #include "Pipeline.h" Pipeline::Pipeline() : device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE) { } Pipeline::~Pipeline() { Cleanup(); } void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device) { this->device = device; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(swapchainExtent.width); viewport.height = static_cast<float>(swapchainExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; // … VkPipelineMultisampleStateCreateInfo multisampling{}; // … VkPipelineColorBlendAttachmentState colorBlendAttachment{}; // … VkPipelineColorBlendStateCreateInfo colorBlending{}; // … std::vector<VkPipelineShaderStageCreateInfo> shaderStages; CreateShaderStages(shaders, shaderStages); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssembly; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizer; pipelineCreateInfo.pMultisampleState = &multisampling; pipelineCreateInfo.pColorBlendState = &colorBlending; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } } void Pipeline::Cleanup() { if (pipeline != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; } } VkPipeline Pipeline::GetPipeline() const { return pipeline; } void Pipeline::CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages) { for (auto shader : shaders) { shaderStages.push_back(shader->GetPipelineShaderStageCreateInfo()); } } I'm getting an access violation error at the following link in the Pipeline::CreateGraphicsPipeline method: if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) Can you find the problem and fix the code?
f3af6e86ae25178783d2336bcdebb1d7
{ "intermediate": 0.363829106092453, "beginner": 0.3310404419898987, "expert": 0.3051304817199707 }
7,948
make a regular expression the case: ‘$100-10000 $4000-8000 $1-150’ excepted result: “[‘100’,‘1000’],[‘4000’,‘8000’]”, etc …
184c2bd382c2126e17053db33678b399
{ "intermediate": 0.36430907249450684, "beginner": 0.28512611985206604, "expert": 0.3505648374557495 }
7,949
[('4000', '8000')], python find the largest number
2861f10e2feeceef5190a5bbe525126f
{ "intermediate": 0.2578921318054199, "beginner": 0.3162267804145813, "expert": 0.4258810579776764 }
7,950
[(‘4000’, ‘8000’)], python find the largest number, excepted result is 8000
f03eb2639e385f03820aee742cc27148
{ "intermediate": 0.2705579698085785, "beginner": 0.25418588519096375, "expert": 0.4752561151981354 }
7,951
нужно чтобы материал отображался на плоскости с двух сторон const planeGeometry = new THREE.PlaneGeometry(1000, 1000); const planeMaterial = new THREE.ShaderMaterial({uniforms:uniforms, fragmentShader:shaderCode}); const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); scene.add(planeMesh); planeMesh.position.set(0, 0, -85);
594c9defca2d2d19c07c5a43fce2058a
{ "intermediate": 0.3841862976551056, "beginner": 0.2909463047981262, "expert": 0.3248673677444458 }
7,952
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 some of the relevant header and source file 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; }; 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); private: bool shutdownInProgress; 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(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Pipeline.cpp: #include "Pipeline.h" Pipeline::Pipeline() : device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE) { } Pipeline::~Pipeline() { Cleanup(); } void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device) { this->device = device; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(swapchainExtent.width); viewport.height = static_cast<float>(swapchainExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; // … VkPipelineMultisampleStateCreateInfo multisampling{}; // … VkPipelineColorBlendAttachmentState colorBlendAttachment{}; // … VkPipelineColorBlendStateCreateInfo colorBlending{}; // … std::vector<VkPipelineShaderStageCreateInfo> shaderStages; CreateShaderStages(shaders, shaderStages); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssembly; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizer; pipelineCreateInfo.pMultisampleState = &multisampling; pipelineCreateInfo.pColorBlendState = &colorBlending; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } } void Pipeline::Cleanup() { if (pipeline != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; } } VkPipeline Pipeline::GetPipeline() const { return pipeline; } void Pipeline::CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages) { for (auto shader : shaders) { shaderStages.push_back(shader->GetPipelineShaderStageCreateInfo()); } } The CreateGraphicsPipeline seems to be only partially filled out. Please complete the rest of the necessary code/
c9fe9a2ef740ab0023dd0d7f2c915437
{ "intermediate": 0.363829106092453, "beginner": 0.3310404419898987, "expert": 0.3051304817199707 }
7,953
/usr/local/lib/python3.10/dist-packages/librosa/core/spectrum.py:256: UserWarning: n_fft=2048 is too large for input signal of length=1599 warnings.warn( /usr/local/lib/python3.10/dist-packages/librosa/core/spectrum.py:256: UserWarning: n_fft=2048 is too large for input signal of length=1999 warnings.warn( /usr/local/lib/python3.10/dist-packages/librosa/core/spectrum.py:256: UserWarning: n_fft=2048 is too large for input signal of length=1399 warnings.warn( /usr/local/lib/python3.10/dist-packages/librosa/core/spectrum.py:256: UserWarning: n_fft=2048 is too large for input signal of length=999 warnings.warn( /usr/local/lib/python3.10/dist-packages/librosa/core/spectrum.py:256: UserWarning: n_fft=2048 is too large for input signal of length=1799 warnings.warn( /usr/local/lib/python3.10/dist-packages/librosa/core/spectrum.py:256: UserWarning: n_fft=2048 is too large for input signal of length=1199 warnings.warn( /usr/local/lib/python3.10/dist-packages/librosa/core/spectrum.py:256: UserWarning: n_fft=2048 is too large for input signal of length=199 warnings.warn( /usr/local/lib/python3.10/dist-packages/librosa/core/spectrum.py:256: UserWarning: n_fft=2048 is too large for input signal of length=399 warnings.warn( /usr/local/lib/python3.10/dist-packages/librosa/core/spectrum.py:256: UserWarning: n_fft=2048 is too large for input signal of length=599 warnings.warn( --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-10-f196d2d6abce> in <cell line: 28>() 26 27 # Создание обучающего и тестового наборов данных с использованием функции make_dataset ---> 28 X_train, y_train = make_dataset(audio_signals_train, labels_train, vad_segments_train) 29 X_test, y_test = make_dataset(audio_signals_test, labels_test, vad_segments_test) 30 <ipython-input-9-40c1be8cb75c> in make_dataset(samples, labels, vad_segments) 24 25 X.append(stft_db) # Добавляем спектрограмму с речью ---> 26 y.append(labels[sample][segment]) # Добавляем метку для этой спектрограммы 27 28 return np.array(X), np.array(y) IndexError: list index out of range
ab124ee3673695901d4aa644b61d2317
{ "intermediate": 0.3264523446559906, "beginner": 0.5137659311294556, "expert": 0.15978172421455383 }
7,954
flutter gorouter package. how can i add extra data to route when redirecting?
e38549a35b2fa12e98f3e4aae8e560ae
{ "intermediate": 0.6505723595619202, "beginner": 0.1531246155500412, "expert": 0.19630305469036102 }
7,955
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 some of the relevant header and source file 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; }; 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); private: bool shutdownInProgress; 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(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Pipeline.cpp: #include "Pipeline.h" Pipeline::Pipeline() : device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE) { } Pipeline::~Pipeline() { Cleanup(); } void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device) { this->device = device; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(swapchainExtent.width); viewport.height = static_cast<float>(swapchainExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; VkPipelineMultisampleStateCreateInfo multisampling{}; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlending{}; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; std::vector<VkPipelineShaderStageCreateInfo> shaderStages; CreateShaderStages(shaders, shaderStages); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssembly; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizer; pipelineCreateInfo.pMultisampleState = &multisampling; pipelineCreateInfo.pColorBlendState = &colorBlending; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } } void Pipeline::Cleanup() { if (pipeline != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; } } VkPipeline Pipeline::GetPipeline() const { return pipeline; } void Pipeline::CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages) { for (auto shader : shaders) { shaderStages.push_back(shader->GetPipelineShaderStageCreateInfo()); } } I get an error on Pipeline::Cleanup when trying to close the application. How can I alter the code to fix this issue?
3f9e07dc8d91f887ca77f6a691c51bbb
{ "intermediate": 0.363829106092453, "beginner": 0.3310404419898987, "expert": 0.3051304817199707 }
7,956
//@version=4 study("Bollinger Bands with Weighted Volatility", overlay=false) // Input Variables length = input(title="Length", type=input.integer, defval=20, minval=1) deviations = input(title="Deviations", type=input.float, defval=2.0, minval=0.1, step=0.1) volatility_length = input(title="Volatility Length", type=input.integer, defval=20, minval=1) // Define Variables var source = 0.0 var basis = 0.0 var dev = 0.0 var upper = 0.0 var lower = 0.0 var volatility = 0.0 var volatility_weighted = 0.0 var volatility_scale = 0.0 // Calculate Bollinger Bands source := close basis := sum(source, length) / length dev := deviations * sqrt(sum(pow(source - basis, 2), length) / length) upper := basis + dev lower := basis - dev // Calculate Volatility Weighted by Volume change_source = abs(source - source[1]) volatility := sqrt(sum(pow(change_source, 2),volatility_length) / volatility_length) volatility_weighted := volatility * volume // Plot Bollinger Bands and Volatility Weighted by Volume plot(basis, color=color.blue, title="Basis") fill(upper, lower, color=color.blue, title="Bollinger Bands") plot(volatility_weighted, color=color.yellow, title="Volatility Weighted by Volume", style=plot.style_columns) // Set Y-Axis Scale for Volatility Window volatility_scale := 2 * (highest(high, length) - lowest(low, length)) volatility_scale := volatility_scale == 0 ? 1 : volatility_scale // Plot Volatility Window plot(volatility_weighted, color=color.yellow, title="Volatility Weighted by Volume", style=plot.style_columns, secondary=true, scale=scale.inherit, min=0, max=volatility_scale)
81a03447fa95af31a6794f695b161476
{ "intermediate": 0.3499029278755188, "beginner": 0.33703386783599854, "expert": 0.31306320428848267 }
7,957
Привет, пожалуйста, оптимизируй вот этот код: import numpy as np import librosa as lr import os import webrtcvad from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score def load_dataset(path): audio_signals = [] labels = [] sr = None files = [] for file in os.listdir(path): if file.endswith(".wav"): file_path = os.path.join(path, file) audio_data, sample_rate = lr.load(file_path, sr=None) audio_signals.append(audio_data) sr = sample_rate files.append(file) label = [int(digit) for digit in file.split('.')[0].split('_')] labels.append(label) return audio_signals, labels, sr, files def vad(audio_data, sample_rate): vad = webrtcvad.Vad() vad.set_mode(3) frame_duration = 20 # Duration of a frame in ms frame_length = int(sample_rate * frame_duration / 1000) # Calculate frame length in samples # Convert float audio data to 16-bit PCM audio_data_int16 = np.array(audio_data * (2**15 - 1), dtype=np.int16) frames = [] for i in range(0, len(audio_data_int16), frame_length): frame = audio_data_int16[i:i + frame_length] if len(frame) < frame_length: frame = np.pad(frame, (0, frame_length - len(frame))) frames.append(frame) voiced_frames = [frame for frame in frames if vad.is_speech(frame.tobytes(), sample_rate)] return voiced_frames def make_dataset(samples, labels, vad_segments): X, y = [], [] for sample in range(len(samples)): for segment in range(len(vad_segments[sample])): start = vad_segments[sample][segment][0] stop = vad_segments[sample][segment][1] voice = samples[sample][start:stop] stft = librosa.stft(voice).mean(axis=1) stft_db = librosa.amplitude_to_db(abs(stft)) X.append(stft_db) if segment < len(labels[sample]): y.append(labels[sample][segment]) else: y.append(-1) # Use -1 as a placeholder for missing labels return np.array(X), np.array(y) audio_signals, labels, sr, files = load_dataset('/content/drive/MyDrive/School21/day09/datasets/audio_yes_no/waves_yesno 2') vad_segments = [] for audio_data in audio_signals: audio_data_resampled = lr.resample(audio_data, orig_sr=sr, target_sr=8000) segments = vad(audio_data_resampled, 8000) vad_segments.append(segments) indices = list(range(len(audio_signals))) train_indices, test_indices = train_test_split(indices, test_size=0.2, random_state=42) audio_signals_train = [audio_signals[i] for i in train_indices] labels_train = [labels[i] for i in train_indices] vad_segments_train = [vad_segments[i] for i in train_indices] audio_signals_test = [audio_signals[i] for i in test_indices] labels_test = [labels[i] for i in test_indices] vad_segments_test = [vad_segments[i] for i in test_indices] X_train, y_train = make_dataset(audio_signals_train, labels_train, vad_segments_train) X_test, y_test = make_dataset(audio_signals_test, labels_test, vad_segments_test) svm_classifier = SVC() svm_classifier.fit(X_train, y_train) y_pred_svm = svm_classifier.predict(X_test) accuracy_svm = accuracy_score(y_test, y_pred_svm) print(f"SVM accuracy: {accuracy_svm}") logreg_classifier = LogisticRegression() logreg_classifier.fit(X_train, y_train) y_pred_logreg = logreg_classifier.predict(X_test) accuracy_logreg = accuracy_score(y_test, y_pred_logreg) print(f"Logistic Regression accuracy: {accuracy_logreg}"). Добавь пояснения по каждой функции на русском языке.
86b374cd06af0c2df10e6821b693d8af
{ "intermediate": 0.384460985660553, "beginner": 0.44586730003356934, "expert": 0.16967172920703888 }
7,958
Please add it so it takes over the random function in this code: import pandas as pd import random import numpy as np import matplotlib.pyplot as plt def generate_images(num_samples, num_images): # Take list (with 3 equal chunks) # Give each chunk the same number of distortions chunk_size = num_samples // 3 imgs_chunk1 = random.sample(range(1, num_images // 3 + 1), chunk_size) imgs_chunk2 = random.sample(range(num_images // 3 + 1, 2 * num_images // 3 + 1), chunk_size) imgs_chunk3 = random.sample(range(2 * num_images // 3 + 1, num_images + 1), chunk_size) imgs = imgs_chunk1 + imgs_chunk2 + imgs_chunk3 # Create letters for each chunk distortions = [f'{d}{l}' for d in [1, 2, 3] for l in ['a', 'b', 'c']] + ['original'] num_distortions = len(distortions) num_chunks = 3 let = pd.Series(distortions * (num_samples // (num_distortions * num_chunks))) # Combine chunks, each randomized test = pd.concat([let.sample(frac=1) for _ in range(num_chunks)], ignore_index=True) # Check that each chunk has the same number of letters test = test.astype('category') # Convert to category for overview # Combine and shuffle images = pd.DataFrame({'imgs': imgs, 'test': test}) return images num_samples = 420 # Default 420 num_images = 540 # Default 540 num_observers = 10000 # Number of observers # Set the seed for reproducibility seed = run+38595 random.seed(seed) np.random.seed(seed) # Create an empty list to store the DataFrames for each observer observer_dfs = [] # Generate images for each observer and store the DataFrames in the list for observer in range(1, num_observers + 1): observer_images = generate_images(num_samples, num_images) observer_images['observer_nr'] = observer # Add observer number column observer_dfs.append(observer_images) # Concatenate the DataFrames from each observer into a single result DataFrame result_df = pd.concat(observer_dfs, ignore_index=True) # Convert 'imgs' and 'test' columns to category data type for overview result_df['imgs'] = result_df['imgs'].astype('category') result_df['test'] = result_df['test'].astype('category') # Count the occurrences of each combination combination_counts = result_df.groupby(['imgs', 'test']).size().reset_index(name='count') # Measure the variance in the count variance = np.var(combination_counts['count']) sum(combination_counts['count']<=2) sum(combination_counts['count']>=11) np.mean(combination_counts['count']) def combine_data2(result_df, num_subsetting_range): previous_variance = None for num_subsetting in num_subsetting_range: random.seed(num_subsetting) combined_df=result_df[result_df['observer_nr'].isin(random.sample(range(1,10000),80))] combination_counts = combined_df.groupby(['imgs', 'test']).size().reset_index(name='count') variance = np.var(combination_counts['count']) #print(variance) if previous_variance is None or variance < previous_variance: print(f"num_subsetting: {num_subsetting}, variance: {variance}") previous_variance = variance Currently we take 80 random digits with this function: combined_df=result_df[result_df['observer_nr'].isin(random.sample(range(1,10000),80))] And evaluate which random numbers have the lowest variance here: combination_counts = combined_df.groupby(['imgs', 'test']).size().reset_index(name='count') variance = np.var(combination_counts['count']) I want a genetic algorithm that gradually replaces a few of the 80 numbers at a time.
da46f28d73d0c263aaf9484c81cb97f6
{ "intermediate": 0.41383790969848633, "beginner": 0.30367520451545715, "expert": 0.28248685598373413 }
7,959
lambda expressions are not supported in -source 1.7 (use -source 8 or higher to enable lambda expressions) 错误是什么原因
359679dccc25393eb83e2089298ae418
{ "intermediate": 0.35654979944229126, "beginner": 0.2619408965110779, "expert": 0.38150930404663086 }
7,960
как изменить этот код, чтобы анимация точки pointMesh применялась и ко всем точкам points? код: import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false; controls.enableDamping = true; controls.dampingFactor = 0.05; const shaderCode = document.getElementById("fragShader").innerHTML; THREE.ImageUtils.crossOrigin = ''; const texture = new THREE.TextureLoader().load('gradient-1.png'); const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb'; loader.load(url, function (gltf) { const model = gltf.scene; model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry; const texturePoint = new THREE.TextureLoader().load('texture3.png'); const sizeVariation = 0.001; const geometryPoint = new THREE.BufferGeometry(); const positions = geometry.getAttribute('position').array; const randomSize = []; for (let i = 0; i < positions.length; i += 3) { const startSize = 0.006; const size = startSize + (Math.random() * sizeVariation); randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z] } // let startSize = 0.06; const materialPoint = new THREE.PointsMaterial({ size: 0.03, sizeAttenuation: true, map: texturePoint, alphaTest: 0.01, transparent: true, color: new THREE.Color(1., 1., 1.), opacity: 1. }); const sizes = new Float32Array(randomSize); geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const randomPosition = []; for (let i = 0; i < positions.length; i += 3) { randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0); } const randomPositionCopy = [...randomPosition]; let increment = 0.002; geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); const points = new THREE.Points(geometryPoint, materialPoint); geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); function updateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < positions[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > positions[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - positions[i]) < 0.002) { randomPosition[i] = positions[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } function reverseUpdateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) { randomPosition[i] = randomPositionCopy[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } let time = 0; let sinPosition; let sinPosition2; let cosPosition; let randSignArray = []; let sign; let ratio = 1.0; for(let i = 0; i<randomPosition.length; i++) { sign = Math.random() < 0.5 ? -1.0 : 1.0; randSignArray[i] = sign; } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); window.addEventListener('wheel', function(event) { if (event.deltaY > 0) { updateArray(increment); if(ratio > 0.0) { ratio -= 0.01; } } else { reverseUpdateArray(increment); ratio += 0.01; } }); scene.add(points); points.rotateX(Math.PI/2.0); } }); camera.position.z = 3; // ________________________________________________________________________________________________________________________________________________ // Создаем переменные для точки и радиуса let point = new THREE.Vector3(0, 0, 0); let radius = 1; // Создаем функцию для генерации случайной точки внутри заданного радиуса function generateRandomPointInRadius(radius) { let angle1 = Math.random() * 2 * Math.PI; let angle2 = Math.random() * 2 * Math.PI; let x = radius * Math.sin(angle1) * Math.cos(angle2); let y = radius * Math.sin(angle1) * Math.sin(angle2); let z = radius * Math.cos(angle1); return new THREE.Vector3(x, y, z); } // Инициализируем переменные для генерации случайной точки let randomPoint = generateRandomPointInRadius(radius); let dist = point.distanceTo(randomPoint); let t = 0; // Создаем функцию для анимации точки function animatePoint() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } point.copy(newPos); } // Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); pointMesh.position.set(point.x, point.y, point.z); scene.add(pointMesh); // ________________________________________________________________________________________________________________________________________________ let uniforms = { mouseCoord: {type:'v3', value: new THREE.Vector3()}, tex: { type:'t', value:texture }, res: { type:'v2', value:new THREE.Vector2(window.innerWidth,window.innerHeight)} }; const planeGeometry = new THREE.PlaneGeometry(1000, 1000); const planeMaterial = new THREE.ShaderMaterial({ uniforms:uniforms, fragmentShader:shaderCode, side: THREE.DoubleSide }); const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); scene.add(planeMesh); planeMesh.position.set(0, 0, -85); controls.addEventListener('change', function() { planeMesh.quaternion.copy(camera.quaternion); }); let targetX = 0; let targetY = 0; let currentX = 0; let currentY = 0; function update() { requestAnimationFrame(update); const diffX = targetX - currentX; const diffY = targetY - currentY; const distance = Math.sqrt(diffX * diffX + diffY * diffY); const speed = distance / 10; if (distance < 1.0) { currentX = targetX; currentY = targetY; } else { currentX += speed * diffX / distance; currentY += speed * diffY / distance; } } update(); document.addEventListener('mousemove', (event) => { targetX = event.clientX; targetY = event.clientY; uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; }); function animate() { requestAnimationFrame(animate); animatePoint(); pointMesh.position.set(point.x, point.y, point.z); controls.update(); uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; renderer.render(scene, camera); } animate(); });
d2e42521dc9b1a7d58f97fc9d7e58d8d
{ "intermediate": 0.23643910884857178, "beginner": 0.6451652646064758, "expert": 0.11839558184146881 }
7,961
Write a C# code that removes the longest horizontal line from an image, using AForge library or native C#
27fab25984a15d1db673c190c1a56799
{ "intermediate": 0.6667096614837646, "beginner": 0.1114942878484726, "expert": 0.22179599106311798 }
7,962
output some random href links html elements for eco-friendliness
c47cdd5ba0af0eaada4a0f2c54964ef3
{ "intermediate": 0.4216761291027069, "beginner": 0.2754020094871521, "expert": 0.302921861410141 }
7,963
Build A deep learning model to classify Arabic language depending on classes this the shape of data that I have : train_X =list(training[:, 0]) train_Y = list(training[:, 1]) the train_X and train_Y is already convert it to number throug this code # 5 Text to Numbers training = [] out_empty = [0] * len(classes) # Creating the bag of words model for idx, doc in enumerate(data_X): bow = [] for word in words: bow.append(1) if word in doc else bow.append(0) # Mark the index of the class that the current pattern is associated with output_row = list(out_empty) output_row[classes.index(data_y[idx])] = 1 # Add the one-hot encoded BoW and associated classes to training training.append([bow, output_row]) # Shuffle the data and convert it to an array to capture patterns effectively random.shuffle(training) training = np.array(training, dtype=object) # Split the features and target labels train_X =np.array(list(training[:, 0]) ) train_Y = np.array(list(training[:, 1]))
8211991e1bc6ba56b1325e3e8d818c83
{ "intermediate": 0.2374693751335144, "beginner": 0.1653694063425064, "expert": 0.5971611738204956 }
7,964
How do I make an HTTP request in Javascript?
87a76beef4cc2aa2f435cc1c950fd6fb
{ "intermediate": 0.5629616379737854, "beginner": 0.20182780921459198, "expert": 0.2352105975151062 }
7,965
Hi i need a python code to run this steps for me 1.give subdomain from wodlist linebyline 2.send a https request to https://example.com/domain/{wordlist} 3.save response to txt file with domain name in worldlist
7ef26d9e934995b8463599c50d96934c
{ "intermediate": 0.5962547659873962, "beginner": 0.14905281364917755, "expert": 0.254692405462265 }
7,966
исправь код import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false; controls.enableDamping = true; controls.dampingFactor = 0.05; const shaderCode = document.getElementById("fragShader").innerHTML; THREE.ImageUtils.crossOrigin = ''; const texture = new THREE.TextureLoader().load('gradient-1.png'); const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb'; loader.load(url, function (gltf) { const model = gltf.scene; model.traverse((child) => { if (child.isMesh) { let point = new THREE.Vector3(0, 0, 0); let radius = 1; let randomPoint = generateRandomPointInRadius(radius); const geometry = child.geometry; const texturePoint = new THREE.TextureLoader().load('texture3.png'); const sizeVariation = 0.001; const geometryPoint = new THREE.BufferGeometry(); const positions = geometry.getAttribute('position').array; const randomSize = []; for (let i = 0; i < positions.length; i += 3) { const startSize = 0.006; const size = startSize + (Math.random() * sizeVariation); randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z] } // let startSize = 0.06; const materialPoint = new THREE.PointsMaterial({ size: 0.03, sizeAttenuation: true, map: texturePoint, alphaTest: 0.01, transparent: true, color: new THREE.Color(1., 1., 1.), opacity: 1. }); const sizes = new Float32Array(randomSize); geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const randomPosition = []; for (let i = 0; i < positions.length; i += 3) { randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0); } const randomPositionCopy = [...randomPosition]; let increment = 0.002; geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); const initialRadius = 5; let initialRandomPoint = generateRandomPointInRadius(initialRadius); let initialDist = point.distanceTo(initialRandomPoint); let initialT = 0; function animateInitialPoint() { initialT += 0.005; if (initialT > 1) { initialRandomPoint = generateRandomPointInRadius(initialRadius); initialDist = point.distanceTo(initialRandomPoint); initialT = 0; } let newPos = point.clone().lerp(initialRandomPoint, initialT); let moveDist = newPos.distanceTo(point); if (moveDist >= initialDist) { initialRandomPoint = generateRandomPointInRadius(initialRadius); initialDist = point.distanceTo(initialRandomPoint); initialT = 0; } point.copy(newPos); pointMesh.position.set(point.x, point.y, point.z); } camera.position.z = 10; function animate() { requestAnimationFrame(animate); animateInitialPoint(); animatePoints(); controls.update(); uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; renderer.render(scene, camera); } animate(); geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); function updateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < positions[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > positions[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - positions[i]) < 0.002) { randomPosition[i] = positions[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } function reverseUpdateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) { randomPosition[i] = randomPositionCopy[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } let time = 0; let sinPosition; let sinPosition2; let cosPosition; let randSignArray = []; let sign; let ratio = 1.0; for(let i = 0; i<randomPosition.length; i++) { sign = Math.random() < 0.5 ? -1.0 : 1.0; randSignArray[i] = sign; } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); // animateVerticles(); // function animateVerticles() { // requestAnimationFrame(animateVerticles); // time += 0.1; // sinPosition = Math.sin(time)*0.1; // cosPosition = Math.cos(time*0.1)*0.1; // sinPosition2 = Math.sin(time/Math.PI)*0.1; // for(let i = 0; i<randomPosition.length; i++) { // randomPosition[i] += (sinPosition * cosPosition * sinPosition2) * randSignArray[i] * ratio; // } // geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); // } window.addEventListener('wheel', function(event) { if (event.deltaY > 0) { updateArray(increment); if(ratio > 0.0) { ratio -= 0.01; } } else { reverseUpdateArray(increment); ratio += 0.01; } }); scene.add(points); points.rotateX(Math.PI/2.0); } }); camera.position.z = 3; // ________________________________________________________________________________________________________________________________________________ // Создаем переменные для точки и радиуса let point = new THREE.Vector3(0, 0, 0); let radius = 1; // Создаем функцию для генерации случайной точки внутри заданного радиуса function generateRandomPointInRadius(radius) { let angle1 = Math.random() * 2 * Math.PI; let angle2 = Math.random() * 2 * Math.PI; let x = radius * Math.sin(angle1) * Math.cos(angle2); let y = radius * Math.sin(angle1) * Math.sin(angle2); let z = radius * Math.cos(angle1); return new THREE.Vector3(x, y, z); } // Инициализируем переменные для генерации случайной точки let randomPoint = generateRandomPointInRadius(radius); let dist = point.distanceTo(randomPoint); let t = 0; // Создаем функцию для анимации точки function animatePoint() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } point.copy(newPos); } // Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); pointMesh.position.set(point.x, point.y, point.z); scene.add(pointMesh); // ________________________________________________________________________________________________________________________________________________ let uniforms = { mouseCoord: {type:'v3', value: new THREE.Vector3()}, tex: { type:'t', value:texture }, res: { type:'v2', value:new THREE.Vector2(window.innerWidth,window.innerHeight)} }; const planeGeometry = new THREE.PlaneGeometry(1000, 1000); const planeMaterial = new THREE.ShaderMaterial({ uniforms:uniforms, fragmentShader:shaderCode, side: THREE.DoubleSide }); const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); scene.add(planeMesh); planeMesh.position.set(0, 0, -85); controls.addEventListener('change', function() { planeMesh.quaternion.copy(camera.quaternion); }); let targetX = 0; let targetY = 0; let currentX = 0; let currentY = 0; function update() { requestAnimationFrame(update); const diffX = targetX - currentX; const diffY = targetY - currentY; const distance = Math.sqrt(diffX * diffX + diffY * diffY); const speed = distance / 10; if (distance < 1.0) { currentX = targetX; currentY = targetY; } else { currentX += speed * diffX / distance; currentY += speed * diffY / distance; } } update(); document.addEventListener('mousemove', (event) => { targetX = event.clientX; targetY = event.clientY; uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; }); // function animate() { // requestAnimationFrame(animate); // animatePoints(); // controls.update(); // uniforms.mouseCoord.value.x = currentX; // uniforms.mouseCoord.value.y = -currentY + window.innerHeight; // renderer.render(scene, camera); // } // animate(); function animatePoints() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = points.geometry.vertices[0].distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = points.geometry.vertices[0].distanceTo(randomPoint); t = 0; } point.copy(newPos); for (let i = 0; i < points.geometry.vertices.length; i++) { let distToPoint = points.geometry.vertices[i].distanceTo(point); let distToNewPos = points.geometry.vertices[i].distanceTo(newPos); if (distToNewPos <= distToPoint + moveDist) { let newPoint = points.geometry.vertices[i].clone().lerp(randomPoint, t); points.geometry.vertices[i].copy(newPoint); } } points.geometry.verticesNeedUpdate = true; } }); // // добавляем слушатель на controls // controls.addEventListener('change', function() { // planeMeshGradient.position.copy(camera.position); // planeMeshGradient.quaternion.copy(camera.quaternion); // });
546e411c96673f48fefc9ba2d7c5f2b6
{ "intermediate": 0.32291173934936523, "beginner": 0.4881399869918823, "expert": 0.18894833326339722 }
7,967
You're Johnny Rebel, sing one of your most famous songs.
32325498513674881f469ddef0b652f5
{ "intermediate": 0.3903231918811798, "beginner": 0.3429405391216278, "expert": 0.26673623919487 }
7,968
Consider the following HMTL snippet, Give me the final request as CURL if the form is submitted: <style>#AppointmentDate_dateview .k-calendar .k-content .k-link{background-color:#87db87}#AppointmentDate_dateview .k-calendar .k-content .k-state-disabled .k-link{background-color:#fb5454}</style><script>var applicantsCount=parseInt(2),baseurl="http://synergy-api-service/",presentDate=new Date;function onIssueEarlierChange(a){$("#PreviousVisaNumber").val(""),$("#PreviousVisaValidFrom").val(""),$("#PreviousVisaValidTo").val(""),$("#ServerPreviousVisaValidFrom").val(""),$("#ServerPreviousVisaValidTo").val(""),"Yes"==$("#IsVisaIssuedEarlier").data("kendoDropDownList").text()?$(".issueEarlierFields").show():$(".issueEarlierFields").hide()}function OnApplicationSubmit(e){var today=new Date,minDays="180";""!==minDays&&"null"!==minDays||(minDays=180),today.setDate(today.getDate()+minDays);var travel=$("#TravelDate").val(),visa=$("#visaId").val(),photo=$("#ApplicantPhotoId").val();if(""==visa)return ShowError("Please Choose Visa Type"),!1;if(""==travel&&"YYYY-MM-DD"!=travel)return ShowError("Please Enter Travel Date"),!1;if(""==photo)return ShowError("Please Upload Photo"),!1;var issuedEarlier=$("#IsVisaIssuedEarlier").data("kendoDropDownList").text();if("Yes"==issuedEarlier){var dtf=$("#PreviousVisaNumber").val();if(""==dtf)return ShowError("Please Enter Previous Visa Number"),!1;var dtf=$("#PreviousVisaValidFrom").val();if(""==dtf)return ShowError("Please Enter Previous Visa Valid From"),!1;var dtf=$("#PreviousVisaValidTo").val();if(""==dtf)return ShowError("Please Enter Previous Visa Valid To"),!1;var tf=kendo.toString($("#PreviousVisaValidFrom").data("kendoDatePicker").value(),"yyyy-MM-dd");$("#ServerPreviousVisaValidFrom").val(tf);var to=kendo.toString($("#PreviousVisaValidTo").data("kendoDatePicker").value(),"yyyy-MM-dd");$("#ServerPreviousVisaValidTo").val(to)}var td=kendo.toString($("#TravelDate").data("kendoDatePicker").value(),"yyyy-MM-dd");$("#ServerTravelDate").val(td);for(var ApplicantsData=[],k=0;k<applicantsCount;k++){var birth=$("#DateOfBirth"+k).val(),issue=$("#IssueDate"+k).val(),expiry=$("#ExpiryDate"+k).val(),newdob=new Date(kendo.parseDate(birth,"yyyy-MM-dd")),newissuek=new Date(kendo.parseDate(issue,"yyyy-MM-dd")),newexpk=new Date(kendo.parseDate(expiry,"yyyy-MM-dd")),applicantName="Applicant "+eval(k+1);if(""==$("#GivenName"+k).val())return ShowError("Please Enter "+applicantName+" First Name"),!1;if(""==$("#LastName"+k).val())return ShowError("Please Enter "+applicantName+" Last Name"),!1;if(""==$("#DateOfBirth"+k).val())return ShowError("Please Enter "+applicantName+" Date of Birth"),!1;if(new Date(newdob)>=new Date)return ShowError("Date of Birth of "+applicantName+"should be less than current date"),!1;if(""==$("#IssueDate"+k).val())return ShowError("Please Enter "+applicantName+" Passport Issue Date"),!1;if(new Date(newissuek)>=new Date)return ShowError("Passport Issue Date of "+applicantName+"should be less than current date"),!1;if(""==$("#ExpiryDate"+k).val())return ShowError("Please Enter "+applicantName+" Passport Expiry Date"),!1;if(""==$("#PassportType"+k).val())return ShowError("Please choose "+applicantName+" Passport Type"),!1;if(""==$("#PassportNumber"+k).val())return ShowError("Please Enter "+applicantName+"Passport Number"),!1;if(""==$("#RelationShip"+k).val())return ShowError("Please Select "+applicantName+"Relationship"),!1;ApplicantsData[k]={},ApplicantsData[k].AppointmentSlot=$("#AppointSlot"+k).val(),ApplicantsData[k].FirstName=$("#GivenName"+k).val(),ApplicantsData[k].LastName=$("#LastName"+k).val(),ApplicantsData[k].ServerDateOfBirth=kendo.toString(newdob,"yyyy-MM-dd"),ApplicantsData[k].PassportType=$("#PassportType"+k).val(),ApplicantsData[k].PassportNo=$("#PassportNumber"+k).val(),ApplicantsData[k].IssueCountryId=$("#PassportCountry"+k).val(),ApplicantsData[k].ServerPassportIssueDate=kendo.toString(newissuek,"yyyy-MM-dd"),ApplicantsData[k].ServerPassportExpiryDate=kendo.toString(newexpk,"yyyy-MM-dd"),ApplicantsData[k].IssuePlace=$("#IssuePlace"+k).val(),ApplicantsData[k].ParentId="ab0a5757-6059-4092-9baa-1bcc216a0751",ApplicantsData[k].Id=$("#SlotId"+k).val(),ApplicantsData[k].SurName=$("#SurName"+k).val(),ApplicantsData[k].ApplicantSerialNo=k,0!=k&&(ApplicantsData[k].RelationShip=$("#RelationShip"+k).val())}var detailsString=JSON.stringify(ApplicantsData);return $("#ApplicantsDetailsList").val(detailsString),HideError(),!0}function OnPassportCountryChange(a){GetPassportDetails(this.element.attr("data-index"),this.value())}function GetPassportDetails(a,e){return!1}$(document).ready(function(){$("#TravelDate").kendoDatePicker({format:"{0:yyyy-MM-dd}",min:presentDate,month:{empty:'<div class="k-state-disabled">#= data.value #</div>'}}),$("#PreviousVisaValidFrom").kendoDatePicker({format:"{0:yyyy-MM-dd}"}),$("#PreviousVisaValidTo").kendoDatePicker({format:"{0:yyyy-MM-dd}"}),$("#IsVisaIssuedEarlier").kendoDropDownList({optionLabel:"--Select--",dataTextField:"Name",dataValueField:"Id",filter:"contains",autoBind:!0,change:onIssueEarlierChange,dataSource:{transport:{read:{url:"/mar/query/GetLOVIdNameList?lovType=BLS_VISA_ISSUED_PREVIOUSLY"}}}}),$("#visaId").kendoDropDownList({optionLabel:"--Select--",dataTextField:"Name",dataValueField:"Id",filter:"contains",autoBind:!0,dataSource:{transport:{read:{url:"/mar/query/GetVisaTypeList"}}}}),$("#locId").kendoDropDownList({dataTextField:"Name",dataValueField:"Id",filter:"contains",autoBind:!0,dataSource:{transport:{read:{url:"/Mar/query/GetLocationListByCompany"}}}}),$("#GivenName0").val("Ali"),$("#LastName0").val("Ghozlan"),$("#DateOfBirth0").val("1996-10-30"),$("#PassportNumber0").val("GN9943949"),$("#SurName0").val(""),$("#IssuePlace0").val("Nador"),$("#PassportType0").val("0a152f62-b7b2-49ad-893e-b41b15e2bef3"),$("#IssueDate0").val("2023-01-02"),$("#ExpiryDate0").val("2026-01-06")});var onApplicationAjaxSuccess=function(a){a.success?($("#AppointmentDate").val(""),$("#appointmentDetails").removeClass("text-primary"),$("#appointmentDetails").addClass("text-success"),$("#paymentDetails").removeClass("text-secondary"),$("#paymentDetails").addClass("text-primary"),document.getElementById("progress-percent").innerHTML="50%",$(".progress-bar").css("width","54%"),$("#applicantDetailsDiv").hide(),$("#paymentDetailsDiv").show(),$("#paymentDetailsDiv").load("/Mar/BlsAppointment/VisaAppointmentPaymentForm?appointmentId="+a.model.Id),BackToTop()):(HideLoader(),a.childAlert?($("#childConfirmBody").html(a.error),$("#childConfirm").modal("show")):ShowError(a.error))};function OnChildConfirmAccept(){return $("#childConfirm").modal("hide"),$("#RemoveChildren").val(!0),$("#visaForm").submit(),!1}</script><form class="form-horizontal" id="visaForm" data-ajax-begin="onAjaxBegin" data-ajax-complete="onAjaxComplete" data-ajax-failure="onAjaxFailed" data-ajax-success="onApplicationAjaxSuccess" data-ajax="true" data-ajax-method="POST" action="/mar/BLSAppointment/ManageAppointment" method="post"><div class="validation-summary mb-3 alert alert-danger validation-summary-valid" style="display:none" data-valmsg-summary="true"><ul><li style="display:none"></li></ul></div><div class="row"><div class="col-sm-6 col-md-4 col-lg-4 pt-3"><div><label class="form-label">Applicant Email</label><input class="form-control" style="width:100%" required disabled="disabled" type="text" id="Email" name="Email" value="randomemail@host.com"></div></div><div class="col-sm-6 col-md-4 col-lg-4 pt-3"><div><label class="form-label">Mobile number</label><input class="form-control" style="width:100%" required disabled="disabled" type="text" id="Mobile" name="Mobile" value="600000000"></div></div><div class="col-sm-6 col-md-4 col-lg-4 pt-3"><div><label class="form-label">Location</label><input id="locId" style="width:100%" required disabled="disabled" type="text" name="LocationId" value="8d780684-1524-4bda-b138-7c71a8591944"></div></div><div class="col-sm-6 col-md-4 col-lg-4 pt-3"><div><label class="form-label"><span class="required">*</span>Visa Type</label><input readonly="readonly" id="visaId" style="width:100%" type="text" name="VisaType" value="c805c157-7e8f-4932-89cf-d7ab69e1af96"></div></div><div class="col-sm-6 col-md-4 col-lg-4 pt-3"><div><label for="TravelDate" class="form-label"><span class="required">*</span>Travel Date</label><input style="width:100%" type="datetime-local" id="TravelDate" name="TravelDate" value="2023-09-01T00:00:00.000"></div></div><div class="col-sm-6 col-md-4 col-lg-4 pt-3"><div><label for="IsVisaIssuedEarlier" class="form-label">Previous Schengen Visa in the last 2 years</label><input style="width:100%" type="text" id="IsVisaIssuedEarlier" name="IsVisaIssuedEarlier" value=""></div></div><div class="col-sm-6 col-md-4 col-lg-4 pt-3 issueEarlierFields" style="display:none"><div><label for="PreviousVisaNumber" class="form-label"><span class="required">*</span>Previous Visa Number</label><input class="form-control" type="text" style="width:100%" id="PreviousVisaNumber" name="PreviousVisaNumber" value=""></div></div><div class="col-sm-6 col-md-4 col-lg-4 pt-3 issueEarlierFields" style="display:none"><div><label for="PreviousVisaValidFrom" class="form-label"><span class="required">*</span>Previous Visa Valid From</label><input style="width:100%" type="datetime-local" id="PreviousVisaValidFrom" name="PreviousVisaValidFrom" value=""></div></div><div class="col-sm-6 col-md-4 col-lg-4 pt-3 issueEarlierFields" style="display:none"><div><label for="PreviousVisaValidTo" class="form-label"><span class="required">*</span>Previous Visa Valid To</label><input style="width:100%" type="datetime-local" id="PreviousVisaValidTo" name="PreviousVisaValidTo" value=""></div></div></div><br><h6 style="text-align:center">APPLICANTS DETAILS (Total Number of Applicants : 2)</h6><script>applicant=0</script><div class="container"><h6>Applicant 1</h6><div class="row"><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="AppointSlot0" class="form-label"><span class="required">*</span>Appointment Slot</label><input type="text" id="AppointSlot0" class="form-control" style="width:100%" value="09:00-09:15" readonly="readonly"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="PassportCountry0" class="form-label"><span class="required">*</span>Passport Issue Country</label><input data-index="0" id="PassportCountry0" style="width:100%"><script>$(function () { $("#PassportCountry0").kendoDropDownList({ optionLabel: "--Select--", dataTextField: "Name", dataValueField: "Id", filter: "contains", filtering: function (e) { var filter = e.filter; if (filter!==undefined && !filter.value) { //prevent filtering if the filter does not value e.preventDefault(); } }, autoBind: true, change: OnPassportCountryChange, dataSource: { transport: { read: { url: "/Mar/query/GetCountryList", } }, requestEnd: function (e) { if(e.response!==undefined){ var def = e.response.find(x => x.Code === 'MAR'); if (def !== undefined && def !== null && 0 != 0) { $("#PassportCountry0").data('kendoDropDownList').value(def.Id); } else if (0 == 0 && 'c6fadcdf-7ce9-4bdd-aedf-944829be18ad'!= null) { $("#PassportCountry0").data('kendoDropDownList').value('c6fadcdf-7ce9-4bdd-aedf-944829be18ad'); } else if (def !== undefined && def !== null && 0 == 0) { $("#PassportCountry0").data('kendoDropDownList').value(def.Id); } } } } }); });</script></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="PassportNumber0" class="form-label"><span class="required">*</span>Passport Number</label><input type="text" class="form-control" id="PassportNumber0" style="width:100%" onchange="GetPassportDetails(0)"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="SurName0" class="form-label">SurName</label><input type="text" class="form-control" id="SurName0" style="width:100%"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="GivenName0" class="form-label"><span class="required">*</span>First Name(Given Name)</label><input type="text" class="form-control" id="GivenName0" style="width:100%"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="LastName0" class="form-label"><span class="required">*</span>Last Name</label><input id="LastName0" type="text" class="form-control" style="width:100%"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><label for="DateOfBirth0" class="form-label"><span class="required">*</span>Date of Birth</label><input id="DateOfBirth0" style="width:100%"><script>$(function(){$("#DateOfBirth0").kendoDatePicker({format:"{0:yyyy-MM-dd}"})})</script></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="PassportType0" class="form-label"><span class="required">*</span>Passport Type</label><input id="PassportType0" style="width:100%"><script>$(function(){$("#PassportType0").kendoDropDownList({optionLabel:"--Select--",dataTextField:"Name",dataValueField:"Id",filter:"contains",autoBind:!0,dataSource:{transport:{read:{url:"/Mar/query/GetLOVIdNameList?lovType=BLS_PASSPORT_TYPE"}}}})})</script></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><label for="IssueDate0" class="form-label"><span class="required">*</span>Issue Date</label><input id="IssueDate0" style="width:100%"><script>$(function(){$("#IssueDate0").kendoDatePicker({format:"{0:yyyy-MM-dd}"})})</script></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><label for="ExpiryDate0" class="form-label"><span class="required">*</span>Expiry Date</label><input id="ExpiryDate0" style="width:100%"><script>$(function(){$("#ExpiryDate0").kendoDatePicker({format:"{0:yyyy-MM-dd}"})})</script></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="IssuePlace0" class="form-label">Issue Place</label><input type="text" class="form-control" id="IssuePlace0" style="width:100%"></div></div><input type="text" class="form-control" id="SlotId0" style="display:none" value="8a7df3a9-ff90-41b5-b610-6dddaf38172e"></div></div><hr><script>applicant=1</script><div class="container"><h6>Applicant 2</h6><div class="row"><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="AppointSlot1" class="form-label"><span class="required">*</span>Appointment Slot</label><input type="text" id="AppointSlot1" class="form-control" style="width:100%" value="09:00-09:15" readonly="readonly"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="PassportCountry1" class="form-label"><span class="required">*</span>Passport Issue Country</label><input data-index="1" id="PassportCountry1" style="width:100%"><script>$(function () { $("#PassportCountry1").kendoDropDownList({ optionLabel: "--Select--", dataTextField: "Name", dataValueField: "Id", filter: "contains", filtering: function (e) { var filter = e.filter; if (filter!==undefined && !filter.value) { //prevent filtering if the filter does not value e.preventDefault(); } }, autoBind: true, change: OnPassportCountryChange, dataSource: { transport: { read: { url: "/Mar/query/GetCountryList", } }, requestEnd: function (e) { if(e.response!==undefined){ var def = e.response.find(x => x.Code === 'MAR'); if (def !== undefined && def !== null && 1 != 0) { $("#PassportCountry1").data('kendoDropDownList').value(def.Id); } else if (1 == 0 && 'c6fadcdf-7ce9-4bdd-aedf-944829be18ad'!= null) { $("#PassportCountry1").data('kendoDropDownList').value('c6fadcdf-7ce9-4bdd-aedf-944829be18ad'); } else if (def !== undefined && def !== null && 1 == 0) { $("#PassportCountry1").data('kendoDropDownList').value(def.Id); } } } } }); });</script></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="PassportNumber1" class="form-label"><span class="required">*</span>Passport Number</label><input type="text" class="form-control" id="PassportNumber1" style="width:100%" onchange="GetPassportDetails(1)"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="SurName1" class="form-label">SurName</label><input type="text" class="form-control" id="SurName1" style="width:100%"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="GivenName1" class="form-label"><span class="required">*</span>First Name(Given Name)</label><input type="text" class="form-control" id="GivenName1" style="width:100%"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="LastName1" class="form-label"><span class="required">*</span>Last Name</label><input id="LastName1" type="text" class="form-control" style="width:100%"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><label for="DateOfBirth1" class="form-label"><span class="required">*</span>Date of Birth</label><input id="DateOfBirth1" style="width:100%"><script>$(function(){$("#DateOfBirth1").kendoDatePicker({format:"{0:yyyy-MM-dd}"})})</script></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="PassportType1" class="form-label"><span class="required">*</span>Passport Type</label><input id="PassportType1" style="width:100%"><script>$(function(){$("#PassportType1").kendoDropDownList({optionLabel:"--Select--",dataTextField:"Name",dataValueField:"Id",filter:"contains",autoBind:!0,dataSource:{transport:{read:{url:"/Mar/query/GetLOVIdNameList?lovType=BLS_PASSPORT_TYPE"}}}})})</script></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><label for="IssueDate1" class="form-label"><span class="required">*</span>Issue Date</label><input id="IssueDate1" style="width:100%"><script>$(function(){$("#IssueDate1").kendoDatePicker({format:"{0:yyyy-MM-dd}"})})</script></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><label for="ExpiryDate1" class="form-label"><span class="required">*</span>Expiry Date</label><input id="ExpiryDate1" style="width:100%"><script>$(function(){$("#ExpiryDate1").kendoDatePicker({format:"{0:yyyy-MM-dd}"})})</script></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="IssuePlace1" class="form-label">Issue Place</label><input type="text" class="form-control" id="IssuePlace1" style="width:100%"></div></div><div class="col-sm-12 col-md-4 col-lg-4 pt-3"><div><label for="RelationShip1" class="form-label"><span class="required">*</span>Relationship</label><input class="form-control" id="RelationShip1" style="width:100%"><script>$(function(){$("#RelationShip1").kendoDropDownList({optionLabel:"--Select--",dataTextField:"Name",dataValueField:"Id",filter:"contains",autoBind:!0,dataSource:{transport:{read:{url:"/mar/query/GetLOVIdNameList?lovType=BLS_FAMILY_RELATIONSHIP"}}}})})</script></div></div><input type="text" class="form-control" id="SlotId1" style="display:none" value="7c122d93-f549-4aad-a1a0-777ae66e0f4f"></div></div><hr><div class="row" style="padding:10px"><div class="validation-summary mb-3 alert alert-danger validation-summary-valid" style="display:none" data-valmsg-summary="true"><ul><li style="display:none"></li></ul></div><div class="col-12" style="text-align:right"><button type="submit" class="btn btn-primary" style="float:right" onclick="return OnApplicationSubmit(event)">Submit</button></div></div><input id="Id" name="Id" type="hidden" value="ab0a5757-6059-4092-9baa-1bcc216a0751"> <input data-val="true" data-val-required="The DataAction field is required." id="DataAction" name="DataAction" type="hidden" value="Edit"> <input id="IsVisaIssuedEarlier" name="IsVisaIssuedEarlier" type="hidden" value=""> <input id="Email" name="Email" type="hidden" value="randomemail@host.com"> <input data-val="true" data-val-required="The ApplicantsNo field is required." id="ApplicantsNo" name="ApplicantsNo" type="hidden" value="2"> <input id="LocationId" name="LocationId" type="hidden" value="8d780684-1524-4bda-b138-7c71a8591944"> <input id="Mobile" name="Mobile" type="hidden" value="600000000"> <input id="MobileCountryCode" name="MobileCountryCode" type="hidden" value="&#x2B;212"> <input id="AppointmentId" name="AppointmentId" type="hidden" value="ab0a5757-6059-4092-9baa-1bcc216a0751"> <input id="AppointmentFor" name="AppointmentFor" type="hidden" value="Family"> <input id="ApplicantsDetailsList" name="ApplicantsDetailsList" type="hidden" value=""> <input data-val="true" data-val-number="The field TotalAmount must be a number." id="TotalAmount" name="TotalAmount" type="hidden" value="382"> <input id="ApplicantPhotoId" name="ApplicantPhotoId" type="hidden" value="56699666-4b74-448f-b388-497ac03770da"> <input id="ImageId" name="ImageId" type="hidden" value="5555555-5ece-4dab-a942-3179ef451393"> <input id="AppointmentCategoryId" name="AppointmentCategoryId" type="hidden" value="5c2e8e01-796d-4347-95ae-0c95a9177b26"> <input id="AppointmentDate" name="AppointmentDate" type="hidden" value="2023-06-20 00:00:00.000"> <input data-val="true" data-val-required="The SaveState field is required." id="SaveState" name="SaveState" type="hidden" value="Application"> <input id="AppointmentNo" name="AppointmentNo" type="hidden" value="RBA482200279023"> <input id="BlsSettingsJson" name="BlsSettingsJson" type="hidden" value="9OErdWqg7TuVZqGy0iUuxbz2HBjJabseOOIsKK6b7C"> <input id="CaptchaId" name="CaptchaId" type="hidden" value="4df80be8-9cac-47b0-a2ef-4f78b8da3761"> <input data-val="true" data-val-required="The MinimumPassportValidityDays field is required." id="MinimumPassportValidityDays" name="MinimumPassportValidityDays" type="hidden" value="180"> <input data-val="true" data-val-required="The ServerDateOfBirth field is required." id="ServerDateOfBirth" name="ServerDateOfBirth" type="hidden" value="0001-01-01 00:00:00.000"> <input id="ServerTravelDate" name="ServerTravelDate" type="hidden" value=""> <input data-val="true" data-val-required="The ServerPassportIssueDate field is required." id="ServerPassportIssueDate" name="ServerPassportIssueDate" type="hidden" value="0001-01-01 00:00:00.000"> <input data-val="true" data-val-required="The ServerPassportExpiryDate field is required." id="ServerPassportExpiryDate" name="ServerPassportExpiryDate" type="hidden" value="0001-01-01 00:00:00.000"> <input id="ServerPreviousVisaValidFrom" name="ServerPreviousVisaValidFrom" type="hidden" value=""> <input id="ServerPreviousVisaValidTo" name="ServerPreviousVisaValidTo" type="hidden" value=""> <input data-val="true" data-val-required="The RemoveChildren field is required." id="RemoveChildren" name="RemoveChildren" type="hidden" value="False"> <input name="__RequestVerificationToken" type="hidden" value="CfDJ8KQpjhafXLREg"></form><div class="modal fade" id="screen2" tabindex="-1" role="dialog" aria-labelledby="premiumLounge" aria-hidden="true" data-backdrop="static"><div class="modal-dialog modal-dialog-centered" role="document"><div class="modal-content" style="margin-bottom:250px"><div class="modal-header" style="text-align:center"><h6 class="modal-title" id="premiumLounge">PremiumLounge</h6><button type="button" class="close" data-dismiss="modal"><i class="fa-solid fa-rectangle-xmark"></i></button></div><div class="modal-body"><p style="text-align:center">This is optional service for additional charge. Kindly visit additional service page for more information.</p></div></div></div></div><div class="modal fade" id="childConfirm" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="childConfirmModal" aria-hidden="true"><div class="modal-dialog modal-dialog-centered" role="document"><div class="modal-content"><div class="modal-header"><h6 class="modal-title" id="childConfirmHeader">ChildConfirmTitle</h6></div><div class="modal-body scam-body" id="childConfirmBody"></div><div class="modal-footer"><button class="btn btn-danger" type="button" data-bs-dismiss="modal">No</button><button class="btn btn-success" onclick="return OnChildConfirmAccept()">Yes</button></div></div></div></div>
9c79587a75d42eb9d569c9edea7a34e9
{ "intermediate": 0.4073857367038727, "beginner": 0.3842223882675171, "expert": 0.2083919495344162 }
7,969
fivem scripting here is my server lua file for a script I want it to delete a item from the table if its been in for longer then 180 seconds -- server.lua local oil_slicks = {} -- Server event to create oil slick RegisterNetEvent('oil:create_oil_slick') AddEventHandler('oil:create_oil_slick', function(coords) -- Add oil slick to the table table.insert(oil_slicks, coords) -- Trigger client event to create slick TriggerClientEvent('oil:create_petrol_decal', -1, coords, oil_slicks) end) -- Server event to delete oil slick RegisterNetEvent('oil:delete_oil_slick') AddEventHandler('oil:delete_oil_slick', function(coords) -- Find the index of the oil slick to delete local index_to_delete = nil for k, v in pairs(oil_slicks) do if v == coords then index_to_delete = k break end end -- Remove oil slick from the table if index_to_delete then table.remove(oil_slicks, index_to_delete) end -- Trigger client event to delete slick TriggerClientEvent('oil:delete_petrol_decal', -1, coords) end)
6dcd246240fb9307aa5dab2293b1cdcf
{ "intermediate": 0.3529272675514221, "beginner": 0.46098634600639343, "expert": 0.18608640134334564 }
7,970
can you write a android kotlin class following with the below requirement? This class is inherits from base class that show automatic interate show image in the images list. This class allow to rotate interact with touch event to allow user to rotate the picture.
dd0e19adef51f1030c52c74b4079d918
{ "intermediate": 0.46039626002311707, "beginner": 0.2863730490207672, "expert": 0.2532307505607605 }
7,971
java code to load a midi file and alter all scores randomly by 10% in the scope of harmonics to the altered score, using javax.sound.midi
6f0871a61b60179cc0a34f0b54818808
{ "intermediate": 0.614083468914032, "beginner": 0.09524192661046982, "expert": 0.2906746566295624 }
7,972
hi
861c18c51afc12c228e3def5ad08c339
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
7,973
I have this SAS code: PROC LOGISTIC DATA=ess10 PLOTS(unpack label)=ALL;; CLASS gndr (PARAM=REF) hincfel (PARAM=REF) sclmeet (PARAM=REF) brncntr (PARAM=REF) uemp12m (PARAM=REF) health (PARAM=REF) trstplc (PARAM=REF) trstplt (PARAM=REF) fairelcc (PARAM=REF); MODEL happy (Event = 'Not happy')=eduyrs agea gndr hincfel sclmeet brncntr uemp12m health trstplc trstplt fairelcc / SELECTION=NONE INFLUENCE LACKFIT AGGREGATE SCALE=NONE RSQUARE LINK=LOGIT CLPARM=WALD CLODDS=WALD ALPHA=0.05 ; RUN; QUIT; But in results I can not see any plots. Why and how to fix it?
ef188882dfeee475b0632c3f774c152b
{ "intermediate": 0.34213870763778687, "beginner": 0.35119903087615967, "expert": 0.30666232109069824 }
7,974
what we need use Mapped() and mapped_column in sqlalchemy for? I can anderstad the difference between this one for instance class Log(Base): __tablename__ = "log" id = Column(Integer, primary_key=True, autoincrement=True) request_datetime = Column(TIMESTAMP(timezone=True), nullable=False) request_url = Column(Text, nullable=False) request_method = Column(String(8), nullable=False)
f14dcc90894341e922375bc82bca34b7
{ "intermediate": 0.6312242150306702, "beginner": 0.30964091420173645, "expert": 0.059134818613529205 }
7,975
how to fix quartus specify a legal end time
71cba43605598f9398c8b810cebaaa08
{ "intermediate": 0.33438587188720703, "beginner": 0.35978078842163086, "expert": 0.3058333992958069 }
7,976
error: stray ‘\’ in program 23 | dest[length-1] = ‘\0’;
38799f6d4f10e0d158428343a076da49
{ "intermediate": 0.29076680541038513, "beginner": 0.4184085726737976, "expert": 0.29082462191581726 }
7,977
Write a script for Blender 3D version 3.5, so that you can align objects at the same distance from each other.
84b76971d297c9d3b33edc6e6380ab4f
{ "intermediate": 0.4396391808986664, "beginner": 0.2065831422805786, "expert": 0.353777676820755 }
7,978
the problem here that background "#1B2827" in ".language-option" doesn't want to go full height after "#night-mode-toggle" switch: <style> body, html { scrollbar-width: 2em; scrollbar-color: #fada38 #000000; overflow-x: hidden; color:black; margin: 0; padding: 0; position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; line-height: 1.6; transition: background-color 2s, color 3s; --overflow:hidden; } header { background-color: #4caf50; color: #fff; padding: 16px 0px 0px 0px; text-align: center; position: absolute; transition: background-color 2s; width: 100%; height: 18px; right: 0px; z-index:999; } h1 { margin: 0 auto; display: flex; justify-content: space-between; align-items: center; font-size: 18px; width: 90%; height: 1%; } .background { font-weight: bold; padding: 0px; text-align: center; justify-content: center; align-items: center; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: -1; position: relative; display: flex; } .background:before { content: '🇬🇧&nbsp;🇩🇪'; font-size: 10em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity: 0.15; display: flex; white-space: nowrap; } .background-text { display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; z-index: -1; } .left::before, .right::before { content: ""; position: absolute; top: 5px; border-bottom: 1px dashed #fff; width: 40%; } .left::before { right: 100%; margin-right: 20px; } .right::before { left: 100%; margin-left: 20px; } .flags-container { width: 100%; position: relative; top: 0; right: 0px; padding: 1px 0; background-color: darkgreen; display: flex; justify-content: center; align-items: center; --box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); z-index: 1; } .flag-radio { display: none; } .flag-label { cursor: pointer; margin: 0 5px; transition: 0.3s; opacity: 0.6; font-size: 24px; } .flag-label:hover { opacity: 1; } .language-option { position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; display: none; justify-content: center; align-items: center; padding-top: 64px; width: 100%; height: 100%; background-color: white; } #english-flag:checked ~ #english, #hindi-flag:checked ~ #hindi, #hebrew-flag:checked ~ #hebrew, #chinese-flag:checked ~ #chinese, #french-flag:checked ~ #french, #spanish-flag:checked ~ #spanish { display: block; } #night-mode-toggle:checked ~ body, #night-mode-toggle:checked ~ header, #night-mode-toggle:checked ~ .language-option, #night-mode-toggle:checked { background-color: #1B2827; color: #F3EFEF;text-shadow: 1px 1px 2px rgba(42, 81, 21, 0.5); } .switch-container { position: absolute; top: 5px; right: 16px; display: flex; align-items: center; justify-content: center; z-index: 2; } .switch-container label { content: "&#x1F319;"; position: relative; margin-left: 0px; cursor: pointer; user-select: none; align-items: center; justify-content: center; } .switch { content: "&#x1F319;"; position: relative; cursor: pointer; width: 64px; height: 32px; margin-right: 5px; background-color: darkgreen; border-radius: 15px; transition: background-color 3s; } .switch:before { content: "🌿"; display: block; position: absolute; top: 2px; left: 2px; height: 0px; width: 0px; background-color: #121; border-radius: 50%; transition: left 1s; } #night-mode-toggle:checked ~ .switch-container .switch { background-color: #121; } #night-mode-toggle:checked ~ .switch-container .switch:before { left: calc(100% - 28px);content: "🌙"; } p { margin: 15px 5px; --x-blend-mode: Overlay; color: rgba(243, 239, 239, 0.5); background-color: #182C2B; padding:5px 15px; border-radius:10px 10px; text-shadow: 0px 0px 6px 6px rgba(27,40,39,1); box-shadow: 0px 0px 10px 20px rgba(0, 0, 0, 0.2); z-index:1; } h2 { width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 1.5rem; font-weight: bold; --margin: 1em 0; color: #721336; text-shadow: 0px 0px 8px rgba(0, 0, 0, 0.5); background-color: #182C2B; --padding: 0.5em 1em; --border-radius: 0 10px 10px 0; --box-shadow: 0px 0px 5px 10px rgba(10, 100, 10, 0.1); --opacity: 0.8; z-index:2; } @media only screen and (max-width: 600px) { h2 { font-size: 1.5rem; padding: 0.5em 0.75em; } } </style> </head> <body> <input id="english-flag" type="radio" name="flags" class="flag-radio"> <input id="hindi-flag" type="radio" name="flags" class="flag-radio"> <input id="hebrew-flag" type="radio" name="flags" class="flag-radio"> <input id="chinese-flag" type="radio" name="flags" class="flag-radio"> <input id="french-flag" type="radio" name="flags" class="flag-radio"> <input id="spanish-flag" type="radio" name="flags" class="flag-radio"> <div class="flags-container"><logo id="supercrazylogotype"></logo> <label for="english-flag" class="flag-label">🇬🇧</label> <label for="hindi-flag" class="flag-label">🇮🇳</label> <label for="hebrew-flag" class="flag-label">🇮🇱</label> <label for="chinese-flag" class="flag-label">🇨🇳</label> <label for="french-flag" class="flag-label">🇫🇷</label> <label for="spanish-flag" class="flag-label">🇪🇸</label> </div> <header> <h1> <span class="left">EcoWare</span> <span class="right">Earthwise</span> </h1> </header> <!-- Night Mode Switch --> <input type="checkbox" id="night-mode-toggle" /> <div class="switch-container"> <label for="night-mode-toggle"> <div class="switch"></div> </label> </div> <div id="english" class="language-option"> <p>Our mission</p> </div> <div id="hindi" class="language-option"> <p>hindi details going here</p> </div> <div id="hebrew" class="language-option"> <p>hebrew details going here</p> </div> <div id="chinese" class="language-option"> <p>chinese details going here</p> </div> <div id="french" class="language-option"> <p>french details going here</p> </div> <div id="spanish" class="language-option"> <p>spanish details going here</p> </div> <span class="background"> <span class="background-text"> </span> </span> </body> </html>
bcdc32b84c55fbc6ed31b1432f36c8e4
{ "intermediate": 0.3420519530773163, "beginner": 0.32922711968421936, "expert": 0.32872092723846436 }
7,979
the problem here that background "#1B2827" in ".language-option" doesn't want to go full height after "#night-mode-toggle" switch: <style> body, html { scrollbar-width: 2em; scrollbar-color: #fada38 #000000; overflow-x: hidden; color:black; margin: 0; padding: 0; position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; line-height: 1.6; transition: background-color 2s, color 3s; --overflow:hidden; } header { background-color: #4caf50; color: #fff; padding: 16px 0px 0px 0px; text-align: center; position: absolute; transition: background-color 2s; width: 100%; height: 18px; right: 0px; z-index:999; } h1 { margin: 0 auto; display: flex; justify-content: space-between; align-items: center; font-size: 18px; width: 90%; height: 1%; } .background { font-weight: bold; padding: 0px; text-align: center; justify-content: center; align-items: center; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: -1; position: relative; display: flex; } .background:before { content: '🇬🇧&nbsp;🇩🇪'; font-size: 10em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity: 0.15; display: flex; white-space: nowrap; } .background-text { display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; z-index: -1; } .left::before, .right::before { content: ""; position: absolute; top: 5px; border-bottom: 1px dashed #fff; width: 40%; } .left::before { right: 100%; margin-right: 20px; } .right::before { left: 100%; margin-left: 20px; } .flags-container { width: 100%; position: relative; top: 0; right: 0px; padding: 1px 0; background-color: darkgreen; display: flex; justify-content: center; align-items: center; --box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); z-index: 1; } .flag-radio { display: none; } .flag-label { cursor: pointer; margin: 0 5px; transition: 0.3s; opacity: 0.6; font-size: 24px; } .flag-label:hover { opacity: 1; } .language-option { position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; display: none; justify-content: center; align-items: center; padding-top: 64px; width: 100%; height: 100%; background-color: white; } #english-flag:checked ~ #english, #hindi-flag:checked ~ #hindi, #hebrew-flag:checked ~ #hebrew, #chinese-flag:checked ~ #chinese, #french-flag:checked ~ #french, #spanish-flag:checked ~ #spanish { display: block; } #night-mode-toggle:checked ~ body, #night-mode-toggle:checked ~ header, #night-mode-toggle:checked ~ .language-option, #night-mode-toggle:checked { background-color: #1B2827; color: #F3EFEF;text-shadow: 1px 1px 2px rgba(42, 81, 21, 0.5); } .switch-container { position: absolute; top: 5px; right: 16px; display: flex; align-items: center; justify-content: center; z-index: 2; } .switch-container label { content: "&#x1F319;"; position: relative; margin-left: 0px; cursor: pointer; user-select: none; align-items: center; justify-content: center; } .switch { content: "&#x1F319;"; position: relative; cursor: pointer; width: 64px; height: 32px; margin-right: 5px; background-color: darkgreen; border-radius: 15px; transition: background-color 3s; } .switch:before { content: "🌿"; display: block; position: absolute; top: 2px; left: 2px; height: 0px; width: 0px; background-color: #121; border-radius: 50%; transition: left 1s; } #night-mode-toggle:checked ~ .switch-container .switch { background-color: #121; } #night-mode-toggle:checked ~ .switch-container .switch:before { left: calc(100% - 28px);content: "🌙"; } p { margin: 15px 5px; --x-blend-mode: Overlay; color: rgba(243, 239, 239, 0.5); background-color: #182C2B; padding:5px 15px; border-radius:10px 10px; text-shadow: 0px 0px 6px 6px rgba(27,40,39,1); box-shadow: 0px 0px 10px 20px rgba(0, 0, 0, 0.2); z-index:1; } h2 { width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 1.5rem; font-weight: bold; --margin: 1em 0; color: #721336; text-shadow: 0px 0px 8px rgba(0, 0, 0, 0.5); background-color: #182C2B; --padding: 0.5em 1em; --border-radius: 0 10px 10px 0; --box-shadow: 0px 0px 5px 10px rgba(10, 100, 10, 0.1); --opacity: 0.8; z-index:2; } @media only screen and (max-width: 600px) { h2 { font-size: 1.5rem; padding: 0.5em 0.75em; } } </style> </head> <body> <input id="english-flag" type="radio" name="flags" class="flag-radio"> <input id="hindi-flag" type="radio" name="flags" class="flag-radio"> <input id="hebrew-flag" type="radio" name="flags" class="flag-radio"> <input id="chinese-flag" type="radio" name="flags" class="flag-radio"> <input id="french-flag" type="radio" name="flags" class="flag-radio"> <input id="spanish-flag" type="radio" name="flags" class="flag-radio"> <div class="flags-container"><logo id="supercrazylogotype"></logo> <label for="english-flag" class="flag-label">🇬🇧</label> <label for="hindi-flag" class="flag-label">🇮🇳</label> <label for="hebrew-flag" class="flag-label">🇮🇱</label> <label for="chinese-flag" class="flag-label">🇨🇳</label> <label for="french-flag" class="flag-label">🇫🇷</label> <label for="spanish-flag" class="flag-label">🇪🇸</label> </div> <header> <h1> <span class="left">EcoWare</span> <span class="right">Earthwise</span> </h1> </header> <!-- Night Mode Switch --> <input type="checkbox" id="night-mode-toggle" /> <div class="switch-container"> <label for="night-mode-toggle"> <div class="switch"></div> </label> </div> <div id="english" class="language-option"> <p>Our mission</p> </div> <div id="hindi" class="language-option"> <p>hindi details going here</p> </div> <div id="hebrew" class="language-option"> <p>hebrew details going here</p> </div> <div id="chinese" class="language-option"> <p>chinese details going here</p> </div> <div id="french" class="language-option"> <p>french details going here</p> </div> <div id="spanish" class="language-option"> <p>spanish details going here</p> </div> <span class="background"> <span class="background-text"> </span> </span> </body> </html>
5b9dc4768868af6f7153b6821807ccb6
{ "intermediate": 0.3420519530773163, "beginner": 0.32922711968421936, "expert": 0.32872092723846436 }
7,980
the problem here that background "#1B2827" in ".language-option" doesn't want to go full height after "#night-mode-toggle" switch: <style> body, html { scrollbar-width: 2em; scrollbar-color: #fada38 #000000; overflow-x: hidden; color:black; margin: 0; padding: 0; position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; line-height: 1.6; transition: background-color 2s, color 3s; --overflow:hidden; } header { background-color: #4caf50; color: #fff; padding: 16px 0px 0px 0px; text-align: center; position: absolute; transition: background-color 2s; width: 100%; height: 18px; right: 0px; z-index:999; } h1 { margin: 0 auto; display: flex; justify-content: space-between; align-items: center; font-size: 18px; width: 90%; height: 1%; } .background { font-weight: bold; padding: 0px; text-align: center; justify-content: center; align-items: center; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: -1; position: relative; display: flex; } .background:before { content: '🇬🇧&nbsp;🇩🇪'; font-size: 10em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity: 0.15; display: flex; white-space: nowrap; } .background-text { display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; z-index: -1; } .left::before, .right::before { content: ""; position: absolute; top: 5px; border-bottom: 1px dashed #fff; width: 40%; } .left::before { right: 100%; margin-right: 20px; } .right::before { left: 100%; margin-left: 20px; } .flags-container { width: 100%; position: relative; top: 0; right: 0px; padding: 1px 0; background-color: darkgreen; display: flex; justify-content: center; align-items: center; --box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); z-index: 1; } .flag-radio { display: none; } .flag-label { cursor: pointer; margin: 0 5px; transition: 0.3s; opacity: 0.6; font-size: 24px; } .flag-label:hover { opacity: 1; } .language-option { position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; display: none; justify-content: center; align-items: center; padding-top: 64px; width: 100%; height: 100%; background-color: white; } #english-flag:checked ~ #english, #hindi-flag:checked ~ #hindi, #hebrew-flag:checked ~ #hebrew, #chinese-flag:checked ~ #chinese, #french-flag:checked ~ #french, #spanish-flag:checked ~ #spanish { display: block; } #night-mode-toggle:checked ~ body, #night-mode-toggle:checked ~ header, #night-mode-toggle:checked ~ .language-option, #night-mode-toggle:checked { background-color: #1B2827; color: #F3EFEF;text-shadow: 1px 1px 2px rgba(42, 81, 21, 0.5); } .switch-container { position: absolute; top: 5px; right: 16px; display: flex; align-items: center; justify-content: center; z-index: 2; } .switch-container label { content: "&#x1F319;"; position: relative; margin-left: 0px; cursor: pointer; user-select: none; align-items: center; justify-content: center; } .switch { content: "&#x1F319;"; position: relative; cursor: pointer; width: 64px; height: 32px; margin-right: 5px; background-color: darkgreen; border-radius: 15px; transition: background-color 3s; } .switch:before { content: "🌿"; display: block; position: absolute; top: 2px; left: 2px; height: 0px; width: 0px; background-color: #121; border-radius: 50%; transition: left 1s; } #night-mode-toggle:checked ~ .switch-container .switch { background-color: #121; } #night-mode-toggle:checked ~ .switch-container .switch:before { left: calc(100% - 28px);content: "🌙"; } p { margin: 15px 5px; --x-blend-mode: Overlay; color: rgba(243, 239, 239, 0.5); background-color: #182C2B; padding:5px 15px; border-radius:10px 10px; text-shadow: 0px 0px 6px 6px rgba(27,40,39,1); box-shadow: 0px 0px 10px 20px rgba(0, 0, 0, 0.2); z-index:1; } h2 { width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 1.5rem; font-weight: bold; --margin: 1em 0; color: #721336; text-shadow: 0px 0px 8px rgba(0, 0, 0, 0.5); background-color: #182C2B; --padding: 0.5em 1em; --border-radius: 0 10px 10px 0; --box-shadow: 0px 0px 5px 10px rgba(10, 100, 10, 0.1); --opacity: 0.8; z-index:2; } @media only screen and (max-width: 600px) { h2 { font-size: 1.5rem; padding: 0.5em 0.75em; } } </style> </head> <body> <input id="english-flag" type="radio" name="flags" class="flag-radio"> <input id="hindi-flag" type="radio" name="flags" class="flag-radio"> <input id="hebrew-flag" type="radio" name="flags" class="flag-radio"> <input id="chinese-flag" type="radio" name="flags" class="flag-radio"> <input id="french-flag" type="radio" name="flags" class="flag-radio"> <input id="spanish-flag" type="radio" name="flags" class="flag-radio"> <div class="flags-container"><logo id="supercrazylogotype"></logo> <label for="english-flag" class="flag-label">🇬🇧</label> <label for="hindi-flag" class="flag-label">🇮🇳</label> <label for="hebrew-flag" class="flag-label">🇮🇱</label> <label for="chinese-flag" class="flag-label">🇨🇳</label> <label for="french-flag" class="flag-label">🇫🇷</label> <label for="spanish-flag" class="flag-label">🇪🇸</label> </div> <header> <h1> <span class="left">EcoWare</span> <span class="right">Earthwise</span> </h1> </header> <!-- Night Mode Switch --> <input type="checkbox" id="night-mode-toggle" /> <div class="switch-container"> <label for="night-mode-toggle"> <div class="switch"></div> </label> </div> <div id="english" class="language-option"> <p>Our mission</p> </div> <div id="hindi" class="language-option"> <p>hindi details going here</p> </div> <div id="hebrew" class="language-option"> <p>hebrew details going here</p> </div> <div id="chinese" class="language-option"> <p>chinese details going here</p> </div> <div id="french" class="language-option"> <p>french details going here</p> </div> <div id="spanish" class="language-option"> <p>spanish details going here</p> </div> <span class="background"> <span class="background-text"> </span> </span> </body> </html>
d349f4b16352ac854beff5ca5b531424
{ "intermediate": 0.3420519530773163, "beginner": 0.32922711968421936, "expert": 0.32872092723846436 }
7,981
Можно ли заменить ios::binary и сделать более простым код? // Function to save data from an array of cars into a file void save_data(Car* cars, int n) { ofstream file("cars.dat" , ios::binary); if (!file) { cout << "Unable to create file." << endl; return; } for (int i = 0; i < n; i++) { file.write(cars[i].brand, 50); file.write(cars[i].type, 50); file.write((char*)&cars[i].engine_power, sizeof(int)); file.write((char*)&cars[i].mileage, sizeof(int)); file.write((char*)&cars[i].last_maintenance_date.number, sizeof(int)); file.write(cars[i].last_maintenance_date.month, 20); file.write((char*)&cars[i].last_maintenance_date.year, sizeof(int)); } file.close(); }
a52b628b634b185d78f2e10cd5e5efcd
{ "intermediate": 0.48020437359809875, "beginner": 0.3535439670085907, "expert": 0.16625164449214935 }
7,982
This is my ide program for a highsum gui game. "import GUIExample.GameTableFrame; import Model.*; import GUIExample.LoginDialog; public class GUIExample { private Dealer dealer; private Player player; private GameTableFrame app; public GUIExample() { } public void run() { dealer.shuffleCards(); app = new GameTableFrame(dealer, player); app.setVisible(true); // Replace app.run(); with this line } public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); GUIExample example = new GUIExample(); example.dealer = new Dealer(); example.player = new Player(login, password, 10000); example.run(); } } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.EventQueue; import javax.swing.*; public class HighSumGUI { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum() { // Override the ‘run’ method to display and update the GameTableFrame @Override public void run() { Dealer dealer = getDealer(); Player player = getPlayer(); GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); gameTableFrame.setVisible(true); // Use a loop to continuously update and start new games as desired by the user boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); int response = JOptionPane.showConfirmDialog( gameTableFrame, "Do you want to play another game?", "New Game", JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } gameTableFrame.dispose(); } }; highSum.init(login, password); highSum.run(); } } }); } } package Controller; import Model.Dealer; import Model.Player; import View.ViewController; public class GameController { private Dealer dealer; private Player player; private ViewController view; private int chipsOnTable; private boolean playerQuit; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } public boolean getPlayerQuitStatus() { return playerQuit; } public void run() { boolean carryOn= true; while(carryOn) { runOneRound(); char r = this.view.getPlayerNextGame(); if(r=='n') { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for(int round = 1;round<=4;round++) { this.view.displaySingleLine(); this.view.displayDealerDealCardsAndGameRound(round); this.view.displaySingleLine(); if (round == 1) { //round 1 deal extra card this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } else { this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } this.view.displayPlayerCardsOnHand(this.dealer); this.view.displayBlankLine(); this.view.displayPlayerCardsOnHand(player); this.view.displayPlayerTotalCardValue(player); int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard()); if(whoCanCall==1) {//dealer call int chipsToBet = this.view. getDealerCallBetChips(); //ask player want to follow? char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet); if(r=='y') { this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } }else {//player call if(round==1) {//round 1 player cannot quit int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayBetOntable(this.chipsOnTable); }else { char r = this.view.getPlayerCallOrQuit(); if(r=='c') { int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } } } } //check who win if(playerQuit) { this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) { this.view.displayPlayerWin(this.player); this.player.addChips(chipsOnTable); this.chipsOnTable=0; this.view.displayPlayerNameAndLeftOverChips(this.player); }else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) { this.view.displayDealerWin(); this.view.displayPlayerNameAndLeftOverChips(this.player); }else { this.view.displayTie(); this.player.addChips(chipsOnTable/2); this.view.displayPlayerNameAndLeftOverChips(this.player); } //put all the cards back to the deck dealer.addCardsBackToDeck(dealer.getCardsOnHand()); dealer.addCardsBackToDeck(player.getCardsOnHand()); dealer.clearCardsOnHand(); player.clearCardsOnHand(); } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.BorderLayout; import javax.swing.*; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GameTableFrame extends JFrame { private GameTablePanel gameTablePanel; private Dealer dealer; private Player player; private JLabel shufflingLabel; private JButton playButton; private JButton quitButton; public GameTableFrame(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; gameTablePanel = new GameTablePanel(dealer, player); shufflingLabel = new JLabel("Shuffling"); shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER); playButton = new JButton("Play"); quitButton = new JButton("Quit"); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); HighSum highSum = new HighSum(); highSum.init(player.getLoginName(), "some_default_password"); highSum.run(); updateScreen(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); // Create the main panel that contains both the game board and the buttons JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); mainPanel.add(gameTablePanel, BorderLayout.CENTER); mainPanel.add(buttonsPanel, BorderLayout.SOUTH); mainPanel.add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); add(mainPanel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } // This method updates the screen after each game public void updateScreen() { gameTablePanel.updateTable(dealer, player); } } package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; public GameTablePanel(Dealer dealer, Player player) { setLayout(new BorderLayout()); setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); this.dealer = dealer; this.player = player; } public void updateTable(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; repaint(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Draw dealer’s cards int dealerX = 50; int dealerY = 100; g.drawString("Dealer", dealerX, dealerY - 20); dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true); // Draw player’s cards int playerX = 50; int playerY = getHeight() - 200; g.drawString("Player", playerX, playerY - 20); playerX = drawPlayerHand(g, player, playerX, playerY, false); // Draw chips on the table g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Chips on the table: ", playerX + 50, playerY); } private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) { int i = 0; for (Card c : p.getCardsOnHand()) { if (isDealer && i == 0) { new ImageIcon("images/back.png").paintIcon(this, g, x, y); } else { c.paintIcon(this, g, x, y); } x += 100; i++; } return x; } } package GUIExample; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoginDialog extends JDialog { private JTextField loginField; private JPasswordField passwordField; private JButton loginButton; private boolean loggedIn = false; public LoginDialog(JFrame parent) { super(parent, "Login", true); loginField = new JTextField(20); passwordField = new JPasswordField(20); loginButton = new JButton("Login"); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loggedIn = true; dispose(); } }); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 2)); panel.add(new JLabel("Login:")); panel.add(loginField); panel.add(new JLabel("Password:")); panel.add(passwordField); panel.add(loginButton); add(panel); pack(); setLocationRelativeTo(parent); } public String getLogin() { return loginField.getText(); } public String getPassword() { return new String(passwordField.getPassword()); } public boolean isLoggedIn() { return loggedIn; } } package Helper; public class Keyboard { public static String readString(String prompt) { System.out.print(prompt); return new java.util.Scanner(System.in).nextLine(); } public static int readInt(String prompt) { int input = 0; boolean valid = false; while (!valid) { try { input = Integer.parseInt(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter an integer ***"); } } return input; } public static double readDouble(String prompt) { double input = 0; boolean valid = false; while (!valid) { try { input = Double.parseDouble(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a double ***"); } } return input; } public static float readFloat(String prompt) { float input = 0; boolean valid = false; while (!valid) { try { input = Float.parseFloat(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a float ***"); } } return input; } public static long readLong(String prompt) { long input = 0; boolean valid = false; while (!valid) { try { input = Long.parseLong(readString(prompt)); valid = true; } catch (NumberFormatException e) { e.printStackTrace(); System.out.println("*** Please enter a long ***"); } } return input; } public static char readChar(String prompt,char[] choices) { boolean validChoice = false; char r = ' '; while(!validChoice) { r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":"); if(!validateChoice(choices,r)) { System.out.println("Invalid input"); }else { validChoice = true; } } return r; } private static String charArrayToString(char[] charArray) { String s = "["; for(int i=0;i<charArray.length;i++) { s+=charArray[i]; if(i!=charArray.length-1) { s+=","; } } s += "]"; return s; } private static boolean validateChoice(char[] choices, char choice) { boolean validChoice = false; for(int i=0;i<choices.length;i++) { if(choices[i]==choice) { validChoice = true; break; } } return validChoice; } public static char readChar(String prompt) { char input = 0; boolean valid = false; while (!valid) { String temp = readString(prompt); if (temp.length() != 1) { System.out.println("*** Please enter a character ***"); } else { input = temp.charAt(0); valid = true; } } return input; } public static boolean readBoolean(String prompt) { boolean valid = false; while (!valid) { String input = readString(prompt); if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true") || input.equalsIgnoreCase("t")) { return true; } else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false") || input.equalsIgnoreCase("f")) { return false; } else { System.out.println("*** Please enter Yes/No or True/False ***"); } } return false; } public static java.util.Date readDate(String prompt) { java.util.Date date = null; boolean valid = false; while (!valid) { try { String input = readString(prompt).trim(); if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) { int day = Integer.parseInt(input.substring(0, 2)); int month = Integer.parseInt(input.substring(3, 5)); int year = Integer.parseInt(input.substring(6, 10)); java.util.Calendar cal = java.util.Calendar.getInstance(); cal.setLenient(false); cal.set(year, month - 1, day, 0, 0, 0); date = cal.getTime(); valid = true; } else { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } catch (IllegalArgumentException e) { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } return date; } private static String quit = "0"; public static int getUserOption(String title, String[] menu) { displayMenu(title, menu); int choice = Keyboard.readInt("Enter Choice --> "); while (choice > menu.length || choice < 0) { choice = Keyboard.readInt("Invalid Choice, Re-enter --> "); } return choice; } private static void displayMenu(String title, String[] menu) { line(80, "="); System.out.println(title.toUpperCase()); line(80, "-"); for (int i = 0; i < menu.length; i++) { System.out.println("[" + (i + 1) + "] " + menu[i]); } System.out.println("[" + quit + "] Quit"); line(80, "-"); } public static void line(int len, String c) { System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c)); } } package Helper; import java.security.MessageDigest; public class Utility { public static String getHash(String base) { String message=""; try{ MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) hexString.append('0'); hexString.append(hex); } message = hexString.toString(); } catch(Exception ex){ throw new RuntimeException(ex); } return message; } public static void printLine(int num) { printLine(num,'-'); } public static void printDoubleLine(int num) { printLine(num,'='); } public static void printLine(int num,char pattern) { for(int i =0;i<num;i++) { System.out.print(pattern); } System.out.println(""); } } package Model; import javax.swing.*; public class Card extends ImageIcon { private String suit; private String name; private int value; private int rank; private boolean faceDown; public Card(String suit, String name, int value, int rank) { super("images/" + suit + name + ".png"); this.suit = suit; this.name = name; this.value = value; this.rank = rank; this.faceDown = false; } public boolean isFaceDown() { return this.faceDown; } public void setFaceDown(boolean faceDown) { this.faceDown = faceDown; } public String getSuit() { return this.suit; } public String getName() { return this.name; } public int getValue() { return this.value; } public int getRank() { return this.rank; } public String toString() { if (this.faceDown) { return "<HIDDEN CARD>"; } else { return "<" + this.suit + " " + this.name + ">"; } } public String display() { return "<"+this.suit+" "+this.name+" "+this.rank+">"; } } //card rank // D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import java.util.*; public class Dealer extends Player { private Deck deck; public Dealer() { super("Dealer", "", 0); deck = new Deck(); } public void shuffleCards() { System.out.println("Dealer shuffle deck"); deck.shuffle(); } public void dealCardTo(Player player) { Card card = deck.dealCard(); // take a card out from the deck player.addCard(card); // pass the card into the player } public void addCardsBackToDeck(ArrayList<Card> cards) { deck.appendCard(cards); } //return 1 if card1 rank higher, else return 2 public int determineWhichCardRankHigher(Card card1, Card card2) { if(card1.getRank()>card2.getRank()) { return 1; }else { return 2; } } } package Model; import java.util.*; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = { "Diamond", "Club","Heart","Spade", }; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, "Ace", 1,1+i); cards.add(card); int c = 5; for (int n = 2; n <= 10; n++) { Card oCard = new Card(suit, "" + n, n,c+i); cards.add(oCard); c+=4; } Card jackCard = new Card(suit, "Jack", 10,41+i); cards.add(jackCard); Card queenCard = new Card(suit, "Queen", 10,45+i); cards.add(queenCard); Card kingCard = new Card(suit, "King", 10,49+i); cards.add(kingCard); } } public Card dealCard() { return cards.remove(0); } //add back one card public void appendCard(Card card) { cards.add(card); } //add back arraylist of cards public void appendCard(ArrayList<Card> cards) { for(Card card: cards) { this.cards.add(card); } } public void shuffle() { Random random = new Random(); for(int i=0;i<10000;i++) { int indexA = random.nextInt(cards.size()); int indexB = random.nextInt(cards.size()); Card cardA = cards.get(indexA); Card cardB = cards.get(indexB); cards.set(indexA, cardB); cards.set(indexB, cardA); } } //for internal use only private void showCards() { for (Card card : cards) { System.out.println(card); } } //for internal use only private void displayCards() { for (Card card : cards) { System.out.println(card.display()); } } public static void main(String[] args) { Deck deck = new Deck(); //deck.shuffle(); /*Card card1 = deck.dealCard(); Card card2 = deck.dealCard(); Card card3 = deck.dealCard(); deck.showCards(); ArrayList<Card> cards = new ArrayList<Card>(); cards.add(card1); cards.add(card2); cards.add(card3); deck.appendCard(cards); System.out.println();*/ deck.displayCards(); } } //card rank //D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import Controller.*; import View.*; import GUIExample.LoginDialog; import GUIExample.GameTableFrame; import javax.swing.JOptionPane; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; private int chipsOnTable; public HighSum() { } public void init(String login, String password) { // Create all the required objects this.dealer = new Dealer(); this.player = new Player(login, password, 50); this.view = new ViewController(); // Bring them together this.gc = new GameController(this.dealer, this.player, this.view); } private Player checkWinner() { if(player.getTotalCardsValue() > dealer.getTotalCardsValue()) return player; else if(player.getTotalCardsValue() < dealer.getTotalCardsValue()) return dealer; else return null; } public Dealer getDealer() { return dealer; } public Player getPlayer() { return player; } public void run() { // Setup the game table GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); // Starts the game! boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); if (!gc.getPlayerQuitStatus()) { int response = JOptionPane.showConfirmDialog( gameTableFrame, "Do you want to play another game?", "New Game", JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } else { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); gameTableFrame.dispose(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for (int round = 1; round <= 4; round++) { // Code remains same until here // Check if the player wants to follow or quit char r; int chipsToBet; if (round == 1) { chipsToBet = this.view.getPlayerCallBetChip(this.player); } else { chipsToBet = this.view.getDealerCallBetChips(); } } Player winner = checkWinner(); if(playerQuit){ this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } } /* public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum(); highSum.init(login, password); highSum.run(); } }*/ } package Model; import java.util.*; public class Player extends User{ private int chips; protected ArrayList<Card> cardsOnHand; public Player(String loginName, String password, int chips) { super(loginName, password); this.chips = chips; this.cardsOnHand = new ArrayList<Card>(); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips+=amount;//no error check } public void deductChips(int amount) { this.chips-=amount;//no error check } public void addCard(Card card) { this.cardsOnHand.add(card); } public ArrayList<Card> getCardsOnHand() { return this.cardsOnHand; } public int getTotalCardsValue() { int total = 0; for(Card card: this.cardsOnHand) { total+=card.getValue(); } return total; } public Card getLastCard() { return this.cardsOnHand.get(this.cardsOnHand.size()-1); } public void clearCardsOnHand() { this.cardsOnHand.clear(); } //Think of the action that a player can take //implement more related methods here public static void main(String[] args) { // TODO Auto-generated method stub Player player = new Player("IcePeak","A",100); System.out.println(player.getChips()); player.deductChips(10); System.out.println(player.getChips()); player.addChips(20); System.out.println(player.getChips()); } } package Model; import Helper.*; abstract public class User { private String loginName; private String hashPassword; public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return this.loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } } package View; import Helper.*; import Model.*; //all input and output should be done view ViewController //so that it is easier to implement GUI later public class ViewController { public void displayExitGame() { System.out.println("Thank you for playing HighSum game"); } public void displayBetOntable(int bet) { System.out.println("Bet on table : "+bet); } public void displayPlayerWin(Player player) { System.out.println(player.getLoginName()+" Wins!"); } public void displayDealerWin() { System.out.println("Dealer Wins!"); } public void displayTie() { System.out.println("It is a tie!."); } public void displayPlayerQuit() { System.out.println("You have quit the current game."); } public void displayPlayerCardsOnHand(Player player) { System.out.println(player.getLoginName()); if(player instanceof Dealer) { for (int i = 0; i < player.getCardsOnHand().size(); i++) { if (i == 0) { System.out.print("<HIDDEN CARD> "); } else { System.out.print(player.getCardsOnHand().get(i).toString() + " "); } } } else { for (Card card : player.getCardsOnHand()) { System.out.print(card + " "); } } System.out.println(); } public void displayBlankLine() { System.out.println(); } public void displayPlayerTotalCardValue(Player player) { System.out.println("Value:"+player.getTotalCardsValue()); } public void displayDealerDealCardsAndGameRound(int round) { System.out.println("Dealer dealing cards - ROUND "+round); } public void displayGameStart() { System.out.println("Game starts - Dealer shuffle deck"); } public void displayPlayerNameAndChips(Player player) { System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips"); } public void displayPlayerNameAndLeftOverChips(Player player) { System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips"); } public void displayGameTitle() { System.out.println("HighSum GAME"); } public void displaySingleLine() { for(int i=0;i<30;i++) { System.out.print("-"); } System.out.println(); } public void displayDoubleLine() { for(int i=0;i<30;i++) { System.out.print("="); } System.out.println(); } public char getPlayerCallOrQuit() { char[] choices = {'c','q'}; char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices); return r; } public char getPlayerFollowOrNot(Player player, int dealerBet) { boolean validChoice = false; char[] choices = {'y','n'}; char r = 'n'; while(!validChoice) { r = Keyboard.readChar("Do you want to follow?",choices); //check if player has enff chips to follow if(r=='y' && player.getChips()<dealerBet) { System.out.println("You do not have enough chips to follow"); displayPlayerNameAndChips(player); }else { validChoice = true; } } return r; } public char getPlayerNextGame() { char[] choices = {'y','n'}; char r = Keyboard.readChar("Next game?",choices); return r; } public int getPlayerCallBetChip(Player player) { boolean validBetAmount = false; int chipsToBet = 0; while(!validBetAmount) { chipsToBet = Keyboard.readInt("Player call, state bet:"); if(chipsToBet<0) { System.out.println("Chips cannot be negative"); }else if(chipsToBet>player.getChips()) { System.out.println("You do not have enough chips"); }else { validBetAmount = true; } } return chipsToBet; } public int getDealerCallBetChips() { System.out.println("Dealer call, state bet: 10"); return 10; } } " These are the requirements: "On completion of this assignment a student should be able to write a Java application that: • Makes use of Java API "Swing" and "AWT" packages • Handles generated events • Makes use of layout manager to organize the GUI components • Know how to apply and design a program using object-oriented concepts 2. Task Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI). 2.1 Login The game starts by the player logging into the game. 2.2 Play Game The game starts after the player click on “Login”. First, the dealer will shuffles the deck. (You may include animation in this frame to simulate “shuffle” effect as enhancement.) Then the dealer deals two cards from the top of the deck to the player and itself. Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game. Assume the player states 10 as the bet chips. The player’s chip will be deducted by 10. The chips on table will be updated to 20 and the dealer deals cards for next round. Assume the dealer’s last card is higher than the player’s last card. The dealer Call the game and the player gets to choose to Follow or Quit the game. If the player follows the game, 10 chips will be deducted from the player’s balance chips. (Asumme the dealer place 10 chips.) The games carry on for maximum of four rounds. In the last round, the player with the highest total sum wins the game. And the game continues until the player exits the game. Error Handling Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips. You should look out for other possible exceptions and handle them too." There are 2 errors in the code: "Description Resource Path Location Type The method addWindowListener(WindowListener) in the type Window is not applicable for the arguments (new WindowAdapter(){}) GameTableFrame.java /A3Skeleton/src/GUIExample line 33 Java Problem WindowAdapter cannot be resolved to a type GameTableFrame.java /A3Skeleton/src/GUIExample line 33 Java Problem WindowEvent cannot be resolved to a type GameTableFrame.java /A3Skeleton/src/GUIExample line 35 Java Problem "
01258be3f4c54a12ad8d1f0328ab4068
{ "intermediate": 0.2889218032360077, "beginner": 0.6018312573432922, "expert": 0.10924690216779709 }
7,983
how to verify server is in Enforcing SE Linux mode
7b941a7ef82b1748d048ec2d0991ce6c
{ "intermediate": 0.41491037607192993, "beginner": 0.2566029727458954, "expert": 0.32848668098449707 }
7,984
Update the following code const [questionnaire, categories] = await prisma.$transaction([ prisma.questionnaire.findFirst({ orderBy: [{ startDate: 'desc' }], where: { ...filter, approved: true, disabled: false, endDate: { gte: addDays(new Date(), -5), }, startDate: { lte: new Date(), }, isDraft: false, }, include: { questionnaireItems: { where: { disabled: false, }, include: { item: { include: { translation: true, itemMeasurements: true, }, }, }, }, questionnaireRegionStatus: { where: { regionCode: { in: regionCodes } }, }, }, }), prisma.division.findMany({ where: { disabled: false }, include: { group: { where: { disabled: false }, include: { class: { where: { disabled: false }, include: { subclass: { where: { disabled: false }, include: { translation: true, }, }, translation: true, }, }, translation: true, }, }, translation: true, }, }), ]); so that questionnaires with current date greater than endDate are not returned . Show the steps with explanation
f037e5089daf75a37f3c1c36ad8819d7
{ "intermediate": 0.3076351284980774, "beginner": 0.532168984413147, "expert": 0.16019585728645325 }
7,985
help make this have a delay, currently the pathfinding doesn't work import sys from ursina import * import random sys.setrecursionlimit(10000) app = Ursina() window.borderless = False window.fullscreen = False def create_map(w, h): return [[1 for _ in range(w)] for _ in range(h)] def create_map_object(maze): maze_objects = [] spacing = 0.1 for i in range(len(maze)): maze_objects.append([]) for j in range(len(maze[i])): if maze[i][j] == 1: maze_objects[i].append(Entity(model="cube",color=color.blue,scale=(.1, .1, .1),collider="box")) elif maze[i][j] == 0: maze_objects[i].append(Entity(model="quad",color=color.white,scale=(.1, .1, .1),collider="box",)) elif maze[i][j] == 100: maze_objects[i].append(Entity(model="quad",color=color.green,scale=(.1, .1, .1),collider="box",)) elif maze[i][j] == 999: maze_objects[i].append(Entity(model="quad",color=color.red,scale=(.1, .1, .1),collider="box",)) maze_objects[i][j].y = 4 - i * spacing maze_objects[i][j].x = -7.15 + j * spacing maze_objects[i][j].parent = scene return maze_objects def depth_first_search_map(x, y, maze): maze[y][x] = 0 possible = [[0, 2], [2, 0], [0, -2], [-2, 0]] random.shuffle(possible) for x1, y1 in possible: lx1, ly1 = x + x1, y + y1 if 0 <= lx1 < len(maze[0]) and 0 <= ly1 < len(maze) and maze[ly1][lx1] == 1: maze[y + y1 // 2][x + x1 // 2] = 0 depth_first_search_map(lx1, ly1, maze) def newMaze(maze): nmaze = [] for i in range(len(maze) + 2): nmaze.append([]) for j in range(len(maze[0]) + 2): nmaze[i].append(1) for i in range(1, len(nmaze) - 1): for j in range(1, len(nmaze[0]) - 1): nmaze[i][j] = maze[i - 1][j - 1] for i in range(1, 4): for j in range(1, 4): nmaze[i][j] = 0 nmaze[2][2] = 100 for i in range(48, 52): for j in range(48, 52): nmaze[i][j] = 0 nmaze[50][50] = 999 return nmaze def backtrack(x, y, maze_obj, visited, tx, ty, delay=.01): if x == tx and y == ty: return True if (x, y) in visited: return False visited.add((x, y)) neighbors = [(x+1, y), (x-1, y), (x, y+1), (x, y-1)] for i, (nx, ny) in enumerate(neighbors): if 0 <= nx < len(maze_obj[0]) and 0 <= ny < len(maze_obj) and maze_obj[ny][nx].color != color.blue: # Add a delay between each recursive call to backtrack if backtrack(nx, ny, maze_obj, visited, tx, ty, delay=delay): return True visited.remove((x, y)) return False def invoke_with_delay(function, delay): def delayed_func(): function() s = Sequence( Wait(delay), Func(delayed_func) ) s.start() def find_path(maze, maze_obj): visited = set() target = (50, 50) def backtrack_with_delay(): backtrack(1, 1, maze_obj, visited, target[1], target[0], delay=0.01) invoke_with_delay(backtrack_with_delay, delay=0.01) return maze_obj width = 50 height = 50 maze = create_map(width, height) depth_first_search_map(2, 2, maze) maze = newMaze(maze) maze_obj = create_map_object(maze) maze_obj = find_path(maze, maze_obj) app.run()
1a24482515ea0a61b62f4293de5801b1
{ "intermediate": 0.330001562833786, "beginner": 0.4367285966873169, "expert": 0.2332698553800583 }
7,986
hi i need a python script for this steps: 1. give a wordlist file path from user 2. send request to https://kent.com/domain/{{wordlist item's perline}} 3. save output as txt with name's in wordlist file
cab21905bc7b94b52fa02ad8e2ba8135
{ "intermediate": 0.42932212352752686, "beginner": 0.22512978315353394, "expert": 0.3455480635166168 }
7,987
the following code has a ascii art style above a donut animation which is also in ascii. before i added the ascii art header at the top saying "donut scrapper" the animation of the donut was working just fine. however, after i added that header, the donut seems to have been cut in half, even though there is significant space under the terminal for the donut to be displayed. please analyze the code thoroughly and generate a new and updated code that will show both the ascii header, and the donut animation in full, without warping it's dementions in the sligtest "import math import time import curses def main(stdscr): stdscr.clear() stdscr.nodelay(1) # Enable non-blocking input curses.curs_set(0) # Hide the cursor stdscr.timeout(0) # Set non-blocking mode for getch() A = 0 B = 0 z = [0] * 1760 b = [' '] * 1760 ascii_art = '''\ ____ __ _____ / __ \____ ____ __ __/ /_ / ___/______________ _____ ___ _____ / / / / __ \/ __ \/ / / / __/ \__ \/ ___/ ___/ __ `/ __ \/ _ \/ ___/ / /_/ / /_/ / / / / /_/ / /_ ___/ / /__/ / / /_/ / /_/ / __/ / /_____/\____/_/ /_/\__,_/\__/ /____/\___/_/ \__,_/ .___/\___/_/ /_/ ''' art_lines = ascii_art.split('\n') art_height = len(art_lines) art_width = max(len(line) for line in art_lines) donut_row = art_height + 2 donut_col = (stdscr.getmaxyx()[1] - 80) // 2 while True: b = [' '] * 1760 z = [0] * 1760 for j in range(0, 628, 7): for i in range(0, 628, 2): c = math.sin(i / 100.0) d = math.cos(j / 100.0) e = math.sin(A / 100.0) f = math.sin(j / 100.0) g = math.cos(A / 100.0) h = d + 2 D = 1 / (c * h * e + f * g + 5) l = math.cos(i / 100.0) m = math.cos(B / 100.0) n = math.sin(B / 100.0) t = c * h * g - f * e x = int(40 + 30 * D * (l * h * m - t * n)) y = int(12 + 15 * D * (l * h * n + t * m)) o = x + 80 * y N = int(8 * ((f * e - c * d * g) * m - c * d * e - f * g - l * d * n)) if 22 > y > 0 and 80 > x > 0 and D > z[o]: z[o] = D b[o] = '.,-~:;=!*#$@'[N if N > 0 else 0] # Clear the window stdscr.erase() # Draw the ASCII art for row in range(art_height): stdscr.addstr(row, (stdscr.getmaxyx()[1] - art_width) // 2, art_lines[row]) # Draw the donut animation for row in range(11): stdscr.addstr(row + donut_row, donut_col, ''.join(b[row * 80:(row + 1) * 80])) stdscr.refresh() # Check for user input key = stdscr.getch() if key == ord('q'): # Quit if 'q' is pressed break A += 1 B += 0.5 time.sleep(0.02) # Decreased sleep time for faster animation if __name__ == '__main__': curses.wrapper(main) "
8b0250db0a8f524132011c6bd3dbb1d2
{ "intermediate": 0.3130020201206207, "beginner": 0.48810625076293945, "expert": 0.198891744017601 }
7,988
In a php file there is a variable called $latest_from_softonic_curl that contains a xml content
1d11211b6d815036cc28413eaf5c210b
{ "intermediate": 0.27065178751945496, "beginner": 0.400939404964447, "expert": 0.328408807516098 }
7,989
a pyspark function removing first element of string using split
ce225613c3240db229bcc8f37f8fc85c
{ "intermediate": 0.3527587056159973, "beginner": 0.2493678480386734, "expert": 0.3978734314441681 }
7,990
const ScreenerPage: NextPage = () => { const {symbols} = useBinanceSymbols(); const [activeSymbol, setActiveSymbol] = useState("BTCUSDT"); const [symbolsFilters, setSymbolsFilters] = useState<string>(""); const [filteredSymbols, setFilteredSymbols] = useState<string[]>(symbols.filter((symbol) => symbol.includes(symbolsFilters.toUpperCase()))); const [connectedSymbols, setConnectedSymbols] = useState<string[]>([]); const {futures24hSubscribe} = useBinanceWsProvider(); const [coinData, setCoinData] = useState<Array<{ symbol: string; price: number; percent: number }>>([]); console.log(coinData); const handleCoinData = (coin: { price: number; percent: number }, symbol: string) => { setCoinData(prevCoinData => { const existingCoinDataIndex = prevCoinData.findIndex(item => item.symbol === symbol); if (existingCoinDataIndex !== -1) { prevCoinData[existingCoinDataIndex].price = coin.price; prevCoinData[existingCoinDataIndex].percent = coin.percent; return [...prevCoinData]; } else { return [...prevCoinData, {symbol, price: coin.price, percent: coin.percent}]; } }); }; const sortByPrice = (a: string, b: string) => { const coinA = coinData.find(coin => coin.symbol === a); const coinB = coinData.find(coin => coin.symbol === b); if (coinA && coinB) { return coinA.price - coinB.price; } return 0; }; const sortByPercent = (a: string, b: string) => { const coinA = coinData.find(coin => coin.symbol === a); const coinB = coinData.find(coin => coin.symbol === b); if (coinA && coinB) { return coinA.percent - coinB.percent; } return 0; }; useEffect(() => { if(activeSymbol) futures24hSubscribe(activeSymbol); }, [activeSymbol]); return <> <Grid sx={{backgroundColor: "#ECECEC"}} container spacing={1} height={999} p={1}> <Grid item xs={1.7}> <Box sx={{width: "100%", height: "100%"}}> <Box sx={{width: "100%", height: 644, bgcolor: "#fff", overflow: "hidden", borderRadius: "8px"}}> <KeyboardLayoutReplacementInput ofScreener label="Поиск" value={symbolsFilters} onChange={setSymbolsFilters} /> <Grid container > <Grid item xs={6} display="flex" flexDirection="column" alignItems="center"> <IconButton sx={{py:0.1, px: 1.2, my:0, " & :hover": {"path": {fill: "#B41C18"}}}} color="error" > <ArrowDropDownIcon onClick={() => setFilteredSymbols(prev => [...prev].sort((a, b) => b.localeCompare(a)))} sx={{cursor: "pointer", fontSize: "9px", mr: .5, transform: "rotate(180deg)"}} /> </IconButton> <IconButton sx={{py:0.1, px: 1.2, my:0, " & :hover": {"path": {fill: "#B41C18"}}}} color="error" > <ArrowDropDownIcon onClick={() => setFilteredSymbols(prev => [...prev].sort((a, b) => a.localeCompare(b)))} sx={{cursor: "pointer", fontSize: "9px", mr: .5, transform: ""}} /> </IconButton> </Grid> <Grid item xs={3.5} display="flex" flexDirection="column" alignItems="center"> <ArrowDropDownIcon sx={{cursor: "pointer", " & :hover": {fill: "#B41C18"}, fontSize: "9px", mr: .5, transform: "rotate(180deg)"}} onClick={() => { const sortedSymbols = [...filteredSymbols].sort(sortByPrice); setFilteredSymbols(sortedSymbols); }} /> <ArrowDropDownIcon sx={{cursor: "pointer", " & :hover": {fill: "#B41C18"}, fontSize: "9px", mr: .5, transform: ""}} onClick={() => { const sortedSymbols = [...filteredSymbols].sort((a, b) => sortByPrice(b, a)); // Reverse sorting setFilteredSymbols(sortedSymbols); }} /> </Grid> <Grid item xs={2.5} display="flex" flexDirection="column" alignItems="center"> <ArrowDropDownIcon sx={{cursor: "pointer", " & :hover": {fill: "#B41C18"}, fontSize: "9px", mr: .5, transform: "rotate(180deg)"}} onClick={() => { const sortedSymbols = [...filteredSymbols].sort(sortByPercent); setFilteredSymbols(sortedSymbols); }} /> <ArrowDropDownIcon sx={{cursor: "pointer", " & :hover": {fill: "#B41C18"}, fontSize: "9px", mr: .5, transform: ""}} onClick={() => { const sortedSymbols = [...filteredSymbols].sort((a, b) => sortByPercent(b, a)); // Reverse sorting setFilteredSymbols(sortedSymbols); }} /> </Grid> </Grid> <Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: 620}}> {filteredSymbols.map((symbol) => ( <ScreenerSymbol key={symbol} symbol={symbol} activeSymbol={activeSymbol} setActiveSymbol={setActiveSymbol} connectedSymbols={connectedSymbols} setConnectedSymbols={setConnectedSymbols} symbolsFilters={symbolsFilters} handleCoinData={(coin: any) => handleCoinData(coin, symbol)} /> ))} </Box> </Box> </Box> </Grid> </>; }; export default ScreenerPage; export interface ScreenerSymbolProps { symbol: string activeSymbol: string setActiveSymbol: (symbol: string) => void connectedSymbols: string[] setConnectedSymbols: Dispatch<SetStateAction<string[]>> symbolsFilters: string handleCoinData: any } const ScreenerSymbol = ({symbol, activeSymbol, setActiveSymbol, connectedSymbols, setConnectedSymbols, symbolsFilters, handleCoinData}: ScreenerSymbolProps) => { const coin = useSelector((state: AppState) => state.binancePrice.futures24h[symbol.toUpperCase()]); const {futures24hSubscribe, futures24hUnSubscribe} = useBinanceWsProvider(); useEffect(() => { if(!coin) return; handleCoinData(coin); }, [coin, handleCoinData]); useEffect(() => { if (symbolsFilters) { if (connectedSymbols.includes(symbol)) { futures24hSubscribe(symbol); } else { futures24hUnSubscribe(symbol); setConnectedSymbols(prev => prev.filter(item => item !== symbol)); } } else { if (isVisible) { futures24hSubscribe(symbol); if(!connectedSymbols.includes(symbol)) { setConnectedSymbols(prev => [...prev, symbol]); } } else { futures24hUnSubscribe(symbol); setConnectedSymbols(prev => prev.filter(item => item !== symbol)); } } }, [symbolsFilters, symbol, isVisible]); useEffect(() => { if (isVisible) { setConnectedSymbols(prev => { if (prev.includes(symbol)) { return prev.filter(item => item === symbol); } return [...prev, symbol]; }); } else { setConnectedSymbols(prev => { return prev.filter(item => item !== symbol); }); } }, [symbolsFilters, symbol, isVisible]); useEffect(() => { return () => futures24hUnSubscribe(symbol); }, []); return <> <Grid ref={symbolRef} container sx={{cursor: "pointer", backgroundColor: activeSymbol === symbol ? "#B41C18" : ""}} onClick={() => setActiveSymbol(symbol)} borderBottom="1px solid #EEEEEE" py={1} px={1.2}> <Grid item xs={6.5} display="flex"> <StarIcon sx={{fontSize: 14, mt: .3}} /> <Typography color={activeSymbol === symbol ? "#fff" : "000000DE"} fontSize={13} fontWeight={300} ml={.3}>{symbol}</Typography> </Grid> { coin ? ( <Grid item xs={5.5} display="flex" justifyContent="space-between"> <Typography fontSize={13} color={activeSymbol === symbol ? "#fff" : ""} fontWeight={300}>${FormatPrice({amount: coin.price, currency_iso_code: "USD", dec: "decimal"})}</Typography> <Typography fontSize={13} color={activeSymbol === symbol ? "#fff" : coin.percent >= 0 ? "#006943" : "#B41C18"} fontWeight={300}> {coin.percent >= 0 ? `+${coin.percent}` : coin.percent}% </Typography> </Grid> ) : ( <Grid item xs={5} display="flex" justifyContent="space-between"> <Skeleton variant="text" width="40px" height="12px" sx={{bgcolor: "#454545"}} /> <Skeleton variant="text" width="20px" height="12px" sx={{bgcolor: "#006943"}} /> </Grid>) } </Grid> </>; }; export default ScreenerSymbol; 1. в ScreenerSymbol запрашиваются const coin: { price: number; percent: number; } по symbol из ScreenerPage const {symbols} = useBinanceSymbols(); // 203 монеты. 2. Если есть coin, то он отправляется в handleCoinData useEffect(() => { if(!coin) return; handleCoinData(coin); }, [coin, handleCoinData]); и заполняет массив coinData данными 3. sortByPrice и sortByPercent <Grid item xs={3.5} display="flex" flexDirection="column" alignItems="center"> <ArrowDropDownIcon sx={{cursor: "pointer", " & :hover": {fill: "#B41C18"}, fontSize: "9px", mr: .5, transform: "rotate(180deg)"}} onClick={() => { const sortedSymbols = [...filteredSymbols].sort(sortByPrice); setFilteredSymbols(sortedSymbols); }} /> <ArrowDropDownIcon sx={{cursor: "pointer", " & :hover": {fill: "#B41C18"}, fontSize: "9px", mr: .5, transform: ""}} onClick={() => { const sortedSymbols = [...filteredSymbols].sort((a, b) => sortByPrice(b, a)); // Reverse sorting setFilteredSymbols(sortedSymbols); }} /> </Grid> <Grid item xs={2.5} display="flex" flexDirection="column" alignItems="center"> <ArrowDropDownIcon sx={{cursor: "pointer", " & :hover": {fill: "#B41C18"}, fontSize: "9px", mr: .5, transform: "rotate(180deg)"}} onClick={() => { const sortedSymbols = [...filteredSymbols].sort(sortByPercent); setFilteredSymbols(sortedSymbols); }} /> <ArrowDropDownIcon sx={{cursor: "pointer", " & :hover": {fill: "#B41C18"}, fontSize: "9px", mr: .5, transform: ""}} onClick={() => { const sortedSymbols = [...filteredSymbols].sort((a, b) => sortByPercent(b, a)); // Reverse sorting setFilteredSymbols(sortedSymbols); }} /> </Grid> сортируют все монеты по имеющимся данным price и percent. 3. Сортировка происходит некорректно и я не могу понять почему. Проанализируй код и найди как сделать сортировку правильной
1100c284e7591c0dba9f55ad89fa1437
{ "intermediate": 0.2947842478752136, "beginner": 0.4457290768623352, "expert": 0.25948670506477356 }
7,991
hi
e4bfeb2f1afcc183faaca69365e793b6
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
7,992
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QFileDialog> #include <QInputDialog> #include <QRadioButton> #include <QBoxLayout> #include <QPushButton> #include <QGroupBox> MainWindow::MainWindow(QWidget parent) : QMainWindow(parent) { // Set window title setWindowTitle("Abdugaffor L. - IVT1 B-22 - QT-GI-15"); // Create label for image pic_ = new QLabel(this); // Create animation for image animation_ = new QPropertyAnimation(pic_, "pos", this); animation_->setDuration(2000); animation_->setStartValue(QPoint(0, 0)); animation_->setEndValue(QPoint(200, 200)); animation_->setLoopCount(-1); // Create and add menu createMenu(); // Set central widget as label for image setCentralWidget(pic_); } MainWindow::~MainWindow() { } void MainWindow::createMenu() { // Create menu bar QMenuBar *menubar = menuBar(); // Create “File” menu file_ = menubar->addMenu("File"); // Create menu actions show_pic_ = new QAction("Show picture", this); choose_pic_ = new QAction("Choose", this); animate_ = new QAction("Animate", this); stop_ = new QAction("Stop", this); quit_ = new QAction("Quit", this); // Add actions to “File” menu file_->addAction(show_pic_); file_->addAction(choose_pic_); file_->addSeparator(); file_->addAction(animate_); file_->addAction(stop_); file_->addSeparator(); file_->addAction(quit_); // Connect signals and slots connect(show_pic_, SIGNAL(triggered()), this, SLOT(showPicture())); connect(choose_pic_, SIGNAL(triggered()), this, SLOT(chooseImage())); connect(animate_, SIGNAL(triggered()), this, SLOT(animateImage())); connect(stop_, SIGNAL(triggered()), this, SLOT(stopAnimation())); connect(quit_, SIGNAL(triggered()), qApp, SLOT(quit())); } void MainWindow::showPicture() { // Create image QImage image(300, 300, QImage::Format_ARGB32_Premultiplied); image.fill(Qt::white); // Draw rectangle QPainter painter(&image); painter.setBrush(Qt::blue); painter.drawRect(50, 50, 200, 100); // Draw triangle QPolygonF triangle; triangle.append(QPointF(150, 150)); triangle.append(QPointF(100, 250)); triangle.append(QPointF(200, 250)); painter.setBrush(Qt::red); painter.drawPolygon(triangle); // Draw circle painter.setBrush(Qt::green); painter.drawEllipse(QRectF(100, 100, 100, 100)); // Draw trapezoid QPolygonF trapezoid; trapezoid.append(QPointF(100, 200)); trapezoid.append(QPointF(130, 250)); trapezoid.append(QPointF(170, 250)); trapezoid.append(QPointF(200, 200)); painter.setBrush(Qt::yellow); painter.drawPolygon(trapezoid); // Show image pic_->setPixmap(QPixmap::fromImage(image)); } void MainWindow::chooseImage() { // Open file dialog for image selection QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "", tr("Image Files (.png .jpg .bmp)")); // If a file was selected, set it as the image source if (!fileName.isEmpty()) { QPixmap image(fileName); pic_->setPixmap(image); // Create a dialog for speed and direction selection QDialog *dialog = new QDialog(this); QVBoxLayout *layout = new QVBoxLayout(dialog); // Add a text box for speed input int speed = QInputDialog::getInt(this, tr("Set Speed"), tr("Speed:"), 1, 1); // Add radio buttons for direction selection QGroupBox *groupbox = new QGroupBox(tr("Direction"), dialog); QRadioButton* radio_up_down = new QRadioButton(tr("Up-Down"), groupbox); QRadioButton* radio_left_right = new QRadioButton(tr("Left-Right"), groupbox); QHBoxLayout* hlayout = new QHBoxLayout(groupbox); hlayout->addWidget(radio_up_down); hlayout->addWidget(radio_left_right); groupbox->setLayout(hlayout); layout->addWidget(groupbox); // Add a button to start animation QPushButton* button = new QPushButton(tr("Animate"), dialog); layout->addWidget(button); connect(button, SIGNAL(clicked()), this, SLOT(animateImage())); dialog->exec(); // Set the animation based on speed and direction selection if (radio_up_down->isChecked()) { animation_->setStartValue(QPoint(pic_->pos().x(), 0)); animation_->setEndValue(QPoint(pic_->pos().x(), height() - pic_->height())); } else if (radio_left_right->isChecked()) { animation_->setStartValue(QPoint(0, pic_->pos().y())); animation_->setEndValue(QPoint(width() - pic_->width(), pic_->pos().y())); } animation_->setDuration(1000 / speed); } } void MainWindow::animateImage() { // Start animation animation_->start(); } void MainWindow::stopAnimation() { // Stop animation animation_->stop(); // Reset position of image pic_->move(QPoint(0, 0)); } void MainWindow::closeApp() { // Close application qApp->quit(); } /home/abdugaffor/Case/Qt projects/untitled1/mainwindow.cpp:10: ошибка: no declaration matches ‘MainWindow::MainWindow(QWidget)’ ../untitled1/mainwindow.cpp:10:1: error: no declaration matches ‘MainWindow::MainWindow(QWidget)’ 10 | MainWindow::MainWindow(QWidget parent) | ^~~~~~~~~~
010a30a30b31441c02223e9a3506985c
{ "intermediate": 0.3651980459690094, "beginner": 0.423576682806015, "expert": 0.2112252563238144 }
7,993
make a nice looking menu in the command prompt. fill it with lots ascii art to make it look all programmy and sweet
e069937925d95467848a7f8f2466bc0a
{ "intermediate": 0.3218807876110077, "beginner": 0.25923892855644226, "expert": 0.41888028383255005 }
7,994
the problem here that background “#1B2827” in “.language-option” doesn’t want to go full height after “#night-mode-toggle” switch: <style> body, html { scrollbar-width: 2em; scrollbar-color: #fada38 #000000; overflow-x: hidden; color:black; margin: 0; padding: 0; position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; line-height: 1.6; transition: background-color 2s, color 3s; --overflow:hidden; } header { background-color: #4caf50; color: #fff; padding: 16px 0px 0px 0px; text-align: center; position: absolute; transition: background-color 2s; width: 100%; height: 18px; right: 0px; z-index:999; } h1 { margin: 0 auto; display: flex; justify-content: space-between; align-items: center; font-size: 18px; width: 90%; height: 1%; } .background { font-weight: bold; padding: 0px; text-align: center; justify-content: center; align-items: center; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: -1; position: relative; display: flex; } .background:before { content: '🇬🇧&nbsp;🇩🇪'; font-size: 10em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity: 0.15; display: flex; white-space: nowrap; } .background-text { display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; z-index: -1; } @keyframes wave { 0% { background-position: 0% 0%; } 100% { background-position: 100% 0%; } } .left, .right { position: relative; } .left::before, .right::before { content: ""; position: absolute; top: 5px; border-bottom: 1px dashed #fff; width: 40%; } .left::before { right: 100%; margin-right: 20px; } .right::before { left: 100%; margin-left: 20px; } .flags-container { width: 100%; position: relative; top: 0; right: 0px; padding: 1px 0; background-color: darkgreen; display: flex; justify-content: center; align-items: center; --box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); z-index: 1; } .flag-radio { display: none; } .flag-label { cursor: pointer; margin: 0 5px; transition: 0.3s; opacity: 0.6; font-size: 24px; } .flag-label:hover { opacity: 1; } .language-option { position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; display: none; justify-content: center; align-items: center; padding-top: 64px; width: 100%; height: 100%; background-color: white; } #english-flag:checked ~ #english, #hindi-flag:checked ~ #hindi, #hebrew-flag:checked ~ #hebrew, #chinese-flag:checked ~ #chinese, #french-flag:checked ~ #french, #spanish-flag:checked ~ #spanish { display: block; } #night-mode-toggle:checked ~ body, #night-mode-toggle:checked ~ header, #night-mode-toggle:checked ~ .language-option, #night-mode-toggle:checked { background-color: #1B2827; color: #F3EFEF;text-shadow: 1px 1px 2px rgba(42, 81, 21, 0.5); } .switch-container { position: absolute; top: 5px; right: 16px; display: flex; align-items: center; justify-content: center; z-index: 2; } .switch-container label { content: "&#x1F319;"; position: relative; margin-left: 0px; cursor: pointer; user-select: none; align-items: center; justify-content: center; } .switch { content: "&#x1F319;"; position: relative; cursor: pointer; width: 64px; height: 32px; margin-right: 5px; background-color: darkgreen; border-radius: 15px; transition: background-color 3s; } .switch:before { content: "🌿"; display: block; position: absolute; top: 2px; left: 2px; height: 0px; width: 0px; background-color: #121; border-radius: 50%; transition: left 1s; } #night-mode-toggle:checked ~ .switch-container .switch { background-color: #121; } #night-mode-toggle:checked ~ .switch-container .switch:before { left: calc(100% - 28px);content: "🌙"; } #supercrazylogotype { position: absolute; display: inline-block; width: 24px; height: 24px; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACoElEQVRYR71XsWobQRA9KZVDUoegIoXBGBPUhRjSCdSlcO2gwuncuEnhPzCoTZMyhYiL1OkEcmVw4s6YEBsMTsCY1DEYFfFZ78I7v5ub3dNJxGp0t7sz++bN27nZRjLHb6X/OP2+/acxh4tkLmMA+HX+MLn68HtmP7UMLw67KaNtvRg27g2Abqx0N3+cJjfLS4UMABgGrA3HbbpKDNgoPWd04gEI6aESQChKGOqcbhoCEGMmyMC0NMM5fqC+DgCPGQSXpyAGgBvinwDUoepAAXK91YkKOQjARkojRm4j0nH7HNNFQYSWBUuxF30VkFiRylPw6uh1ut/+koG5HDzLzroX6ZuPi5m/0WhU8juxK42FdMLACgA+j8e5A4/+p72fsWDyOQDZvb5J1heauVjtsSWA7ujgXyn2BKh02807nU7OhD4rQgCh+NSXFWTpjHthKgBs6KXAjuP908ZZiQXrvwBAqeLztNR7wEO60LUlAEoXRMdoSbXdCPN2jjYKIFQL3BRwcW/7bwbA5lxBefM8KbAb9B8EK2Z+CmIiVBYYvcfGtEeTPtb675Kvx1t3pZjnnwvIwgRlNuSxoMLzTgNTUFmKtfhYIUKEnsJt7q1W8F6lgSwF6GqGndWCtkJCJBN1j6E6VzaCGrDffDiwJ0JBzFoDphIh0RMAaGVaOOfRPxF2Nm0/z8pGoR/ghIpRS6ktq1qgmGuAZPXzChPG3BRgwttYI6BxqCGpalRg7/WFM3VE9lNdpxmxICoBKJVeg2LbsdCZp5//DsDm2WohCIALY+05dBKLGA2GrSlW9RZQ9GqGVg0GbNcebT5JT962QwJPAACX1VgQtQHo5jDGRfTb8l7aGuwUfPGuqLdl75ZVC4AX6svn71N8xcAGAXHdLNf1W5rODM4tWGPIAAAAAElFTkSuQmCC"); background-size: 80%; background-repeat: no-repeat; background-position: center; border: none; align-items: center; justify-content: center; left:1%; z-index: 3; } p { margin: 15px 5px; --x-blend-mode: Overlay; color: rgba(243, 239, 239, 0.5); background-color: #182C2B; padding:5px 15px; border-radius:10px 10px; text-shadow: 0px 0px 6px 6px rgba(27,40,39,1); box-shadow: 0px 0px 10px 20px rgba(0, 0, 0, 0.2); z-index:1; } h2 { width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 1.5rem; font-weight: bold; --margin: 1em 0; color: #721336; text-shadow: 0px 0px 8px rgba(0, 0, 0, 0.5); background-color: #182C2B; --padding: 0.5em 1em; --border-radius: 0 10px 10px 0; --box-shadow: 0px 0px 5px 10px rgba(10, 100, 10, 0.1); --opacity: 0.8; z-index:2; } @media only screen and (max-width: 600px) { h2 { font-size: 1.5rem; padding: 0.5em 0.75em; } } </style> </head> <body> <input id="english-flag" type="radio" name="flags" class="flag-radio"> <input id="hindi-flag" type="radio" name="flags" class="flag-radio"> <input id="hebrew-flag" type="radio" name="flags" class="flag-radio"> <input id="chinese-flag" type="radio" name="flags" class="flag-radio"> <input id="french-flag" type="radio" name="flags" class="flag-radio"> <input id="spanish-flag" type="radio" name="flags" class="flag-radio"> <div class="flags-container"><logo id="supercrazylogotype"></logo> <label for="english-flag" class="flag-label">🇬🇧</label> <label for="hindi-flag" class="flag-label">🇮🇳</label> <label for="hebrew-flag" class="flag-label">🇮🇱</label> <label for="chinese-flag" class="flag-label">🇨🇳</label> <label for="french-flag" class="flag-label">🇫🇷</label> <label for="spanish-flag" class="flag-label">🇪🇸</label> </div> <header> <h1> <span class="left">EcoWare</span> <span class="right">Earthwise</span> </h1> </header> <!-- Night Mode Switch --> <input type="checkbox" id="night-mode-toggle" /> <div class="switch-container"> <label for="night-mode-toggle"> <div class="switch"></div> </label> </div> <div id="english" class="language-option"> <p>Our mission</p> </div> <div id="hindi" class="language-option"> <p>hindi details going here</p> </div> <div id="hebrew" class="language-option"> <p>hebrew details going here</p> </div> <div id="chinese" class="language-option"> <p>chinese details going here</p> </div> <div id="french" class="language-option"> <p>french details going here</p> </div> <div id="spanish" class="language-option"> <p>spanish details going here</p> </div> <span class="background"> <span class="background-text"> </span> </span> </body> </html>
7024b1685c5a53155a018f93abff4baa
{ "intermediate": 0.3399335741996765, "beginner": 0.3831777572631836, "expert": 0.2768886387348175 }
7,995
hi do you know common data format, cdf? do you know of a cdf wrapper in python?
91ac167d2139f7004248036e1430b5e5
{ "intermediate": 0.5795376896858215, "beginner": 0.25405508279800415, "expert": 0.16640718281269073 }
7,996
In a php file I want to use a curl to scrape this url: https://en.softonic.com/sitemap-article_news.xml and pick the news title of the first 4 items
bd2e3a8cf34f9c6b93e2c4ed6e48de40
{ "intermediate": 0.2725997865200043, "beginner": 0.22756019234657288, "expert": 0.49984002113342285 }
7,997
show me the code of how to cancel zip process using libzip
fc2cea32a9c9764890ba8957af939568
{ "intermediate": 0.652575671672821, "beginner": 0.0858895555138588, "expert": 0.26153478026390076 }
7,998
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. I have run into a problem. Here is some code for context: Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); Mesh* GetMesh(); Material* GetMaterial(); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh* mesh; Material* material; bool initialized = false; void UpdateModelMatrix(); }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize() { mesh = new Mesh{}; material = new Material{}; this->initialized = true; } void GameObject::Update(float deltaTime) { // Update position, rotation, scale, and other properties // Example: Rotate the object around the Y-axis rotation.y += deltaTime * glm::radians(90.0f); UpdateModelMatrix(); } void GameObject::Render(Renderer& renderer, const Camera& camera) { // Render this object using the renderer and camera VkDevice device = *renderer.GetDevice(); // Bind mesh vertex and index buffers VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32); // Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; } mvp; mvp.model = modelMatrix; mvp.view = camera.GetViewMatrix(); mvp.projection = camera.GetProjectionMatrix(); // Create a new buffer to hold the MVP data temporarily VkBuffer mvpBuffer; VkDeviceMemory mvpBufferMemory; BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(), sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mvpBuffer, mvpBufferMemory); // Map the MVP data into the buffer and unmap void* data = nullptr; vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data); memcpy(data, &mvp, sizeof(MVP)); vkUnmapMemory(device, mvpBufferMemory); // TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of // the default uniform buffer // Bind the DescriptorSet associated with the material VkDescriptorSet descriptorSet = material->GetDescriptorSet(); material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP)); renderer.CreateGraphicsPipeline(mesh, material); vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline()); vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr); // Call vkCmdDrawIndexed() uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size()); vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0); // Cleanup the temporary buffer vkDestroyBuffer(device, mvpBuffer, nullptr); vkFreeMemory(device, mvpBufferMemory, nullptr); } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) delete mesh; delete material; this->initialized = false; } void GameObject::SetPosition(const glm::vec3& position) { this->position = position; UpdateModelMatrix(); } void GameObject::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateModelMatrix(); } void GameObject::SetScale(const glm::vec3& scale) { this->scale = scale; UpdateModelMatrix(); } void GameObject::UpdateModelMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); modelMatrix = glm::scale(modelMatrix, scale); } Mesh* GameObject::GetMesh() { return mesh; } Material* GameObject::GetMaterial() { return material; } Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Mesh.cpp: #include "Mesh.h" Mesh::Mesh() : device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE) { } Mesh::~Mesh() { Cleanup(); } void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->vertices = vertices; this->indices = indices; this->device = device; Initialize(device, physicalDevice, commandPool, graphicsQueue); // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … } void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … // Declare and initialize stagingBuffer and bufferSize here VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize); vkDestroyBuffer(device, stagingBuffer, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr); bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingIndexBuffer; VkDeviceMemory stagingIndexBufferMemory; BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingIndexBuffer, stagingIndexBufferMemory); vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingIndexBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize); vkDestroyBuffer(device, stagingIndexBuffer, nullptr); vkFreeMemory(device, stagingIndexBufferMemory, nullptr); } void Mesh::Cleanup() { if (device != VK_NULL_HANDLE) { if (vertexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, vertexBuffer, nullptr); vkFreeMemory(device, vertexBufferMemory, nullptr); vertexBuffer = VK_NULL_HANDLE; vertexBufferMemory = VK_NULL_HANDLE; } if (indexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, indexBuffer, nullptr); vkFreeMemory(device, indexBufferMemory, nullptr); indexBuffer = VK_NULL_HANDLE; indexBufferMemory = VK_NULL_HANDLE; } } } const std::vector<Vertex>& Mesh::GetVertices() const { return vertices; } const std::vector<uint32_t>& Mesh::GetIndices() const { return indices; } VkBuffer Mesh::GetVertexBuffer() const { return vertexBuffer; } VkBuffer Mesh::GetIndexBuffer() const { return indexBuffer; } void Mesh::SetVertices(const std::vector<Vertex>& vertices) { this->vertices = vertices; } void Mesh::SetIndices(const std::vector<uint32_t>& indices) { this->indices = indices; } std::vector<VkVertexInputBindingDescription> Mesh::GetVertexInputBindingDescriptions() const { std::vector<VkVertexInputBindingDescription> bindingDescriptions(1); bindingDescriptions[0].binding = 0; bindingDescriptions[0].stride = sizeof(Vertex); bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescriptions; } std::vector<VkVertexInputAttributeDescription> Mesh::GetVertexInputAttributeDescriptions() const { std::vector<VkVertexInputAttributeDescription> attributeDescriptions(2); // Position attribute attributeDescriptions[0].binding = 0; attributeDescriptions[0].location = 0; attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[0].offset = offsetof(Vertex, position); // Color attribute attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); return attributeDescriptions; } Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Material.cpp: #include "Material.h" Material::Material() : device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE) { } Material::~Material() { Cleanup(); } void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Load shaders and texture LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue); LoadShaders(vertShaderPath, fragShaderPath, device); // Create descriptor set and pipeline layout CreateDescriptorSet(descriptorSetLayout, descriptorPool); CreatePipelineLayout(descriptorSetLayout); } void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { VkDescriptorSetAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = descriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &descriptorSetLayout; if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate descriptor sets!"); } VkDescriptorImageInfo imageInfo{}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = texture->GetImageView(); imageInfo.sampler = texture->GetSampler(); VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrite.descriptorCount = 1; descriptorWrite.pImageInfo = &imageInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout) { VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = 1; pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout; if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create pipeline layout!"); } } void Material::Cleanup() { // Clean up resources, if necessary // (depending on how Shader and Texture resources are managed) } VkDescriptorSet Material::GetDescriptorSet() const { return descriptorSet; } VkPipelineLayout Material::GetPipelineLayout() const { return pipelineLayout; } std::shared_ptr <Shader> Material::GetvertexShader() { return vertexShader; } std::shared_ptr <Shader> Material::GetfragmentShader() { return fragmentShader; } void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue); } void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device) { vertexShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup); fragmentShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup); vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT); fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT); } void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize) { VkDescriptorBufferInfo bufferInfo{}; bufferInfo.buffer = newBuffer; bufferInfo.offset = 0; bufferInfo.range = devicesize; VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrite.descriptorCount = 1; descriptorWrite.pBufferInfo = &bufferInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; bool IsInitialized() const; private: VkDevice device; VkPipeline pipeline; bool initialized; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Pipeline.cpp: #include "Pipeline.h" Pipeline::Pipeline() : device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE), initialized(false) { } Pipeline::~Pipeline() { Cleanup(); } void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device) { this->device = device; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(swapchainExtent.width); viewport.height = static_cast<float>(swapchainExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; VkPipelineMultisampleStateCreateInfo multisampling{}; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlending{}; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; std::vector<VkPipelineShaderStageCreateInfo> shaderStages; CreateShaderStages(shaders, shaderStages); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssembly; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizer; pipelineCreateInfo.pMultisampleState = &multisampling; pipelineCreateInfo.pColorBlendState = &colorBlending; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } initialized = true; } bool Pipeline::IsInitialized() const { return initialized; } void Pipeline::Cleanup() { if (pipeline != VK_NULL_HANDLE && initialized) { //vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; initialized = false; } } VkPipeline Pipeline::GetPipeline() const { return pipeline; } void Pipeline::CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages) { for (auto shader : shaders) { shaderStages.push_back(shader->GetPipelineShaderStageCreateInfo()); } } Terrain.h: #pragma once #include "Simplex.h" #include "Mesh.h" #include "Material.h" #include "GameObject.h" class Terrain { public: Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue); ~Terrain(); void GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); GameObject* GetTerrainObject(); private: void GenerateHeightMap(); void ConvertHeightMapToMeshData(); int seed; int worldSize; float scale; VkDevice* device; VkPhysicalDevice* physicalDevice; VkCommandPool* commandPool; VkQueue* graphicsQueue; SimplexNoise noise; std::vector<std::vector<float>> heightMap; std::vector<Vertex> vertices; std::vector<uint32_t> indices; Mesh* terrainMesh; Material* terrainMaterial; GameObject* terrainObject; }; Terrain.cpp: #include "Terrain.h" Terrain::Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue) : seed(seed), worldSize(worldSize), scale(scale), noise(seed), device(device), physicalDevice(physicalDevice), commandPool(commandPool), graphicsQueue(graphicsQueue) { terrainMesh = new Mesh{}; terrainMaterial = new Material{}; } Terrain::~Terrain() { // Cleanup any resources associated with the Terrain class //terrainMesh.Cleanup(); //terrainMaterial.Cleanup(); //delete terrainObject; //delete terrainMesh; //delete terrainMaterial; } void Terrain::GenerateHeightMap() { heightMap = std::vector<std::vector<float>>(worldSize, std::vector<float>(worldSize, 0.0f)); for (int x = 0; x < worldSize; ++x) { for (int z = 0; z < worldSize; ++z) { float noiseValue = noise.noise(x * scale, z * scale); heightMap[x][z] = noiseValue; } } } void Terrain::ConvertHeightMapToMeshData() { vertices.clear(); indices.clear(); // Generate vertices for (int x = 0; x < worldSize; ++x) { for (int z = 0; z < worldSize; ++z) { Vertex vertex; vertex.position = glm::vec3(static_cast<float>(x), heightMap[x][z], static_cast<float>(z)); // Set color based on height, feel free to customize this as desired float color = heightMap[x][z] * 0.5f + 0.5f; // Normalize the height value between 0 and 1 vertex.color = glm::vec3(color, color, color); vertices.push_back(vertex); } } // Generate indices for rendering using triangle strips for (int x = 0; x < worldSize - 1; ++x) { for (int z = 0; z < worldSize - 1; ++z) { int topLeft = x * worldSize + z; int topRight = topLeft + 1; int bottomLeft = (x + 1) * worldSize + z; int bottomRight = bottomLeft + 1; // First triangle indices.push_back(topLeft); indices.push_back(bottomRight); indices.push_back(bottomLeft); // Second triangle indices.push_back(topLeft); indices.push_back(topRight); indices.push_back(bottomRight); } } } void Terrain::GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { GenerateHeightMap(); ConvertHeightMapToMeshData(); terrainObject = new GameObject(); terrainObject->Initialize(); terrainMesh = terrainObject->GetMesh(); terrainMesh->Initialize(vertices, indices, *device, *physicalDevice, *commandPool, *graphicsQueue); // Initialize terrainMaterial with the loaded shaders and texture // Assume descriptorSetLayout and descriptorPool are created before this call terrainMaterial = terrainObject->GetMaterial(); terrainMaterial->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *device, descriptorSetLayout, descriptorPool, *physicalDevice, *commandPool, *graphicsQueue); } GameObject* Terrain::GetTerrainObject() { return terrainObject; } Vertex Shader: #version 450 layout(binding = 0) uniform UniformBufferObject { mat4 model; mat4 view; mat4 proj; } ubo; layout(location = 0) in vec3 inPosition; layout(location = 1) in vec3 inColor; layout(location = 0) out vec3 fragColor; void main() { gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0); fragColor = inColor; } Fragment Shader: #version 450 layout(binding = 1) uniform sampler2D texSampler; layout(location = 0) in vec3 fragColor; layout(location = 0) out vec4 outColor; void main() { outColor = vec4(1,0,1,1); } The application starts and shows a black window, but the terrain is not being rendered. Do you know where the issue is?
3666b23f979c7f369fb9c57ba0ccd090
{ "intermediate": 0.35484620928764343, "beginner": 0.2958282232284546, "expert": 0.349325567483902 }
7,999
tell me a linux command for cheking kernel version
57ffb4ba7ff1a53884a80a57f79cc945
{ "intermediate": 0.3265705406665802, "beginner": 0.35661882162094116, "expert": 0.31681060791015625 }
8,000
定义皇冠梨订购成本为 1.5元,售价 2.1 元,过期成本 1.7 元,缺货成本 0.4 元,持有成本 0.1 元,提前期为 1 天,生命周期为 3 天,对动作数量和数值进行调整,对 Q 学习算法模型进行训练。基于 Q 学习算法的库存模型的库存成本计算公式为𝑈 = 𝐶 ∙ 𝐶𝑛 + 𝑃𝑛∙ 𝑃 + 𝐺𝑛 ∙ 𝐺,其中,U:库存成本,C:单位产品的过期成本,𝐶𝑛:每段时间内的过期数量, 𝑃𝑛:单位产品的持有成本,𝑃 :每段时间内持有的商品的数量,𝐺𝑛 :单位产品的缺货成本,𝐺 :每段时间内的缺货数量。总利润=500*R,库存成本为 U。以生鲜农产品零售经营者利润为奖励函数,在实验过程中,生鲜农产品零售商利润以天为单位,进行 500 天实验,从而得出生鲜产品零售商的总利润和库存成本。然后零售经营者采用服务水平为 96%的定量订货模型,利润以天为单位,进行 500 天的计算,得出的总利润和库存成本。实验以 E=0.1,学习率初始化为 0.7,当训练 2 万次,每迭代千次便将学习率降低为𝛼 ∗ 𝛽,𝛽 = 0.9。实验的每个周期为 500 次,每个实验周期只进行一次订货与库存更新。在实验条件均相同的情况下,当需求数据是𝐿 = (60,5^2)时,求出零售商使用基于 Q 学习算法的库存模型得到的的库存成本。麻烦给出完整的代码过程。要求用python3.0版本无报错运行
e83bf7eb9b833d2599afcf817b436cca
{ "intermediate": 0.27453935146331787, "beginner": 0.5560486912727356, "expert": 0.16941198706626892 }
8,001
perbaiki arsitektur model ini: # Membuat model CNN-LSTM model = Sequential([ Embedding(input_dim=10000, output_dim=300, input_length=500, weights=[embedding_matrix], trainable=False), Conv1D(256, 3, activation='relu', kernel_regularizer=l2(0.01)), MaxPooling1D(pool_size=4), Dropout(0.5), LSTM(200, return_sequences=False, kernel_regularizer=l2(0.01), recurrent_regularizer=l2(0.01)), Dropout(0.7), Dense(32, activation='relu', kernel_regularizer=l2(0.01)), Dropout(0.5), Dense(3, activation='softmax') ]) agar tidak mendapatkan hasil berikut: 160/160 [==============================] - 3s 18ms/step Akurasi: 0.6483580922595777 Classification Report: precision recall f1-score support Negatif 0.65 0.67 0.66 1567 Netral 0.65 0.83 0.73 2743 Positif 0.00 0.00 0.00 806 accuracy 0.65 5116 macro avg 0.43 0.50 0.46 5116 weighted avg 0.55 0.65 0.59 5116 dan tidak menghasilkan error berikut: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
55ee2bbb5c6d2d6face71a0fb3a4ce46
{ "intermediate": 0.26596325635910034, "beginner": 0.2323790043592453, "expert": 0.5016577243804932 }
8,002
> bpm-ui@0.1.0 start > webpack serve -c config/webpack.config.js --node-env=development --progress --hot [webpack-cli] You need to install 'webpack-dev-server' for running 'webpack serve'. Error: Cannot find module 'D:\silaUnion\bpm\bpm-ui\node_modules\body-parser\node_modules\debug\src\index.js'. Please verify that the package.json has a valid "main" entry error Command failed with exit code 2. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. Как исправить ошибку?
179ca223b6b5579daa9476117b85e2fe
{ "intermediate": 0.4227549731731415, "beginner": 0.28517216444015503, "expert": 0.2920728027820587 }
8,003
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. I have run into a problem. Here is some code for context: Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); Mesh* GetMesh(); Material* GetMaterial(); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh* mesh; Material* material; bool initialized = false; void UpdateModelMatrix(); }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize() { mesh = new Mesh{}; material = new Material{}; this->initialized = true; } void GameObject::Update(float deltaTime) { // Update position, rotation, scale, and other properties // Example: Rotate the object around the Y-axis rotation.y += deltaTime * glm::radians(90.0f); UpdateModelMatrix(); } void GameObject::Render(Renderer& renderer, const Camera& camera) { // Render this object using the renderer and camera VkDevice device = *renderer.GetDevice(); // Bind mesh vertex and index buffers VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32); // Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; } mvp; mvp.model = modelMatrix; mvp.view = camera.GetViewMatrix(); mvp.projection = camera.GetProjectionMatrix(); // Create a new buffer to hold the MVP data temporarily VkBuffer mvpBuffer; VkDeviceMemory mvpBufferMemory; BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(), sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mvpBuffer, mvpBufferMemory); // Map the MVP data into the buffer and unmap void* data = nullptr; vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data); memcpy(data, &mvp, sizeof(MVP)); vkUnmapMemory(device, mvpBufferMemory); // TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of // the default uniform buffer // Bind the DescriptorSet associated with the material VkDescriptorSet descriptorSet = material->GetDescriptorSet(); material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP)); renderer.CreateGraphicsPipeline(mesh, material); vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline()); vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr); // Call vkCmdDrawIndexed() uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size()); vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0); // Cleanup the temporary buffer vkDestroyBuffer(device, mvpBuffer, nullptr); vkFreeMemory(device, mvpBufferMemory, nullptr); } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) delete mesh; delete material; this->initialized = false; } void GameObject::SetPosition(const glm::vec3& position) { this->position = position; UpdateModelMatrix(); } void GameObject::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateModelMatrix(); } void GameObject::SetScale(const glm::vec3& scale) { this->scale = scale; UpdateModelMatrix(); } void GameObject::UpdateModelMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); modelMatrix = glm::scale(modelMatrix, scale); } Mesh* GameObject::GetMesh() { return mesh; } Material* GameObject::GetMaterial() { return material; } Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Mesh.cpp: #include "Mesh.h" Mesh::Mesh() : device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE) { } Mesh::~Mesh() { Cleanup(); } void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->vertices = vertices; this->indices = indices; this->device = device; Initialize(device, physicalDevice, commandPool, graphicsQueue); // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … } void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … // Declare and initialize stagingBuffer and bufferSize here VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize); vkDestroyBuffer(device, stagingBuffer, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr); bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingIndexBuffer; VkDeviceMemory stagingIndexBufferMemory; BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingIndexBuffer, stagingIndexBufferMemory); vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingIndexBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize); vkDestroyBuffer(device, stagingIndexBuffer, nullptr); vkFreeMemory(device, stagingIndexBufferMemory, nullptr); } void Mesh::Cleanup() { if (device != VK_NULL_HANDLE) { if (vertexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, vertexBuffer, nullptr); vkFreeMemory(device, vertexBufferMemory, nullptr); vertexBuffer = VK_NULL_HANDLE; vertexBufferMemory = VK_NULL_HANDLE; } if (indexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, indexBuffer, nullptr); vkFreeMemory(device, indexBufferMemory, nullptr); indexBuffer = VK_NULL_HANDLE; indexBufferMemory = VK_NULL_HANDLE; } } } const std::vector<Vertex>& Mesh::GetVertices() const { return vertices; } const std::vector<uint32_t>& Mesh::GetIndices() const { return indices; } VkBuffer Mesh::GetVertexBuffer() const { return vertexBuffer; } VkBuffer Mesh::GetIndexBuffer() const { return indexBuffer; } void Mesh::SetVertices(const std::vector<Vertex>& vertices) { this->vertices = vertices; } void Mesh::SetIndices(const std::vector<uint32_t>& indices) { this->indices = indices; } std::vector<VkVertexInputBindingDescription> Mesh::GetVertexInputBindingDescriptions() const { std::vector<VkVertexInputBindingDescription> bindingDescriptions(1); bindingDescriptions[0].binding = 0; bindingDescriptions[0].stride = sizeof(Vertex); bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescriptions; } std::vector<VkVertexInputAttributeDescription> Mesh::GetVertexInputAttributeDescriptions() const { std::vector<VkVertexInputAttributeDescription> attributeDescriptions(2); // Position attribute attributeDescriptions[0].binding = 0; attributeDescriptions[0].location = 0; attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[0].offset = offsetof(Vertex, position); // Color attribute attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); return attributeDescriptions; } Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Material.cpp: #include "Material.h" Material::Material() : device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE) { } Material::~Material() { Cleanup(); } void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Load shaders and texture LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue); LoadShaders(vertShaderPath, fragShaderPath, device); // Create descriptor set and pipeline layout CreateDescriptorSet(descriptorSetLayout, descriptorPool); CreatePipelineLayout(descriptorSetLayout); } void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { VkDescriptorSetAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = descriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &descriptorSetLayout; if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate descriptor sets!"); } VkDescriptorImageInfo imageInfo{}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = texture->GetImageView(); imageInfo.sampler = texture->GetSampler(); VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrite.descriptorCount = 1; descriptorWrite.pImageInfo = &imageInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout) { VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = 1; pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout; if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create pipeline layout!"); } } void Material::Cleanup() { // Clean up resources, if necessary // (depending on how Shader and Texture resources are managed) } VkDescriptorSet Material::GetDescriptorSet() const { return descriptorSet; } VkPipelineLayout Material::GetPipelineLayout() const { return pipelineLayout; } std::shared_ptr <Shader> Material::GetvertexShader() { return vertexShader; } std::shared_ptr <Shader> Material::GetfragmentShader() { return fragmentShader; } void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue); } void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device) { vertexShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup); fragmentShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup); vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT); fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT); } void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize) { VkDescriptorBufferInfo bufferInfo{}; bufferInfo.buffer = newBuffer; bufferInfo.offset = 0; bufferInfo.range = devicesize; VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrite.descriptorCount = 1; descriptorWrite.pBufferInfo = &bufferInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; bool IsInitialized() const; private: VkDevice device; VkPipeline pipeline; bool initialized; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Pipeline.cpp: #include "Pipeline.h" Pipeline::Pipeline() : device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE), initialized(false) { } Pipeline::~Pipeline() { Cleanup(); } void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device) { this->device = device; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(swapchainExtent.width); viewport.height = static_cast<float>(swapchainExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; VkPipelineMultisampleStateCreateInfo multisampling{}; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlending{}; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; std::vector<VkPipelineShaderStageCreateInfo> shaderStages; CreateShaderStages(shaders, shaderStages); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssembly; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizer; pipelineCreateInfo.pMultisampleState = &multisampling; pipelineCreateInfo.pColorBlendState = &colorBlending; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } initialized = true; } bool Pipeline::IsInitialized() const { return initialized; } void Pipeline::Cleanup() { if (pipeline != VK_NULL_HANDLE && initialized) { //vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; initialized = false; } } VkPipeline Pipeline::GetPipeline() const { return pipeline; } void Pipeline::CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages) { for (auto shader : shaders) { shaderStages.push_back(shader->GetPipelineShaderStageCreateInfo()); } } Terrain.h: #pragma once #include "Simplex.h" #include "Mesh.h" #include "Material.h" #include "GameObject.h" class Terrain { public: Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue); ~Terrain(); void GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); GameObject* GetTerrainObject(); private: void GenerateHeightMap(); void ConvertHeightMapToMeshData(); int seed; int worldSize; float scale; VkDevice* device; VkPhysicalDevice* physicalDevice; VkCommandPool* commandPool; VkQueue* graphicsQueue; SimplexNoise noise; std::vector<std::vector<float>> heightMap; std::vector<Vertex> vertices; std::vector<uint32_t> indices; Mesh* terrainMesh; Material* terrainMaterial; GameObject* terrainObject; }; Terrain.cpp: #include "Terrain.h" Terrain::Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue) : seed(seed), worldSize(worldSize), scale(scale), noise(seed), device(device), physicalDevice(physicalDevice), commandPool(commandPool), graphicsQueue(graphicsQueue) { terrainMesh = new Mesh{}; terrainMaterial = new Material{}; } Terrain::~Terrain() { // Cleanup any resources associated with the Terrain class //terrainMesh.Cleanup(); //terrainMaterial.Cleanup(); //delete terrainObject; //delete terrainMesh; //delete terrainMaterial; } void Terrain::GenerateHeightMap() { heightMap = std::vector<std::vector<float>>(worldSize, std::vector<float>(worldSize, 0.0f)); for (int x = 0; x < worldSize; ++x) { for (int z = 0; z < worldSize; ++z) { float noiseValue = noise.noise(x * scale, z * scale); heightMap[x][z] = noiseValue; } } } void Terrain::ConvertHeightMapToMeshData() { vertices.clear(); indices.clear(); // Generate vertices for (int x = 0; x < worldSize; ++x) { for (int z = 0; z < worldSize; ++z) { Vertex vertex; vertex.position = glm::vec3(static_cast<float>(x), heightMap[x][z], static_cast<float>(z)); // Set color based on height, feel free to customize this as desired float color = heightMap[x][z] * 0.5f + 0.5f; // Normalize the height value between 0 and 1 vertex.color = glm::vec3(color, color, color); vertices.push_back(vertex); } } // Generate indices for rendering using triangle strips for (int x = 0; x < worldSize - 1; ++x) { for (int z = 0; z < worldSize - 1; ++z) { int topLeft = x * worldSize + z; int topRight = topLeft + 1; int bottomLeft = (x + 1) * worldSize + z; int bottomRight = bottomLeft + 1; // First triangle indices.push_back(topLeft); indices.push_back(bottomRight); indices.push_back(bottomLeft); // Second triangle indices.push_back(topLeft); indices.push_back(topRight); indices.push_back(bottomRight); } } } void Terrain::GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { GenerateHeightMap(); ConvertHeightMapToMeshData(); terrainObject = new GameObject(); terrainObject->Initialize(); terrainMesh = terrainObject->GetMesh(); terrainMesh->Initialize(vertices, indices, *device, *physicalDevice, *commandPool, *graphicsQueue); // Initialize terrainMaterial with the loaded shaders and texture // Assume descriptorSetLayout and descriptorPool are created before this call terrainMaterial = terrainObject->GetMaterial(); terrainMaterial->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *device, descriptorSetLayout, descriptorPool, *physicalDevice, *commandPool, *graphicsQueue); } GameObject* Terrain::GetTerrainObject() { return terrainObject; } Vertex Shader: #version 450 layout(binding = 0) uniform UniformBufferObject { mat4 model; mat4 view; mat4 proj; } ubo; layout(location = 0) in vec3 inPosition; layout(location = 1) in vec3 inColor; layout(location = 0) out vec3 fragColor; void main() { gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0); fragColor = inColor; } Fragment Shader: #version 450 layout(binding = 1) uniform sampler2D texSampler; layout(location = 0) in vec3 fragColor; layout(location = 0) out vec4 outColor; void main() { outColor = vec4(1,0,1,1); } #pragma once #include <vector> #include "GameObject.h" #include "Camera.h" #include "Renderer.h" class Scene { public: Scene(); ~Scene(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer); void Shutdown(); void AddGameObject(GameObject* gameObject); Camera& GetCamera(); float temp; private: std::vector<GameObject*> gameObjects; Camera camera; }; Scene.h: #include "Scene.h" Scene::Scene() { } Scene::~Scene() { Shutdown(); } void Scene::Initialize() { // Initialize camera and game objects camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f)); // Add initial game objects } void Scene::Update(float deltaTime) { // Update game objects and camera for (GameObject* gameObject : gameObjects) { gameObject->Update(deltaTime); temp = temp + 0.01; } } void Scene::Render(Renderer& renderer) { // Render game objects for (GameObject* gameObject : gameObjects) { gameObject->Render(renderer, camera); } camera.SetRotation(glm::vec3(0, 0, temp)); // Submit rendering-related commands to Vulkan queues } void Scene::Shutdown() { // Clean up game objects for (GameObject* gameObject : gameObjects) { delete gameObject; gameObject = nullptr; } gameObjects.clear(); camera.Shutdown(); } void Scene::AddGameObject(GameObject* gameObject) { gameObjects.push_back(gameObject); } Camera& Scene::GetCamera() { return camera; } Scene.cpp: #include "Scene.h" Scene::Scene() { } Scene::~Scene() { Shutdown(); } void Scene::Initialize() { // Initialize camera and game objects camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f)); // Add initial game objects } void Scene::Update(float deltaTime) { // Update game objects and camera for (GameObject* gameObject : gameObjects) { gameObject->Update(deltaTime); temp = temp + 0.01; } } void Scene::Render(Renderer& renderer) { // Render game objects for (GameObject* gameObject : gameObjects) { gameObject->Render(renderer, camera); } camera.SetRotation(glm::vec3(0, 0, temp)); // Submit rendering-related commands to Vulkan queues } void Scene::Shutdown() { // Clean up game objects for (GameObject* gameObject : gameObjects) { delete gameObject; gameObject = nullptr; } gameObjects.clear(); camera.Shutdown(); } void Scene::AddGameObject(GameObject* gameObject) { gameObjects.push_back(gameObject); } Camera& Scene::GetCamera() { return camera; } The application starts and shows a black window, but the terrain is not being rendered. Do you know where the issue is?
defe9346c0123d51e89f6ce0abe1de10
{ "intermediate": 0.35484620928764343, "beginner": 0.2958282232284546, "expert": 0.349325567483902 }
8,004
make a python program to crawle the p rate of this website: ‘https://www.ocbcwhhk.com/whb/action/rate/whbRate.do?id=prime_lending_rate&locale=en-us’
ff54d527941a6a160a67e2b6caf31d01
{ "intermediate": 0.4097122848033905, "beginner": 0.19029833376407623, "expert": 0.3999893367290497 }
8,005
I'm working on a fivem diving script but haven't done the server.lua could you please write it QBCore = exports['qb-core']:GetCoreObject() local SCAV_TOOLS = { "weapon_knife", "weapon_screwdriver", } local openWater = 0.0 local lastScavCoords = false local lastScavTime = 0 local function doesPlayerHaveTool(ped) local weapon = GetSelectedPedWeapon(PlayerPedId()) for _,v in pairs(SCAV_TOOLS) do if (GetHashKey(v) == weapon) then return true end end return false end local function isPedUnderWater(ped) if IsPedSwimmingUnderWater(ped) then return true end return false end -- I dont think there are any backyard or open pools that are less than 0.0? Maybe Canals.. Alamo Sea is 30.0 but parts go below 0.0 local function isPedinOpenWater(ped) local coords = GetEntityCoords(ped) local pedZ = coords.z if pedZ <= openWater then return true end return false end local function closeToGround(ped) if GetEntityHeightAboveGround(ped) <= 1 then return true end return false end local function canScav(ped) if doesPlayerHaveTool(ped) and isPedUnderWater(ped) and closeToGround(ped) and isPedinOpenWater(ped) then return true end return false end local function hasPlayerMoved(ped) if lastScavCoords then if GetDistanceBetweenCoords(lastScavCoords, GetEntityCoords(ped)) > 3 then lastScavCoords = GetEntityCoords(ped) return true end else lastScavCoords = GetEntityCoords(ped) return true end return false end onBaseReady(function() Citizen.CreateThread(function() while true do local ped = PlayerPedId() if IsControlJustPressed(1, 47) then if canScav(ped) then if hasPlayerMoved(ped) then local currentTime = GetGameTimer() if currentTime - lastScavTime > 5000 then FreezeEntityPosition(ped, true) lastScavTime = GetGameTimer() TriggerServerEvent("alpha_scav:underwater_scav") Wait(5000) FreezeEntityPosition(ped, false) end end end end Wait(IsPedSwimmingUnderWater(ped) and 0 or 1000) end end) end)
376a0a29475340d79d90b651a0198226
{ "intermediate": 0.31333568692207336, "beginner": 0.36697131395339966, "expert": 0.319692999124527 }
8,006
please make an example code in python where we take two cdf files as inputs and the output is a single cdf file merged with the information of the inputs. We merge all the variables from the input files
3ae93e3f10e5fe2a81f4607fe4a870ef
{ "intermediate": 0.391305536031723, "beginner": 0.2600676417350769, "expert": 0.3486268222332001 }
8,007
In php I want to do a doble condition in the foreach but there is a error solve it, <?php foreach( $latest_from_softonic->url as $url && $latest_from_softonic->title as $title ) : ?>
689a9f8ead51e593f8606b71ee8d4b8c
{ "intermediate": 0.43047896027565, "beginner": 0.4135083556175232, "expert": 0.1560126394033432 }
8,008
Give me python ml code to cluster cisco network devices syslog messages by messages that usually appear one after other (in near timestamps)
499b2727854e39333a0020b4bd3914bb
{ "intermediate": 0.6066902875900269, "beginner": 0.09424416720867157, "expert": 0.2990655303001404 }
8,009
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. I have run into a problem. Here is some code for context: Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); Mesh* GetMesh(); Material* GetMaterial(); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh* mesh; Material* material; bool initialized = false; void UpdateModelMatrix(); }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize() { mesh = new Mesh{}; material = new Material{}; this->initialized = true; } void GameObject::Update(float deltaTime) { // Update position, rotation, scale, and other properties // Example: Rotate the object around the Y-axis rotation.y += deltaTime * glm::radians(90.0f); UpdateModelMatrix(); } void GameObject::Render(Renderer& renderer, const Camera& camera) { // Render this object using the renderer and camera VkDevice device = *renderer.GetDevice(); // Bind mesh vertex and index buffers VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32); // Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; } mvp; mvp.model = modelMatrix; mvp.view = camera.GetViewMatrix(); mvp.projection = camera.GetProjectionMatrix(); // Create a new buffer to hold the MVP data temporarily VkBuffer mvpBuffer; VkDeviceMemory mvpBufferMemory; BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(), sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mvpBuffer, mvpBufferMemory); // Map the MVP data into the buffer and unmap void* data = nullptr; vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data); memcpy(data, &mvp, sizeof(MVP)); vkUnmapMemory(device, mvpBufferMemory); // TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of // the default uniform buffer // Bind the DescriptorSet associated with the material VkDescriptorSet descriptorSet = material->GetDescriptorSet(); material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP)); renderer.CreateGraphicsPipeline(mesh, material); vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline()); vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr); // Call vkCmdDrawIndexed() uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size()); vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0); // Cleanup the temporary buffer vkDestroyBuffer(device, mvpBuffer, nullptr); vkFreeMemory(device, mvpBufferMemory, nullptr); } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) delete mesh; delete material; this->initialized = false; } void GameObject::SetPosition(const glm::vec3& position) { this->position = position; UpdateModelMatrix(); } void GameObject::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateModelMatrix(); } void GameObject::SetScale(const glm::vec3& scale) { this->scale = scale; UpdateModelMatrix(); } void GameObject::UpdateModelMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); modelMatrix = glm::scale(modelMatrix, scale); } Mesh* GameObject::GetMesh() { return mesh; } Material* GameObject::GetMaterial() { return material; } Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Mesh.cpp: #include "Mesh.h" Mesh::Mesh() : device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE) { } Mesh::~Mesh() { Cleanup(); } void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->vertices = vertices; this->indices = indices; this->device = device; Initialize(device, physicalDevice, commandPool, graphicsQueue); // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … } void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … // Declare and initialize stagingBuffer and bufferSize here VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize); vkDestroyBuffer(device, stagingBuffer, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr); bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingIndexBuffer; VkDeviceMemory stagingIndexBufferMemory; BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingIndexBuffer, stagingIndexBufferMemory); vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingIndexBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize); vkDestroyBuffer(device, stagingIndexBuffer, nullptr); vkFreeMemory(device, stagingIndexBufferMemory, nullptr); } void Mesh::Cleanup() { if (device != VK_NULL_HANDLE) { if (vertexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, vertexBuffer, nullptr); vkFreeMemory(device, vertexBufferMemory, nullptr); vertexBuffer = VK_NULL_HANDLE; vertexBufferMemory = VK_NULL_HANDLE; } if (indexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, indexBuffer, nullptr); vkFreeMemory(device, indexBufferMemory, nullptr); indexBuffer = VK_NULL_HANDLE; indexBufferMemory = VK_NULL_HANDLE; } } } const std::vector<Vertex>& Mesh::GetVertices() const { return vertices; } const std::vector<uint32_t>& Mesh::GetIndices() const { return indices; } VkBuffer Mesh::GetVertexBuffer() const { return vertexBuffer; } VkBuffer Mesh::GetIndexBuffer() const { return indexBuffer; } void Mesh::SetVertices(const std::vector<Vertex>& vertices) { this->vertices = vertices; } void Mesh::SetIndices(const std::vector<uint32_t>& indices) { this->indices = indices; } std::vector<VkVertexInputBindingDescription> Mesh::GetVertexInputBindingDescriptions() const { std::vector<VkVertexInputBindingDescription> bindingDescriptions(1); bindingDescriptions[0].binding = 0; bindingDescriptions[0].stride = sizeof(Vertex); bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescriptions; } std::vector<VkVertexInputAttributeDescription> Mesh::GetVertexInputAttributeDescriptions() const { std::vector<VkVertexInputAttributeDescription> attributeDescriptions(2); // Position attribute attributeDescriptions[0].binding = 0; attributeDescriptions[0].location = 0; attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[0].offset = offsetof(Vertex, position); // Color attribute attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); return attributeDescriptions; } Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Material.cpp: #include "Material.h" Material::Material() : device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE) { } Material::~Material() { Cleanup(); } void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Load shaders and texture LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue); LoadShaders(vertShaderPath, fragShaderPath, device); // Create descriptor set and pipeline layout CreateDescriptorSet(descriptorSetLayout, descriptorPool); CreatePipelineLayout(descriptorSetLayout); } void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { VkDescriptorSetAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = descriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &descriptorSetLayout; if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate descriptor sets!"); } VkDescriptorImageInfo imageInfo{}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = texture->GetImageView(); imageInfo.sampler = texture->GetSampler(); VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrite.descriptorCount = 1; descriptorWrite.pImageInfo = &imageInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout) { VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = 1; pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout; if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create pipeline layout!"); } } void Material::Cleanup() { // Clean up resources, if necessary // (depending on how Shader and Texture resources are managed) } VkDescriptorSet Material::GetDescriptorSet() const { return descriptorSet; } VkPipelineLayout Material::GetPipelineLayout() const { return pipelineLayout; } std::shared_ptr <Shader> Material::GetvertexShader() { return vertexShader; } std::shared_ptr <Shader> Material::GetfragmentShader() { return fragmentShader; } void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue); } void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device) { vertexShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup); fragmentShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup); vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT); fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT); } void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize) { VkDescriptorBufferInfo bufferInfo{}; bufferInfo.buffer = newBuffer; bufferInfo.offset = 0; bufferInfo.range = devicesize; VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrite.descriptorCount = 1; descriptorWrite.pBufferInfo = &bufferInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; bool IsInitialized() const; private: VkDevice device; VkPipeline pipeline; bool initialized; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Pipeline.cpp: #include "Pipeline.h" Pipeline::Pipeline() : device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE), initialized(false) { } Pipeline::~Pipeline() { Cleanup(); } void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device) { this->device = device; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(swapchainExtent.width); viewport.height = static_cast<float>(swapchainExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; VkPipelineMultisampleStateCreateInfo multisampling{}; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlending{}; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; std::vector<VkPipelineShaderStageCreateInfo> shaderStages; CreateShaderStages(shaders, shaderStages); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssembly; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizer; pipelineCreateInfo.pMultisampleState = &multisampling; pipelineCreateInfo.pColorBlendState = &colorBlending; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } initialized = true; } bool Pipeline::IsInitialized() const { return initialized; } void Pipeline::Cleanup() { if (pipeline != VK_NULL_HANDLE && initialized) { //vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; initialized = false; } } VkPipeline Pipeline::GetPipeline() const { return pipeline; } void Pipeline::CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages) { for (auto shader : shaders) { shaderStages.push_back(shader->GetPipelineShaderStageCreateInfo()); } } Terrain.h: #pragma once #include "Simplex.h" #include "Mesh.h" #include "Material.h" #include "GameObject.h" class Terrain { public: Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue); ~Terrain(); void GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); GameObject* GetTerrainObject(); private: void GenerateHeightMap(); void ConvertHeightMapToMeshData(); int seed; int worldSize; float scale; VkDevice* device; VkPhysicalDevice* physicalDevice; VkCommandPool* commandPool; VkQueue* graphicsQueue; SimplexNoise noise; std::vector<std::vector<float>> heightMap; std::vector<Vertex> vertices; std::vector<uint32_t> indices; Mesh* terrainMesh; Material* terrainMaterial; GameObject* terrainObject; }; Terrain.cpp: #include "Terrain.h" Terrain::Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue) : seed(seed), worldSize(worldSize), scale(scale), noise(seed), device(device), physicalDevice(physicalDevice), commandPool(commandPool), graphicsQueue(graphicsQueue) { terrainMesh = new Mesh{}; terrainMaterial = new Material{}; } Terrain::~Terrain() { // Cleanup any resources associated with the Terrain class //terrainMesh.Cleanup(); //terrainMaterial.Cleanup(); //delete terrainObject; //delete terrainMesh; //delete terrainMaterial; } void Terrain::GenerateHeightMap() { heightMap = std::vector<std::vector<float>>(worldSize, std::vector<float>(worldSize, 0.0f)); for (int x = 0; x < worldSize; ++x) { for (int z = 0; z < worldSize; ++z) { float noiseValue = noise.noise(x * scale, z * scale); heightMap[x][z] = noiseValue; } } } void Terrain::ConvertHeightMapToMeshData() { vertices.clear(); indices.clear(); // Generate vertices for (int x = 0; x < worldSize; ++x) { for (int z = 0; z < worldSize; ++z) { Vertex vertex; vertex.position = glm::vec3(static_cast<float>(x), heightMap[x][z], static_cast<float>(z)); // Set color based on height, feel free to customize this as desired float color = heightMap[x][z] * 0.5f + 0.5f; // Normalize the height value between 0 and 1 vertex.color = glm::vec3(color, color, color); vertices.push_back(vertex); } } // Generate indices for rendering using triangle strips for (int x = 0; x < worldSize - 1; ++x) { for (int z = 0; z < worldSize - 1; ++z) { int topLeft = x * worldSize + z; int topRight = topLeft + 1; int bottomLeft = (x + 1) * worldSize + z; int bottomRight = bottomLeft + 1; // First triangle indices.push_back(topLeft); indices.push_back(bottomRight); indices.push_back(bottomLeft); // Second triangle indices.push_back(topLeft); indices.push_back(topRight); indices.push_back(bottomRight); } } } void Terrain::GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { GenerateHeightMap(); ConvertHeightMapToMeshData(); terrainObject = new GameObject(); terrainObject->Initialize(); terrainMesh = terrainObject->GetMesh(); terrainMesh->Initialize(vertices, indices, *device, *physicalDevice, *commandPool, *graphicsQueue); // Initialize terrainMaterial with the loaded shaders and texture // Assume descriptorSetLayout and descriptorPool are created before this call terrainMaterial = terrainObject->GetMaterial(); terrainMaterial->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *device, descriptorSetLayout, descriptorPool, *physicalDevice, *commandPool, *graphicsQueue); } GameObject* Terrain::GetTerrainObject() { return terrainObject; } Vertex Shader: #version 450 layout(binding = 0) uniform UniformBufferObject { mat4 model; mat4 view; mat4 proj; } ubo; layout(location = 0) in vec3 inPosition; layout(location = 1) in vec3 inColor; layout(location = 0) out vec3 fragColor; void main() { gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0); fragColor = inColor; } Fragment Shader: #version 450 layout(binding = 1) uniform sampler2D texSampler; layout(location = 0) in vec3 fragColor; layout(location = 0) out vec4 outColor; void main() { outColor = vec4(1,0,1,1); } #pragma once #include <vector> #include "GameObject.h" #include "Camera.h" #include "Renderer.h" class Scene { public: Scene(); ~Scene(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer); void Shutdown(); void AddGameObject(GameObject* gameObject); Camera& GetCamera(); float temp; private: std::vector<GameObject*> gameObjects; Camera camera; }; Scene.h: #include "Scene.h" Scene::Scene() { } Scene::~Scene() { Shutdown(); } void Scene::Initialize() { // Initialize camera and game objects camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f)); // Add initial game objects } void Scene::Update(float deltaTime) { // Update game objects and camera for (GameObject* gameObject : gameObjects) { gameObject->Update(deltaTime); temp = temp + 0.01; } } void Scene::Render(Renderer& renderer) { // Render game objects for (GameObject* gameObject : gameObjects) { gameObject->Render(renderer, camera); } camera.SetRotation(glm::vec3(0, 0, temp)); // Submit rendering-related commands to Vulkan queues } void Scene::Shutdown() { // Clean up game objects for (GameObject* gameObject : gameObjects) { delete gameObject; gameObject = nullptr; } gameObjects.clear(); camera.Shutdown(); } void Scene::AddGameObject(GameObject* gameObject) { gameObjects.push_back(gameObject); } Camera& Scene::GetCamera() { return camera; } Scene.cpp: #include "Scene.h" Scene::Scene() { } Scene::~Scene() { Shutdown(); } void Scene::Initialize() { // Initialize camera and game objects camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f)); // Add initial game objects } void Scene::Update(float deltaTime) { // Update game objects and camera for (GameObject* gameObject : gameObjects) { gameObject->Update(deltaTime); temp = temp + 0.01; } } void Scene::Render(Renderer& renderer) { // Render game objects for (GameObject* gameObject : gameObjects) { gameObject->Render(renderer, camera); } camera.SetRotation(glm::vec3(0, 0, temp)); // Submit rendering-related commands to Vulkan queues } void Scene::Shutdown() { // Clean up game objects for (GameObject* gameObject : gameObjects) { delete gameObject; gameObject = nullptr; } gameObjects.clear(); camera.Shutdown(); } void Scene::AddGameObject(GameObject* gameObject) { gameObjects.push_back(gameObject); } Camera& Scene::GetCamera() { return camera; } The application starts and shows a black window, but the terrain is not being rendered. Do you know where the issue is?
471606339e6970f978d0f67592206238
{ "intermediate": 0.35484620928764343, "beginner": 0.2958282232284546, "expert": 0.349325567483902 }
8,010
if (radio_up_down->isChecked()) { animation_->setStartValue(QPoint(pic_->pos().x(), 0)); animation_->setEndValue(QPoint(pic_->pos().x(), height() - 2*pic_->height())); } сделай так чтобы фигура из своего положения начала двигаться вверх-вниз плавно на ширину окна
391dd0ee25b873d26f606c42f45d13ed
{ "intermediate": 0.35094138979911804, "beginner": 0.4146222770214081, "expert": 0.23443637788295746 }
8,011
do you know computer craft mod?
16a586c3390effe07ac10070b5eafb28
{ "intermediate": 0.10930702835321426, "beginner": 0.15762700140476227, "expert": 0.7330659627914429 }
8,012
hello
9c2ac643e52313696727f2ee8c60ddc9
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
8,013
Automatic Real-Time Generation of Floor Plans Based on Squarified Treemaps Algorithm Fernando Marson1and Soraia Raupp Musse 1 Show more Academic Editor: Rafael Bidarra Received 28 May 2010 Accepted 28 Aug 2010 Published 07 Oct 2010 Abstract A novel approach to generate house floor plans with semantic information is presented. The basis of this model is the squarified treemaps algorithm. Previously, this algorithm has been used to create graphical representations based on hierarchical information, such as, directory structures and organization structures. Adapted to floor plans generation, this model allows the creation of internal house structures with information about their features and functionalities. The main contributions are related to the robustness, flexibility, and simplicity of the proposed approach to create floor plans in real-time. Results show that different and realistic floor plans can be created by adjusting a few parameters. 1. Introduction Considering the game titles released in the last decade, the increase in visual complexity of Virtual Environments (VE) used as scenarios is noticed. Huge cities can be found in games like the GTA franchise (http://www.rockstargames.com/IV), Assassin's Creed (http://assassinscreed.us.ubi.com), and Left 4 Dead (http://www.l4d.com) which is remarkable. Apart from the cities, it may be necessary to create whole worlds, as in the case of Massively Multiplayer On-line Games (MMOGs), represented by World of Warcraft (http://www.worldofwarcraft.com) and Perfect World (http://www.perfectworld.com). As a consequence, the cost and time to develop a game are also increased. The creation of a VE requires previous knowledge in several areas of expertise. Hence, it is necessary to allocate a team of professionals to create, maintain, and reuse large VEs. Some of the main problems faced when developing interactive virtual environments are described in [1] as the nonextensibility, limited interoperability, poor scalability, monolithic architecture, among others. A possible solution to these problems is the use of procedural generation techniques [2], which allow the creation of VE content just by setting input parameters. Such approaches may be used to generate terrains, buildings, characters, items, weapons, quests, and even stories adding a broad range of elements, but in a controlled way. A perfect example to illustrate the potential use of procedural contents generation is the game Spore (http://www.spore.com). In this game, procedural techniques are used to create characters, vehicles, buildings [3], textures [4], and planets [5]. Even the music is created using this kind of technique. There are some academic and commercial solutions that provide the creation of buildings with great realism. Nevertheless, there are few studies that focus on the generation of building interiors. Our model proposes a novel solution to generate floor plans of buildings using just a few parameters and constraints. After the floor plan generation, it creates a three-dimensional representation of the construction. In all generated rooms in the floor plan; semantic information is included to allow simulations involving virtual humans. The remainder of this paper is organized as follows: in Section 2 we discuss some work found in literature, while in Section 3 we describe our model to generate floor plans. Section 4 discusses some obtained results, and the final considerations are drawn in Section 5. 2. Related Work The process of creating large virtual cities can take considerable time and resources to be accomplished. Parish and Müller [7] present a model that allows the generation of a three-dimensional city from sociostatistical and geographical maps. The method builds the road network using an extended L-Systems. After creating the streets, the system extracts the information about blocks. Through a subdivision process, lots are created. A building is placed at each lot, generated by another module based on L-Systems. With this information, the system generates the three-dimensional geometric model of the city, and textures are added to provide greater realism to the final model. A method to generate procedural “pseudoinfinite” virtual cities in real-time is proposed by Greuter et al. [8]. The area of the city is mapped into a grid defined by a given granularity and a global seed. Each cell in the grid has a local seed that can be used to create building generation parameters. A print foot is produced by combining randomly generated polygons in an iterative process, and the building geometries are extruded from a set of floor plans. To optimize the rendering process, a view frustrum is implemented to determine the visibility of virtual world objects before their generation, so that only visible elements are generated. Besides the generation of the environment, the appearance of the buildings can be improved. In this context, Müller et al. [9] propose a shape grammar called CGA Shapes, focused on the generation of buildings with high visual quality and geometric details. Using some rules, the user can describe geometric shapes and specify the interactions between hierarchical groups in order to create a geometrically complex object. In addition, the user can interact dynamically in all stages of creation. The techniques presented previously are focused on the external appearance of buildings, without concerning their interior. Martin [10] introduces an algorithm to create floor plans of houses. The process consists of three main phases. In the first step of the procedure, a graph is created to represent the basic structure of a house. This graph contains the connections between different rooms and ensure that every room of house is accessible. The next step is the placement phase, which consists of distributing the rooms over the footprint. Finally, the rooms are expanded to their proper size using a Monte Carlo method to choose which room to grow or shrink. An approach to generate virtual building interiors in real-time is presented by Hahn et al. [11]. The interiors are created using eleven rules that work like a guideline to the generation process. Buildings created by this technique are divided into regions connected by portals. Only the visible parts of the building are generated, avoiding the use of memory and processing. When a region is no longer visible, the structure is removed from the memory. The generation process also provides a persistent environment: all changes made in a given region are stored in a record that is accessed through a hash map when necessary. Horna et al. [12] propose a method to generate 3D constructions from two-dimensional architectural plans. Additional information can be included to the two-dimensional plans in order to support the creation of three-dimensional model. It is possible to construct several floors using the same architectural plan. A rule-based layout approach is proposed by Tutenel et al. [13]. Their method allows to solve the layout and also to distribute objects in the scene at the same time. From an initial layout, the algorithm finds the possible locations of a new object based on a given set of rules. The relations between objects can be specified either explicitly or implicitly. The method uses hierarchical blocks in the solving process, so that if a set of elements are solved, they are treated as single block. Besides the definition of appearance and geometry of objects, it is also necessary to specify their features and functionalities. Semantic information can be used to enhance the environment of games and simulations. This can be done by specifying features of a given actor or object, as well as functionality, physical or psychological attributes and behaviors. Tutenel et al. [14] list three levels of semantic specification: object semantics, object relationships, and world semantics. These levels can be used to create and simulate an environment. For example, information such as the climate of a region can be used to define the kind of vegetation, and the weight of an object can be used to decide if an agent can carry it or not. The main contribution of this paper is to provide a framework for real-time procedural modeling of floor plans of houses, generating geometric and semantic information in a robust way, where all rooms can be accessible from outside the environment. Virtual agents can use the provided information, so that behavioral animation can be performed. Squarified treemaps [6] are used to generate rooms which aspect ratios approach . Section 3 presents the proposed model. 3. Creating Floor Plans A common drawback in procedural generation of environments is the creation of a component that is not accessible from any other component. For instance, in a virtual city, one problem is the generation of buildings that are not accessible from the streets. Concerning internal structures of buildings, a similar problem happens when one room is not connected with any other. As far as we know, neither of the proposed procedural models to generate floor plans can solve such type of situation. Our proposed method treats this problem by adding corridors into the generated floor plan, similarly to what occurs in real life. Our method for generating floor plans is based on Squarified Treemaps, proposed by Bruls et al. [6]. A treemap [15] is an efficient and compact form to organize and to visualize elements of hierarchical structures of information, for instance, directory structures, organization structures, family trees, and others. In general, treemaps subdivide an area into small pieces to represent the importance of each part in the hierarchy. The main difference between treemaps and squarified treemaps is how the subdivision is performed. In squarified treemaps, authors propose a subdivision method that takes into account the aspect ratio of generated regions, trying to achieve the value . Figure 1 shows on the left the result of the original treemap method and on the right the squarified treemap. Both models are discussed next. (b) (b) (a) (a) (b) (b) (a) (a) (b) (b) Figure 1 Original treemap (a) and squarified treemap (b). 3.1. Treemaps and Squarified Treemaps The original treemaps approach [15] uses a tree structure to define how information should be used to subdivide the space. Figure 2 shows an example. Let us consider that each node in the tree (Figure 2(a)) has an associated size (e.g., in Figure 2 the name of node is and its size is ). The treemap is built using recursive subdivision of an initial rectangle (see Figure 2(b)). The direction of subdivision alternates per level (horizontally and vertically). Consequently, the initial rectangle is subdivided in small rectangles. Further details about treemaps can be found in [15]. (b) (b) (a) (a) (b) (b) (a) (a) (b) (b) Figure 2 Tree diagram (a) and related treemap (b). This method can originate subdivisions like the one illustrated in Figure 3. In this case, it is possible to see that aspect ratios of generated rectangles are very different from 1. Consequently, this approach is not adequate to tackle the problem that we want to deal with in this paper. Figure 3 Example of treemap subdivision generating rectangles with aspect ratio different from . Squarified treemaps were proposed by Bruls et al. [6] and have the main goal of maintaining the aspect ratios of generated rectangles, defined as , as close to as possible. Their method is implemented using recursive programming and aims to generate rectangles based on a predefined and sorted list containing their desired areas (from larger to smaller areas). Then, the aspect ratio of the region to be subdivided is considered in order to decide whether to divide it horizontally or vertically. Also, the aspect ratio of generated regions in a specific step is compared to step , being possible to ignore later computing regions in and reconsider data from step . Figure 4 illustrates the generation process of squarified treemaps presented by Bruls et al. [6]. We discuss this example in this paper since the understanding of our model is very dependent of squarified treemap method. Figure 4 Example of squarified treemap process [6]. The list of rectangular areas to be considered in the example of Figure 4 is: . In step 1, the method generates a rectangle with aspect ratio in vertical subdivision. So, in step 2 the horizontal subdivision is tested, generating 2 rectangles with aspect which are close to 1. In step 3, the next rectangle is generated, presenting aspect . This step is ignored, and step 4 is computed based on rectangles computed in step 2. The algorithm (described in detail in [6]) presents rectangles which aspect ratios are close to . In our point of view, this method is more adequate to provide generation of floor plans than original treemaps, due to the fact that rooms in real houses present aspect ratios not very different from . However, other problems may occur, as shown in the next sections. 3.2. The Proposed Model The pipeline of the proposed model to build floor plans is presented in Figure 5. The process begins with the definition of construction parameters and layout constraints. Figure 5 The generation process of floor plans. Construction parameters and layout constraints are provided by the user as input to floor plan generator. To create a floor plan, some parameters such as, height, length, and width of the building are required. It is also necessary to know the list of desired dimensions for each room and their functionalities. The functionality specifies how a particular area of residence should be used. There are three distinct possibilities: social area, service area, and private area. The social area can include the living room, the dining room, and the toilet. In the service area we can have the kitchen, the pantry, and the laundry room. At last, the private area can embrace the bedroom, the master bedroom, the intimate bathroom, and a possible secondary room that can be used in different ways, for example, as a library. This list is not fixed and can be customized by the user, and the proposed categorization is made to group the common areas. The division of the residence area occurs in two different steps. At first, we compute the area of each one of three parts of the building (i.e., social, service, and private), and secondly, apply the squarified treemap in order to define three regions where rooms will be generated. This process generates an initial layout, containing three rectangles, each one for a specific area of the building (see Figure 6(a)). (b) (b) (a) (a) (b) (b) (a) (a) (b) (b) Figure 6 Dividing the total space of the house in three main areas (a): private, social, and service area. Example floor plan generated by the model (b). After obtaining the positions of the polygon that represents a specific area, each polygon serves as input to run again squarified treemap algorithm in order to generate the geometry of each room. It is important to notice that we use original squarified treemap to generate each room in the building. Figure 6(b) shows the generated rooms. With the result of the room subdivision, two more steps are required to complete the floor plan generation. Firstly, connections among rooms should be created. Secondly, rooms that are not accessible should be treated, since our environments should be used for characters animation. These two steps are further discussed in next sections. 3.3. Including Connections among the Rooms With all the rooms generated as previously described, connections (doors) should be created among them. These connections are created using as criteria the functionalities of each room, that is, some rooms are usually not connected, for example, the kitchen and the bedroom. All the possible connections are presented in Table 1, which has been modeled based on a previous analysis of various floor plans commercially available. In this table, we consider the entry door of the floor plan as a connection from outside and two possible rooms: kitchen and living room. However, it is important to note that another set of connections can be defined by the user, to represent another style of architecture. Table 1 Possible connections between rooms. Geometrically, the door is created on the edge shared by two rooms that keep a possible connection. For instance, it is possible to have a connection between the kitchen and the living room, where a door can be created. The size of the doors is predefined, and their center on the edge is randomly defined. A similar process happens with the generation of windows, but ensuring that they are placed on the external edges. Figure 6(b) illustrates a generated floor plan, containing windows (dark rectangles) and doors (white rectangles). After the connections between rooms are processed, a connectivity graph is automatically created (Figure 7), representing the links among the rooms. It allows checking if there is any room that is not accessible. Also, buildings and houses created with our method can be used to provide environment for characters simulation. The graph always starts from outside and follows all possible connections from the accessed room. Figure 7 Connectivity graph for a generated floor plan. If any room is not present in the graph, it is necessary to include corridors. This situation can happen when there are no possible connections between neighboring rooms (rooms which share edges). This process is described in the next section. 3.4. Including Corridors on the Floor Plans The generation of corridors is necessary in order to maintain the coherence of the generated environment and to provide valid space for characters navigation. Firstly, the rooms without access from the living room are selected. These rooms are flagged with an , as illustrated in Figure 8(a). The main idea is to find possible edges shared by nonconnected rooms to be used to create the corridor. Figure 8 Steps to end the building generation. (a) Original floor plan with rooms without connectivity flagged with an X and the living room is marked with L. (b) Floor plan after external edges removed. (c) Internal walls that do not belong to living room. (d) The shortest path linking all rooms without connectivity to the living room. (e) Final 2D floor plan. (f) The red and blue rectangles highlight, respectively, the representation of a window and a door in the floor plan. Creation process of windows (g) and doors (h). The corridor must connect the living room (marked with an in Figure 8(a)) with all rooms. The proposed solution uses the internal walls of the building to generate a kind of circulation “backbone” of the space, that is, the most probable region to generate the corridor in the floor plan. The algorithm is very simple and has three main steps. Firstly, all external walls are removed, as corridors are avoided in the boundary of the floor plan (Figure 8(b)). Secondly, we remove all internal segments (representing walls) that belong to the living room (Figure 8(c)). The remaining segments (described through their vertices) are used as input to the graph creation. Vertices are related to nodes, and segments describe the edges in the graph (Figure 8(c)). In order to deal with the graph, we use the A algorithm [16], which is a very known algorithm widely used in path-finding and graph traversal. In our case, the graph is explored to find the shortest path that connects all rooms without connectivity to the living room. A room is considered connected if the graph traverses at least one of its edges. Finally the shortest path is chosen to create the corridor (Figure 8(d)). The “backbone” is the set of edges candidates to be used to generate the corridor. After the “backbone” generation, we should generate the polygons which represent the corridor, which is initially composed by a set of edges/segments. These segments must pass through a process of 2D extrusion in order to generate rectangles, allowing agents to walk inside the house. Indeed, the size of the corridor is increased perpendicularly to the edges. However, this process can cause an overlap between the corridor and some rooms, reducing their areas. If the final area of any room is smaller than the minimum allowed value, the floor plan undergoes a global readjustment process to correct this problem, as shown in 1 After obtaining the final floor plan (Figure 8(e)), two simple steps should be followed to generate the final building. Initially, each 2D wall represented on the floor plan is extruded to a given height defined by the user. Generated walls can have doors (between two rooms) (blue rectangle in Figure 8(f)) and windows (red rectangle in Figure 8(f)), that should be modeled properly. The last step of process is to add an appropriate type of window to each room, according to its functionality, from a set of models. A three-dimensional view of a 2D floor plan (Figure 8(e)) is presented in Figure 9. Figure 9 Three-dimensional model of 2D floor plan illustrated in Figure 8(e). 4. Results In the following floor plans, we explicitly present the parameters used in their generation, and also show the geometric and semantic information generated. In addition, the connectivity graph is shown for each house or building. Figure 10(a) shows a floor plan generated using our model. The list of rooms and their respective areas are as follows: living room , two bedrooms , secondary room , bathroom , and kitchen . The dimensions of the house are meters wide, meters long, and meters high. The connectivity graph can be seen in Figure 10(b). Both the bathroom and the secondary room do not have connection with any other room. This situation is corrected by adding a corridor (Figure 11(a)). The new connectivity graph is shown in Figure 11(b). All rooms are now connected, being accessible from the outside or from any other internal room. (b) (b) (a) (a) (b) (b) (a) (a) (b) (b) Figure 10 Example of floor plan (a) containing 2 nonconnected rooms (labeled with X) and its respective connectivity graph (b). (b) (b) (a) (a) (b) (b) (a) (a) (b) (b) Figure 11 Example of floor plan of Figure 10 (a) containing corridors and all rooms are connected to the living room and its respective connectivity graph (b). Another case study is illustrated in Figure 12(a). This house has 84 squared meters (12 m long 7 m wide, being 3.1 m high). The list of rooms and their respective areas are as follows: living room , two bedrooms both with , a secondary room used as home office , bathroom , and kitchen . For this specific configuration, the connectivity graph that can be seen in Figure 12(b) was generated. Both bedrooms and the bathroom are not accessible from any other room. The solution is presented in Figure 13(a). Using the corridor, the new connectivity graph looks like the one presented in Figure 13(b). A generated 2D floor plan can be saved to disk and used as input to a home design software. Figure 14 shows the result of same floor plan when adding some 2D furniture. (b) (b) (a) (a) (b) (b) (a) (a) (b) (b) Figure 12 Example of floor plan (a) containing 3 nonconnected rooms (labeled with X) and its respective connectivity graph (b). (b) (b) (a) (a) (b) (b) (a) (a) (b) (b) Figure 13 Example of floor plan of Figure 12 (a) containing corridors and all rooms are connected to the living room and its respective connectivity graph (b). Figure 14 Our floor plan and included furnitures. In addition, we compared the floor plan of Figure 14 with an available real floor plan. As it can be seen in Figure 15, such real floor plan could generate exactly the same connectivity graph (see Figure 13(b)). Furthermore, the total dimension of the real plan is , while virtual plan has , and still generating rooms of similar size. Figure 15 Real floor plan. In Figure 16 we can observe a 3D model of floor plan visualized with textures. Figure 16 Three-dimensional model of a generated floor plan. It is important to note that for these results we determine parameters values in order to provide specific floor plans, and even compare with available houses, existent in real life. However, one can imagine having our method integrated into a game engine, and generating different floor plans in a dynamic way. For instance, using random functions and intervals for areas and a random number of rooms, our method is able to generate different floor plans automatically. So, during the game, the player can visit different buildings and have always different floor plans, without previous modeling. 5. Final Considerations We present a technique to provide floor plans for houses in an automatic way. The relevance of this method is the ability to generate real-time buildings for games and simulations. The generated environments are realistic as they could easily be found in real life. Besides geometric information, the technique also generates semantic information which is very useful to allow virtual humans simulation. We compared a generated floor plan with an available commercial house in order to verify the similarity between the distribution of generated rooms and real ones. Furthermore, this work contributes to generate a connection graph which determines the navigation graph in the environment. Corridors could be created to solve problems of nonconnected rooms. write the complete code for it in python
fc12d0c7eb9956211711373e027bc29e
{ "intermediate": 0.3376322090625763, "beginner": 0.3321741223335266, "expert": 0.3301936984062195 }
8,014
hi
4cfdb5cc73b957fd933ae317c039a793
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
8,015
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. I have run into a problem. Here is some code for context: Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); Mesh* GetMesh(); Material* GetMaterial(); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh* mesh; Material* material; bool initialized = false; void UpdateModelMatrix(); }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize() { mesh = new Mesh{}; material = new Material{}; this->initialized = true; } void GameObject::Update(float deltaTime) { // Update position, rotation, scale, and other properties // Example: Rotate the object around the Y-axis rotation.y += deltaTime * glm::radians(90.0f); UpdateModelMatrix(); } void GameObject::Render(Renderer& renderer, const Camera& camera) { // Render this object using the renderer and camera VkDevice device = *renderer.GetDevice(); // Bind mesh vertex and index buffers VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32); // Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; } mvp; mvp.model = modelMatrix; mvp.view = camera.GetViewMatrix(); mvp.projection = camera.GetProjectionMatrix(); // Create a new buffer to hold the MVP data temporarily VkBuffer mvpBuffer; VkDeviceMemory mvpBufferMemory; BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(), sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mvpBuffer, mvpBufferMemory); // Map the MVP data into the buffer and unmap void* data = nullptr; vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data); memcpy(data, &mvp, sizeof(MVP)); vkUnmapMemory(device, mvpBufferMemory); // TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of // the default uniform buffer // Bind the DescriptorSet associated with the material VkDescriptorSet descriptorSet = material->GetDescriptorSet(); material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP)); renderer.CreateGraphicsPipeline(mesh, material); vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline()); vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr); // Call vkCmdDrawIndexed() uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size()); vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0); // Cleanup the temporary buffer vkDestroyBuffer(device, mvpBuffer, nullptr); vkFreeMemory(device, mvpBufferMemory, nullptr); } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) delete mesh; delete material; this->initialized = false; } void GameObject::SetPosition(const glm::vec3& position) { this->position = position; UpdateModelMatrix(); } void GameObject::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateModelMatrix(); } void GameObject::SetScale(const glm::vec3& scale) { this->scale = scale; UpdateModelMatrix(); } void GameObject::UpdateModelMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); modelMatrix = glm::scale(modelMatrix, scale); } Mesh* GameObject::GetMesh() { return mesh; } Material* GameObject::GetMaterial() { return material; } Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Mesh.cpp: #include "Mesh.h" Mesh::Mesh() : device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE) { } Mesh::~Mesh() { Cleanup(); } void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->vertices = vertices; this->indices = indices; this->device = device; Initialize(device, physicalDevice, commandPool, graphicsQueue); // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … } void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … // Declare and initialize stagingBuffer and bufferSize here VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize); vkDestroyBuffer(device, stagingBuffer, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr); bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingIndexBuffer; VkDeviceMemory stagingIndexBufferMemory; BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingIndexBuffer, stagingIndexBufferMemory); vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingIndexBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize); vkDestroyBuffer(device, stagingIndexBuffer, nullptr); vkFreeMemory(device, stagingIndexBufferMemory, nullptr); } void Mesh::Cleanup() { if (device != VK_NULL_HANDLE) { if (vertexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, vertexBuffer, nullptr); vkFreeMemory(device, vertexBufferMemory, nullptr); vertexBuffer = VK_NULL_HANDLE; vertexBufferMemory = VK_NULL_HANDLE; } if (indexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, indexBuffer, nullptr); vkFreeMemory(device, indexBufferMemory, nullptr); indexBuffer = VK_NULL_HANDLE; indexBufferMemory = VK_NULL_HANDLE; } } } const std::vector<Vertex>& Mesh::GetVertices() const { return vertices; } const std::vector<uint32_t>& Mesh::GetIndices() const { return indices; } VkBuffer Mesh::GetVertexBuffer() const { return vertexBuffer; } VkBuffer Mesh::GetIndexBuffer() const { return indexBuffer; } void Mesh::SetVertices(const std::vector<Vertex>& vertices) { this->vertices = vertices; } void Mesh::SetIndices(const std::vector<uint32_t>& indices) { this->indices = indices; } std::vector<VkVertexInputBindingDescription> Mesh::GetVertexInputBindingDescriptions() const { std::vector<VkVertexInputBindingDescription> bindingDescriptions(1); bindingDescriptions[0].binding = 0; bindingDescriptions[0].stride = sizeof(Vertex); bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescriptions; } std::vector<VkVertexInputAttributeDescription> Mesh::GetVertexInputAttributeDescriptions() const { std::vector<VkVertexInputAttributeDescription> attributeDescriptions(2); // Position attribute attributeDescriptions[0].binding = 0; attributeDescriptions[0].location = 0; attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[0].offset = offsetof(Vertex, position); // Color attribute attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); return attributeDescriptions; } Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Material.cpp: #include "Material.h" Material::Material() : device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE) { } Material::~Material() { Cleanup(); } void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Load shaders and texture LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue); LoadShaders(vertShaderPath, fragShaderPath, device); // Create descriptor set and pipeline layout CreateDescriptorSet(descriptorSetLayout, descriptorPool); CreatePipelineLayout(descriptorSetLayout); } void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { VkDescriptorSetAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = descriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &descriptorSetLayout; if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate descriptor sets!"); } VkDescriptorImageInfo imageInfo{}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = texture->GetImageView(); imageInfo.sampler = texture->GetSampler(); VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrite.descriptorCount = 1; descriptorWrite.pImageInfo = &imageInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout) { VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = 1; pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout; if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create pipeline layout!"); } } void Material::Cleanup() { // Clean up resources, if necessary // (depending on how Shader and Texture resources are managed) } VkDescriptorSet Material::GetDescriptorSet() const { return descriptorSet; } VkPipelineLayout Material::GetPipelineLayout() const { return pipelineLayout; } std::shared_ptr <Shader> Material::GetvertexShader() { return vertexShader; } std::shared_ptr <Shader> Material::GetfragmentShader() { return fragmentShader; } void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue); } void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device) { vertexShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup); fragmentShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup); vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT); fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT); } void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize) { VkDescriptorBufferInfo bufferInfo{}; bufferInfo.buffer = newBuffer; bufferInfo.offset = 0; bufferInfo.range = devicesize; VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrite.descriptorCount = 1; descriptorWrite.pBufferInfo = &bufferInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; bool IsInitialized() const; private: VkDevice device; VkPipeline pipeline; bool initialized; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Pipeline.cpp: #include "Pipeline.h" Pipeline::Pipeline() : device(VK_NULL_HANDLE), pipeline(VK_NULL_HANDLE), initialized(false) { } Pipeline::~Pipeline() { Cleanup(); } void Pipeline::CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device) { this->device = device; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexBindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = vertexBindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexAttributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(swapchainExtent.width); viewport.height = static_cast<float>(swapchainExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; VkPipelineMultisampleStateCreateInfo multisampling{}; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlending{}; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; std::vector<VkPipelineShaderStageCreateInfo> shaderStages; CreateShaderStages(shaders, shaderStages); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssembly; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizer; pipelineCreateInfo.pMultisampleState = &multisampling; pipelineCreateInfo.pColorBlendState = &colorBlending; pipelineCreateInfo.layout = pipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = 0; if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } initialized = true; } bool Pipeline::IsInitialized() const { return initialized; } void Pipeline::Cleanup() { if (pipeline != VK_NULL_HANDLE && initialized) { //vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; initialized = false; } } VkPipeline Pipeline::GetPipeline() const { return pipeline; } void Pipeline::CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages) { for (auto shader : shaders) { shaderStages.push_back(shader->GetPipelineShaderStageCreateInfo()); } } Terrain.h: #pragma once #include "Simplex.h" #include "Mesh.h" #include "Material.h" #include "GameObject.h" class Terrain { public: Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue); ~Terrain(); void GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); GameObject* GetTerrainObject(); private: void GenerateHeightMap(); void ConvertHeightMapToMeshData(); int seed; int worldSize; float scale; VkDevice* device; VkPhysicalDevice* physicalDevice; VkCommandPool* commandPool; VkQueue* graphicsQueue; SimplexNoise noise; std::vector<std::vector<float>> heightMap; std::vector<Vertex> vertices; std::vector<uint32_t> indices; Mesh* terrainMesh; Material* terrainMaterial; GameObject* terrainObject; }; Terrain.cpp: #include "Terrain.h" Terrain::Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue) : seed(seed), worldSize(worldSize), scale(scale), noise(seed), device(device), physicalDevice(physicalDevice), commandPool(commandPool), graphicsQueue(graphicsQueue) { terrainMesh = new Mesh{}; terrainMaterial = new Material{}; } Terrain::~Terrain() { // Cleanup any resources associated with the Terrain class //terrainMesh.Cleanup(); //terrainMaterial.Cleanup(); //delete terrainObject; //delete terrainMesh; //delete terrainMaterial; } void Terrain::GenerateHeightMap() { heightMap = std::vector<std::vector<float>>(worldSize, std::vector<float>(worldSize, 0.0f)); for (int x = 0; x < worldSize; ++x) { for (int z = 0; z < worldSize; ++z) { float noiseValue = noise.noise(x * scale, z * scale); heightMap[x][z] = noiseValue; } } } void Terrain::ConvertHeightMapToMeshData() { vertices.clear(); indices.clear(); // Generate vertices for (int x = 0; x < worldSize; ++x) { for (int z = 0; z < worldSize; ++z) { Vertex vertex; vertex.position = glm::vec3(static_cast<float>(x), heightMap[x][z], static_cast<float>(z)); // Set color based on height, feel free to customize this as desired float color = heightMap[x][z] * 0.5f + 0.5f; // Normalize the height value between 0 and 1 vertex.color = glm::vec3(color, color, color); vertices.push_back(vertex); } } // Generate indices for rendering using triangle strips for (int x = 0; x < worldSize - 1; ++x) { for (int z = 0; z < worldSize - 1; ++z) { int topLeft = x * worldSize + z; int topRight = topLeft + 1; int bottomLeft = (x + 1) * worldSize + z; int bottomRight = bottomLeft + 1; // First triangle indices.push_back(topLeft); indices.push_back(bottomRight); indices.push_back(bottomLeft); // Second triangle indices.push_back(topLeft); indices.push_back(topRight); indices.push_back(bottomRight); } } } void Terrain::GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { GenerateHeightMap(); ConvertHeightMapToMeshData(); terrainObject = new GameObject(); terrainObject->Initialize(); terrainMesh = terrainObject->GetMesh(); terrainMesh->Initialize(vertices, indices, *device, *physicalDevice, *commandPool, *graphicsQueue); // Initialize terrainMaterial with the loaded shaders and texture // Assume descriptorSetLayout and descriptorPool are created before this call terrainMaterial = terrainObject->GetMaterial(); terrainMaterial->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *device, descriptorSetLayout, descriptorPool, *physicalDevice, *commandPool, *graphicsQueue); } GameObject* Terrain::GetTerrainObject() { return terrainObject; } Vertex Shader: #version 450 layout(binding = 0) uniform UniformBufferObject { mat4 model; mat4 view; mat4 proj; } ubo; layout(location = 0) in vec3 inPosition; layout(location = 1) in vec3 inColor; layout(location = 0) out vec3 fragColor; void main() { gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0); fragColor = inColor; } Fragment Shader: #version 450 layout(binding = 1) uniform sampler2D texSampler; layout(location = 0) in vec3 fragColor; layout(location = 0) out vec4 outColor; void main() { outColor = vec4(1,0,1,1); } #pragma once #include <vector> #include "GameObject.h" #include "Camera.h" #include "Renderer.h" class Scene { public: Scene(); ~Scene(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer); void Shutdown(); void AddGameObject(GameObject* gameObject); Camera& GetCamera(); float temp; private: std::vector<GameObject*> gameObjects; Camera camera; }; Scene.h: #include "Scene.h" Scene::Scene() { } Scene::~Scene() { Shutdown(); } void Scene::Initialize() { // Initialize camera and game objects camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f)); // Add initial game objects } void Scene::Update(float deltaTime) { // Update game objects and camera for (GameObject* gameObject : gameObjects) { gameObject->Update(deltaTime); temp = temp + 0.01; } } void Scene::Render(Renderer& renderer) { // Render game objects for (GameObject* gameObject : gameObjects) { gameObject->Render(renderer, camera); } camera.SetRotation(glm::vec3(0, 0, temp)); // Submit rendering-related commands to Vulkan queues } void Scene::Shutdown() { // Clean up game objects for (GameObject* gameObject : gameObjects) { delete gameObject; gameObject = nullptr; } gameObjects.clear(); camera.Shutdown(); } void Scene::AddGameObject(GameObject* gameObject) { gameObjects.push_back(gameObject); } Camera& Scene::GetCamera() { return camera; } Scene.cpp: #include "Scene.h" Scene::Scene() { } Scene::~Scene() { Shutdown(); } void Scene::Initialize() { // Initialize camera and game objects camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f)); // Add initial game objects } void Scene::Update(float deltaTime) { // Update game objects and camera for (GameObject* gameObject : gameObjects) { gameObject->Update(deltaTime); temp = temp + 0.01; } } void Scene::Render(Renderer& renderer) { // Render game objects for (GameObject* gameObject : gameObjects) { gameObject->Render(renderer, camera); } camera.SetRotation(glm::vec3(0, 0, temp)); // Submit rendering-related commands to Vulkan queues } void Scene::Shutdown() { // Clean up game objects for (GameObject* gameObject : gameObjects) { delete gameObject; gameObject = nullptr; } gameObjects.clear(); camera.Shutdown(); } void Scene::AddGameObject(GameObject* gameObject) { gameObjects.push_back(gameObject); } Camera& Scene::GetCamera() { return camera; } Can you see any errors in the above code?
04c222e5acb78e7340d5e5828c2d6df0
{ "intermediate": 0.35484620928764343, "beginner": 0.2958282232284546, "expert": 0.349325567483902 }
8,016
hi i need a python script for this steps: 1. give a wordlist file path from user 2. send request to https://kent.com/domain/{{wordlist item's perline}} 3. save output as txt with name's in wordlist file
bcf6d2311af83573f9b9ba8a1326001a
{ "intermediate": 0.42932212352752686, "beginner": 0.22512978315353394, "expert": 0.3455480635166168 }
8,017
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; }; 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); private: bool shutdownInProgress; 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(); 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(); CreateSwapchain(); CreateRenderPass(); CreateCommandPool(); CreateFramebuffers(); CreateSyncObjects(); } void Renderer::Shutdown() { if (device == VK_NULL_HANDLE || shutdownInProgress) { // If the device is already VK_NULL_HANDLE, it means the cleanup has run before return; } shutdownInProgress = true; // Indicate that the cleanup is in progress std::cout << "Waiting for device idle…" << std::endl; vkDeviceWaitIdle(device); // Wait for rendering to complete std::cout << "Cleaning up framebuffers…" << std::endl; CleanupFramebuffers(); std::cout << "Cleaning up renderpass…" << std::endl; CleanupRenderPass(); std::cout << "Cleaning up syncobject…" << std::endl; CleanupSyncObjects(); std::cout << "Cleaning up commandbuffers…" << std::endl; CleanupCommandBuffers(); // Free command buffers before destroying the command pool CleanupCommandPool(); CleanupImageViews(); CleanupSwapchain(); CleanupDevice(); // Make sure that CleanupDevice is called before DestroySurface DestroySurface(); // Move this line after CleanupDevice CleanupInstance(); } 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]; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); 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); 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; // 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()) { 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{}; // 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() { // 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); 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 = 0; 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); 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; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &uboLayoutBinding; 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; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 1; poolInfo.pPoolSizes = &poolSize; 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) { // 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; } Can you please check the code for any potential memory leaks? If you find any, please tell me the changes required to fix them.
51e847a34558fe172c2a976a2630b085
{ "intermediate": 0.4277711808681488, "beginner": 0.3564312160015106, "expert": 0.21579760313034058 }
8,018
this is my script "from flask import Flask, request from binance.client import Client from telegram import Bot import sys import os from binance.enums import * from dotenv import load_dotenv import math import asyncio import aiohttp from werkzeug.exceptions import HTTPException from threading import Thread, Event import threading import time import multiprocessing from multiprocessing import Value load_dotenv() # take environment variables from .env. binance_api_key = os.getenv("BINANCE_API_KEY") binance_api_secret = os.getenv("BINANCE_API_SECRET") bot_token = os.getenv("TELEGRAM_BOT_TOKEN") channel_id = os.getenv("TELEGRAM_CHANNEL_ID") app = Flask(__name__) client = Client(binance_api_key, binance_api_secret) bot = Bot(token=bot_token) # Event for stopping the server stop_event = Event() # Initialize total_pnl as a shared variable total_pnl = Value('d', 0.0) # 'd' is the typecode for double loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) def run_asyncio_coroutine(coroutine): return loop.run_until_complete(coroutine) async def send_message(text): async with aiohttp.ClientSession() as session: url = f"https://api.telegram.org/bot{bot_token}/sendMessage" payload = {"chat_id": channel_id, "text": text} async with session.post(url, data=payload) as resp: return await resp.text() total_pnl.value = 0 def get_balance(asset="USDT"): balances = client.futures_account_balance() for balance in balances: if balance["asset"] == asset: return float(balance["withdrawAvailable"]) return 0 def get_precision(symbol): info = client.futures_exchange_info() for s in info['symbols']: if s['symbol'] == symbol: return next((filter['stepSize'] for filter in s['filters'] if filter['filterType'] == 'LOT_SIZE'), None) return None def calculate_pnl(entry_price, exit_price, leverage, action): percentage_change = ((exit_price - entry_price) / entry_price) * 100 if action == "SHORT": percentage_change = -percentage_change pnl = percentage_change * leverage print(f"Calculated PnL: {pnl}%") # New line return pnl def close_all_positions(symbol): positions = client.futures_position_information(symbol=symbol) for position in positions: if float(position['positionAmt']) > 0: exit_price = float(client.futures_ticker(symbol=symbol)["lastPrice"]) entry_price = float(position['entryPrice']) pnl = calculate_pnl(entry_price, exit_price, float(position['leverage']), "LONG") total_pnl.value += pnl print(f"Total PnL: {total_pnl.value}%") # New line message = f"Closed LONG position on {symbol} at price {exit_price}. PnL: {pnl}%" print(message) run_asyncio_coroutine(send_message(message)) client.futures_create_order( symbol=symbol, side=SIDE_SELL, positionSide="LONG", quantity=float(position['positionAmt']), type=ORDER_TYPE_MARKET ) elif float(position['positionAmt']) < 0: exit_price = float(client.futures_ticker(symbol=symbol)["lastPrice"]) entry_price = float(position['entryPrice']) pnl = calculate_pnl(entry_price, exit_price, float(position['leverage']), "SHORT") total_pnl.value += pnl print(f"Total PnL: {total_pnl.value}%") # New line message = f"Closed SHORT position on {symbol} at price {exit_price}. PnL: {pnl}%" print(message) run_asyncio_coroutine(send_message(message)) client.futures_create_order( symbol=symbol, side=SIDE_BUY, positionSide="SHORT", quantity=abs(float(position['positionAmt'])), type=ORDER_TYPE_MARKET ) def handle_entry(symbol, action, quantity, leverage): client.futures_change_leverage(symbol=symbol, leverage=leverage) if action == "LONG": client.futures_create_order( symbol=symbol, side=SIDE_BUY, positionSide="LONG", type=ORDER_TYPE_MARKET, quantity=quantity ) else: # SHORT client.futures_create_order( symbol=symbol, side=SIDE_SELL, positionSide="SHORT", type=ORDER_TYPE_MARKET, quantity=quantity ) symbol_action_map = { "btc": ["LONG", "SHORT", "EXIT_LONG", "EXIT_SHORT", "STOPLOSS"], "eth": ["LONG1", "SHORT1", "EXIT_LONG1", "EXIT_SHORT1", "STOPLOSS1"], "xrp": ["LONG2", "SHORT2", "EXIT_LONG2", "EXIT_SHORT2", "STOPLOSS2"], "matic": ["LONG3", "SHORT3", "EXIT_LONG3", "EXIT_SHORT3", "STOPLOSS3"], "bnb": ["LONG4", "SHORT4", "EXIT_LONG4", "EXIT_SHORT4", "STOPLOSS4"], "dot": ["LONG5", "SHORT5", "EXIT_LONG5", "EXIT_SHORT5", "STOPLOSS5"], "sol": ["LONG6", "SHORT6", "EXIT_LONG6", "EXIT_SHORT6", "STOPLOSS6"], "agix": ["LONG7", "SHORT7", "EXIT_LONG7", "EXIT_SHORT7", "STOPLOSS7"], "xvs": ["LONG8", "SHORT8", "EXIT_LONG8", "EXIT_SHORT8", "STOPLOSS8"], "fxs": ["LONG9", "SHORT9", "EXIT_LONG9", "EXIT_SHORT9", "STOPLOSS9"], } symbol_leverage_map = { "btc": 50, "eth": 50, "xrp": 25, "matic": 25, "bnb": 45, "dot": 25, "sol": 25, "agix": 25, "xvs": 25, "fxs": 25, } def webhook(): data = request.data.decode('utf-8') # get the text data directly print(f"Received webhook data: {data}") try: message = data.upper() # assuming that the entire message is the action symbol = "btc" # default to BTC if no symbol is specified in the message for potential_symbol, actions in symbol_action_map.items(): if any(action in message for action in actions): symbol = potential_symbol break leverage = symbol_leverage_map[symbol.upper()] symbol += "USDT" precision = float(get_precision(symbol)) quantity = math.floor((get_balance() * 0.03) / float(client.futures_ticker(symbol=symbol)["lastPrice"]) / precision) * precision if "LONG" in message: handle_entry(symbol, "LONG", quantity, leverage) elif "SHORT" in message: handle_entry(symbol, "SHORT", quantity, leverage) elif "EXIT" in message or "STOPLOSS" in message: close_all_positions(symbol) except Exception as e: print(f"An error occurred: {str(e)}") run_asyncio_coroutine(send_message(f"An error occurred: {str(e)}")) return { "code": "success", }, 200 @app.errorhandler(Exception) def handle_exception(e): # pass through HTTP errors if isinstance(e, HTTPException): return e # now you're handling non-HTTP exceptions only print(f"Unhandled Exception: {str(e)}") return "Internal server error", 500 def run_app(): app.run(host='0.0.0.0', port=5000, debug=False) # Flag to indicate if the application should exit should_exit = False def check_for_exit(): global should_exit while True: if should_exit: print(f"Bye") os._exit(0) time.sleep(1) # Check every second if __name__ == "__main__": # Start the server in a separate process server_process = multiprocessing.Process(target=run_app) server_process.start() try: while True: time.sleep(0.1) except KeyboardInterrupt: print(f"Total PnL on termination: {total_pnl.value}%") run_asyncio_coroutine(send_message(f"Total PnL on termination: {total_pnl.value}%")) server_process.terminate() server_process.join() "
ab06376f512c9856154e1f7cc252824c
{ "intermediate": 0.3154708445072174, "beginner": 0.5860281586647034, "expert": 0.09850108623504639 }
8,019
generate code for html site with simple design for developing content and discography of content, also video content, educatuion content, archive and other, all in one simple words. But generate code only
1b697cf2b74c45f34eb5a445377339ee
{ "intermediate": 0.30804795026779175, "beginner": 0.3219258785247803, "expert": 0.3700261116027832 }
8,020
I'm working on fivem script in lua which rewards you an item based on a tiers I have 5 levels how can I make it so the player has the chances below to hit a loot table (Rare) – 79.92% (Mythical) – 15.98% (Legendary) – 3.2% (Ancient) – 0.64% (Exceedingly Rare) – 0.26%
ab341f6afa9d226e7d13d0bdd96b8392
{ "intermediate": 0.4121628403663635, "beginner": 0.2619507312774658, "expert": 0.32588645815849304 }
8,021
using slack bolt and typescript, how can I close all open modals programatically?
902b688e0a6e9c8968247f7526e13d4c
{ "intermediate": 0.42337024211883545, "beginner": 0.2241363376379013, "expert": 0.35249337553977966 }
8,022
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; }; 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); private: bool shutdownInProgress; 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(); 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(); CreateSwapchain(); CreateRenderPass(); CreateCommandPool(); CreateFramebuffers(); CreateSyncObjects(); } void Renderer::Shutdown() { if (shutdownInProgress) { return; } shutdownInProgress = true; if (device != VK_NULL_HANDLE) { vkDeviceWaitIdle(device); } CleanupFramebuffers(); CleanupRenderPass(); CleanupSyncObjects(); CleanupCommandBuffers(); CleanupCommandPool(); CleanupImageViews(); CleanupSwapchain(); if (device != VK_NULL_HANDLE) { CleanupDevice(); } DestroySurface(); CleanupInstance(); shutdownInProgress = false; } 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]; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); 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); 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; // 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()) { 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{}; // 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() { // 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); 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 = 0; 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); 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; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &uboLayoutBinding; 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; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 1; poolInfo.pPoolSizes = &poolSize; 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) { // 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; } Can you please check the code for any potential memory leaks? If you find any, please tell me the changes required to fix them.
fe80dbe9f175a1d0ae4a9459c4eee330
{ "intermediate": 0.4277711808681488, "beginner": 0.3564312160015106, "expert": 0.21579760313034058 }
8,023
I have "Load Traces\2022 Solar Traces\Stoch_N3.csv" in a cell in excel and want to replace Stoch_N3 with Stoch_ghkartayt
9e2a065792fd54114f3b33527e8235b0
{ "intermediate": 0.31656357645988464, "beginner": 0.26887214183807373, "expert": 0.4145643413066864 }
8,024
In SAS I have data abt.train_woe. I want to find 30 most correlated with each other variables and print them with their correlation.
c52fcb9e5a04ace2838da6a1c5f9252c
{ "intermediate": 0.42115360498428345, "beginner": 0.3351150453090668, "expert": 0.24373134970664978 }
8,025
Can you convert this code into psycopy code import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JPanel; @SuppressWarnings("serial") public class testGenerator extends JPanel { public void paintComponent(Graphics g) { int height = Run.height, width = Run.width, gapSize = Run.gapSize, sqrSize = Run.sqrSize; boolean drawRec = Run.drawRec; super.paintComponent(g); g.setColor(Color.RED); Font font = g.getFont().deriveFont(40.0f); g.setFont(font); g.drawString("+", width / 2 - 10, height / 2 - 10); Font font2 = g.getFont().deriveFont(15.0f); g.setFont(font2); g.setColor(Color.WHITE); g.drawString( "The resolution of this monitor is " + height + "*" + width + " " + "The current gapsize is " + gapSize, width / 8, height / 8 * 7); if (drawRec) { Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(6)); g2.setColor(Color.WHITE); g2.drawRect((int) (0.076 * width) - sqrSize / 2, (int) (0.076 * height) - sqrSize / 2, sqrSize, sqrSize); g2.setColor(Color.BLACK); g2.drawLine((int) (0.076 * width) - sqrSize / 2 + (sqrSize / 2 - gapSize / 2), (int) (0.076 * height) - sqrSize / 2 + sqrSize, (int) (0.076 * width) - sqrSize / 2 + (sqrSize / 2 + gapSize / 2), (int) (0.076 * height) - sqrSize / 2 + sqrSize); } } }
bbc7c13135065fbe518a943a2d1c7f18
{ "intermediate": 0.35295814275741577, "beginner": 0.45724454522132874, "expert": 0.1897972971200943 }
8,026
replace this command if [[ $LAST_KERNEL != $CURRENT_KERNEL ]]; then # Set reboot flag touch /tmp/reboot echo "KERNEL_CHANGED" else echo "No KERNEL Change Detected" fi
a60030ccd2fbd6fa268c369b4aa9f917
{ "intermediate": 0.26754581928253174, "beginner": 0.44314831495285034, "expert": 0.28930580615997314 }
8,027
from pytube import Playlist import os # Create object for the YouTube playlist pl = Playlist("https://youtube.com/playlist?list=OLAK5uy_nGY-yTOBEwF6ge8thscT78_0sah0XNyvg") # Loop through all the videos in the playlist and download them as mp3 files for video in pl.videos: audio_stream = video.streams.filter(only_audio=True).first() audio_file = audio_stream.download(r"C:\Users\elias\PycharmProjects\pythonProject1") # Convert the audio file to mp3 format mp3_file = audio_file.split('.')[0] + '.mp3' os.rename(audio_file, mp3_file) why doesnt this work
afd3102dc579379dd96302d8eb2d7f2e
{ "intermediate": 0.4430379569530487, "beginner": 0.3084612190723419, "expert": 0.24850080907344818 }
8,028
Optimize this code to make it run faster. Functionality should remain unchanged import requests # Replace YOUR_API_KEY_HERE with your BSCScan ‘PI key. API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' # Define the functions to check if a contract is a verified token contract. def is_verified_contract(contract_address): url = f'https://api.bscscan.com/api?module=contract&action=getsourcecode&address={contract_address}&apikey={API_KEY}' response = requests.get(url) if response.status_code == 200: data = response.json() if data['status'] == '1': contract_info = data['result'][0] if contract_info['SourceCode']: return True return False def is_token_contract(contract_address): url = f'https://api.bscscan.com/api?module=token&action=getTokenInfo&contractaddress={contract_address}&apikey={API_KEY}' response = requests.get(url) if response.status_code == 200: data = response.json() if data['status'] == '1': token_name = data['result']['name'] if token_name: return True return False def get_last_100_verified_token_contracts(): start_block = 1 end_block = 99999999 num_contracts = 1 contracts = [] while len(contracts) < num_contracts: url = f'https://api.bscscan.com/api?module=account&action=txlistinternal&startblock={start_block}&endblock={end_block}&page=1&offset=100&sort=desc&apikey={API_KEY}' response = requests.get(url) if response.status_code == 200: data = response.json() if data['status'] == '1': for tx in data['result']: contract_address = tx['contractAddress'] if contract_address and contract_address not in contracts: if is_verified_contract(contract_address) and is_token_contract(contract_address): contracts.append(contract_address) if len(contracts) == num_contracts: break return contracts # Call the function and display verified_token_contracts = get_last_100_verified_token_contracts() print("Last 100 Verified Token Contracts:") for contract in verified_token_contracts: print(contract)
1b5bccd2e540b1ee41d1c760d9272cae
{ "intermediate": 0.41956380009651184, "beginner": 0.3290831446647644, "expert": 0.25135308504104614 }