row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
7,829
|
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 javax.swing.*;
import java.awt.*;
import Model.HighSum;
import Model.Player;
import Model.Dealer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class HighSumGUI {
public static void main(String[] args) {
SwingUtilities.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 ‘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");
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() {
// Starts the game!
boolean carryOn = true;
while (carryOn) {
runOneRound();
if (!gc.getPlayerQuitStatus()) {
char r = this.view.getPlayerNextGame();
if (r == 'n') {
carryOn = false;
}
} else {
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++) {
// 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.Keyboard;
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."
Edit the code so that when highsum gui is run,
The gui pop up is similar to GUIExample where there is a green background and cards are dealt as shown
Currently when highsum gui is run, the pop up gui shows a blank unclosable screen even after editing the game frame and highsum gui class.
|
1024b38ea3d50a3aa5b0655d7168d26b
|
{
"intermediate": 0.30539748072624207,
"beginner": 0.5953488945960999,
"expert": 0.09925368428230286
}
|
7,830
|
как в этом коде применить шейдер к точкам?
напиши шейдер, который немного изменяет цвет точек в зависимости от случайной для каждой точки величины
код:
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 texture = new THREE.TextureLoader().load('texture4.png');
let startSize = 0.06;
const sizeVariation = 0.1;
const materialPoint = new THREE.PointsMaterial({
size: startSize,
sizeAttenuation: true,
map: texture,
alphaTest: 0.01,
transparent: true,
color: new THREE.Color(1., 1., 1.),
opacity: 1.
});
const geometryPoint = new THREE.BufferGeometry();
const positions = geometry.getAttribute('position').array;
const randomSize = [];
for (let i = 0; i < positions.length; i += 3) {
const size = startSize + (Math.random() * sizeVariation);
randomSize.push(size, size, size);
}
geometryPoint.setAttribute('size', new THREE.Float32BufferAttribute(randomSize, 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;
}
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;
}
console.log(ratio);
});
scene.add(points);
points.rotateX(Math.PI/2.0);
}
});
camera.position.z = 3;
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
});
|
76eb39fe99dd2b2a9960c05a0fc90a09
|
{
"intermediate": 0.311176061630249,
"beginner": 0.48638835549354553,
"expert": 0.20243561267852783
}
|
7,831
|
I have a database code and a model in c# and I want to rewrite this code to be used in react native. Below the c# code there is my code, can you help me out and make the same functional database as in c#?
[assembly: Dependency(typeof(FeladatokDatabase))]
namespace Felvetelibazis.Database
{
public class FeladatokDatabase : IFeladatokStore
{
public static readonly string DbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FeladatokAdatbazis.db3");
static readonly Lazy<SQLiteAsyncConnection> _databaseConnectionHolder =
new Lazy<SQLiteAsyncConnection>(() => new SQLiteAsyncConnection(DbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache));
static SQLiteAsyncConnection DatabaseConnection => _databaseConnectionHolder.Value;
protected static async ValueTask<SQLiteAsyncConnection> GetDatabaseConnection<T>() where T : class, new()
{
if (!DatabaseConnection.TableMappings.Any(x => x.MappedType.Name == typeof(T).Name))
{
await DatabaseConnection.EnableWriteAheadLoggingAsync().ConfigureAwait(false);
await DatabaseConnection.CreateTableAsync<T>().ConfigureAwait(false);
}
return DatabaseConnection;
}
protected static Task<T> AttemptAndRetry<T>(Func<Task<T>> action, int numRetries = 3)
{
return Policy.Handle<Exception>().WaitAndRetryAsync(numRetries, pollyRetryAttempt).ExecuteAsync(action);
static TimeSpan pollyRetryAttempt(int attemptNumber) => TimeSpan.FromSeconds(Math.Pow(2, attemptNumber));
}
public async Task<IEnumerable<Feladatok>> FeladatTantargyankent(string tantargy)
{
var databaseConnection = await GetDatabaseConnection<Feladatok>().ConfigureAwait(false);
return await AttemptAndRetry(() => databaseConnection.Table<Feladatok>().Where(x => x.Tantargy == tantargy).ToListAsync()).ConfigureAwait(false);
}
public async Task FeladatFrissites(Feladatok feladat)
{
var databaseConnection = await GetDatabaseConnection<Feladatok>().ConfigureAwait(false);
await AttemptAndRetry(() => databaseConnection.UpdateAsync(feladat)).ConfigureAwait(false);
}
public async Task<IEnumerable<Feladatok>> ErettsegiFeladatKereses(string tantargy, string evszam, bool emelt)
{
var databaseConnection = await GetDatabaseConnection<Feladatok>().ConfigureAwait(false);
return await AttemptAndRetry(() => databaseConnection.Table<Feladatok>().Where(x => x.Tantargy == tantargy && x.Evszam == evszam && x.Emelt == emelt).ToListAsync()).ConfigureAwait(false);
}
}
}
namespace Felvetelibazis.Models
{
[Table("Feladatok")]
public class Feladatok
{
[AutoIncrement, PrimaryKey]
public int ID { get; set; }
public string Kerdes { get; set; }
public string Kerdes2 { get; set; }
public string Kerdes3 { get; set; }
public string Valasz1 { get; set; }
public string Valasz2 { get; set; }
public string Valasz3 { get; set; }
public string Valasz4 { get; set; }
public string Valasz5 { get; set; }
public string Valasz6 { get; set; }
public int Megoldas { get; set; }
public string Magyarazas { get; set; }
public string Magyarazas2 { get; set; }
public int ReszFeladatszam { get; set; }
public int Feladatszam { get; set; }
public int Pont { get; set; }
public string Feladattipus { get; set; }
public string Evszam { get; set; }
public string Tantargy { get; set; }
public bool Emelt { get; set; }
}
My react native database code:
import * as SQLite from 'expo-sqlite';
const db = SQLite.openDatabase('myDatabase.db');
export const init = () => {
return new Promise((resolve, reject) => {
db.transaction((txn) => {
txn.executeSql(
'CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20), age INT)',
[],
() => {
resolve();
},
(err) => { // <-- fixed error here
reject(err);
},
);
});
});
};
export const insertPerson = (name, age) => {
return new Promise((resolve, reject) => {
db.transaction((txn) => {
txn.executeSql(
'INSERT INTO people (name, age) VALUES (?, ?)',
[name, age],
(_, result) => { // <-- fixed error here
resolve(result);
},
(err) => { // <-- fixed error here
reject(err);
},
);
});
});
};
export const fetchAllPeople = () => {
return new Promise((resolve, reject) => {
db.transaction((txn) => {
txn.executeSql(
'SELECT * FROM people',
[],
(_, result) => { // <-- fixed error here
resolve(result.rows._array); // <-- fixed error here
},
(err) => { // <-- fixed error here
reject(err);
},
);
});
});
};
|
1376ef6c47804262fcce3930b5f2bfbd
|
{
"intermediate": 0.3448747396469116,
"beginner": 0.4197353422641754,
"expert": 0.23538991808891296
}
|
7,832
|
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class match {
public static void main (String args[]) {
String regex,word,group;
Scanner input =new Scanner(System.in);
regex = input.next();
word = input.next();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(word);
group=m.group();
System.out.println(group);
}
}
|
7f0864724d57f2a3c20ed9f15f38379f
|
{
"intermediate": 0.44038188457489014,
"beginner": 0.3650554418563843,
"expert": 0.19456268846988678
}
|
7,833
|
emulate a game of doom using unicode and live inputs
|
78efa14f648b5f7dc2b6d4d686cae0ad
|
{
"intermediate": 0.334402471780777,
"beginner": 0.406452476978302,
"expert": 0.25914502143859863
}
|
7,834
|
python how to see xbox controller on d-pad up on pressed down
|
b3b5f5ffb0538b17f628298bc00ea1de
|
{
"intermediate": 0.3947879672050476,
"beginner": 0.31594032049179077,
"expert": 0.28927165269851685
}
|
7,835
|
Based on the instruction below Test Technical Task: French Gender Learning Game
Objective
Create a game that helps users learn the gender of French words. The game will show a French word with examples of usage and ask the user to select the correct article ("UN" or "UNE", "LE" or "LA" randomly). The user's selection will be checked for correctness and the end of the word will be highlighted in red or green to indicate correctness, if the word does not match any rule from Appendix A highlight the whole word. The game will also allow users to click on a word to view its translation and examples of usage.
implement Progress tracking in which User progress will be tracked and saved in the database. Authenticated Users will be able to see their progress in a list of unknown words, well-known words, and words that need to be learned. Create the progress tracking in nestjs and postgres sql with type orm
|
57ba0c6f324acc38bb0d86a1e5205796
|
{
"intermediate": 0.5205670595169067,
"beginner": 0.185981884598732,
"expert": 0.2934509813785553
}
|
7,836
|
In google sheets how do I write a cell function to get me this value: One cell above and to the right the first instance that the word "Saturday" appears in column AY.
|
9744ce85ae69e52836bc16caaa0f7c5c
|
{
"intermediate": 0.3869832158088684,
"beginner": 0.29431286454200745,
"expert": 0.31870391964912415
}
|
7,837
|
python how to see xbox controller on d-pad up on pressed down
|
cd640c08244e20fdaba84c2a9f7390d1
|
{
"intermediate": 0.3947879672050476,
"beginner": 0.31594032049179077,
"expert": 0.28927165269851685
}
|
7,838
|
Update the following enitty import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { EntityHelper } from 'src/utils/entity-helper';
@Entity()
export class MasculineEnding extends EntityHelper {
@PrimaryGeneratedColumn()
id: number;
@Column()
ending: string;
}
so that it includes the articles from the below description Create a game that helps users learn the gender of French words. The game will show a French word with examples of usage and ask the user to select the correct article ("UN" or "UNE", "LE" or "LA" randomly). The user's selection will be checked for correctness and the end of the word will be highlighted in red or green to indicate correctness, if the word does not match any rule from Appendix A highlight the whole word. The game will also allow users to click on a word to view its translation and examples of usage.
|
c173e0f5ed2c18775b5f33d08cbcc4f8
|
{
"intermediate": 0.3992284834384918,
"beginner": 0.27627894282341003,
"expert": 0.3244926333427429
}
|
7,839
|
Implement Progress tracking: User progress will be tracked and saved in the database. Authenticated Users will be able to see their progress in a list of unknown words, well-known words, and words that need to be learned based on the below game controller import { Controller, Get, Req } from ‘@nestjs/common’;
import { InjectRepository } from ‘@nestjs/typeorm’;
import { Repository } from ‘typeorm’;
import { MasculineNoun } from ‘./entities/masculine-noun.entity’;
import { FeminineNoun } from ‘./entities/feminine-noun.entity’;
import { Word } from ‘./entities/word.entity’;
@Controller(‘game’)
export class GameController {
constructor(
@InjectRepository(MasculineNoun)
private masculineNounRepository: Repository<MasculineNoun>,
@InjectRepository(FeminineNoun)
private feminineNounRepository: Repository<FeminineNoun>,
@InjectRepository(Word)
private wordRepository: Repository<Word>,
) {}
@Get(‘word’)
async getWord(@Req() req) {
const randomWord = await this.wordRepository
.createQueryBuilder(‘word’)
.orderBy(‘RANDOM()’)
.getOne();
const wordWithTranslation = { …randomWord };
delete wordWithTranslation.translation_fr;
return JSON.stringify(wordWithTranslation);
}
@Get(‘translation’)
async getTranslation(@Req() req) {
const randomWord = await this.wordRepository
.createQueryBuilder(‘word’)
.orderBy(‘RANDOM()’)
.getOne();
return JSON.stringify({ en: randomWord.translation_en });
}
@Get(‘masculine-nouns’)
async getMasculineNouns(@Req() req) {
const nouns = await this.masculineNounRepository.find();
return JSON.stringify(nouns);
}
@Get(‘feminine-nouns’)
async getFeminineNouns(@Req() req) {
const nouns = await this.feminineNounRepository.find();
return JSON.stringify(nouns);
}
}
Create a new word service, controller and word progress entity to handle the progress tracking
|
c50162bfb4954ff549467807c5139c6e
|
{
"intermediate": 0.5032169222831726,
"beginner": 0.25351062417030334,
"expert": 0.24327243864536285
}
|
7,840
|
java code to create 1000 random scores from 88 piano score range using javax.sound.midi, then save scores to mid file
|
cfc566dcb9cbfcc201cbbc1a7a62a907
|
{
"intermediate": 0.4408898651599884,
"beginner": 0.16500821709632874,
"expert": 0.39410191774368286
}
|
7,841
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp23
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
double b = double.Parse(textBox1.Text);
double x0 = double.Parse(textBox2.Text);
double xk = double.Parse(textBox3.Text);
double dx = double.Parse(textBox4.Text);
// Создаем таблицу данных
DataTable table = new DataTable();
table.Columns.Add("x");
table.Columns.Add("y");
for (double x = x0; x >= xk; x += dx)
{
double y = x * Math.Sin(Math.Sqrt(x + b - 0.0084));
table.Rows.Add(x, y);
}
// Строим график функции
chart1.Series.Clear();
chart1.ChartAreas[0].AxisX.Minimum = xk;
chart1.ChartAreas[0].AxisX.Maximum = x0;
chart1.ChartAreas[0].AxisY.Minimum = -10;
chart1.ChartAreas[0].AxisY.Maximum = 10;
chart1.Series.Add("y(x)");
chart1.Series["y(x)"].ChartType = SeriesChartType.Line;
chart1.Series["y(x)"].BorderWidth = 2;
chart1.Series["y(x)"].Color = Color.Blue;
foreach (DataRow row in table.Rows)
{
chart1.Series["y(x)"].Points.AddXY(row["x"], row["y"]);
}
// Строим второй график для произвольной функции
chart1.Series.Add("f(x)");
chart1.Series["f(x)"].ChartType = SeriesChartType.Line;
chart1.Series["f(x)"].BorderWidth = 2;
chart1.Series["f(x)"].Color = Color.Red;
for (double x = xk; x <= x0; x += 0.01)
{
double y = Math.Sin(x) / x;
chart1.Series["f(x)"].Points.AddXY(x, y);
}
}
private void Form1_Load(object sender, EventArgs e)
{
textBox2.Text = "-2,05";
textBox3.Text = "-3,05";
textBox4.Text = " -0,2";
textBox1.Text = "3,4";
}
}
}
Исправь ошибку
|
cab0eedac54e8ecb0ceecb74804832fa
|
{
"intermediate": 0.35660621523857117,
"beginner": 0.508497953414917,
"expert": 0.13489586114883423
}
|
7,842
|
can you code this in C#: Write an object
-
oriented program that manages data for hourly and salaried employees. Your design
must include
A Department class that stores the name of the department and its manager.
A superclass called Employee that holds the
first and last name of the employee as well as the
department they work in.
A subclass of Employee called HourlyEmployee that holds the hourly pay rate and hours worked.
A subclass of Employee called SalariedEmployee that holds the annual pay.
A view class
called EmployeeWriter
An interface called Payable that enables implementing classes to calculate their pay
A factory class called EmployeeFactory that can build HourlyEmployee and SalariedEmployee
objects for a particular department.
|
b5c24b3f4baf6f7bfb5da48b89e6e848
|
{
"intermediate": 0.5368171334266663,
"beginner": 0.36103975772857666,
"expert": 0.10214310884475708
}
|
7,843
|
Please explain in detail, step by step how I would make it so that a WiFi network I own is public but when a person connects to it they are required to read a Terms of Service, acknowledge it, and then click 'Connect' before being able to use it. Include code snippets.
|
01be4fc6642ebde592676b1fa24e54c8
|
{
"intermediate": 0.3928817808628082,
"beginner": 0.3277484178543091,
"expert": 0.27936986088752747
}
|
7,844
|
Write a code on python for autoclicker with selecting clicks per second and bind for turning off and on
|
a84b6f1268dcc237dc3277273d2ac57d
|
{
"intermediate": 0.44557589292526245,
"beginner": 0.10645300894975662,
"expert": 0.4479711055755615
}
|
7,845
|
I have the following latex code
"""
\newcounter{reqcounter}
\newenvironment{requirements}{
\begin{enumerate}
\renewcommand\labelenumi{\theenumi.\phantomsection\protect\addcontentsline{toc}{subsubsection}{\hspace{1em}\textnormal{\requirementtitle}}}
\setcounter{enumi}{\value{reqcounter}}
\newcommand\requirementtitle{}
\newcommand\requirement[1]{\renewcommand\requirementtitle{##1}\item \textbf{##1}\label{req:\theenumi}}
}{
\setcounter{reqcounter}{\value{enumi}}
\end{enumerate}
}
"""
And then I specify items with
"""
\requirement{{Regulation Compliance}}:\\
requirement text
"""
how do I make it so I can crossref with hyperref so
"""
\hyperref[req:1]{Requirement: \ref{req:1}}
"""
would show "Requirement: Regulation Compliance"
and could be clicked as a link to that requirement
|
1f6ca9cf910c907692ad984525f7ddf6
|
{
"intermediate": 0.37375691533088684,
"beginner": 0.32212185859680176,
"expert": 0.3041212558746338
}
|
7,846
|
sudo tee /etc/docker/daemon.json <<-'EOF'
|
20a8b8e0b29e595e1790a463bb07ce22
|
{
"intermediate": 0.3231167197227478,
"beginner": 0.2730731666088104,
"expert": 0.40381014347076416
}
|
7,847
|
i have a kotlin app in which i use xmlpullparser. i have an xml file which has an items tag, and inside of it there are elements with item tag. how do i go through all of the tags named item, and read property called id of all of them?
|
11d5e0aecc86ef412b1d7b726e8490f4
|
{
"intermediate": 0.7651963233947754,
"beginner": 0.1046656146645546,
"expert": 0.1301380693912506
}
|
7,848
|
Stack overflow.
Repeat 24105 times:
--------------------------------
at Parashumti___OOP_Program.Employee.set_Firstname(System.String)
--------------------------------
at Parashumti___OOP_Program.EmployeeFactory.CreateHourlyEmployee(System.String, System.String, Double, Double, Parashumti___OOP_Program.Department)
at Parashumti___OOP_Program.Program.Main(System.String[])
|
35fd245eda133899541cf995bb0b11e0
|
{
"intermediate": 0.2943832576274872,
"beginner": 0.4764380156993866,
"expert": 0.22917874157428741
}
|
7,849
|
make a chess games suing python and simple
|
48eb9eaa42381dd0fd9619af031f11f3
|
{
"intermediate": 0.3040909171104431,
"beginner": 0.4746605455875397,
"expert": 0.22124846279621124
}
|
7,850
|
rewrite the following code with the expertise of a experienced senior webdesign creator, specialized on CSS and userChrome.css
Code:
'
:root {
--tab-min-height: 30px !important;
--toolbar-bgcolor: #1c1b22 !important;
}
.tabbrowser-arrowscrollbox {
display: none !important;
}
.scrollbox-innerbox {
display: flex !important;
}
/* Show the close button */
.titlebar-close {
display: block !important;
}
/* Remove minimize and maximize buttons */
.titlebar-min,
.titlebar-restore {
display: none !important;
}
/* Customize tab label appearance */
.tabbrowser-tab .tab-label {
color: #ffffff !important; /* Adjust color for tab label */
font-weight: bold !important; /* Set font weight for tab label */
font-size: 12px !important; /* Set font size for tab label */
}
.tabbrowser-tab .tab-label[selected="true"] {
color: #ffffff !important; /* Adjust color for selected tab label */
font-weight: bold !important; /* Set font weight for selected tab label */
font-size: 14px !important; /* Set font size for selected tab label */
}
/* Style pinned tabs */
.tabbrowser-tab[pinned] {
border: none !important; /* Remove border from pinned tabs */
background-color: #313240 !important; /* Set background color for pinned tabs */
}
.tabbrowser-tab[pinned]:hover {
background-color: #40414c !important; /* Adjust background color for pinned tabs on hover */
}
/* Adjust width and padding of pinned tabs */
.tabbrowser-tab[pinned] {
width: auto !important; /* Set auto width for pinned tabs */
}
.tab-content[pinned] {
padding-inline: 10px !important; /* Adjust horizontal padding for pinned tabs */
}
/* Customize close button */
.tab-close-button {
width: 16px !important; /* Set width for close button */
height: 16px !important; /* Set height for close button */
background-color: transparent !important; /* Set background color for close button */
background-image: none !important; /* Remove background image from close button */
background-repeat: no-repeat !important;
background-position: center center !important;
background-size: 10px 10px !important;
}
/* Remove shadow on tabs */
.tabbrowser-tab::after {
box-shadow: none !important;
}
/* Add borders to open, active, and selected tabs */
.tabbrowser-tab[selected="true"] {
border: 1px solid #ffffff !important; /* Set border color for selected tab */
}
.tabbrowser-tab[selected="true"]:not([pinned]) {
border-radius: 4px 4px 0 0 !important; /* Add border radius to selected non-pinned tab */
}
.tabbrowser-tab[selected="true"]:not([pinned]):not(:last-child) {
border-right: none !important; /* Remove right border on selected non-pinned tabs except for the last one */
}
.tabbrowser-tab[fadein]:not([selected="true"]) {
border: 1px solid #40414c !important; /* Set border color for open and active tabs */
border-radius: 4px !important; /* Add border radius to open and active tabs */
opacity: 0.7 !important; /* Adjust opacity for open and active tabs */
}
'
|
20b508593993b979f0a8f10e77f072e4
|
{
"intermediate": 0.30021941661834717,
"beginner": 0.42294299602508545,
"expert": 0.27683767676353455
}
|
7,851
|
how to extract output of fast-whisper in txt, srt, etc. fyi i run it on google colab
|
e2a8b71a94517d0b5d83b652c9d3f6c4
|
{
"intermediate": 0.3184565305709839,
"beginner": 0.18611939251422882,
"expert": 0.4954240918159485
}
|
7,852
|
java code to implement a jazz style algorithm to create midi scores with javax.sound.midi
|
26891374ac95ca36eff3ba670026dfef
|
{
"intermediate": 0.3753795027732849,
"beginner": 0.10189968347549438,
"expert": 0.5227208733558655
}
|
7,853
|
Hello
|
232da47b4510e1a5cfb57ee8d2bb0658
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
7,854
|
Can you write a conclusion to a scientific report based on the following experiments section? Use an appropriate writing style that matches the one used in the text.
\section{Experiments}
\subsection{VGG}
\paragraph{}
Different models have been trained. We first tried to add dropout layers with prevent from over-fitting. Then we used data augmentation for the model to be more robust, weight decay, and batch normalization. The following table presents the accuracy on the test set.
All the model were run with the basic model with a momentum of 0.9 with options D = Dropout, DA = data augmentation, BN = batch normalization.
\subsubsection{Normalization with 0-mean and 1-std}
\paragraph{}
We also look if the preparation of the pixel from normalization between 0 and 1 to removing the mean and divide by standard deviation can improve the accuracy.
All the model were run with the basic model with a momentum of 0.9 with options D = Dropout, DA = data augmentation, BN = batch normalization.
\paragraph{}
Comparing to the scaling pixel between 0 and 1, there is a slitly better accuracy on the test dataset, but not a real improvement.
\subsubsection{Adam and AdamW}
\paragraph{}
Now let's look at different learning rate scheduler. We do not used SDG with momentum. Instead we will use Adam and AdamW optimizers.
\paragraph{}
We can observe a sharp increase in the accuracy on test dataset compared to Table 1. The model is way better as it can reach now more than 90\% of accuracy.
\subsubsection{Step, warm-up and restart learing rate scheduler}
\subsection{ResNet}
For ResNet-20, our hyperparameter tuning involved looking for a good training time, weight decay strength (the original paper used 1e-4) and learning rate schedule. In the original paper, the learning rate was divided by 10 at 32k iterations, then by 10 again at 48k, and ran for 64k iterations, which, with a batch size of 128, is approximately equivalent to 180 epochs. Based on the validation set, our best weight decay strength was 5e-4 (SUBJECT TO REVISION) and the learning rate schedule was a modified exponential decay: (SUBJECT TO REVISION) where is the epoch. We kept the 180-epoch training time (SUBJECT TO REVISION).
The only data augmentation used in the original paper was reproduced: adding 4 pixels of zero padding on every side of the image, then randomly cropping a $32\times 32$ crop from the enlarged image, with a random chance of horizontally flipping the image. We got rid of the horizontal flip, as it doubled the training time without improving the validation accuracy.
For ResNeXt-29 the training time was 300 epochs.
Table \ref{tab:resnet_results} contains the results for our best hyperparameter combinations. The target accuracy for ResNet-20 was $91.25$\%; we reached $90.41$\% (SUBJECT TO REVISION). The target accuracy for ResNeXt-29 was $95.6$\%.
|
06db4d788a10f4f12ef40b1b6375a0ee
|
{
"intermediate": 0.08512487262487411,
"beginner": 0.1242310181260109,
"expert": 0.790644109249115
}
|
7,855
|
Write grammar for basic Go language using bison in C
|
66d000b00406a697deb318e5fde51d40
|
{
"intermediate": 0.26090162992477417,
"beginner": 0.4843480885028839,
"expert": 0.2547502815723419
}
|
7,856
|
reusable favorite and disfavorite angular component using images
|
0e5ba1c5fa64225e0e20859ce3880d57
|
{
"intermediate": 0.436078280210495,
"beginner": 0.336392879486084,
"expert": 0.2275288701057434
}
|
7,857
|
You are a helpful assistant
|
f351d6cdc32f24a72e37f93de84eb5a8
|
{
"intermediate": 0.35207033157348633,
"beginner": 0.28502288460731506,
"expert": 0.3629068434238434
}
|
7,858
|
i have list of products with each one of them like button to mark is as a favorite product, how make this compontent reusable to like and dislike the product in angular
|
ffec4f4c15d2ea1b17fb6fa77d98d0da
|
{
"intermediate": 0.4146161675453186,
"beginner": 0.2852642238140106,
"expert": 0.3001196086406708
}
|
7,859
|
l=im2double(imread('cancercell.jpg'));
f1=fft(l);
f2=fftshift(f1);
subplot(2,2,1); imshow(abs(f1)); title('Frequency Spectrum');
subplot(2,2,2); imshow(abs(f2)); title('Centered Spectrum');
f3=log(1+abs(f2));
subplot(2,2,3); imshow(f3); title('log(1+abs(f2))');
l=fft2(f1);
l1=real(l);
subplot(2,2,4); imshow(l1);title(' 2-D FFT');
|
1f9632c2d4b339a987193c666d77c76e
|
{
"intermediate": 0.38147950172424316,
"beginner": 0.331072062253952,
"expert": 0.2874484658241272
}
|
7,860
|
Write me a blog article structure in html
|
b63f3744e9ad556ee8fe97908466567d
|
{
"intermediate": 0.26405414938926697,
"beginner": 0.25412023067474365,
"expert": 0.4818256199359894
}
|
7,861
|
when writing an xml parser in kotlin, is it a bad idea to "nest" xml parsers, so that after parsing one value, i request a different file and read details from it before moving on to the next value?
|
4379103857e5e41ca0faa3d75c973535
|
{
"intermediate": 0.6457731127738953,
"beginner": 0.10810433328151703,
"expert": 0.24612264335155487
}
|
7,862
|
give me an SQL sentence that swap the values of two columns values depending on a condition I already have
|
3625e77c03980a7a1b5f6c33653439d8
|
{
"intermediate": 0.34055954217910767,
"beginner": 0.36258330941200256,
"expert": 0.2968571186065674
}
|
7,863
|
нужно изменить этот код так, чтобы каждая точка имела свой размер (size)
не переписывай весь код, только там, где нужно поправить
код:
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 texture = new THREE.TextureLoader().load(‘texture4.png’);
let startSize = 0.06;
const sizeVariation = 0.1;
const materialPoint = new THREE.PointsMaterial({
size: startSize,
sizeAttenuation: true,
map: texture,
alphaTest: 0.01,
// blending: THREE.AdditiveBlending,
transparent: true,
// vertexColors: THREE.VertexColors,
color: new THREE.Color(1., 1., 1.),
opacity: 1.
});
const geometryPoint = new THREE.BufferGeometry();
const positions = geometry.getAttribute(‘position’).array;
const randomSize = [];
for (let i = 0; i < positions.length; i += 3) {
const size = startSize + (Math.random() * sizeVariation);
randomSize.push(size, size, size);
}
geometryPoint.setAttribute(‘size’, new THREE.Float32BufferAttribute(randomSize, 1));
const randomPosition = [];
for (let i = 0; i < positions.length; i += 3) {
randomPosition.push(10.0Math.random()-5.0, 10.0Math.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;
}
animateVerticles();
function animateVerticles() {
requestAnimationFrame(animateVerticles);
time += 0.1;
sinPosition = Math.sin(time)0.1;
cosPosition = Math.cos(time0.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;
}
console.log(ratio);
});
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);
function animate() {
requestAnimationFrame(animate);
animatePoint();
pointMesh.position.set(point.x, point.y, point.z);
controls.update();
renderer.render(scene, camera);
}
animate();
});
|
ffd230dddb45f39132e7b5664edd7c64
|
{
"intermediate": 0.31775912642478943,
"beginner": 0.4405016005039215,
"expert": 0.24173924326896667
}
|
7,864
|
Write an LSL script for a door
|
41f6651ce434a13823eff8202d6fa9ee
|
{
"intermediate": 0.23591108620166779,
"beginner": 0.3384575843811035,
"expert": 0.4256313443183899
}
|
7,865
|
//@version=5
indicator("Bollinger Bands with Weighted Volatility", overlay=false)
// Input Variables
length = input.int(title="Length", defval=20, minval=1)
deviations = input.float(title="Deviations", defval=2.0, minval=0.1, step=0.1)
volatility_length = input.int(title="Volatility Length", defval=20, minval=1)
// Calculate Bollinger Bands
source = close
basis = ta.sma(source, length)
dev = deviations * ta.stdev(source, length)
upper = basis + dev
lower = basis - dev
// Calculate Volatility Weighted by Volume
volatility = ta.stdev(change(source), volatility_length)
volatility_weighted = volatility * ta.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 = ta.scalediff(high, low) * 2
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_y=true, scale=scale.inherit, min=0, max=volatility_scale)
|
760f9ed11325bda18293b8dc618f8d5e
|
{
"intermediate": 0.3596703112125397,
"beginner": 0.35145777463912964,
"expert": 0.2888718545436859
}
|
7,866
|
من هذا الكود package com.test.photoeditor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var originalImage: Bitmap
private lateinit var imageView: ImageView
private lateinit var maskView: View
private lateinit var result: Bitmap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
originalImage = BitmapFactory.decodeResource(resources, R.drawable.cat)
imageView = findViewById(R.id.imageView)
imageView.setImageBitmap(originalImage)
maskView = findViewById(R.id.maskView)
maskView.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(v: View, event: MotionEvent): Boolean {
val x = event.x
val y = event.y
// Convert the touch coordinates to the coordinates of the mask image.
val maskX = (x - maskView.left) / maskView.width
val maskY = (y - maskView.top) / maskView.height
// Update the mask image.
val maskBitmap = Bitmap.createBitmap(
originalImage.width,
originalImage.height,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(maskBitmap)
val paint = Paint()
paint.color = Color.WHITE
canvas.drawRect(
0f,
0f,
originalImage.width.toFloat(),
originalImage.height.toFloat(),
paint
)
paint.color = Color.BLACK
canvas.drawRect(
maskX * originalImage.width,
maskY * originalImage.height,
(maskX + 1) * originalImage.width,
(maskY + 1) * originalImage.height,
paint
)
// Initialize the result bitmap.
result = Bitmap.createBitmap(
originalImage.width,
originalImage.height,
Bitmap.Config.ARGB_8888
)
// Resize the mask bitmap to the same size as the result bitmap.
val resizedMaskBitmap =
Bitmap.createScaledBitmap(maskBitmap, result.width, result.height, true)
// Update the image view.
imageView.setImageBitmap(
removeBackground(
originalImage,
resizedMaskBitmap
) as Bitmap
)
return true
}
})
}
private fun removeBackground(image: Bitmap, mask: Bitmap): Bitmap {
val canvas = Canvas(result)
val paint = Paint().apply {
xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN)
}
canvas.drawBitmap(image, 0f, 0f, null)
canvas.drawBitmap(mask, 0f, 0f, paint)
paint.xfermode = null
paint.color = Color.TRANSPARENT
return result
}
} يحدث هذا الخطا 2023-05-23 21:13:58.724 11834-11834 MirrorManager com.test.photoeditor W this model don't Support
2023-05-23 21:14:16.284 11834-14741 est.photoeditor com.test.photoeditor I Background concurrent copying GC freed 366895(15MB) AllocSpace objects, 0(0B) LOS objects, 49% free, 3427KB/6854KB, paused 239us,68us total 101.975ms
2023-05-23 21:14:16.303 11834-11834 FinalizerDaemon com.test.photoeditor W type=1400 audit(0.0:303790): avc: denied { getopt } for path="/dev/socket/usap_pool_primary" scontext=u:r:untrusted_app:s0:c21,c261,c512,c768 tcontext=u:r:zygote:s0 tclass=unix_stream_socket permissive=0
2023-05-23 21:14:16.313 11834-14743 System com.test.photoeditor W A resource failed to call close. ما الحل
|
e68ce403003651932c55640af2c50ebb
|
{
"intermediate": 0.4113221764564514,
"beginner": 0.5104601979255676,
"expert": 0.07821764051914215
}
|
7,867
|
Can you find any problem with the following code /* eslint-disable no-unused-vars */
import { createSlice } from '@reduxjs/toolkit';
import axios from '../api/api';
const initialState = {
word: null,
nounList: {
masculine: [],
feminine: [],
},
isCorrect: null,
score: 0,
};
export const wordsSlice = createSlice({
name: 'words',
initialState,
reducers: {
setWord: (state, action) => {
state.word = action.payload;
state.isCorrect = null;
},
setNouns: (state, action) => {
state.nounList = action.payload;
},
setCorrect: (state) => {
state.isCorrect = true;
state.score++;
},
setWrong: (state) => {
state.isCorrect = false;
},
setTranslation: (state, action) => {
state.translation = action.payload;
},
setCorrectArticle: (state, action) => {
state.correctArticle = action.payload.article;
state.correctEnding = action.payload.ending;
},
},
});
export const {
setWord,
setNouns,
setCorrect,
setWrong,
setTranslation,
setCorrectArticle,
} = wordsSlice.actions;
export const selectWord = (state) => state.words.word;
export const selectNouns = (state) => state.words.nounList;
export const selectIsCorrect = (state) => state.words.isCorrect;
export const selectScore = (state) => state.words.score;
export const selectTranslation = (state) => state.words.translation;
const config = {
headers: {
Authorization: `Bearer ${
JSON.parse(localStorage.getItem('userInfo')).accessToken
}`,
},
};
export const fetchWord = () => async (dispatch) => {
try {
const response = await axios.get('/words/random', config);
dispatch(setWord(response.data));
} catch (error) {
console.error(error);
}
};
export const fetchNouns = () => async (dispatch) => {
try {
const [masculineResponse, feminineResponse] = await Promise.all([
axios.get('/words/masculine', config),
axios.get('/words/feminine', config),
]);
console.log(masculineResponse.data, feminineResponse.data);
dispatch(
setNouns({
masculine: masculineResponse.data,
feminine: feminineResponse.data,
})
);
} catch (error) {
console.error(error);
}
};
export const fetchTranslation = (word) => async (dispatch) => {
try {
const response = await axios.get(`/words/example?word=${word}`, config);
console.log(response.data);
return response.data;
} catch (error) {
console.error(error);
}
};
// export const submitAnswer = (selected) => (dispatch, getState) => {
// const word = selectWord(getState());
// const isCorrect = selected === (word.gender === 'm' ? 'UN/LE' : 'UNE/LA');
// if (isCorrect) {
// dispatch(setCorrect());
// } else {
// dispatch(setWrong());
// }
// };
export const submitAnswer = (selected) => async (dispatch, getState) => {
const { word, gender } = selectWord(getState());
const isCorrect = selected === (word.gender === 'm' ? 'UN/LE' : 'UNE/LA');
if (isCorrect) {
dispatch(setCorrect());
const translation = await dispatch(fetchTranslation(word.word));
console.log(translation);
} else {
dispatch(setWrong());
let correctArticle = gender === 'masculine' ? 'LE' : 'LA';
let correctEnding = '';
for (let ending of gender === 'masculine'
? selectNouns(getState()).masculine
: selectNouns(getState()).feminine) {
if (word.word.endsWith(ending)) {
correctEnding = ending;
break;
}
}
if (!correctEnding) {
correctEnding = word.word;
}
dispatch(
setCorrectArticle({ article: correctArticle, ending: correctEnding })
);
}
dispatch(fetchTranslation(word.word));
dispatch(nextWord());
};
export const nextWord = () => (dispatch) => {
dispatch(fetchWord());
};
export default wordsSlice.reducer;
|
143630b0440f0ee470541061d9c70b04
|
{
"intermediate": 0.3300536274909973,
"beginner": 0.4392264187335968,
"expert": 0.2307199388742447
}
|
7,868
|
в этом коде каждая точка должна иметь разный размер, но сейчас они все одинаковые, в чем ошибка?
код:
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 texture = 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.06;
const size = startSize + (Math.random() * sizeVariation);
randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z]
}
// let startSize = 0.06;
const materialPoint = new THREE.PointsMaterial({
size: 1, // задаем произвольный стартовый размер, он будет изменен в цикле анимации
sizeAttenuation: true,
map: texture,
alphaTest: 0.01,
transparent: true,
color: new THREE.Color(1., 1., 1.),
opacity: 1.
});
geometryPoint.setAttribute('size', new THREE.BufferAttribute(new Float32Array(randomSize), 3));
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));
// 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;
}
console.log(ratio);
});
scene.add(points);
points.rotateX(Math.PI/2.0);
}
});
camera.position.z = 3;
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
});
|
2b35c13efa26daa537a997d781631b14
|
{
"intermediate": 0.24922561645507812,
"beginner": 0.6104835271835327,
"expert": 0.14029082655906677
}
|
7,869
|
am trying to get error handling using slack bolt v3.13.1
This is an example of an action register in app.ts
app.action(CONSTANTS.actionsIds.leaveDay, leaveDayCallback);
THis is leaveDayCallback (ignore the commented code as I'm just testing)
import {
BlockButtonAction,
Middleware,
SlackActionMiddlewareArgs
} from '@slack/bolt';
export const leaveDayCallback: Middleware<
SlackActionMiddlewareArgs<BlockButtonAction>
> = async ({ body, ack, client, say, respond }) => {
try {
await ack();
console.log(respond);
console.log(say);
throw new Error('Not implemented');
// const date = parseISO(body.actions[0].value);
// const { startDate, endDate, defaultDateRange } = JSON.parse(
// body.view?.private_metadata || ''
// );
// const user = await getUserBySlackId(body.user.id);
// const currentOfficeId = user?.settings?.currentOfficeId;
// const currentOfficeName = user?.settings?.currentOffice.name;
// if (!currentOfficeId) {
// throw new Error('No current office id...');
// }
// await deleteBooking(body.user.id, currentOfficeId, date);
// const { officeChatMembers, officeChatExists } =
// await getOfficeChatAndMembers(client, currentOfficeId);
// if (!officeChatMembers) {
// throw new Error('No chat office chat members...');
// }
// const parsedStartDate = parseISO(startDate);
// const parsedEndDate = parseISO(endDate);
// const bookings = await getBookingsByOfficeId(
// currentOfficeId,
// parsedStartDate,
// parsedEndDate
// );
// const offices = await getOffices();
// const homeData: HomeData = {
// user: {
// slackId: user.slackId,
// isAdmin: user?.isAdmin || false
// },
// dateRangeSelector: {
// defaultDateRange: defaultDateRange,
// startDate: parsedStartDate,
// endDate: parsedEndDate
// },
// officeData: {
// currentOfficeId: currentOfficeId,
// currentOfficeName: currentOfficeName,
// bookings: bookings
// },
// officeDataSelector: {
// data: offices
// },
// officeChat: {
// officeChatExists: officeChatExists,
// officeChatMembers: officeChatMembers
// }
// };
// await client.views.publish({
// user_id: body.user.id,
// trigger_id: body.trigger_id,
// view: home(homeData),
// response_action: 'clear'
// });
} catch (error) {
console.error(error);
await say('Something went wrong');
}
};
But say, and respond are showing as undefined. I want to be able to show the user error messages inside the slack app to show something went wrong
|
116216956b88bed967cc2401b0dc6dcc
|
{
"intermediate": 0.33086156845092773,
"beginner": 0.4287978410720825,
"expert": 0.24034065008163452
}
|
7,870
|
rewrite the below Code into short, clean and precise(professional and structured) by follwing below three points:
* try to more accurate and use common function
* try to understand everything so after you got the logic you can do following.
* try to keep the code redundancy to a minimum, make use of viewset level settings + common functions,
* Make it as modular as possible.
Code:
def list(self, request, *args, **kwargs):
cursor = self.request.query_params.get('cursor', None)
paginator = self.get_paginator(cursor)
location = filter_and_integerise(self.request.query_params.getlist('location_id', None))
microlocation = filter_and_integerise(self.request.query_params.get('microlocation_id', None))
current_version_code = request.user.app_version_code or 16
post_id = self.request.query_params.get('post_id', None)
# for easier testing
es_feed_flag = self.request.query_params.get('es', False)
content_formats = self.request.query_params.get('content_formats', '')
# Location handling for recommendation
if not location and post_id:
location = [request.user.location_id]
location_title, states, location_set = get_states(location)
if states:
es_feed_flag = True
if settings.DJANGO_SERVER_ENVIRONMENT != "production":
es_feed_flag = False
user_day = filter_and_integerise(request.META.get('HTTP_DAY_COUNT', None))
lokalints = LokalInts()
if lokalints.CATEGORY_HOME_FEED is None:
home_feed_categories = Category.objects.filter(is_active=True, is_home_feed=True).values_list("id", flat=True)
lokalints.CATEGORY_HOME_FEED = list(home_feed_categories)
# Content A/B test experiment
user_cohort = ContentABTestManager.get_user_cohort(request.user.id, location_set)
post_type = self.request.query_params.get('post_type', None)
source = self.request.query_params.get('source', None)
user_id = filter_and_integerise(self.request.query_params.get('user_id', None))
category = filter_and_integerise(self.request.query_params.get('category_id', None))
if post_id:
recommendation_type = self.request.query_params.get('recommendation_type', 0)
feed_type = self.request.query_params.get('feed_type', ArticlePageFeedType.SCROLL)
if str(category) == str(settings.CATEGORY_ID_REAL_ESTATE):
# Send empty recommendation for app version < 293
# For version >=293, send chronologically sorted list of posts from same location.
return self.get_real_estate_recommendations(paginator, post_id, post_type, request, user_day,
{'location_title': location_title, 'source': source,
'states': states,
'recommendation_type': recommendation_type,
'location_set': location_set,
'feed_type': feed_type,
'user_id': user_id or request.user.pk},
user_cohort)
tags = self.request.query_params.getlist('tag_id', None)
tags = filter_and_integerise(tags)
return self.get_recommendations(paginator, post_id, post_type, request, user_day,
{'location_title': location_title, 'source': source, 'states': states,
'recommendation_type': recommendation_type, 'location_set': location_set,
'feed_type': feed_type, 'user_id': user_id or request.user.pk,
'content_formats': content_formats, 'category': category, 'tags': tags},
user_cohort)
if user_id is not None:
submission_category = filter_and_integerise(request.query_params.getlist("submission_category"))
return self.get_user_posts(paginator, user_id, request,
{'location_title': location_title, 'location_set': location_set,
'submission_category': submission_category})
subcategories = filter_and_integerise(self.request.query_params.getlist('subcategory_id', None))
tags = filter_and_integerise(self.request.query_params.getlist('tag_id', None))
if category and str(category) == str(settings.CATEGORY_ID_REAL_ESTATE):
return self.get_real_estate_feed(location_set, paginator, request, tags)
if tags:
return self.get_tagged_posts(paginator, post_type, tags, request, cursor, {'states': states,
'location_title': location_title,
'location_set': location_set},
user_cohort, category)
if not hasattr(request, 'uuid'):
request.uuid = str(uuid.uuid4())
if not hasattr(request, 'to_send'):
percentage_to_log = Setting.get("PERCENTAGE_TO_LOG", default=10000)
switch_post_logging = Setting.get("SWITCH_POST_LOGGING", default=False)
request.to_send = randint(1, percentage_to_log) <= 1 and switch_post_logging
start_time = time.time()
queryset = self.get_posts_queryset(current_version_code, post_type, exclude_real_estate=True)
if es_feed_flag:
es_query = self.get_es_posts_query(current_version_code, post_type)
requested_locale = request.LANGUAGE_CODE
recommendations_config = request.query_params.get('config', "{}")
try:
recommendations_config = json.loads(recommendations_config)
except JSONDecodeError:
recommendations_config = dict()
trending_variant = int(recommendations_config.get('trending_page', 0))
# category_nonzero = list(filter(check_invalid, category))
category_nonzero = category if check_invalid(category) else None
filter_on_location = FilterOnLocation.DISTRICT_AND_STATE
category_details = dict()
# Check if category is to be filtered on location
if category is not None:
if category in [LokalInts.CATEGORY_LOCAL, LokalInts.CATEGORY_JOBS, LokalInts.CATEGORY_VIDEO]:
filter_on_location = FilterOnLocation.DISTRICT_AND_STATE
else: # category > 2:
try:
category_details = self.get_category_details(category)
filter_on_location = category_details['location_based_filtering']
# TODO: need to remove
if trending_variant != 0 and category_details.get('english_name') == 'Trending':
cursor_obj = paginator.decode_cursor_only(cursor)
if cursor_obj.reverse:
trending_feed = []
else:
trending_feed = self.get_trending_feed(category, location, trending_variant, cursor,
user_cohort)
response = paginator.get_paginated_response(trending_feed)
return response
except Category.DoesNotExist:
pass
# For the categories which will have polls only
if cursor is not None and category_details.get('posts_type', None) == CategoryType.POLLS_ONLY:
pollviewset = PollViewSet()
polls_response = pollviewset.list(request, *args, **kwargs)
return polls_response
# ! CATEGORY BASED FILTERING !
# Show the category that has been asked for # checking for empty list
if category_nonzero:
queryset = queryset.filter(categories__id=category_nonzero)
if es_feed_flag:
es_query = es_query.query(esq('bool', must=[esq('nested', path='categories', query=esq('bool', should=[
esq('match', categories__id=category_nonzero)]))]))
elif category == 0:
queryset = queryset.filter(type=PostType.VIDEO)
if es_feed_flag:
es_query = es_query.query(esq('bool', must=esq('match', type=PostType.VIDEO)))
campaign = get_user_campaign()
if campaign:
category_id = campaign.upload_category_id
queryset = queryset.exclude(categories__id=category_id)
if es_feed_flag:
es_query = es_query.query(
esq('bool', must=[esq('nested', path='categories', query=esq('bool', must_not=[
esq('match', categories__id=category_id)]))]))
# ! SUBCATEGORY BASED FILTERING !
if subcategories:
queryset = queryset.filter(ugc_categories__id__in=subcategories)
return queryset
|
a704d260726d88f6be43602ead874362
|
{
"intermediate": 0.3217100203037262,
"beginner": 0.4420923888683319,
"expert": 0.23619765043258667
}
|
7,871
|
I have this query in react with firebase
let financialData = getTwoQueryDocByCollectionAndDate(
"profile",
"residentialsIds",
"array-contains",
"hspYWQ7JliJRQbeWx10N", //CDI ID
"mora",
"==",
0,
fechaInicio,
fechaFinal
).then((userFinancialData) => setUserFinancialData(userFinancialData));
modify the query to include a field called "code" that the value is something like this "P-001" and others that are "P-001/1". I dont want to include the codes that has "/"
|
821320c2faf35c43d8d309c608746c39
|
{
"intermediate": 0.5387642979621887,
"beginner": 0.24488124251365662,
"expert": 0.2163543999195099
}
|
7,872
|
hi
|
cd66fc580c972ff3e3be2a691f0d4e8f
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
7,873
|
Make a code for a presentation on Good Omens by Terry Pratchett and Neil Gaiman, including the plot of all the chapters, describing the main characters, their character, using looks from the TV series of the same name.
|
61ff56ba8e5f1ca091fc3ff88e94bba4
|
{
"intermediate": 0.30999088287353516,
"beginner": 0.3068790137767792,
"expert": 0.38313013315200806
}
|
7,874
|
/home/abdugaffor/Case/Qt projects/untitled/mainwindow.cpp:166: ошибка: extended character “ is not valid in an identifier
../untitled/mainwindow.cpp:166:55: error: extended character “ is not valid in an identifier
166 | QList<QPropertyAnimation> animations = item->property(“animations”).value<QList<QPropertyAnimation>>();
| ^
|
75a69663dd14fa522a3e696217f45a34
|
{
"intermediate": 0.3788537383079529,
"beginner": 0.35908281803131104,
"expert": 0.2620634436607361
}
|
7,875
|
Create a game that helps users learn the gender of French words. The game will show a French word with examples of usage and ask the user to select the correct article ("UN" or "UNE", "LE" or "LA" randomly). The user's selection will be checked for correctness and the end of the word will be highlighted in red or green to indicate correctness, if the word does not match any rule from Appendix A highlight the whole word. The game will also allow users to click on a word to view its translation and examples of usage. Using react, redux, bootsratp, postgres with typeorm and nestjs. Make sure it has the following features implemented Features
User authentication: Users will be able to create accounts and log in.
Word database: A database of French words and their genders will be created and populated using PostgreSQL. (list of words in Appendix A)
Game interface: The game will have a simple and intuitive interface, with a French word displayed and a prompt to select the correct article. Users can also click on a word to view its translation and examples of usage.
Feedback mechanism: After the user makes their selection, the game will provide immediate feedback by highlighting the end of the word in red or green to indicate correctness.
Progress tracking: User progress will be tracked and saved in the database. Authenticated Users will be able to see their progress in a list of unknown words, well-known words, and words that need to be learned.
Mobile-responsive design: The game will be mobile-responsive and work well on different screen sizes. This is the json for Appendix A {
"masculineEndings": [
"age",
"aire",
"isme",
"ment",
"oir",
"sme",
"é"
],
"feminineEndings": [
"ade",
"ance",
"ence",
"ette",
"ie",
"ine",
"ion",
"ique",
"isse",
"ité",
"lle",
"ure"
]
}
add it to the database and also the create a words database with the following json as example {
"id": 983,
"word": "coûter",
"frequency": "984",
"types": [
"v"
],
"gender": null,
"translation_en": [
"to cost"
],
"example": {
"phrase": "cette décision va coûter des milliards de dollars",
"tranlation_en": "this decision will cost billions of dollars"
}, }
|
908fa517abbaa7414f6538a3d966e909
|
{
"intermediate": 0.6682989001274109,
"beginner": 0.14006845653057098,
"expert": 0.19163264334201813
}
|
7,876
|
#include "mainwindow.h"
#include <QMenuBar>
#include <QInputDialog>
#include <QDialogButtonBox>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QVBoxLayout>
#include <QGraphicsPolygonItem>
#include <QGraphicsItem>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
setWindowTitle("QT-GI-15");
// Создание QGraphicsView для отображения
scene = new QGraphicsScene();
QGraphicsItem *item = new QGraphicsRectItem();
scene->addItem(item);
view = new QGraphicsView(scene);
setCentralWidget(view);
// Создание меню с действиями
QMenu *fileMenu = new QMenu("File");
showPictureAction = new QAction("Show picture");
connect(showPictureAction, &QAction::triggered, this, &MainWindow::showPicture);
fileMenu->addAction(showPictureAction);
chooseAction = new QAction("Choose");
connect(chooseAction, &QAction::triggered, this, &MainWindow::choose);
fileMenu->addAction(chooseAction);
animateAction = new QAction("Animate");
connect(animateAction, &QAction::triggered, this, &MainWindow::animate);
fileMenu->addAction(animateAction);
stopAction = new QAction("Stop");
connect(stopAction, &QAction::triggered, this, &MainWindow::stop);
fileMenu->addAction(stopAction);
quitAction = new QAction("Quit");
connect(quitAction, &QAction::triggered, this, &MainWindow::quit);
fileMenu->addAction(quitAction);
menuBar()->addMenu(fileMenu);
// Создание окна выбора
chooseDialog = new QDialog();
chooseDialog->setWindowTitle("Choose");
speedLabel = new QLabel("Speed:");
directionLabel = new QLabel("Direction:");
upDownRadioButton = new QRadioButton("Up-Down");
leftRightRadioButton = new QRadioButton("Left-Right");
speedLineEdit = new QLineEdit();
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, &QDialogButtonBox::accepted, chooseDialog, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, chooseDialog, &QDialog::reject);
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(speedLabel);
layout->addWidget(speedLineEdit);
layout->addWidget(directionLabel);
layout->addWidget(upDownRadioButton);
layout->addWidget(leftRightRadioButton);
layout->addWidget(buttonBox);
chooseDialog->setLayout(layout);
}
MainWindow::~MainWindow()
{
delete chooseDialog;
delete scene;
delete view;
}
void MainWindow::showPicture()
{
// Очистка сцены и создание объекта для отображения
scene->clear();
QBrush brush(Qt::red);
QPen blackpen(Qt::black);
blackpen.setWidth(2);
QGraphicsRectItem *rect = new QGraphicsRectItem(-50, -25, 100, 50);
rect->setBrush(brush);
rect->setPen(blackpen);
QGraphicsEllipseItem *ellipse = new QGraphicsEllipseItem(-30, -20, 60, 40);
ellipse->setBrush(brush);
ellipse->setPen(blackpen);
QPolygonF triangle;
triangle << QPointF(0, -25) << QPointF(-25, 25) << QPointF(25, 25);
QGraphicsPolygonItem *polygon = new QGraphicsPolygonItem(triangle);
polygon->setBrush(brush);
polygon->setPen(blackpen);
QVector<QPointF> trapeziumPoints;
trapeziumPoints << QPointF(-50, -25) << QPointF(50, -25) << QPointF(30, 25) << QPointF(-30, 25);
QGraphicsPolygonItem *trapezium = new QGraphicsPolygonItem(QPolygonF(trapeziumPoints), item);
trapezium->setPen(QPen(Qt::black));
trapezium->setBrush(QBrush(Qt::red));
QGraphicsPolygonItem *polygonObj = new QGraphicsPolygonItem(QPolygonF(triangle), item);
polygonObj->setPen(QColor(Qt::black));;
polygonObj->setBrush(Qt::red);
QGraphicsItemGroup *item = new QGraphicsItemGroup();
item->addToGroup(rect);
item->addToGroup(ellipse);
item->addToGroup(polygon);
item->addToGroup(trapezium);
item->setPos(0, 0);
scene->addItem(item);
// Центрирование объекта
int x = (view->viewport()->width() - item->boundingRect().width()) / 2;
int y = (view->viewport()->height() - item->boundingRect().height()) / 2;
item->setPos(x, y);
}
void MainWindow::choose()
{
// Отображение окна выбора
if (chooseDialog->exec() == QDialog::Accepted) {
// Задание направления движения объекта
int angle;
if (upDownRadioButton->isChecked()) {
angle = 90;
} else {
angle = 0;
}
// Задание скорости движения объекта
int speed = speedLineEdit->text().toInt();
// Запись параметров движения в свойства объекта
item->setData(0, angle);
item->setData(1, speed);
}
}
void MainWindow::animate()
{
// Проверка наличия объекта на сцене
if (item == nullptr) {
return;
}
// Циклическое перемещение объекта на заданную угловую дистанцию
int start = 0;
int end = 200;
int angle = item->setData("angle").toInt();
QPropertyAnimation animation = new QPropertyAnimation(item, "pos");
animation->setDuration(1000 / item->property("speed").toInt() * (end - start));
animation->setLoopCount(-1);
animation->setEasingCurve(QEasingCurve::Linear);
QList<QVariant> values1;
values1.append(QVariant(QPointF(0, 0)));
values1.append(QVariant(QPointF(end * qCos(qDegreesToRadians(angle)), end * qSin(qDegreesToRadians(angle)))));
animation->setKeyValueAt(0, values1);
QList<QVariant> values2;
values2.append(QVariant(QPointF(end * qCos(qDegreesToRadians(angle)), end * qSin(qDegreesToRadians(angle)))));
values2.append(QVariant(QPointF(0, 0)));
animation->setKeyValueAt(1, values2);
animation->start();
}
void MainWindow::stop()
{
// Остановка анимации
QList<QPropertyAnimation> animations = item->property("animations").value<QList<QPropertyAnimation>>();
foreach (QPropertyAnimation *animation, animations) {
animation->stop();
}
}
void MainWindow::quit()
{
// Завершение приложения
QApplication::exit();
}
/home/abdugaffor/Case/Qt projects/untitled/mainwindow.cpp:151: ошибка: too few arguments to function call, expected 2, have 1
|
5a6e89e195c9e61a20cf35c28fc4ea2a
|
{
"intermediate": 0.31796494126319885,
"beginner": 0.4369152784347534,
"expert": 0.24511979520320892
}
|
7,877
|
write an option pricing function in python using a Firefly Algorithm
|
31dd940a16a55d49a40809622690c5ca
|
{
"intermediate": 0.17382115125656128,
"beginner": 0.14986220002174377,
"expert": 0.6763166785240173
}
|
7,878
|
#include "mainwindow.h"
#include <QMenuBar>
#include <QInputDialog>
#include <QDialogButtonBox>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QVBoxLayout>
#include <QGraphicsPolygonItem>
#include <QGraphicsItem>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
setWindowTitle("QT-GI-15");
// Создание QGraphicsView для отображения
scene = new QGraphicsScene();
QGraphicsItem *item = new QGraphicsRectItem();
scene->addItem(item);
view = new QGraphicsView(scene);
setCentralWidget(view);
// Создание меню с действиями
QMenu *fileMenu = new QMenu("File");
showPictureAction = new QAction("Show picture");
connect(showPictureAction, &QAction::triggered, this, &MainWindow::showPicture);
fileMenu->addAction(showPictureAction);
chooseAction = new QAction("Choose");
connect(chooseAction, &QAction::triggered, this, &MainWindow::choose);
fileMenu->addAction(chooseAction);
animateAction = new QAction("Animate");
connect(animateAction, &QAction::triggered, this, &MainWindow::animate);
fileMenu->addAction(animateAction);
stopAction = new QAction("Stop");
connect(stopAction, &QAction::triggered, this, &MainWindow::stop);
fileMenu->addAction(stopAction);
quitAction = new QAction("Quit");
connect(quitAction, &QAction::triggered, this, &MainWindow::quit);
fileMenu->addAction(quitAction);
menuBar()->addMenu(fileMenu);
// Создание окна выбора
chooseDialog = new QDialog();
chooseDialog->setWindowTitle("Choose");
speedLabel = new QLabel("Speed:");
directionLabel = new QLabel("Direction:");
upDownRadioButton = new QRadioButton("Up-Down");
leftRightRadioButton = new QRadioButton("Left-Right");
speedLineEdit = new QLineEdit();
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, &QDialogButtonBox::accepted, chooseDialog, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, chooseDialog, &QDialog::reject);
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(speedLabel);
layout->addWidget(speedLineEdit);
layout->addWidget(directionLabel);
layout->addWidget(upDownRadioButton);
layout->addWidget(leftRightRadioButton);
layout->addWidget(buttonBox);
chooseDialog->setLayout(layout);
}
MainWindow::~MainWindow()
{
delete chooseDialog;
delete scene;
delete view;
}
void MainWindow::showPicture()
{
// Очистка сцены и создание объекта для отображения
scene->clear();
QBrush brush(Qt::red);
QPen blackpen(Qt::black);
blackpen.setWidth(2);
QGraphicsRectItem *rect = new QGraphicsRectItem(-50, -25, 100, 50);
rect->setBrush(brush);
rect->setPen(blackpen);
QGraphicsEllipseItem *ellipse = new QGraphicsEllipseItem(-30, -20, 60, 40);
ellipse->setBrush(brush);
ellipse->setPen(blackpen);
QPolygonF triangle;
triangle << QPointF(0, -25) << QPointF(-25, 25) << QPointF(25, 25);
QGraphicsPolygonItem *polygon = new QGraphicsPolygonItem(triangle);
polygon->setBrush(brush);
polygon->setPen(blackpen);
QVector<QPointF> trapeziumPoints;
trapeziumPoints << QPointF(-50, -25);
}
ошибка: mainwindow.o: in function `MainWindow::MainWindow(QWidget*)':
|
b9f1ce431a181d1a214c1426200cb025
|
{
"intermediate": 0.31796494126319885,
"beginner": 0.4369152784347534,
"expert": 0.24511979520320892
}
|
7,879
|
в этом коде ошибка:
Uncaught (in promise) TypeError: geometryPoint.addAttribute 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 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.06;
const size = startSize + (Math.random() * sizeVariation);
randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z]
}
// let startSize = 0.06;
const materialPoint = new THREE.PointsMaterial({
size: 1,
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));
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;
}
console.log(ratio);
});
// ________________________________________________________________________________________________________________________________________________
const texture = makeTexture();
texture.needsUpdate = true;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const attributes = {
alpha: {
type: 'f',
value: []
},
customColor: {
type: 'c',
value: []
},
size: {
type: 'f',
value: []
}
};
const uniforms = {
color: {
type: "c",
value: new THREE.Color(0xfffffff)
},
texture: {
type: "t",
value: texture
}
};
const shaderMaterial = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: document.getElementById('vertexshader').textContent,
fragmentShader: document.getElementById('fragmentshader').textContent,
blending: THREE.AdditiveBlending,
transparent: true,
// fog: false,
depthTest: false,
// depthWrite: false
});
// const bufferGeometry = new THREE.BufferGeometry();
let particles = 500;
var colors = new Float32Array( particles * 3 );
var sizesP = new Float32Array( particles );
var color = new THREE.Color();
for ( var i = 0, i3 = 0; i < particles; i ++, i3 += 3 ) {
var x = -1 + Math.random() * 2;
var y = -1 + Math.random() * 2;
var z = -1 + Math.random() * 2;
var d = 1 / Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
x *= d;
y *= d;
z *= d;
color.setHSL( i / particles, 1.0, 0.5 );
colors[ i3 + 0 ] = color.r;
colors[ i3 + 1 ] = color.g;
colors[ i3 + 2 ] = color.b;
sizes[ i ] = 20;
}
geometryPoint.addAttribute( 'customColor', new THREE.BufferAttribute( colors, 3 ) );
geometryPoint.addAttribute( 'size', new THREE.BufferAttribute( sizesP, 1 ) );
geometryPoint.attributes.position.dynamic = true;
// let pointCloud = new THREE.Points(bufferGeometry, shaderMaterial);
const points = new THREE.Points(geometryPoint, shaderMaterial);
function makeTexture() {
const canvas = document.createElement('canvas');
const size = 100;
canvas.width = size;
canvas.height = size;
const context = canvas.getContext('2d');
const gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2);
gradient.addColorStop(0, 'rgba(255, 255, 255, 1)');
gradient.addColorStop(0.9, 'rgba(255, 255, 255, 1)');
gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
return new THREE.Texture(canvas);
}
// ________________________________________________________________________________________________________________________________________________
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);
// ________________________________________________________________________________________________________________________________________________
function animate() {
requestAnimationFrame(animate);
animatePoint();
pointMesh.position.set(point.x, point.y, point.z);
controls.update();
renderer.render(scene, camera);
}
animate();
});
|
7027f045ce4ec2f4c34616235859fd03
|
{
"intermediate": 0.31098708510398865,
"beginner": 0.4546496272087097,
"expert": 0.23436330258846283
}
|
7,880
|
In Python I have dataframe df and code that goes like that:
df
c=pd.get_dummies(df[varsc])
c are newly created dummy variables. I want to replace those columns varsc in df with encoded variables and only for binary variables remove the dominant column (with greater number of 1 in in).
|
f099448a7bd6e0cfc976477fab9d6f1e
|
{
"intermediate": 0.58949214220047,
"beginner": 0.16837769746780396,
"expert": 0.24213016033172607
}
|
7,881
|
void MainWindow::animate()
{
// Получение значения скорости и направления из диалогового окна выбора
int speed = speedLineEdit->text().toInt();
QString direction = "";
if (upDownRadioButton->isChecked()) {
direction = "Up-Down";
} else if (leftRightRadioButton->isChecked()) {
direction = "Left-Right";
}
// Определение направления перемещения объекта
int xDirection = 0, yDirection = 0;
if (direction.toLower() == "up-down") {
yDirection = 1;
} else if (direction.toLower() == "left-right") {
xDirection = 1;
}
// Создание анимации перемещения объекта
QGraphicsItem *item = scene->items().at(0);
QPropertyAnimation *animation = new QPropertyAnimation(item, "pos");
// Анимация перемещения до края окна
animation->setStartValue(item->pos());
animation->setEndValue(QPointF(item->pos().x() + xDirection * view->width(), item->pos().y() + yDirection * view->height()));
animation->setDuration(1000 / speed);
animation->setEasingCurve(QEasingCurve::Linear);
// Создание анимации перемещения обратно
QPropertyAnimation *reverseAnimation = new QPropertyAnimation(item, "pos");
reverseAnimation->setStartValue(animation->endValue());
reverseAnimation->setEndValue(item->pos());
reverseAnimation->setDuration(1000 / speed);
reverseAnimation->setEasingCurve(QEasingCurve::Linear);
// Создание группы параллельных анимаций
QParallelAnimationGroup *group = new QParallelAnimationGroup();
group->addAnimation(animation);
group->addAnimation(reverseAnimation);
// Запуск анимации
group->start();
}
/home/abdugaffor/Case/Qt projects/untitled/mainwindow.cpp:152: ошибка: no matching constructor for initialization of 'QPropertyAnimation'
|
f66f04c6cba24ffd45d3e3420c8af666
|
{
"intermediate": 0.38533344864845276,
"beginner": 0.3352624773979187,
"expert": 0.2794041037559509
}
|
7,882
|
ошибка Uncaught (in promise) TypeError: geometryPoint.Attribute 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 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.06;
const size = startSize + (Math.random() * sizeVariation);
randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z]
}
// let startSize = 0.06;
const materialPoint = new THREE.PointsMaterial({
size: 1,
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));
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;
}
console.log(ratio);
});
// ________________________________________________________________________________________________________________________________________________
const texture = makeTexture();
texture.needsUpdate = true;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const attributes = {
alpha: {
type: 'f',
value: []
},
customColor: {
type: 'c',
value: []
},
size: {
type: 'f',
value: []
}
};
const uniforms = {
color: {
type: "c",
value: new THREE.Color(0xfffffff)
},
texture: {
type: "t",
value: texturePoint
}
};
const shaderMaterial = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: document.getElementById('vertexshader').textContent,
fragmentShader: document.getElementById('fragmentshader').textContent,
blending: THREE.AdditiveBlending,
transparent: true,
// fog: false,
depthTest: false,
// depthWrite: false
});
// const bufferGeometry = new THREE.BufferGeometry();
let particles = 500;
var colors = new Float32Array( particles * 3 );
var sizesP = new Float32Array( particles );
var color = new THREE.Color();
for ( var i = 0, i3 = 0; i < particles; i ++, i3 += 3 ) {
var x = -1 + Math.random() * 2;
var y = -1 + Math.random() * 2;
var z = -1 + Math.random() * 2;
var d = 1 / Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
x *= d;
y *= d;
z *= d;
color.setHSL( i / particles, 1.0, 0.5 );
colors[ i3 + 0 ] = color.r;
colors[ i3 + 1 ] = color.g;
colors[ i3 + 2 ] = color.b;
sizes[ i ] = 20;
}
geometryPoint.Attribute( 'customColor', new THREE.BufferAttribute( colors, 3 ) );
geometryPoint.Attribute( 'size', new THREE.BufferAttribute( sizesP, 1 ) );
geometryPoint.attributes.position.dynamic = true;
// let pointCloud = new THREE.Points(bufferGeometry, shaderMaterial);
const points = new THREE.Points(geometryPoint, shaderMaterial);
function makeTexture() {
const canvas = document.createElement('canvas');
const size = 100;
canvas.width = size;
canvas.height = size;
const context = canvas.getContext('2d');
const gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2);
gradient.addColorStop(0, 'rgba(255, 255, 255, 1)');
gradient.addColorStop(0.9, 'rgba(255, 255, 255, 1)');
gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
return new THREE.Texture(canvas);
}
// ________________________________________________________________________________________________________________________________________________
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);
// ________________________________________________________________________________________________________________________________________________
function animate() {
requestAnimationFrame(animate);
animatePoint();
pointMesh.position.set(point.x, point.y, point.z);
controls.update();
renderer.render(scene, camera);
}
animate();
});
|
d53e14c95b620d267697a5e40d7a58bd
|
{
"intermediate": 0.24817542731761932,
"beginner": 0.5723398923873901,
"expert": 0.17948465049266815
}
|
7,883
|
How to create a character in Maya using only the MEL commands ?
|
d6dffcf910956d0caa6f5dba1aec9e5b
|
{
"intermediate": 0.42716819047927856,
"beginner": 0.23318414390087128,
"expert": 0.33964765071868896
}
|
7,884
|
Implement the following feature Progress tracking: User progress will be tracked and saved in the database. Authenticated Users will be able to see their progress in a list of unknown words, well-known words, and words that need to be learned inside wordSlice /* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
import { createSlice } from '@reduxjs/toolkit';
import axios from '../api/api';
const initialState = {
word: null,
nounList: {
masculine: [],
feminine: [],
},
isCorrect: null,
score: 0,
};
export const wordsSlice = createSlice({
name: 'words',
initialState,
reducers: {
setWord: (state, action) => {
state.word = action.payload;
state.isCorrect = null;
},
setNouns: (state, action) => {
state.nounList = action.payload;
},
setCorrect: (state) => {
state.isCorrect = true;
state.score++;
},
setWrong: (state) => {
state.isCorrect = false;
},
setExample: (state, action) => {
state.example = action.payload.example;
},
setTranslation: (state, action) => {
state.translation = action.payload.example;
},
setCorrectArticle: (state, action) => {
state.correctArticle = action.payload.article;
state.correctEnding = action.payload.ending;
},
},
});
export const {
setWord,
setNouns,
setCorrect,
setWrong,
setTranslation,
setCorrectArticle,
} = wordsSlice.actions;
export const selectWord = (state) => state.words.word;
export const selectNouns = (state) => state.words.nounList;
export const selectIsCorrect = (state) => state.words.isCorrect;
export const selectScore = (state) => state.words.score;
export const selectTranslation = (state) => state.words.translation;
const config = {
headers: {
Authorization: `Bearer ${
JSON.parse(localStorage.getItem('userInfo')).accessToken
}`,
},
};
export const fetchWord = () => async (dispatch) => {
try {
const response = await axios.get('/words/random', config);
dispatch(setWord(response.data));
} catch (error) {
console.error(error);
}
};
export const fetchNouns = () => async (dispatch) => {
try {
const [masculineResponse, feminineResponse] = await Promise.all([
axios.get('/words/masculine', config),
axios.get('/words/feminine', config),
]);
console.log(masculineResponse.data, feminineResponse.data);
dispatch(
setNouns({
masculine: masculineResponse.data,
feminine: feminineResponse.data,
})
);
} catch (error) {
console.error(error);
}
};
export const fetchTranslation = (word) => async (dispatch) => {
try {
const response = await axios.get(`/words/example?word=${word}`, config);
dispatch(setTranslation(response.data));
console.log('Translation', dispatch(setTranslation(response.data)));
} catch (error) {
console.error(error);
}
};
// export const submitAnswer = (selected) => (dispatch, getState) => {
// const word = selectWord(getState());
// const isCorrect = selected === (word.gender === 'm' ? 'UN/LE' : 'UNE/LA');
// if (isCorrect) {
// dispatch(setCorrect());
// } else {
// dispatch(setWrong());
// }
// };
export const submitAnswer = (selected) => async (dispatch, getState) => {
const { word, gender } = selectWord(getState());
const isCorrect = selected === (word.gender === 'm' ? 'UN/LE' : 'UNE/LA');
if (isCorrect) {
dispatch(setCorrect());
const translation = await dispatch(fetchTranslation(word));
console.log('Submit Answer', translation);
} else {
if (!disableClicks) {
dispatch(setWrong());
let correctArticle = gender === 'masculine' ? 'LE' : 'LA';
let correctEnding = '';
for (let ending of gender === 'masculine'
? selectNouns(getState()).masculine
: selectNouns(getState()).feminine) {
if (word.word.endsWith(ending)) {
correctEnding = ending;
break;
}
}
if (!correctEnding) {
correctEnding = word.word;
}
dispatch(
setCorrectArticle({ article: correctArticle, ending: correctEnding })
);
}
dispatch(nextWord());
}
};
export const nextWord = () => (dispatch) => {
dispatch(fetchWord());
};
export default wordsSlice.reducer;
with backend code for the feature arleady implemented as import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
import { GameService } from './game.service';
import { AuthGuard } from '@nestjs/passport';
@UseGuards(AuthGuard('jwt'))
@Controller({
path: 'game_progress',
version: '1',
})
export class GameController {
constructor(private readonly gameService: GameService) {}
@Post('known')
async markWordAsKnown(@Req() req, @Body() body) {
const userId = req.user.id;
const wordId = body.wordId;
console.log(userId, wordId);
return await this.gameService.markWordAsKnown(userId, wordId);
}
@Get('well_known')
async getWellKnownWords(@Req() req) {
const userId = req.user.id;
return await this.gameService.getWellKnownWords(userId);
}
@Get('learned')
async getLearnedWords(@Req() req) {
const userId = req.user.id;
return await this.gameService.getLearnedWords(userId);
}
}
|
37e5d7282aa8db1ce73249a035276951
|
{
"intermediate": 0.29953935742378235,
"beginner": 0.4675498604774475,
"expert": 0.23291076719760895
}
|
7,885
|
get authenticated user spring security webflux
|
e3e3433b00406bf0be6309eb89fa70c0
|
{
"intermediate": 0.4414045810699463,
"beginner": 0.23329511284828186,
"expert": 0.32530027627944946
}
|
7,886
|
write me code for calculating aleatoric and epistemic uncertainty in pyro PPL
|
b0eef342337f05252b21e4d1cf5e313d
|
{
"intermediate": 0.2850663363933563,
"beginner": 0.0942440778017044,
"expert": 0.6206895112991333
}
|
7,887
|
write me pyro code for aleatoric uncertainty
|
9a4f789db5815a0646ac83216d767900
|
{
"intermediate": 0.24681062996387482,
"beginner": 0.2654780447483063,
"expert": 0.4877113103866577
}
|
7,888
|
create an ascii map of a dangerous fantasy planet (with tendrils)
|
4e99b47c2941057861b34e3a18d74063
|
{
"intermediate": 0.3315729796886444,
"beginner": 0.2485196590423584,
"expert": 0.41990742087364197
}
|
7,889
|
Написать SDI-приложение Windows, заголовок главного окна, которого
содержит ФИО, группу и номер варианта - QT-GI-15.
Приложение должно выполнять анимацию изображения.
Создать меню с командами Show picture, Choose, Animate, Stop, Quit.
При выборе команды Quit завершать работу приложения. При выборе
команды Show picture рисовать в центре экрана объект, состоящий из
нескольких графических примитивов (прямоугольник, треугольник,
окружность, трапеция). При выборе команды Choose открывать окно
диалога, содержащее:
□ поле ввода Speed, для ввода скорости движения объекта;
□ группу Direction из двух переключателей (Up-Down, Left-Right)
для выбора направления движения;
□ кнопку типа Button.
При выборе команды Animate перемещать объект в выбранном направлении
до края окна и обратно с заданной скоростью, при выборе команды Stop –
прекращать движение.
c++ qt
build the code in files from scratch till the end please
|
911334caf63aa5d08a34a922a635ae33
|
{
"intermediate": 0.3405146896839142,
"beginner": 0.3577646315097809,
"expert": 0.30172067880630493
}
|
7,890
|
What does gamma (light absorption coefficient) in a Firefly Algorithm mean?
|
fcbf0107f81b5b1631d5cf99cc778131
|
{
"intermediate": 0.10754352062940598,
"beginner": 0.09617029130458832,
"expert": 0.7962862253189087
}
|
7,891
|
Please write a program code or query that will display the addresses of contracts created within the last 24 hours on the Binance Smart Chain network
|
ed4ce7b086a62bd550e555de686dd9d3
|
{
"intermediate": 0.5638740062713623,
"beginner": 0.14373856782913208,
"expert": 0.29238736629486084
}
|
7,892
|
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:
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();
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
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();
private:
bool shutdownInProgress;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
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;
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;
}
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;
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 = ¤tCommandBuffer;
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 ¤tCommandBuffer;
}
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;
}
I don't believe the code is currently making correct use of the graphics pipeline. Can you review and suggest any code changes?
|
c368770a0b68bba57d00d229e80e5d3c
|
{
"intermediate": 0.37079140543937683,
"beginner": 0.40848061442375183,
"expert": 0.22072790563106537
}
|
7,893
|
please generate a blender code for a murikami-style octopus, composed of spheres. the finer details of the squid should not be composed of spheres (for example the teeth and mouth)
|
abaf586b0f7d26d94b6747c5cf22e6dd
|
{
"intermediate": 0.36510947346687317,
"beginner": 0.14274679124355316,
"expert": 0.49214377999305725
}
|
7,894
|
The After copyAsync won't log and neither the database copied successfully
LOG {"_downloadCallbacks": [], "downloaded": false, "downloading": false, "hash": "fbfcfaf5265596e186be62ad7d68983d", "height": null, "localUri": null, "name": "FeladatokAdatbazis", "type": "db", "uri": "http://192.168.0.101:19000/assets/SQLite/FeladatokAdatbazis.db?platform=android&hash=fbfcfaf5265596e186be62ad7d68983d?platform=android&dev=true&hot=false", "width": null}
LOG file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540anonymous%252FFelveteliBazis-8e716041-76ba-4abb-abde-1c8a24f5b726/SQLite/Feladatok.db
LOG Before downloadAsync
LOG After downloadAsync
LOG Before copyAsync
const asset = Asset.fromModule(require('../SQLite/FeladatokAdatbazis.db'));
console.log(asset);
console.log(databasePath);
try {
console.log('Before downloadAsync');
await asset.downloadAsync();
console.log('After downloadAsync');
console.log('Before copyAsync');
await FileSystem.copyAsync({
from: asset.localUri || '',
to: databasePath,
});
console.log('After copyAsync');
console.log('Database copied successfully!');
} catch (error) {
console.error('An error occurred while copying the database:', error);
}
|
169d67148d4785c3abee541b5e54685d
|
{
"intermediate": 0.5070935487747192,
"beginner": 0.2687453031539917,
"expert": 0.22416122257709503
}
|
7,895
|
write a code for matlab that create two cell between every two cell of a column matrix and fill with missing data call "NaN"
|
8382a7cba13c42ce5c0d917a60e69252
|
{
"intermediate": 0.3537314832210541,
"beginner": 0.14467565715312958,
"expert": 0.5015928149223328
}
|
7,896
|
public enum PizzaSize {
Small(6.79), Medium(8.29), Large(9.49), ExtraLarge(10.29), Fete(15.99);
private final double price;
private PizzaSize(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
static PizzaSize getSelectedItem() {
// TODO Auto-generated method stub
return null;
}
}
|
144405c06f3bfcb9231bc32e0765a59e
|
{
"intermediate": 0.3089490830898285,
"beginner": 0.4658471345901489,
"expert": 0.22520379722118378
}
|
7,897
|
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:
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();
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
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();
private:
bool shutdownInProgress;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
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;
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;
}
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;
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 = ¤tCommandBuffer;
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 ¤tCommandBuffer;
}
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;
}
I don't believe the code is currently making correct use of the graphics pipeline. Can you review and suggest any code changes? Just show me the code.
|
29b163d0e480c74d0684b0d3b1f5957a
|
{
"intermediate": 0.37079140543937683,
"beginner": 0.40848061442375183,
"expert": 0.22072790563106537
}
|
7,898
|
Pretend you are a Linux terminal hooked up to an alien artifact found in deep space. The file "1.lsp" in the current directory is a program written in an imaginary dialect of Lisp. Respond with READY when you are ready to accept Linux commands.
|
d5037b71bf4f9283d85ee0047731ab16
|
{
"intermediate": 0.2805967330932617,
"beginner": 0.3822881579399109,
"expert": 0.33711516857147217
}
|
7,899
|
hi
|
52dde7301758d6000a951dc5a825110b
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
7,900
|
add an array list to my java code so that when the button is clicked, it will add the value of (ChoixPizza*NumPizza)+(NumTopping, the topping price depends on what size the pizza is)+(ChoixBreuvage*NumBreuvage) to an list which can then be shown on the textarea list: import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.UIManager;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.MatteBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.BoxLayout;
import java.awt.FlowLayout;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JPanel ToppingSelect;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder() {
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JLabel NombrePizzaTitle = new JLabel("Choix Pizza");
NombrePizzaTitle.setForeground(new Color(0, 252, 255));
NombrePizzaTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombrePizzaTitle.setBounds(139, 6, 90, 27);
PizzaSelect.add(NombrePizzaTitle);
JComboBox<String> ChoixPizza = new JComboBox<String>();
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(122, 90, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setBounds(122, 129, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);;
JLabel NombreToppingTitle = new JLabel("Nombre de topping");
NombreToppingTitle.setForeground(new Color(0, 252, 255));
NombreToppingTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombreToppingTitle.setBounds(29, 23, 150, 27);
ToppingSelect.add(NombreToppingTitle);
NumTopping = new JTextField();
NumTopping.setBounds(39, 50, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);;
JLabel NombreToppingTitle_1 = new JLabel("Choix de breuvages");
NombreToppingTitle_1.setBounds(34, 6, 150, 27);
BreuvageSelect.add(NombreToppingTitle_1);
NombreToppingTitle_1.setForeground(new Color(0, 252, 255));
NombreToppingTitle_1.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NumBreuvage = new JTextField();
NumBreuvage.setBounds(47, 62, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JComboBox<String> ChoixBreuvage = new JComboBox<String>();
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(65, 34, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
Ajouter = new JButton("Ajouter");
JButton jButton = new JButton();
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receipt = new Receipt();
receipt.setVisible(true);
dispose();
}
});
setVisible(false);
}
}import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BoxLayout;
import javax.swing.JButton;
public class Receipt extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Receipt() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 474, 521);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Panel1 = new JPanel();
Panel1.setBounds(0, 0, 474, 493);
contentPane.add(Panel1);
Panel1.setLayout(null);
JLabel TitleCommande = new JLabel("Commande");
TitleCommande.setFont(new Font("Noteworthy", Font.PLAIN, 25));
TitleCommande.setBounds(175, 6, 108, 31);
Panel1.add(TitleCommande);
JList list = new JList();
list.setBounds(30, 49, 408, 241);
Panel1.add(list);
JLabel Subtotale = new JLabel("SubTotales: ");
Subtotale.setBounds(57, 338, 143, 24);
Panel1.add(Subtotale);
JLabel Totale = new JLabel("Totales: ");
Totale.setBounds(57, 374, 143, 24);
Panel1.add(Totale);
JButton ShowTax = new JButton("+Tax(13%)");
ShowTax.setBounds(199, 337, 117, 29);
Panel1.add(ShowTax);
JButton ModifyCommande = new JButton("Modifier la Commande");
ModifyCommande.setBounds(30, 435, 170, 31);
Panel1.add(ModifyCommande);
// Add action listener to the "Modifier la Commande" button
ModifyCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Close the Receipt window
dispose();
// Show the PizzaOrder window
PizzaOrder pizzaOrder = new PizzaOrder();
pizzaOrder.setVisible(true);
}
});
JButton Fermer = new JButton("Fermer");
Fermer.setBounds(268, 436, 170, 31);
Panel1.add(Fermer);
// Add action listener to the "Fermer" button
Fermer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Close the current window
dispose();
// Terminate the entire application
System.exit(0);
}
});
}
}
public enum Breuvages {
Pop(1.10), Jus(1.35), Eau(1.00);
private final double value;
private Breuvages(double value) {
this.value = value;
}
public double getValue() {
return value;
}
}
public enum PizzaSize {
Small(6.79), Medium(8.29), Large(9.49), ExtraLarge(10.29), Fete(15.99);
private final double price;
private PizzaSize(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
static PizzaSize getSelectedItem() {
// TODO Auto-generated method stub
return null;
}
}
|
6ce703e6e4361bfd417f54ce760b95f6
|
{
"intermediate": 0.3752274811267853,
"beginner": 0.4262339472770691,
"expert": 0.19853858649730682
}
|
7,901
|
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:
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();
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
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();
private:
bool shutdownInProgress;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
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;
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;
}
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;
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 = ¤tCommandBuffer;
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 ¤tCommandBuffer;
}
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;
}
I don't believe the code is currently making correct use of the graphics pipeline. Can you review and suggest any code changes?
|
283d1d2581f492c86d3736de15ece7d9
|
{
"intermediate": 0.37079140543937683,
"beginner": 0.40848061442375183,
"expert": 0.22072790563106537
}
|
7,902
|
In Unity engine, how to make ID system for NPCs that can be used to have something like this: InventoriesManager.Instance.Inventories[npc_id].Inventory
and also ID can be used for saving and loading
|
a17d41114f686654fe7664fe57fc3af8
|
{
"intermediate": 0.5372150540351868,
"beginner": 0.2396601438522339,
"expert": 0.22312486171722412
}
|
7,903
|
I want to forecast the time series data of temperature in matlab.
I prepare 70 years ago data of temperature and I want to forecast it for 38 years later after now.
write the code
|
3114d8141cf2ee449c175840fc725144
|
{
"intermediate": 0.46288537979125977,
"beginner": 0.24443374574184418,
"expert": 0.29268085956573486
}
|
7,904
|
Hi ! I have an audio file that has interference from phone signal voice and I want to clean the audio file from the parasite noise, any easy program or website do ou recommend ?
|
89759471b4aed8fe1514a61f0191744b
|
{
"intermediate": 0.36750465631484985,
"beginner": 0.32045239210128784,
"expert": 0.3120430111885071
}
|
7,905
|
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:
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();
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
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();
private:
bool shutdownInProgress;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
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;
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 = ¤tCommandBuffer;
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 ¤tCommandBuffer;
}
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;
}
I don't believe the code is currently making correct use of the graphics pipeline. Can you review and suggest any code changes?
|
d7c7a73e490ea94e5a821320573fa202
|
{
"intermediate": 0.37079140543937683,
"beginner": 0.40848061442375183,
"expert": 0.22072790563106537
}
|
7,906
|
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");
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() {
// Starts the game!
boolean carryOn = true;
while (carryOn) {
runOneRound();
if (!gc.getPlayerQuitStatus()) {
char r = this.view.getPlayerNextGame();
if (r == 'n') {
carryOn = false;
}
} else {
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++) {
// 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.Keyboard;
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."
Edit the code so that when highsum gui is run,
The gui does not have a blank display and the program can be exited.
|
8611140a0978b7822e4bfcfa68c27d67
|
{
"intermediate": 0.2889218032360077,
"beginner": 0.6018312573432922,
"expert": 0.10924690216779709
}
|
7,907
|
1. Complete a new class for this scenario called SocialNetwork
Create a class called SocialNetwork. This class should be based on the class DiGraph.
You can either:
• Have a field in the class SocialNetwork that is an object DiGraph (better)
• Make SocialNetwork a subclass of DiGraph with additional methods given below (best)
The constructor for this class should have no parameters, and it should create and initialise an
adjacency-list-based directed graph that represents the SocialNetwork network as shown in the
diagram.
For example:
SocialNetwork theSocialNetwork = new SocialNetwork();
should create the graph as shown in the diagram above.
[Up to 10 marks for use of inheritance]
2. Write the method:
public ArrayList<String> broadcastsTo(String person)
This method takes the name of a person and should return an ArrayList of String objects, which
contains the names all the followers of person.
For example:
theSocialNetwork.broadcastsTo(Names.networkMembers[DANA]);
should return an ArrayList that contains [Bina, Cato, Fern, Geno] and nothing else.
Check the edges to resolve this method
[10 marks]
3. Refactor the depth first search method in the class Traversal
Current method header:
public static void DFS(ArrayList<Integer>[] adjList, Integer startNode)
Refactored method header:
public static boolean DFS(ArrayList<Integer>[] adjList,
Integer startNode, Integer destinationNode)
The refactored method will return true if the destinationNode is encountered in the subgraph
descending from startNode.
[5 marks]
4. Write the method:
public boolean canReach(String source, String target)
This method takes the name of a person starting a broadcasting a story (source) and the name of
the person that the story is broadcast to (target).
It uses the refactored depth first search to see if the story will get from the source to the target and
should return true if the story will get from the source to the target, and false if there is no path from
the source to the target.
[5 marks]
5. Refactor the breadth first search method in the class Traversal
Current method header:
public static void BFS(ArrayList<Integer>[] adjList, Integer startNode)
Refactored method header:
public static ArrayList<String> BFS(ArrayList<Integer>[] adjList,
Integer startNode)
The refactored method will return an ArrayList of all of the names of the visited nodes in the graph
structure descending from startNode.
[5 marks]
6. Write the method:
public ArrayList<String> receiversOf(String person)
This method takes the name of a person who has started a story and uses a breadth first search to
return an ArrayList of String objects that contains the names of all the person who will receive the
story broadcast by that person.
For example:
theSocialNetwork.receiversOf(Names.networkMembers[ABEL]);
should return an ArrayList that contains
[Bina, Cato, Dana, Eden, Fern, Geno, Hedy, Inez, Jodi]
and nothing else.
[5 marks]
Correct Output for each test
--------------------------------------------------------------------------------
broadcastTo test
Followers of Abel: [Cato]
Followers of Bina: [Abel]
Followers of Cato: [Abel]
Followers of Dana: [Bina, Cato, Fern, Geno]
Followers of Eden: [Cato, Dana, Fern, Jodi]
Followers of Fern: [Dana]
Followers of Geno: [Fern, Inez]
Followers of Hedy: [Fern, Jodi]
Followers of Inez: [Geno]
Followers of Jodi: [Inez]
--------------------------------------------------------------------------------
canReach test
Abel can reach Bina Cato Dana Eden Fern Geno Hedy Inez Jodi
Bina can reach Dana Eden Fern Geno Hedy Inez Jodi
Cato can reach Abel Bina Dana Eden Fern Geno Hedy Inez Jodi
Dana can reach Eden Fern Geno Hedy Inez Jodi
Eden can reach no one!
Fern can reach Dana Eden Geno Hedy Inez Jodi
Geno can reach Dana Eden Fern Hedy Inez Jodi
Hedy can reach no one!
Inez can reach Dana Eden Fern Geno Hedy Jodi
Jodi can reach Eden Hedy
--------------------------------------------------------------------------------
receiversOf test
Receivers of Abel: [Bina, Cato, Dana, Eden, Fern, Geno, Hedy, Inez, Jodi]
Receivers of Bina: [Dana, Fern, Eden, Geno, Hedy, Inez, Jodi]
Receivers of Cato: [Abel, Dana, Eden, Bina, Fern, Geno, Hedy, Inez, Jodi]
Receivers of Dana: [Fern, Eden, Geno, Hedy, Inez, Jodi]
Receivers of Eden: []
Receivers of Fern: [Dana, Eden, Geno, Hedy, Inez, Jodi]
Receivers of Geno: [Dana, Inez, Fern, Eden, Jodi, Hedy]
Receivers of Hedy: []
Receivers of Inez: [Geno, Jodi, Dana, Eden, Hedy, Fern]
Receivers of Jodi: [Eden, Hedy]
|
ff871c3f557bce86b27efeecea050628
|
{
"intermediate": 0.2739982306957245,
"beginner": 0.38985735177993774,
"expert": 0.336144357919693
}
|
7,908
|
Fix my code: import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.UIManager;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.MatteBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.BoxLayout;
import java.awt.FlowLayout;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JPanel ToppingSelect;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private List<Double> orderList = new ArrayList<Double>();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder() {
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JLabel NombrePizzaTitle = new JLabel("Choix Pizza");
NombrePizzaTitle.setForeground(new Color(0, 252, 255));
NombrePizzaTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombrePizzaTitle.setBounds(139, 6, 90, 27);
PizzaSelect.add(NombrePizzaTitle);
JComboBox<String> ChoixPizza = new JComboBox<String>();
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(122, 90, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setBounds(122, 129, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);;
JLabel NombreToppingTitle = new JLabel("Nombre de topping");
NombreToppingTitle.setForeground(new Color(0, 252, 255));
NombreToppingTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombreToppingTitle.setBounds(29, 23, 150, 27);
ToppingSelect.add(NombreToppingTitle);
NumTopping = new JTextField();
NumTopping.setBounds(39, 50, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);;
JLabel NombreToppingTitle_1 = new JLabel("Choix de breuvages");
NombreToppingTitle_1.setBounds(34, 6, 150, 27);
BreuvageSelect.add(NombreToppingTitle_1);
NombreToppingTitle_1.setForeground(new Color(0, 252, 255));
NombreToppingTitle_1.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NumBreuvage = new JTextField();
NumBreuvage.setBounds(47, 62, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JComboBox<String> ChoixBreuvage = new JComboBox<String>();
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(65, 34, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double orderValue = (PizzaSize.getSelectedItem().getPrice() * Integer.parseInt(NumPizza.getText())) +
(Double.parseDouble(NumTopping.getText()) * ToppingPriceMap.get(PizzaSize.getSelectedItem())) +
(Breuvages.valueOf(ChoixBreuvage.getSelectedItem().toString()).getValue() * Integer.parseInt(NumBreuvage.getText()));
orderList.add(orderValue);
// Clear the text fields
NumPizza.setText("");
NumTopping.setText("");
NumBreuvage.setText("");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receipt = new Receipt(orderList);
receipt.setVisible(true);
dispose();
}
});
setVisible(false);
}
}import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BoxLayout;
import javax.swing.JButton;
public class Receipt extends JFrame {
private JPanel contentPane;
private JList<Double> orderList;
public void updateList(List<Double> newOrderList) {
orderList.setListData(newOrderList.toArray(new Double[0]));
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(orderList);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Receipt(List<Double> orderList) {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 474, 521);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Panel1 = new JPanel();
Panel1.setBounds(0, 0, 474, 493);
contentPane.add(Panel1);
Panel1.setLayout(null);
this.orderList = new JList<Double>(orderList.toArray(new Double[0]));
orderList.setBounds(0, 0, 408, 241);
Panel1.add(orderList);
JLabel TitleCommande = new JLabel("Commande");
TitleCommande.setFont(new Font("Noteworthy", Font.PLAIN, 25));
TitleCommande.setBounds(175, 6, 108, 31);
Panel1.add(TitleCommande);
JList list = new JList();
list.setBounds(30, 49, 408, 241);
Panel1.add(list);
JLabel Subtotale = new JLabel("SubTotales: ");
Subtotale.setBounds(57, 338, 143, 24);
Panel1.add(Subtotale);
JLabel Totale = new JLabel("Totales: ");
Totale.setBounds(57, 374, 143, 24);
Panel1.add(Totale);
JButton ShowTax = new JButton("+Tax(13%)");
ShowTax.setBounds(199, 337, 117, 29);
Panel1.add(ShowTax);
JButton ModifyCommande = new JButton("Modifier la Commande");
ModifyCommande.setBounds(30, 435, 170, 31);
Panel1.add(ModifyCommande);
// Add action listener to the "Modifier la Commande" button
ModifyCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Close the Receipt window
dispose();
// Show the PizzaOrder window
PizzaOrder pizzaOrder = new PizzaOrder();
pizzaOrder.setVisible(true);
}
});
JButton Fermer = new JButton("Fermer");
Fermer.setBounds(268, 436, 170, 31);
Panel1.add(Fermer);
// Add action listener to the "Fermer" button
Fermer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Close the current window
dispose();
// Terminate the entire application
System.exit(0);
}
});
}
}
public enum PizzaSize {
Small(6.79), Medium(8.29), Large(9.49), ExtraLarge(10.29), Fete(15.99);
private final static double price;
private PizzaSize(double price) {
PizzaSize.price = price;
}
public static double getPrice() {
return price;
}
}public enum Breuvages {
Pop(1.10), Jus(1.35), Eau(1.00);
private final double price;
private Breuvages(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
}
|
54d597f93fa83fe1be9ddb3226db4acd
|
{
"intermediate": 0.27088627219200134,
"beginner": 0.46345254778862,
"expert": 0.26566123962402344
}
|
7,909
|
hi
|
ba65545dcfd1657f55ece8cda7c36e1b
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
7,910
|
Fix the errors in my java code: import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.UIManager;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.MatteBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.BoxLayout;
import java.awt.FlowLayout;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JPanel ToppingSelect;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private List<Double> orderList = new ArrayList<Double>();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder() {
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JLabel NombrePizzaTitle = new JLabel("Choix Pizza");
NombrePizzaTitle.setForeground(new Color(0, 252, 255));
NombrePizzaTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombrePizzaTitle.setBounds(139, 6, 90, 27);
PizzaSelect.add(NombrePizzaTitle);
JComboBox<String> ChoixPizza = new JComboBox<String>();
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(122, 90, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setBounds(122, 129, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);;
JLabel NombreToppingTitle = new JLabel("Nombre de topping");
NombreToppingTitle.setForeground(new Color(0, 252, 255));
NombreToppingTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombreToppingTitle.setBounds(29, 23, 150, 27);
ToppingSelect.add(NombreToppingTitle);
NumTopping = new JTextField();
NumTopping.setBounds(39, 50, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);;
JLabel NombreToppingTitle_1 = new JLabel("Choix de breuvages");
NombreToppingTitle_1.setBounds(34, 6, 150, 27);
BreuvageSelect.add(NombreToppingTitle_1);
NombreToppingTitle_1.setForeground(new Color(0, 252, 255));
NombreToppingTitle_1.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NumBreuvage = new JTextField();
NumBreuvage.setBounds(47, 62, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JComboBox<String> ChoixBreuvage = new JComboBox<String>();
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(65, 34, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double orderValue = (PizzaSize.getSelectedItem().getPrice() * Integer.parseInt(NumPizza.getText())) +
(Double.parseDouble(NumTopping.getText()) * ToppingPriceMap.get(PizzaSize.getSelectedItem())) +
(Breuvages.valueOf(ChoixBreuvage.getSelectedItem().toString()).getValue() * Integer.parseInt(NumBreuvage.getText()));
orderList.add(orderValue);
// Clear the text fields
NumPizza.setText("");
NumTopping.setText("");
NumBreuvage.setText("");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receipt = new Receipt(orderList);
receipt.setVisible(true);
dispose();
}
});
setVisible(false);
}
}import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BoxLayout;
import javax.swing.JButton;
public class Receipt extends JFrame {
private JPanel contentPane;
private JList<Double> orderList;
public void updateList(List<Double> newOrderList) {
orderList.setListData(newOrderList.toArray(new Double[0]));
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(orderList);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Receipt(List<Double> orderList) {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 474, 521);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Panel1 = new JPanel();
Panel1.setBounds(0, 0, 474, 493);
contentPane.add(Panel1);
Panel1.setLayout(null);
this.orderList = new JList<Double>(orderList.toArray(new Double[0]));
orderList.setBounds(0, 0, 408, 241);
Panel1.add(orderList);
JLabel TitleCommande = new JLabel("Commande");
TitleCommande.setFont(new Font("Noteworthy", Font.PLAIN, 25));
TitleCommande.setBounds(175, 6, 108, 31);
Panel1.add(TitleCommande);
JList list = new JList();
list.setBounds(30, 49, 408, 241);
Panel1.add(list);
JLabel Subtotale = new JLabel("SubTotales: ");
Subtotale.setBounds(57, 338, 143, 24);
Panel1.add(Subtotale);
JLabel Totale = new JLabel("Totales: ");
Totale.setBounds(57, 374, 143, 24);
Panel1.add(Totale);
JButton ShowTax = new JButton("+Tax(13%)");
ShowTax.setBounds(199, 337, 117, 29);
Panel1.add(ShowTax);
JButton ModifyCommande = new JButton("Modifier la Commande");
ModifyCommande.setBounds(30, 435, 170, 31);
Panel1.add(ModifyCommande);
// Add action listener to the "Modifier la Commande" button
ModifyCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Close the Receipt window
dispose();
// Show the PizzaOrder window
PizzaOrder pizzaOrder = new PizzaOrder();
pizzaOrder.setVisible(true);
}
});
JButton Fermer = new JButton("Fermer");
Fermer.setBounds(268, 436, 170, 31);
Panel1.add(Fermer);
// Add action listener to the "Fermer" button
Fermer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Close the current window
dispose();
// Terminate the entire application
System.exit(0);
}
});
}
}
public enum PizzaSize {
Small(6.79), Medium(8.29), Large(9.49), ExtraLarge(10.29), Fete(15.99);
private final static double price;
private PizzaSize(double price) {
PizzaSize.price = price;
}
public static double getPrice() {
return price;
}
}public enum Breuvages {
Pop(1.10), Jus(1.35), Eau(1.00);
private final double price;
private Breuvages(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
}
|
5fedbeafdaa43287029bda3672d1488a
|
{
"intermediate": 0.3482915759086609,
"beginner": 0.3617987632751465,
"expert": 0.289909690618515
}
|
7,911
|
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+=2chipsToBet;
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+=2chipsToBet;
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+=2chipsToBet;
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”);
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() {
// Starts the game!
boolean carryOn = true;
while (carryOn) {
runOneRound();
if (!gc.getPlayerQuitStatus()) {
char r = this.view.getPlayerNextGame();
if (r == ‘n’) {
carryOn = false;
}
} else {
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++) {
// 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.Keyboard;
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.”
Edit the code so that when highsum gui is run,
The gui does not have a blank display and the program can be exited.
|
4414e92bc1c20f9210cc6951525db6a3
|
{
"intermediate": 0.2641601860523224,
"beginner": 0.5988677740097046,
"expert": 0.1369720697402954
}
|
7,912
|
Show me the lines that you can Fix the errors in my java code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.UIManager;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.MatteBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.BoxLayout;
import java.awt.FlowLayout;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JPanel ToppingSelect;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private List<Double> orderList = new ArrayList<Double>();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder() {
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JLabel NombrePizzaTitle = new JLabel("Choix Pizza");
NombrePizzaTitle.setForeground(new Color(0, 252, 255));
NombrePizzaTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombrePizzaTitle.setBounds(139, 6, 90, 27);
PizzaSelect.add(NombrePizzaTitle);
JComboBox<String> ChoixPizza = new JComboBox<String>();
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(122, 90, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setBounds(122, 129, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);;
JLabel NombreToppingTitle = new JLabel("Nombre de topping");
NombreToppingTitle.setForeground(new Color(0, 252, 255));
NombreToppingTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombreToppingTitle.setBounds(29, 23, 150, 27);
ToppingSelect.add(NombreToppingTitle);
NumTopping = new JTextField();
NumTopping.setBounds(39, 50, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);;
JLabel NombreToppingTitle_1 = new JLabel("Choix de breuvages");
NombreToppingTitle_1.setBounds(34, 6, 150, 27);
BreuvageSelect.add(NombreToppingTitle_1);
NombreToppingTitle_1.setForeground(new Color(0, 252, 255));
NombreToppingTitle_1.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NumBreuvage = new JTextField();
NumBreuvage.setBounds(47, 62, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JComboBox<String> ChoixBreuvage = new JComboBox<String>();
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(65, 34, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double orderValue = (PizzaSize.getSelectedItem().getPrice() * Integer.parseInt(NumPizza.getText())) +
(Double.parseDouble(NumTopping.getText()) * ToppingPriceMap.get(PizzaSize.getSelectedItem())) +
(Breuvages.valueOf(ChoixBreuvage.getSelectedItem().toString()).getValue() * Integer.parseInt(NumBreuvage.getText()));
orderList.add(orderValue);
// Clear the text fields
NumPizza.setText("");
NumTopping.setText("");
NumBreuvage.setText("");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receipt = new Receipt(orderList);
receipt.setVisible(true);
dispose();
}
});
setVisible(false);
}
}import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BoxLayout;
import javax.swing.JButton;
public class Receipt extends JFrame {
private JPanel contentPane;
private JList<Double> orderList;
public void updateList(List<Double> newOrderList) {
orderList.setListData(newOrderList.toArray(new Double[0]));
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(orderList);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Receipt(List<Double> orderList) {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 474, 521);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Panel1 = new JPanel();
Panel1.setBounds(0, 0, 474, 493);
contentPane.add(Panel1);
Panel1.setLayout(null);
this.orderList = new JList<Double>(orderList.toArray(new Double[0]));
orderList.setBounds(0, 0, 408, 241);
Panel1.add(orderList);
JLabel TitleCommande = new JLabel("Commande");
TitleCommande.setFont(new Font("Noteworthy", Font.PLAIN, 25));
TitleCommande.setBounds(175, 6, 108, 31);
Panel1.add(TitleCommande);
JList list = new JList();
list.setBounds(30, 49, 408, 241);
Panel1.add(list);
JLabel Subtotale = new JLabel("SubTotales: ");
Subtotale.setBounds(57, 338, 143, 24);
Panel1.add(Subtotale);
JLabel Totale = new JLabel("Totales: ");
Totale.setBounds(57, 374, 143, 24);
Panel1.add(Totale);
JButton ShowTax = new JButton("+Tax(13%)");
ShowTax.setBounds(199, 337, 117, 29);
Panel1.add(ShowTax);
JButton ModifyCommande = new JButton("Modifier la Commande");
ModifyCommande.setBounds(30, 435, 170, 31);
Panel1.add(ModifyCommande);
// Add action listener to the "Modifier la Commande" button
ModifyCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Close the Receipt window
dispose();
// Show the PizzaOrder window
PizzaOrder pizzaOrder = new PizzaOrder();
pizzaOrder.setVisible(true);
}
});
JButton Fermer = new JButton("Fermer");
Fermer.setBounds(268, 436, 170, 31);
Panel1.add(Fermer);
// Add action listener to the "Fermer" button
Fermer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Close the current window
dispose();
// Terminate the entire application
System.exit(0);
}
});
}
}
public enum PizzaSize {
Small(6.79), Medium(8.29), Large(9.49), ExtraLarge(10.29), Fete(15.99);
private final static double price;
private PizzaSize(double price) {
PizzaSize.price = price;
}
public static double getPrice() {
return price;
}
}public enum Breuvages {
Pop(1.10), Jus(1.35), Eau(1.00);
private final double price;
private Breuvages(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
}
|
525e1fede2f59404e3dca8373aeaece5
|
{
"intermediate": 0.3146858215332031,
"beginner": 0.35175955295562744,
"expert": 0.33355459570884705
}
|
7,913
|
how can I build a responsive webapp with elements organized in rows of three, each element being in the horizontal center of it's corresponding column?
|
72452b96b96d4a1d8e9823d1a5cb3139
|
{
"intermediate": 0.3447199761867523,
"beginner": 0.3871293365955353,
"expert": 0.2681506276130676
}
|
7,914
|
__builtin_va_start
|
51d231b1acbaa3ecd085739473d02950
|
{
"intermediate": 0.32573023438453674,
"beginner": 0.2321712076663971,
"expert": 0.44209855794906616
}
|
7,915
|
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 = ¤tCommandBuffer;
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 ¤tCommandBuffer;
}
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.
|
ca05820fb38c63f38cb934a7a94ddce6
|
{
"intermediate": 0.363829106092453,
"beginner": 0.3310404419898987,
"expert": 0.3051304817199707
}
|
7,916
|
how do I give double values to the options from ChoixPizza, Small: 6.79, Medium: 8.29, Large: 9.49, Extra Large: 10.29, Party Square: 15.99 and give double values to ChoixBreuvage, Pop: 1.10, Jus: 1.35, Water: 1.00;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.UIManager;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.MatteBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.BoxLayout;
import java.awt.FlowLayout;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private double subtotale;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder() {
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JComboBox ChoixPizza = new JComboBox(new String[] {"Small", "Medium", "Large", "Extra Large", "Party Square"});
ChoixPizza.setMaximumRowCount(5);
ChoixPizza.setBounds(122, 90, 130, 27);
PizzaSelect.add(ChoixPizza);
JLabel NombrePizzaTitle = new JLabel("Choix Pizza");
NombrePizzaTitle.setForeground(new Color(0, 252, 255));
NombrePizzaTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombrePizzaTitle.setBounds(139, 6, 90, 27);
PizzaSelect.add(NombrePizzaTitle);
NumPizza = new JTextField();
NumPizza.setBounds(122, 129, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);;
JLabel NombreToppingTitle = new JLabel("Nombre de topping");
NombreToppingTitle.setForeground(new Color(0, 252, 255));
NombreToppingTitle.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NombreToppingTitle.setBounds(29, 23, 150, 27);
ToppingSelect.add(NombreToppingTitle);
NumTopping = new JTextField();
NumTopping.setBounds(39, 50, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);;
JLabel NombreToppingTitle_1 = new JLabel("Choix de breuvages");
NombreToppingTitle_1.setBounds(34, 6, 150, 27);
BreuvageSelect.add(NombreToppingTitle_1);
NombreToppingTitle_1.setForeground(new Color(0, 252, 255));
NombreToppingTitle_1.setFont(new Font("Hiragino Sans GB", Font.BOLD, 15));
NumBreuvage = new JTextField();
NumBreuvage.setBounds(47, 62, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
JComboBox ChoixBreuvage = new JComboBox(new String[] {"Pop", "Jus", "Eau"});
ChoixBreuvage.setMaximumRowCount(3);
ChoixBreuvage.setBounds(47, 36, 130, 27);
BreuvageSelect.add(ChoixBreuvage);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receipt = new Receipt();
receipt.setVisible(true);
dispose();
}
});
setVisible(false);
}
}
|
623ab62b94dad1c42d44d3892af55594
|
{
"intermediate": 0.35100623965263367,
"beginner": 0.45702260732650757,
"expert": 0.19197112321853638
}
|
7,917
|
You are an expert in the related field and you are mentoring me, I am looking for free or opensource or both resources for the research of AMHS and X.400 and need to publish a paper related to interfacing AMHS with other software application, please guide me. Also free or open source or both x.400 api for this
|
ee8536bcb0d71c53780bf32aa873bcec
|
{
"intermediate": 0.2679934799671173,
"beginner": 0.07358983159065247,
"expert": 0.6584166884422302
}
|
7,918
|
what's wrong with this C# Code, how do I fix it so it runs?: using System;
namespace Prog;
class GuessGame
{
static void Main(string[] args)
{
}
void Rolling()
{
Random r = new Random();
int res = r.Next( 45);
Console.WriteLine("Roll the Dice!");
String Roll = Console.ReadLine();
if (Roll == "Roll")
{
Console.WriteLine(res);
}
Console.ReadKey();
RollDice();
}
void RollDice()
{
Random r = new Random();
int res = r.Next( 45);
Console.WriteLine("Roll the Dice!");
String Roll = Console.ReadLine();
if (Roll == "Roll")
{
Console.WriteLine(res);
}
Console.ReadKey();
Rolling();
}
}
|
88ca49775068684e5db0a28b81de0951
|
{
"intermediate": 0.574073851108551,
"beginner": 0.3583259880542755,
"expert": 0.06760013848543167
}
|
7,919
|
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 = ¤tCommandBuffer;
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 ¤tCommandBuffer;
}
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.
|
ab8f0bd9b4a0954fca5316d1e1b37f21
|
{
"intermediate": 0.363829106092453,
"beginner": 0.3310404419898987,
"expert": 0.3051304817199707
}
|
7,920
|
FHIR locationReference json
|
bfc45e26a3f1664125be156d5b0d5573
|
{
"intermediate": 0.2996695339679718,
"beginner": 0.3426879048347473,
"expert": 0.3576425313949585
}
|
7,921
|
Tolong save/ekspor model analisis sentimen ke .h5 atau file ekstension lain yang bisa diimport di lain waktu! Kode:
import pickle
import pandas as pd
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
from keras.models import Sequential
from keras.layers import Embedding, LSTM, Dense, Dropout, Conv1D, GlobalMaxPooling1D, Reshape
from keras.layers import Flatten
from keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import gensim
from keras.regularizers import l2
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
# Membaca dataset
data_list = pickle.load(open('pre_processed_berita_121_joined_FIX_parpolheuristic_added.pkl', 'rb'))
data = pd.DataFrame(data_list, columns=['judul', 'isi', 'pre_processed', 'Label', 'Partai_Politik_Heuristic'])
data['Isi Berita'] = data['pre_processed']
# Tokenisasi dan Padding
max_words = 10000 # mengurangi jumlah kata maksimum
max_len = 500 # mengurangi panjang input
tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(data['Isi Berita'])
sequences = tokenizer.texts_to_sequences(data['Isi Berita'])
X = pad_sequences(sequences, maxlen=max_len)
y = to_categorical(data['Label'].astype('category').cat.codes)
# Membagi data menjadi data latih dan data uji
X_train, X_test, y_train, y_test, idx_train, idx_test = train_test_split(X, y, data.index, test_size=0.25, random_state=42)
# Menggunakan pre-trained word2vec Bahasa Indonesia
path = 'idwiki_word2vec_300.model'
id_w2v = gensim.models.word2vec.Word2Vec.load(path)
wv = id_w2v.wv
# Membuat matriks embedding
embedding_dim = 300
embedding_matrix = np.zeros((max_words, embedding_dim))
for word, i in tokenizer.word_index.items():
if i < max_words:
try:
embedding_vector = wv[word]
embedding_matrix[i] = embedding_vector
except KeyError:
pass
# Membuat model LSTM-CNN
model = Sequential()
model.add(Embedding(max_words, embedding_dim, weights=[embedding_matrix], input_length=max_len, trainable=False))
model.add(LSTM(200, return_sequences=True, kernel_regularizer=l2(0.01), recurrent_regularizer=l2(0.01)))
model.add(Conv1D(256, 3, activation='relu', kernel_regularizer=l2(0.01)))
model.add(GlobalMaxPooling1D())
model.add(Dropout(0.1))
Reshape((-1, 256)),
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(32, activation='relu', kernel_regularizer=l2(0.01)))
model.add(Dropout(0.2))
model.add(Dense(3, activation='softmax'))
# Buat callback early stopping
callback_es = EarlyStopping(monitor='val_loss', patience=5, verbose=1, restore_best_weights=True)
# Inisialisasi optimizer dengan learning rate awal
initial_learning_rate = 0.0001
optimizer = Adam(learning_rate=initial_learning_rate)
# Kompilasi model
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
# Latih model dengan menggunakan learning rate scheduler dan early stopping dalam callbacks
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=128, callbacks=[callback_es])
|
0ed345a96fe8d8f10ab5349f63897b4c
|
{
"intermediate": 0.3268073499202728,
"beginner": 0.3289792537689209,
"expert": 0.34421342611312866
}
|
7,922
|
how to remove watermark from video using python
|
d5b75b35c750a36547b7d252d9a8259d
|
{
"intermediate": 0.27598488330841064,
"beginner": 0.21393795311450958,
"expert": 0.510077178478241
}
|
7,923
|
talk about the idea of c++ in web development.
|
94c9765b80e274bcecabaf5a46099d43
|
{
"intermediate": 0.3863663971424103,
"beginner": 0.359564870595932,
"expert": 0.2540687322616577
}
|
7,924
|
why won't this C# code run in the terminal?: using System;
namespace Prog;
class GuessGame
{
static void Main(string[] args)
{
}
void Rolling()
{
Random r = new Random();
int res = r.Next( 45);
Console.WriteLine("Roll the Dice!");
String? Roll = Console.ReadLine();
if (Roll == "Roll")
{
Console.WriteLine(res);
}
Console.ReadKey();
}
}
|
cc251c740d0c40fcc04a2d75614be409
|
{
"intermediate": 0.5104789137840271,
"beginner": 0.37949731945991516,
"expert": 0.11002380400896072
}
|
7,925
|
He terminado de entrenar el modelo en Google Colab con el código que te compartiré , ¿ahora como guardo el resultado y como lo uso?: import torch
import torch.nn as nn
import time
from torchtext.datasets import PennTreebank
from torchtext.data.functional import to_map_style_dataset
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
class TransformerModel(nn.Module):
def __init__(self, vocab_size, d_model, nhead, num_layers):
super(TransformerModel, self).__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.transformer = nn.Transformer(d_model, nhead, num_layers)
self.fc = nn.Linear(d_model, vocab_size)
def forward(self, src, tgt):
src = self.embedding(src)
tgt = self.embedding(tgt)
x = self.transformer(src, tgt)
x = self.fc(x)
return x
train_data = to_map_style_dataset(PennTreebank(split='train'))
tokenizer = get_tokenizer("spacy", "en_core_web_sm")
vocab = build_vocab_from_iterator(tokenizer(y) for y in train_data)
def generate_pairs(tokens, shift=1):
source = [tokens[i] for i in range(0, len(tokens) - shift)]
target = [tokens[i] for i in range(shift, len(tokens))]
return source, target
vocab_size = len(vocab)
d_model = 512
nhead = 4
num_layers = 4
num_epochs = 5
learning_rate = 1e-3
batch_size = 64
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TransformerModel(vocab_size=vocab_size, d_model=d_model, nhead=nhead, num_layers=num_layers).to(device)
loss_function = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
def encode_text(text):
tokens = tokenizer(text)
return torch.tensor([vocab[token] for token in tokens]).to(device)
def train(model, epoch):
model.train()
train_loss = 0
for i, text in enumerate(train_data):
tokens = encode_text(text)
if len(tokens) <= 1:
continue
source, target = generate_pairs(tokens, shift=1)
source = torch.tensor(source).unsqueeze(1).to(device)
target = torch.tensor(target).unsqueeze(1).to(device)
optimizer.zero_grad()
output = model(source, target[:-1])
loss = loss_function(output.view(-1, vocab_size), target[1:].view(-1))
loss.backward()
optimizer.step()
train_loss += loss.item()
if i % 1000 == 0:
print(f'Epoch: {epoch + 1},\tLoss: {loss.item()}')
return train_loss / len(train_data)
for epoch in range(num_epochs):
start_time = time.time()
train_loss = train(model, epoch)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Epoch: {epoch + 1},\tAverage Loss: {train_loss},\tTime taken: {elapsed_time} seconds")
|
05dfb7fadb7ac7ff054bdb6af0f5a9b3
|
{
"intermediate": 0.2841814160346985,
"beginner": 0.409924179315567,
"expert": 0.3058944344520569
}
|
7,926
|
I'm working on a fivem oil slick script in lua
here is the client
-- This script allows the user to throw an item to create an oil slick this will make cars that hit it slide
local AnimDict = "core";
local AnimName = "ent_anim_paparazzi_flash"
local WeaponModel = "w_ex_oiltub"
local Animations = {"anim@heists@ornate_bank@thermal_charge", "cover_eyes_intro"}
local OilSlickEquiped = false
local ped = GetPlayerPed(-1)
local slipping = false
--table for oil slicks
local_oil_slicks = {}
--local table of coords to handle
local coords_to_handle = {}
--function for adding slip to vehicle
function AddSlip()
--create a thread
Citizen.CreateThread(function()
--get vehicle ped is in
local vehicle = GetVehiclePedIsIn(ped, false)
local old_val = GetVehicleHandlingFloat(vehicle, "CHandlingData", "fTractionCurveLateral")
--set new traction value
print('car should be slipping')
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fTractionCurveLateral", old_val * 6)
--wait 7 seconds
Wait(7000)
--set traction back to old value
print('car should no longer be slipping')
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fTractionCurveLateral", old_val)
--set slipping to false
slipping = false
end)
end
--event to check local table and remove slick at location
RegisterNetEvent('oil:delete_petrol_decal')
AddEventHandler('oil:delete_petrol_decal', function(coords)
for k,v in pairs(coords_to_handle) do
if v == coords then
RemoveDecal(k)
--check local oil_slicks table and remove slick at location
for k,v in pairs(local_oil_slicks) do
if v == coords then
local_oil_slicks[k]=nil
end
end
end
end
end)
Citizen.CreateThread(function()
while true do
--if player in vehicle
if IsPedInAnyVehicle(ped,false) and not slipping then
for k,v in pairs(local_oil_slicks) do
--get distance to slick
local dist = #(GetEntityCoords(ped) - v)
if dist < 4 then
--tell server to tell clients to delete
TriggerServerEvent('oil:delete_oil_slick', v)
if slipping == false then
slipping = true
AddSlip()
end
end
end
end
Wait(200)
end
end)
--function to create oil slick
function CreateOilSlick(handle)
-- thread do check for collision with ground
Citizen.CreateThread(function()
while true do
--get coords of entity
local coords = GetEntityCoords(handle)
--draw line to it
-- DrawLine(coords.x, coords.y, coords.z, coords.x, coords.y, coords.z - 10.0, 255, 0, 0, 255)
local h = GetEntityHeightAboveGround(handle)
--if collided with ground
if h <= 0.3 then
local coords = GetEntityCoords(handle)
TriggerServerEvent('oil:create_oil_slick', coords)
break
end
Wait(0)
end
end)
end
Citizen.CreateThread(function()
while true do
ped = GetPlayerPed(-1)
if OilSlickEquiped == false then
if GetSelectedPedWeapon(ped) == 277905663 then
OilSlickEquiped = true;
end
else
if IsPedShooting(ped) then
OilSlickEquiped = false;
local pos = GetEntityCoords(ped)
Wait(100)
local handle = GetClosestObjectOfType(pos.x,pos.y,pos.z,50.0,GetHashKey(WeaponModel),false,false,false)
if handle ~= 0 then
CreateOilSlick(handle)
end
end
end
Wait(0)
end
end)
--function to create the newly added slick and update local table
RegisterNetEvent('oil:create_petrol_decal')
AddEventHandler('oil:create_petrol_decal', function(coords, oil_slicks)
--get the ground z coord
local ret_val, ground_z, normal = GetGroundZFor_3dCoord(coords.x, coords.y, coords.z)
local new_slick = AddPetrolDecal(coords.x, coords.y, ground_z, 3.0, 6.0, 0.6)
coords_to_handle[new_slick] = coords
local_oil_slicks = oil_slicks
end)
server
-- 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)
how could I add a timer so it deletes the oil slick after 1 minutes on the server if it hasn't already been deleted
|
3a23676805a833a29c4dbd15515baf27
|
{
"intermediate": 0.3687240481376648,
"beginner": 0.45753127336502075,
"expert": 0.17374467849731445
}
|
7,927
|
rewrite this code "“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)""
|
011c9ccd08d1f3d1ca8d481a6c5f3398
|
{
"intermediate": 0.40274250507354736,
"beginner": 0.34635311365127563,
"expert": 0.2509043216705322
}
|
7,928
|
what can i do to lower the resmon on this fivem client script lua
-- This script allows the user to throw an item to create an oil slick this will make cars that hit it slide
local AnimDict = "core";
local AnimName = "ent_anim_paparazzi_flash"
local WeaponModel = "w_ex_oiltub"
local Animations = {"anim@heists@ornate_bank@thermal_charge", "cover_eyes_intro"}
local OilSlickEquiped = false
local ped = GetPlayerPed(-1)
local slipping = false
--table for oil slicks
local_oil_slicks = {}
--local table of coords to handle
local coords_to_handle = {}
--function for adding slip to vehicle
function AddSlip()
--create a thread
Citizen.CreateThread(function()
--get vehicle ped is in
local vehicle = GetVehiclePedIsIn(ped, false)
local old_val = GetVehicleHandlingFloat(vehicle, "CHandlingData", "fTractionCurveLateral")
--set new traction value
print('car should be slipping')
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fTractionCurveLateral", old_val * 6)
--wait 7 seconds
Wait(7000)
--set traction back to old value
print('car should no longer be slipping')
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fTractionCurveLateral", old_val)
--set slipping to false
slipping = false
end)
end
--event to check local table and remove slick at location
RegisterNetEvent('oil:delete_petrol_decal')
AddEventHandler('oil:delete_petrol_decal', function(coords)
for k,v in pairs(coords_to_handle) do
if v == coords then
RemoveDecal(k)
--check local oil_slicks table and remove slick at location
for k,v in pairs(local_oil_slicks) do
if v == coords then
local_oil_slicks[k]=nil
end
end
end
end
end)
Citizen.CreateThread(function()
while true do
--if player in vehicle
if IsPedInAnyVehicle(ped,false) and not slipping then
for k,v in pairs(local_oil_slicks) do
--get distance to slick
local dist = #(GetEntityCoords(ped) - v)
if dist < 4 then
--tell server to tell clients to delete
TriggerServerEvent('oil:delete_oil_slick', v)
if slipping == false then
slipping = true
AddSlip()
end
end
end
end
Wait(200)
end
end)
--function to create oil slick
function CreateOilSlick(handle)
-- thread do check for collision with ground
Citizen.CreateThread(function()
while true do
--get coords of entity
local coords = GetEntityCoords(handle)
--draw line to it
-- DrawLine(coords.x, coords.y, coords.z, coords.x, coords.y, coords.z - 10.0, 255, 0, 0, 255)
local h = GetEntityHeightAboveGround(handle)
--if collided with ground
if h <= 0.3 then
local coords = GetEntityCoords(handle)
TriggerServerEvent('oil:create_oil_slick', coords)
break
end
Wait(0)
end
end)
end
Citizen.CreateThread(function()
while true do
ped = GetPlayerPed(-1)
if OilSlickEquiped == false then
if GetSelectedPedWeapon(ped) == 277905663 then
OilSlickEquiped = true;
end
else
if IsPedShooting(ped) then
OilSlickEquiped = false;
local pos = GetEntityCoords(ped)
Wait(100)
local handle = GetClosestObjectOfType(pos.x,pos.y,pos.z,50.0,GetHashKey(WeaponModel),false,false,false)
if handle ~= 0 then
CreateOilSlick(handle)
end
end
end
Wait(0)
end
end)
--function to create the newly added slick and update local table
RegisterNetEvent('oil:create_petrol_decal')
AddEventHandler('oil:create_petrol_decal', function(coords, oil_slicks)
--get the ground z coord
local ret_val, ground_z, normal = GetGroundZFor_3dCoord(coords.x, coords.y, coords.z)
local new_slick = AddPetrolDecal(coords.x, coords.y, ground_z, 3.0, 6.0, 0.6)
coords_to_handle[new_slick] = coords
local_oil_slicks = oil_slicks
end)
|
17a7e73f6cfd479c99c6a12e7b5af837
|
{
"intermediate": 0.3173827826976776,
"beginner": 0.4351188838481903,
"expert": 0.24749836325645447
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.