row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
8,935
|
can you fix problem with scaling and zooming, along with actual transformation variance. add some intriguing function to update the actual shape of a figurine and transform the amount of edges and vertices used to produce some unusual forms from basic 3d cube to something fractal-like. also, if you as well add some vibrance to stroke lines it will look just truly otherworldly. and output all control parameters at the top.: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
// Transformation parameters
const scale = 0.35;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX / (zoom + posZ) + canvas.width / 2),
(posY / (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
let angleX = 0;
let angleY = 0;
let angleZ = 0;
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 100;
const amplitude = 0.015;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.strokeStyle = '#000';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
angleX += 0.001;
angleY += 0.0013;
angleZ += 0.0007;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
c0fdf57c4a61c5b81c02dfeca8cf0a78
|
{
"intermediate": 0.31122568249702454,
"beginner": 0.3761667013168335,
"expert": 0.31260767579078674
}
|
8,936
|
как прокинуть значения из post запроса в ответ в java
|
a9eba7c5c5fb8fc74061ceaf1e8dd0c8
|
{
"intermediate": 0.33694058656692505,
"beginner": 0.25582781434059143,
"expert": 0.4072316586971283
}
|
8,937
|
create a file tslint in order to format code for a react project
|
2ad525de3ca7f2e11f7b3e7b47289dd4
|
{
"intermediate": 0.3496388792991638,
"beginner": 0.27471643686294556,
"expert": 0.37564465403556824
}
|
8,938
|
is there a type of config file that steam writes to to force compatability on a nonsteam game?
|
ed556b1bdccc2d14f3d1f23280db637b
|
{
"intermediate": 0.37254494428634644,
"beginner": 0.2820449471473694,
"expert": 0.3454100489616394
}
|
8,939
|
given an array of object typed interface AvvocatoParte {
indirizzi: Indirizzo[];
indirizzo?: Indirizzo;
cassazionista?: boolean | null;
tipoDifensore?: string;
tipo?: TipoAvvocato;
foroRif?: string;
tipoParte?: string;
avvocato: avvocato;
}
and an array of type interface DifensoreVerbale {
id: DifensoreVerbaleID;
idRicUdien: number;
idAnagDifen: number;
idParte: number;
comparso: boolean;
operatore: number;
oggi: number;
parte?: Parte;
anagraficaAvvocato?: AnagraficaAvvocato;
tipoDif: string;
citta: string;
via: string;
}
return one array where it removes all duplicates of Difensore verbale, check if the id that i’ll give is equal to DifensoreVerbale.idParte, if is equal remove all the duplicates where DifensoreVerbale.idAnagDifen is equal to AvvocatoParte.avvocato.id using lodash functions
|
4b2ee4a5da4274665894b40164f7f9e1
|
{
"intermediate": 0.39880743622779846,
"beginner": 0.2639824151992798,
"expert": 0.33721017837524414
}
|
8,940
|
make django models for a movie management system for different movie that can be seen many times and a show table that consist of time, uuid and movie foreign key as well as keep track of the seat matrix. each person can only maximum book 2 tickets in a month and when the month is over ticket count should be zero.
|
8ecdd5f1e51228dd8bef5a938374eb37
|
{
"intermediate": 0.3216712176799774,
"beginner": 0.08032089471817017,
"expert": 0.59800785779953
}
|
8,941
|
<div class="common-top-search-div">
<div class="label-div">下发日期:</div>
<el-date-picker
v-model="query.startdate" class="input-div" value-format="yyyy-MM-dd"
type="date" placeholder="开始日期" />
<el-date-picker v-model="query.enddate" class="input-div" value-format="yyyy-MM-dd"
type="date" placeholder="结束日期" />
</div>
|
19a1eea49ca4f5286268a1fd1b1a1820
|
{
"intermediate": 0.3249683082103729,
"beginner": 0.4015311598777771,
"expert": 0.27350062131881714
}
|
8,942
|
In the picture we have a variable signal (it can be any:
sine wave, square wave, triangle, etc...) included in the Arduino
In a similar reader.
The amplitude and frequency of the signal are variable, one thing we know is that the voltage
The maximum value relative to ground may vary from 1 to 5
to volts, while the signal voltage never goes negative, as far as
The frequency is from 0 to 100 hertz. Our task is to read this through the Arduino
Divide the signal and the given input signal at any moment of time by 2
state: logic high and logic low. logically higher
Consider the input signal if its instantaneous amplitude is greater than or equal to (Vmax +
Vmin)/2, and logical low if it is less than the given image. ours
The task is that when we have a logical high, then we have a voltage of 12 volts
We have to let the voltage from the source into the lamp, and when we have a logical low
The current should no longer flow through the lamp. That is, it is easy to understand that it should be in the lamp
Let's run square wave 12 volt pulses depending on the input signal. also
The picture shows the screen on which we should output the input signal
frequency and maximum voltage to ground.
Also worth noting is the fact that the signal may be in some period of time
Let it be, for example, a sinusoid with a frequency of 5 Hz, and the voltage should vary from Vmin=2
Vmax=3 volts to ground and at this time, it should be displayed
Image: 3 volts, 5 hertz. And after some time it becomes sinusoidal
The signal may be replaced by a rectangular signal that oscillates Vmin=1-
from Vmax=5 volts, and the frequency will be 20 hertz, and at this time the screen
The values should be changed accordingly. corresponding to the input signal
Data changes should be updated on the screen every 5 seconds.
Create a Proteus circuit using the components in the picture
in the simulator and write the code for Arduino.
|
a87b98fe1f848a0529ad0535baf408c2
|
{
"intermediate": 0.3607264459133148,
"beginner": 0.3221786916255951,
"expert": 0.3170948624610901
}
|
8,943
|
for the below code inorder for branch statistician role to see their approved quotations with status QuotationStatus.Statistician_Approved what change must i make
|
b03810edae397c78b40d796a9a2fac2f
|
{
"intermediate": 0.3813885748386383,
"beginner": 0.31076937913894653,
"expert": 0.3078420162200928
}
|
8,944
|
Consider the missionaries and cannibals problem. Analyze this problem with respect to
seven problem characteristics and find a good state space representation.
|
cae0d398ba2404cbb43eb7cecf0582f8
|
{
"intermediate": 0.2506197392940521,
"beginner": 0.3266375660896301,
"expert": 0.42274272441864014
}
|
8,945
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
try:
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC'))
frame = frame.iloc[:60,:6]
frame.columns = ['Time','Open','High','Low','Close','Volume']
frame = frame.set_index('Time')
today = dt.date.today()
frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S")
frame = frame.astype(float)
return frame
except Exception as e:
print(f"Error getting minute data: {str(e)}")
return
df = getminutedata('BTCUSDT', '1m', '44640')
def signal_generator(df):
try:
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ''
except Exception as e:
print(f"Error generating signal: {str(e)}")
return signal_generator(df)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = client.futures_account_balance()
usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAm’'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True
)
time.sleep(1)
if opposite_position is not None:
opposite_side = (SIDE_SELL if opposite_position['positionSide'] ==
POSITION_SIDE_LONG
else SIDE_BUY)
else:
opposite_side = None
# Place the order and capture the returned order ID
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side,
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
else:
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side
)
# Print order creation confirmation messages
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop
if df is None:
continue
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
time.sleep(1) # Add a delay of 1 second But I getting ERROR: The signal time is: 2023-05-29 11:58:02 :buy
Both positions closed.
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 211, in <module>
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 151, in order_execution
order = client.futures_create_order(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client.py", line 6209, in futures_create_order
return self._request_futures_api('post', 'order', True, data=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client.py", line 382, in _request_futures_api
return self._request(method, uri, signed, True, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client.py", line 358, in _request
return self._handle_response(self.response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client.py", line 367, in _handle_response
raise BinanceAPIException(response, response.status_code, response.text)
binance.exceptions.BinanceAPIException: APIError(code=-1102): Mandatory parameter 'positionSide' was not sent, was empty/null, or malformed. please give me right code as solution
|
ab04202af42f5005948cbb1cc0865c55
|
{
"intermediate": 0.41107699275016785,
"beginner": 0.3534979224205017,
"expert": 0.23542502522468567
}
|
8,946
|
how to parse all variable names in javascript expression using rhino engine.
|
b90f8c20e7cfb19fadfd0280617a938c
|
{
"intermediate": 0.32332152128219604,
"beginner": 0.49077388644218445,
"expert": 0.18590454757213593
}
|
8,947
|
Давай начнем с самого простого. В этом упражнении тебе необходимо получить отфильтрованные данные из таблицы
в базе данных. Почему важно фильтровать данные именно в запросе, а не после этого в библиотеке Pandas?
Потому что таблицы могут иметь огромный размер. Если ты попыташься получить всю таблицу, то не сможешь ее "переварить"
– у тебя может не хватить оперативной памяти. Всегда помни об этом.
Первый способ фильтрации — выбрать только те столбцы, которые тебе действительно нужны.
Второй способ — выбрать только те строки, которые тебе действительно нужны.
Подробное описание задания:
Помести базу данных в подкаталог data в корневом каталоге, используемом в рамках этого проекта.
Создай соединение с базой данных с помощью библиотеки .sqlite3
Получи схему таблицы с помощью и запроса .pageviewspd.io.sql.read_sqlPRAGMA table_info(pageviews);
Получи только первые строк таблицы , чтобы проверить, как она выглядит.10pageviews
Получи подтаблицу с помощью только одного запроса, в котором:
используются только и uiddatetime;
используются только данные пользователей (), и не используются данные администраторов;user_*
сортировка выполняется по в порядке возрастания;uid
столбец индекса — это datetime;
datetime преобразован в DatetimeIndex;
имя датафрейма — .pageviews
Закрой соединение с базой данных.
|
82b6dde4d501ecc2e7e871b2a57f11a7
|
{
"intermediate": 0.2926642894744873,
"beginner": 0.4998176395893097,
"expert": 0.20751804113388062
}
|
8,948
|
add certain characters at the head of a line in python
|
75a20b826cf5e2a210fbdac917b2e008
|
{
"intermediate": 0.2844889163970947,
"beginner": 0.23599852621555328,
"expert": 0.4795125722885132
}
|
8,949
|
import os
# input directory path
input_directory = 'T:/Fivem Related/Alpha Dev/stream_weapons/metas/addon'
# loop through all folders in input directory
for folder in os.listdir(input_directory):
if os.path.isdir(os.path.join(input_directory, folder)):
# do something with folder
#print(folder)
folderpath = os.path.join(input_directory, folder)
for filename in os.listdir(folderpath):
if filename.endswith('weapons.meta'):
#print('found weapons.meta')
file_path = os.path.join(folderpath, filename)
with open(file_path, 'r') as file:
#print('opened file: %s' % file)
lines = file.readlines()
# iterate through each line and check if it starts with "<Item type="CWeaponInfo">"
print('hi')
for i in range(len(lines)):
if lines[i].startswith('<Item type="CWeaponInfo">'):
# print the line below it
print(lines[i])
for some reason its not printing the line below <Item type="CWeaponInfo">
its getting up to the hi print statement
|
062f2efa1ea2bbf48373cf671d31bd39
|
{
"intermediate": 0.22738705575466156,
"beginner": 0.6507689356803894,
"expert": 0.12184397876262665
}
|
8,950
|
what is the command "# stty -F /dev/" for?
|
55d6daac572d6fad4ecd357f7815a30c
|
{
"intermediate": 0.4649333655834198,
"beginner": 0.2727673649787903,
"expert": 0.2622992992401123
}
|
8,951
|
hi
|
137ddfac48a81c2dc76a1ba3249b07eb
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
8,952
|
В этом упражнении ты создашь так называемую витрину данных. Она представляет собой таблицу,
которую можно использовать для аналитических целей. Обычно она создается путем объединения нескольких отдельных таблиц.
В этом упражнении мы будем собирать различные данные о наших пользователях: когда они сделали свои первые коммиты,
когда они впервые посетили ленту новостей и т. д. Это поможет позднее выполнить анализ данных.
Что тебе нужно сделать в этом упражнении (ознакомься с полным описанием задания):
Создай соединение с базой данных с помощью библиотеки .sqlite3
Создай новую таблицу в базе данных, объединив таблицы и с помощью только одного запроса.
datamartpageviewschecker
Таблица должна содержать следующие столбцы: , , , .uidlabnamefirst_commit_tsfirst_view_ts
first_commit_ts — это просто новое имя для столбца из таблицы ; он показывает первый коммит конкретного лабораторного задания конкретного пользователя.timestampchecker
first_view_ts — первое посещение пользователем из таблицы , метка времени посещения пользователем ленты новостей.pageviews
По-прежнему нужно использовать фильтр .status = 'ready'
По-прежнему нужно использовать фильтр .numTrials = 1
Имена лабораторных заданий по-прежнему должны быть из следующего списка: , , , , , .laba04laba04slaba05laba06laba06sproject1
Таблица должна содержать только пользователей ( с ), а не администраторов.uiduser_*
first_commit_ts и должны быть распарсены как .first_view_tsdatetime64[ns]
Используя методы библиотеки Pandas, создай два датафрейма: и . testcontrol
test должен включать пользователей, у которых имеются значения в .first_view_ts
control должен включать пользователей, у которых отсутствуют значения в .first_view_ts
Замени пропущенные значения в средним значением пользователей из (оно пригодится нам для анализа в будущем).controlfirst_view_tstest
Сохрани обе таблицы в базе данных (вы будете использовать их в следующих упражнениях).
Закрой соединение.
Небольшой совет — выполняй все операции поочередно, от простой к более сложной, а не пытаясь сделать всё вместе и сразу. Это поможет в отладке твоих запросов.
|
487afbadba5b70eef356376e53bdbf3f
|
{
"intermediate": 0.18666768074035645,
"beginner": 0.5202290415763855,
"expert": 0.29310330748558044
}
|
8,953
|
#1. Помещаем базу данных checking-logs.sqlite в подкаталог data в корневом каталоге:
import shutil
# Копирование базы данных в подкаталог data
shutil.copyfile('C:/Users/lpoti/Documents/DS_21/DS10-1-develop/datasets/checking-logs.sqlite', 'C:/Users/lpoti/Documents/DS_21/DS10-1-develop/datasets/data/checking-logs.sqlite')
#2. Создаем соединение с базой данных с помощью библиотеки sqlite3:
import sqlite3
# Создание соединения с базой данных
conn = sqlite3.connect('C:/Users/lpoti/Documents/DS_21/DS10-1-develop/datasets/data/checking-logs.sqlite')
#3. Получаем схему таблицы pageviews с помощью функции read_sql и запроса PRAGMA table_info:
import pandas.io.sql as pd_sql
# Получение схемы таблицы pageviews
schema_query = "PRAGMA table_info(pageviews);"
schema = pd_sql.read_sql(schema_query, conn)
print(schema)
#4. Получаем только первые 10 строк таблицы pageviews:
# Получение первых 10 строк таблицы pageviews
query = "SELECT * FROM pageviews LIMIT 10;"
pageviews = pd_sql.read_sql(query, conn)
print(pageviews)
#5. Получаем подтаблицу pageviews с помощью запроса, который отбирает данные пользователей, сортирует их по идентификатору пользователя (uid) в порядке возрастания и преобразует столбец datetime в индекс типа DatetimeIndex:
# Получение подтаблицы pageviews с отбором данных по пользователям и сортировкой по uid
query = """
SELECT datetime, uid
FROM pageviews
WHERE uid LIKE 'user_%'
ORDER BY uid ASC;
"""
# Чтение подтаблицы из базы данных и подгонка типов столбцов
pageviews = pd_sql.read_sql(query, conn, parse_dates=['datetime'], index_col='datetime')
print(pageviews)
#6. Закрываем соединение с базой данных:
# Закрытие соединения с базой данных
conn.close()
|
2129d17c90b11c2592c20b8e2edd4945
|
{
"intermediate": 0.29480499029159546,
"beginner": 0.5752201676368713,
"expert": 0.12997476756572723
}
|
8,954
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Renderer.cpp:
#include "Renderer.h"
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandBuffers();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
}
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//currentCommandBuffer = commandBuffers[currentFrame];
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2;
currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex];
// Add debug message before vkBeginCommandBuffer
std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n";
std::cout << "Calling vkBeginCommandBuffer…\n";
vkBeginCommandBuffer(currentCommandBuffer, &beginInfo);
std::cout << "vkBeginCommandBuffer called…\n";
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
// Set the clear color to black
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
}
void Renderer::EndFrame()
{
vkCmdEndRenderPass(currentCommandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame];
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ¤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);
std::cout << "Frame rendered: " << currentFrame << "\n";
if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) {
// Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes
}
else if (queuePresentResult != VK_SUCCESS) {
throw std::runtime_error("Failed to present the swapchain image.");
}
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
void Renderer::CreateSurface()
{
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a window surface.");
}
}
void Renderer::DestroySurface()
{
vkDestroySurfaceKHR(instance, surface, nullptr);
}
void Renderer::CreateInstance()
{
// Set up the application info
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Game Engine";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "Game Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_2;
// Set up the instance create info
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
// Set up the required extensions
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
createInfo.enabledExtensionCount = glfwExtensionCount;
createInfo.ppEnabledExtensionNames = glfwExtensions;
createInfo.enabledLayerCount = 0;
std::vector<const char*> validationLayers;
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
validationLayers.push_back("VK_LAYER_KHRONOS_validation");
#endif
if (enableValidationLayers) {
// Check if validation layers are supported
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char* layerName : validationLayers) {
bool layerFound = false;
for (const auto& layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
throw std::runtime_error("Validation layer requested, but it’s not available.");
}
}
// Enable the validation layers
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
}
else {
createInfo.enabledLayerCount = 0;
}
// Create the Vulkan instance
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create the Vulkan instance.");
}
}
void Renderer::CleanupInstance()
{
// Destroy the Vulkan instance
vkDestroyInstance(instance, nullptr);
}
void Renderer::ChoosePhysicalDevice()
{
// Enumerate the available physical devices and choose one that supports required features
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0)
{
throw std::runtime_error("Failed to find a GPU with Vulkan support.");
}
std::vector<VkPhysicalDevice> allDevices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data());
for (const auto& testDevice : allDevices)
{
if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) &&
CheckPhysicalDeviceExtensionSupport(testDevice).empty() &&
GetQueueFamilyIndices(testDevice).IsComplete())
{
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);
commandBuffers.resize(kMaxFramesInFlight * 2);
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size());
if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate command buffers.");
}
// Set the initial value of the currentCommandBuffer
currentCommandBuffer = commandBuffers[currentFrame];
}
void Renderer::CleanupCommandBuffers()
{
vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
}
void Renderer::CreateFramebuffers()
{
// Check if the framebuffers vector is not empty, and call CleanupFramebuffers()
if (!framebuffers.empty()) {
CleanupFramebuffers();
}
// Create Vulkan framebuffers for swapchain images
framebuffers.resize(swapChainImageViews.size());
for (size_t i = 0; i < swapChainImageViews.size(); ++i)
{
VkImageView attachments[] = { swapChainImageViews[i] };
VkFramebufferCreateInfo framebufferInfo{};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.renderPass = renderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = attachments;
framebufferInfo.width = swapChainExtent.width;
framebufferInfo.height = swapChainExtent.height;
framebufferInfo.layers = 1;
if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create framebuffer.");
}
}
}
void Renderer::CleanupFramebuffers()
{
for (auto framebuffer : framebuffers)
{
if (framebuffer != VK_NULL_HANDLE)
{
vkDestroyFramebuffer(device, framebuffer, nullptr);
framebuffer = VK_NULL_HANDLE;
}
}
framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer
}
void Renderer::CreateSyncObjects()
{
imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
VkSemaphoreCreateInfo semaphoreInfo{};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fenceInfo{};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create synchronization objects for a frame.");
}
}
}
void Renderer::CleanupSyncObjects()
{
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (renderFinishedSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
if (imageAvailableSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
if (inFlightFences[i] != VK_NULL_HANDLE)
vkDestroyFence(device, inFlightFences[i], nullptr);
}
}
SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface)
{
SwapChainSupportDetails details;
// Query the capabilities
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
// Query the supported formats
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
if (formatCount != 0)
{
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
}
// Query the supported present modes
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
if (presentModeCount != 0)
{
details.presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
}
return details;
}
VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats)
{
for (const auto& availableFormat : availableFormats)
{
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
{
return availableFormat;
}
}
return availableFormats[0];
}
VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes)
{
for (const auto& availablePresentMode : availablePresentModes)
{
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR)
{
return availablePresentMode;
}
}
return VK_PRESENT_MODE_FIFO_KHR;
}
VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window)
{
if (capabilities.currentExtent.width != UINT32_MAX)
{
return capabilities.currentExtent;
}
else
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) };
actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width));
actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height));
return actualExtent;
}
}
std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice)
{
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const auto& extension : availableExtensions)
{
requiredExtensions.erase(extension.extensionName);
}
std::vector<const char*> remainingExtensions;
for (const auto& extension : requiredExtensions)
{
remainingExtensions.push_back(extension.c_str());
}
return remainingExtensions;
}
QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice)
{
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto& queueFamily : queueFamilies)
{
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
indices.graphicsFamily = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport);
if (presentSupport)
{
indices.presentFamily = i;
}
if (indices.IsComplete())
{
break;
}
i++;
}
return indices;
}
VkDevice* Renderer::GetDevice() {
return &device;
};
VkPhysicalDevice* Renderer::GetPhysicalDevice() {
return &physicalDevice;
};
VkCommandPool* Renderer::GetCommandPool() {
return &commandPool;
};
VkQueue* Renderer::GetGraphicsQueue() {
return &graphicsQueue;
};
VkCommandBuffer* Renderer::GetCurrentCommandBuffer() {
return ¤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) {
if (pipeline)
{
pipeline->Cleanup();
}
// Create pipeline object and configure its properties
pipeline = std::make_shared<Pipeline>();
pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(),
mesh->GetVertexInputAttributeDescriptions(),
swapChainExtent,
{material->GetvertexShader().get(), material->GetfragmentShader().get()},
renderPass,
material->GetPipelineLayout(),
device);
}
std::shared_ptr<Pipeline> Renderer::GetPipeline() {
return pipeline;
}
I am getting a repeating error coming through the Vulkan validation layers:
VUID-VkFramebufferCreateInfo-height-00887(ERROR / SPEC): msgNum: -1513456701 - Validation Error: [ VUID-VkFramebufferCreateInfo-height-00887 ] Object 0: handle = 0x2ecd60e5490, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0xa5ca7bc3 | vkCreateFramebuffer(): Requested VkFramebufferCreateInfo height must be greater than zero. The Vulkan spec states: height must be greater than 0 (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkFramebufferCreateInfo-height-00887)
Objects: 1
[0] 0x2ecd60e5490, type: 3, name: NULL
What does it mean and how do I fix it?
|
fb908d1742512cb385272f7fea3954ce
|
{
"intermediate": 0.32107990980148315,
"beginner": 0.3840792775154114,
"expert": 0.29484084248542786
}
|
8,955
|
caffeine redis整合
|
fd344a8a4f1d55cd7e4126f8d3495d93
|
{
"intermediate": 0.49791419506073,
"beginner": 0.29588183760643005,
"expert": 0.20620395243167877
}
|
8,956
|
flutter get global offset for widget when in customList how?
|
5b3dbed158480321423cc08aa268955e
|
{
"intermediate": 0.5196170806884766,
"beginner": 0.20890243351459503,
"expert": 0.2714804410934448
}
|
8,957
|
Where is issue in this code? Code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
date = dt.datetime.now().strftime(“%m/%d/%Y %H:%M:%S”)
print(date)
url = “https://api.binance.com/api/v1/time”
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ‘’
API_SECRET = ‘’
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = ‘SELL’
POSITION_SIDE_LONG = ‘BUY’
symbol = ‘BTCUSDT’
quantity = 1
order_type = ‘MARKET’
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
try:
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+‘min ago UTC’))
frame = frame.iloc[:60,:6]
frame.columns = [‘Time’,‘Open’,‘High’,‘Low’,‘Close’,‘Volume’]
frame = frame.set_index(‘Time’)
today = dt.date.today()
frame.index = pd.to_datetime(frame.index, unit=‘ms’).tz_localize(‘UTC’).tz_convert(‘Etc/GMT+3’).strftime(f"{today} %H:%M:%S")
frame = frame.astype(float)
return frame
except Exception as e:
print(f"Error getting minute data: {str(e)}“)
return
df = getminutedata(‘BTCUSDT’, ‘1m’, ‘44640’)
def signal_generator(df):
try:
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return ‘sell’
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return ‘buy’
# No clear pattern
else:
return ‘’
except Exception as e:
print(f"Error generating signal: {str(e)}”)
return signal_generator(df)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = client.futures_account_balance()
usdt_balance = float([x[‘balance’] for x in account_balance if x[‘asset’] == ‘USDT’][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p[‘positionSide’] == ‘LONG’:
long_position = p
elif p[‘positionSide’] == ‘SHORT’:
short_position = p
if long_position is not None and short_position is not None:
print(“Multiple positions found. Closing both positions.”)
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position[‘positionAm’’],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position[‘positionAmt’],
reduceOnly=True
)
time.sleep(1)
print(“Both positions closed.”)
if signal == ‘buy’:
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == ‘sell’:
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print(“Invalid signal. No order placed.”)
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position[‘positionAmt’])))
if opposite_position is not None and opposite_position[‘positionSide’] != position_side:
print(“Opposite position found. Closing position before placing order.”)
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if opposite_position[‘positionSide’] == POSITION_SIDE_LONG else SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position[‘positionSide’]
)
time.sleep(1)
if opposite_position is not None:
opposite_side = (SIDE_SELL if opposite_position[‘positionSide’] ==
POSITION_SIDE_LONG
else SIDE_BUY)
else:
opposite_side = None
# Place the order and capture the returned order ID
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == ‘buy’ else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side,
leverage=leverage
)
if order is None:
print(“Order not placed successfully. Skipping setting stop loss and take profit orders.”)
order_id = order[‘orderId’]
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}“)
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print(“Error getting order information. Skipping setting stop loss and take profit orders.”)
else:
order_price = float(order_info[‘avgPrice’])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == ‘sell’ else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == ‘buy’ else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == ‘buy’ else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == ‘buy’ else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side
)
# Print order creation confirmation messages
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}”)
print(f"Placed stop loss order with stop loss price {stop_loss_price}“)
print(f"Placed take profit order with take profit price {take_profit_price}”)
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime(“%Y-%m-%d %H:%M:%S”)
df = getminutedata(‘BTCUSDT’, ‘1m’, ‘44640’) # Get minute data each loop
if df is None:
continue
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution(‘BTCUSDT’, current_signal, max_trade_quantity_percentage, leverage)
time.sleep(1) # Add a delay of 1 second
|
c286257d2b21cf8b65fa3b94998b252c
|
{
"intermediate": 0.33115994930267334,
"beginner": 0.4354007840156555,
"expert": 0.2334393411874771
}
|
8,958
|
make a DNA structure out of this 3d cube form in 3d and apply its vertices and edges to 3d matrix model in this code: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
// Transformation parameters
const scale = 0.01;
const zoom = 0.01;
const offsetX = 0.5;
const offsetY = 0.5;
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
let angleX = 0;
let angleY = 0;
let angleZ = 0;
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 100;
const amplitude = 1;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 6;
ctx.strokeStyle = 'hsla(' + (angleX + angleY) * 10 + ', 10%, 50%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
const angle = Math.atan2(y2 - y1, x2 - x1);
// Calculate control point for curved edge
const cpDist = 0.2 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2);
ctx.moveTo(x1, y1);
ctx.quadraticCurveTo(cpX, cpY, x2, y2);
}
ctx.stroke();
angleX += 0.005;
angleY += -0.005;
angleZ += -0.01;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
6210e95a2fc1951856328cbd4f547833
|
{
"intermediate": 0.28481894731521606,
"beginner": 0.39147916436195374,
"expert": 0.3237018883228302
}
|
8,959
|
make a DNA structure out of this 3d cube form in 3d and apply its vertices and edges to 3d matrix model in this code: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
// Transformation parameters
const scale = 0.01;
const zoom = 0.01;
const offsetX = 0.5;
const offsetY = 0.5;
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
let angleX = 0;
let angleY = 0;
let angleZ = 0;
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 100;
const amplitude = 1;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 6;
ctx.strokeStyle = 'hsla(' + (angleX + angleY) * 10 + ', 10%, 50%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
const angle = Math.atan2(y2 - y1, x2 - x1);
// Calculate control point for curved edge
const cpDist = 0.2 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2);
ctx.moveTo(x1, y1);
ctx.quadraticCurveTo(cpX, cpY, x2, y2);
}
ctx.stroke();
angleX += 0.005;
angleY += -0.005;
angleZ += -0.01;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
94b9ab068e6729bdf7834dd0b68363ba
|
{
"intermediate": 0.28481894731521606,
"beginner": 0.39147916436195374,
"expert": 0.3237018883228302
}
|
8,960
|
make a DNA structure out of this 3d cube form in 3d and apply its vertices and edges to 3d matrix model in this code: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
// Transformation parameters
const scale = 0.01;
const zoom = 0.01;
const offsetX = 0.5;
const offsetY = 0.5;
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
let angleX = 0;
let angleY = 0;
let angleZ = 0;
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 100;
const amplitude = 1;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 6;
ctx.strokeStyle = 'hsla(' + (angleX + angleY) * 10 + ', 10%, 50%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
const angle = Math.atan2(y2 - y1, x2 - x1);
// Calculate control point for curved edge
const cpDist = 0.2 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2);
ctx.moveTo(x1, y1);
ctx.quadraticCurveTo(cpX, cpY, x2, y2);
}
ctx.stroke();
angleX += 0.005;
angleY += -0.005;
angleZ += -0.01;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
a85e4c31bd128905be068bd92916fd6b
|
{
"intermediate": 0.28481894731521606,
"beginner": 0.39147916436195374,
"expert": 0.3237018883228302
}
|
8,961
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Renderer.cpp:
#include "Renderer.h"
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandBuffers();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
}
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//currentCommandBuffer = commandBuffers[currentFrame];
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2;
currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex];
// Add debug message before vkBeginCommandBuffer
std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n";
std::cout << "Calling vkBeginCommandBuffer…\n";
vkBeginCommandBuffer(currentCommandBuffer, &beginInfo);
std::cout << "vkBeginCommandBuffer called…\n";
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
// Set the clear color to black
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
}
void Renderer::EndFrame()
{
vkCmdEndRenderPass(currentCommandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame];
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ¤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);
std::cout << "Frame rendered: " << currentFrame << "\n";
if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) {
// Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes
}
else if (queuePresentResult != VK_SUCCESS) {
throw std::runtime_error("Failed to present the swapchain image.");
}
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
void Renderer::CreateSurface()
{
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a window surface.");
}
}
void Renderer::DestroySurface()
{
vkDestroySurfaceKHR(instance, surface, nullptr);
}
void Renderer::CreateInstance()
{
// Set up the application info
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Game Engine";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "Game Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_2;
// Set up the instance create info
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
// Set up the required extensions
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
createInfo.enabledExtensionCount = glfwExtensionCount;
createInfo.ppEnabledExtensionNames = glfwExtensions;
createInfo.enabledLayerCount = 0;
std::vector<const char*> validationLayers;
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
validationLayers.push_back("VK_LAYER_KHRONOS_validation");
#endif
if (enableValidationLayers) {
// Check if validation layers are supported
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char* layerName : validationLayers) {
bool layerFound = false;
for (const auto& layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
throw std::runtime_error("Validation layer requested, but it’s not available.");
}
}
// Enable the validation layers
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
}
else {
createInfo.enabledLayerCount = 0;
}
// Create the Vulkan instance
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create the Vulkan instance.");
}
}
void Renderer::CleanupInstance()
{
// Destroy the Vulkan instance
vkDestroyInstance(instance, nullptr);
}
void Renderer::ChoosePhysicalDevice()
{
// Enumerate the available physical devices and choose one that supports required features
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0)
{
throw std::runtime_error("Failed to find a GPU with Vulkan support.");
}
std::vector<VkPhysicalDevice> allDevices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data());
for (const auto& testDevice : allDevices)
{
if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) &&
CheckPhysicalDeviceExtensionSupport(testDevice).empty() &&
GetQueueFamilyIndices(testDevice).IsComplete())
{
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);
// Update the swapChainExtent with the chosen extent
swapChainExtent = extent;
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount)
{
imageCount = swapChainSupport.capabilities.maxImageCount;
}
// Create the swapchain
// …
VkSwapchainCreateInfoKHR createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = surface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice);
uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
if (indices.graphicsFamily != indices.presentFamily) {
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
createInfo.queueFamilyIndexCount = 2;
createInfo.pQueueFamilyIndices = queueFamilyIndices;
}
else {
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;
if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) {
throw std::runtime_error("failed to create swap chain!");
}
// Retrieve swapchain images (color buffers)
// …
// Retrieve swapchain images
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr);
swapChainImages.resize(imageCount);
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data());
// Create image views for swapchain images
CreateImageViews();
}
void Renderer::CleanupSwapchain()
{
// Clean up Vulkan swapchain
if (swapchain != VK_NULL_HANDLE)
{
vkDestroySwapchainKHR(device, swapchain, nullptr);
swapchain = VK_NULL_HANDLE;
}
}
void Renderer::CreateImageViews()
{
swapChainImageViews.resize(swapChainImages.size());
for (size_t i = 0; i < swapChainImages.size(); ++i)
{
VkImageViewCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.image = swapChainImages[i];
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = swapChainImageFormat;
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
createInfo.flags = 0;
if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create an image view.");
}
}
}
void Renderer::CleanupImageViews()
{
for (auto imageView : swapChainImageViews)
{
vkDestroyImageView(device, imageView, nullptr);
}
swapChainImageViews.clear();
}
void Renderer::CreateRenderPass()
{
VkAttachmentDescription colorAttachment{};
colorAttachment.format = swapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorAttachmentRef{};
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
VkRenderPassCreateInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &colorAttachment;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
VkSubpassDependency dependency{};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &dependency;
if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create render pass.");
}
}
void Renderer::CleanupRenderPass()
{
vkDestroyRenderPass(device, renderPass, nullptr);
}
void Renderer::CreateCommandPool()
{
// Find a queue family index that supports graphics operations
QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice);
// Create a command pool for the queue family
VkCommandPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
poolInfo.flags = 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);
commandBuffers.resize(kMaxFramesInFlight * 2);
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size());
if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate command buffers.");
}
// Set the initial value of the currentCommandBuffer
currentCommandBuffer = commandBuffers[currentFrame];
}
void Renderer::CleanupCommandBuffers()
{
vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
}
void Renderer::CreateFramebuffers()
{
// Check if the framebuffers vector is not empty, and call CleanupFramebuffers()
if (!framebuffers.empty()) {
CleanupFramebuffers();
}
// Create Vulkan framebuffers for swapchain images
framebuffers.resize(swapChainImageViews.size());
for (size_t i = 0; i < swapChainImageViews.size(); ++i)
{
VkImageView attachments[] = { swapChainImageViews[i] };
VkFramebufferCreateInfo framebufferInfo{};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.renderPass = renderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = attachments;
framebufferInfo.width = swapChainExtent.width;
framebufferInfo.height = swapChainExtent.height;
framebufferInfo.layers = 1;
if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create framebuffer.");
}
}
}
void Renderer::CleanupFramebuffers()
{
for (auto framebuffer : framebuffers)
{
if (framebuffer != VK_NULL_HANDLE)
{
vkDestroyFramebuffer(device, framebuffer, nullptr);
framebuffer = VK_NULL_HANDLE;
}
}
framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer
}
void Renderer::CreateSyncObjects()
{
imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
VkSemaphoreCreateInfo semaphoreInfo{};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fenceInfo{};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create synchronization objects for a frame.");
}
}
}
void Renderer::CleanupSyncObjects()
{
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (renderFinishedSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
if (imageAvailableSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
if (inFlightFences[i] != VK_NULL_HANDLE)
vkDestroyFence(device, inFlightFences[i], nullptr);
}
}
SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface)
{
SwapChainSupportDetails details;
// Query the capabilities
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
// Query the supported formats
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
if (formatCount != 0)
{
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
}
// Query the supported present modes
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
if (presentModeCount != 0)
{
details.presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
}
return details;
}
VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats)
{
for (const auto& availableFormat : availableFormats)
{
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
{
return availableFormat;
}
}
return availableFormats[0];
}
VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes)
{
for (const auto& availablePresentMode : availablePresentModes)
{
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR)
{
return availablePresentMode;
}
}
return VK_PRESENT_MODE_FIFO_KHR;
}
VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window)
{
if (capabilities.currentExtent.width != UINT32_MAX)
{
return capabilities.currentExtent;
}
else
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) };
actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width));
actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height));
return actualExtent;
}
}
std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice)
{
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const auto& extension : availableExtensions)
{
requiredExtensions.erase(extension.extensionName);
}
std::vector<const char*> remainingExtensions;
for (const auto& extension : requiredExtensions)
{
remainingExtensions.push_back(extension.c_str());
}
return remainingExtensions;
}
QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice)
{
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto& queueFamily : queueFamilies)
{
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
indices.graphicsFamily = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport);
if (presentSupport)
{
indices.presentFamily = i;
}
if (indices.IsComplete())
{
break;
}
i++;
}
return indices;
}
VkDevice* Renderer::GetDevice() {
return &device;
};
VkPhysicalDevice* Renderer::GetPhysicalDevice() {
return &physicalDevice;
};
VkCommandPool* Renderer::GetCommandPool() {
return &commandPool;
};
VkQueue* Renderer::GetGraphicsQueue() {
return &graphicsQueue;
};
VkCommandBuffer* Renderer::GetCurrentCommandBuffer() {
return ¤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) {
if (pipeline)
{
pipeline->Cleanup();
}
// Create pipeline object and configure its properties
pipeline = std::make_shared<Pipeline>();
pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(),
mesh->GetVertexInputAttributeDescriptions(),
swapChainExtent,
{material->GetvertexShader().get(), material->GetfragmentShader().get()},
renderPass,
material->GetPipelineLayout(),
device);
}
std::shared_ptr<Pipeline> Renderer::GetPipeline() {
return pipeline;
}
I am getting a repeating error coming through the Vulkan validation layers:
VUID-vkBeginCommandBuffer-commandBuffer-00050(ERROR / SPEC): msgNum: -1303445259 - Validation Error: [ VUID-vkBeginCommandBuffer-commandBuffer-00050 ] Object 0: handle = 0x1b56b937740, type = VK_OBJECT_TYPE_COMMAND_BUFFER; Object 1: handle = 0xcfef35000000000a, type = VK_OBJECT_TYPE_COMMAND_POOL; | MessageID = 0xb24f00f5 | Call to vkBeginCommandBuffer() on VkCommandBuffer 0x1b56b937740[] attempts to implicitly reset cmdBuffer created from VkCommandPool 0xcfef35000000000a[] that does NOT have the VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit set. The Vulkan spec states: If commandBuffer was allocated from a VkCommandPool which did not have the VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT flag set, commandBuffer must be in the initial state (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkBeginCommandBuffer-commandBuffer-00050)
Objects: 2
[0] 0x1b56b937740, type: 6, name: NULL
[1] 0xcfef35000000000a, type: 25, name: NULL
What does it mean and how do I fix it?
|
8e8434c467e1ef489bc1a61b8e10428f
|
{
"intermediate": 0.32107990980148315,
"beginner": 0.3840792775154114,
"expert": 0.29484084248542786
}
|
8,962
|
Based on the below column {
title: 'User Type',
dataIndex: 'role',
width: '20%',
key: 'role',
...getColumnSearchProps('role'),
// sorter: (a, b) => a.role < b.role,
sorter: (a, b) =>
userRolesById[a.role] > userRolesById[b.role] ? 1 : -1,
render: (_, { role }) => renderUserType(role),
}, const renderUserType = (role) => {
return userRolesById[role];
}; export const userRolesById = {
6789: "DATA COLLECTOR",
1456: "SUPERVISOR",
2148: "BRANCH MANAGER",
5278: "ADMIN",
4362: "STATISTICIAN",
8346: "BRANCH STATISTICIAN",
7812: "DATA CLEANER",
3420: "DIRECTORATE DIRECTOR",
9101: "SUPER ADMIN",
} why is searching by usertype not working
|
18d2ef80d6de352a2f1c71cf2671f711
|
{
"intermediate": 0.396370530128479,
"beginner": 0.29238972067832947,
"expert": 0.31123974919319153
}
|
8,963
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
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);
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
//scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreateDescriptorSet(descriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pBufferInfo = &bufferInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Texture.cpp:
#include "Texture.h"
#include "BufferUtils.h"
#include <iostream>
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
}
void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->physicalDevice = physicalDevice;
this->commandPool = commandPool;
this->graphicsQueue = graphicsQueue;
this->initialized = true;
// Load image from file using stb_image
int width, height, channels;
stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
{
throw std::runtime_error("Failed to load texture image!");
}
// Calculate the number of mip levels
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
// Create a buffer to store the image data
VkDeviceSize imageSize = width * height * 4;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
// Create and fill the buffer
// …
// Create the staging buffer for transferring image data
VkBufferCreateInfo bufferCreateInfo{};
bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferCreateInfo.size = imageSize;
bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferCreateInfo, nullptr, &stagingBuffer) != VK_SUCCESS) {
throw std::runtime_error("Failed to create staging buffer!");
}
VkMemoryRequirements memoryRequirements;
vkGetBufferMemoryRequirements(device, stagingBuffer, &memoryRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memoryRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
if (vkAllocateMemory(device, &allocInfo, nullptr, &stagingBufferMemory) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate staging buffer memory!");
}
// Create the staging buffer and staging buffer memory
BufferUtils::CreateBuffer(device, physicalDevice, imageSize,VK_BUFFER_USAGE_TRANSFER_SRC_BIT,VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,stagingBuffer, stagingBufferMemory);
vkBindBufferMemory(device, stagingBuffer, stagingBufferMemory, 0);
// Copy image data to the buffer
void* bufferData;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData);
memcpy(bufferData, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
// Free the stb_image buffer
stbi_image_free(pixels);
// Create vkImage, copy buffer to image, and create imageView and sampler
// …
CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
CreateSampler(mipLevels);
CopyBufferToImage(stagingBuffer, width, height);
// Cleanup the staging buffer and staging buffer memory
// …
// Destroy the staging buffer and free the staging buffer memory
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Texture::Cleanup(Texture* texture)
{
// Put the content of the old Cleanup() method here
// Make sure to replace this with texture keyword
// …
}
VkImageView Texture::GetImageView() const
{
return imageView;
}
VkSampler Texture::GetSampler() const
{
return sampler;
}
void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties)
{
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0;
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate image memory!");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
void Texture::TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels)
{
// …
// Create a one-time-use command buffer and record image layout transition commands
// …
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
// …
}
void Texture::CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels)
{
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture image view!");
}
}
void Texture::CreateSampler(uint32_t mipLevels)
{
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = static_cast<float>(mipLevels);
if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture sampler!");
}
}
void Texture::CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// Record buffer to image copy command in the command buffer
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
I am getting an error coming through the Vulkan validation layers:
VUID-vkBindBufferMemory-buffer-07459(ERROR / SPEC): msgNum: 1342280572 - Validation Error: [ VUID-vkBindBufferMemory-buffer-07459 ] Object 0: handle = 0xc4f3070000000021, type = VK_OBJECT_TYPE_DEVICE_MEMORY; Object 1: handle = 0xab64de0000000020, type = VK_OBJECT_TYPE_BUFFER; Object 2: handle = 0xc4f3070000000021, type = VK_OBJECT_TYPE_DEVICE_MEMORY; | MessageID = 0x5001937c | In vkBindBufferMemory(), attempting to bind VkDeviceMemory 0xc4f3070000000021[] to VkBuffer 0xab64de0000000020[] which has already been bound to VkDeviceMemory 0xc4f3070000000021[]. The Vulkan spec states: buffer must not have been bound to a memory object (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkBindBufferMemory-buffer-07459)
Objects: 3
[0] 0xc4f3070000000021, type: 8, name: NULL
[1] 0xab64de0000000020, type: 9, name: NULL
[2] 0xc4f3070000000021, type: 8, name: NULL
This error seems to occur in the Texture::LoadFromFile method at line:
vkBindBufferMemory(device, stagingBuffer, stagingBufferMemory, 0);
What does it mean and how do I fix it?
|
5b22bda8282b2db561966b44eb43f799
|
{
"intermediate": 0.32107990980148315,
"beginner": 0.3840792775154114,
"expert": 0.29484084248542786
}
|
8,964
|
const columns = [
{
title: "Users",
dataIndex: "fullName",
key: "fullName",
width: "40%",
...getColumnSearchProps("fullName"),
// sorter: (a, b) => a.fullName.length - b.fullName.length,
sorter: (a, b) => a.fullName.localeCompare(b.fullName),
},
{
title: "Status",
dataIndex: "disabled",
key: "disabled",
width: "20%",
...getColumnSearchProps("disabled"),
sorter: (a, b) => (a.disabled === b.disabled ? 0 : a.disabled ? -1 : 1), //return 0 if they’re equal, -1 if the first value is true, and 1 if the second value is true.
render: (_, { disabled }) => renderUserStatus(disabled),
},
{
title: "User Type",
dataIndex: "role",
width: "20%",
key: "role",
...getColumnSearchProps("role"),
// sorter: (a, b) => a.role < b.role,
sorter: (a, b) =>
userRolesById[a.role] > userRolesById[b.role] ? 1 : -1,
render: (_, { role }) => renderUserType(role),
},
{
title: "User Name",
dataIndex: "userName",
width: "20%",
key: "userName",
...getColumnSearchProps("userName"),
sorter: (a, b) => a.userName.toLowerCase() < b.userName.toLowerCase(),
},
]; all this columns use the below function to search columns const getColumnSearchProps = (dataIndex) => ({
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}) => (
<div
style={{
padding: 8,
}}
>
<Input
ref={searchInput}
placeholder={`Search ${dataIndex}`}
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
style={{
marginBottom: 8,
display: "block",
}}
/>
<Space>
<Button
type="primary"
onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
icon={<SearchOutlined />}
size="small"
style={{
width: 90,
}}
>
Search
</Button>
<Button
onClick={() => clearFilters && handleReset(clearFilters)}
size="small"
style={{
width: 90,
}}
>
Reset
</Button>
<Button
type="link"
size="small"
onClick={() => {
confirm({
closeDropdown: false,
});
setSearchText(selectedKeys[0]);
setSearchedColumn(dataIndex);
}}
>
Filter
</Button>
</Space>
</div>
),
filterIcon: (filtered) => (
<SearchOutlined
style={{
color: filtered ? "#1890ff" : undefined,
}}
/>
),
onFilter: (value, record) => {
dataIndex
? renderUserType(record[dataIndex])
.toLowerCase()
.includes(value.toLowerCase())
: record[dataIndex]
.toString()
.toLowerCase()
.includes(value.toLowerCase());
},
onFilterDropdownVisibleChange: (visible) => {
if (visible) {
setTimeout(() => searchInput.current?.select(), 100);
}
},
render: (text) =>
searchedColumn === dataIndex ? (
<Highlighter
highlightStyle={{
backgroundColor: "#ffc069",
padding: 0,
}}
searchWords={[searchText]}
autoEscape
textToHighlight={text ? text.toString() : ""}
/>
) : (
text
),
}); update onFilter so that is will conditionally use one of the methods when dataIndex is role
|
01317e5ec0eab35cd3befe41211523a1
|
{
"intermediate": 0.3855694532394409,
"beginner": 0.41873469948768616,
"expert": 0.1956958770751953
}
|
8,965
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
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);
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
//scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreateDescriptorSet(descriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pBufferInfo = &bufferInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Texture.cpp:
#include "Texture.h"
#include "BufferUtils.h"
#include <iostream>
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
}
void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->physicalDevice = physicalDevice;
this->commandPool = commandPool;
this->graphicsQueue = graphicsQueue;
this->initialized = true;
// Load image from file using stb_image
int width, height, channels;
stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
{
throw std::runtime_error("Failed to load texture image!");
}
// Calculate the number of mip levels
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
// Create a buffer to store the image data
VkDeviceSize imageSize = width * height * 4;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
// Create and fill the buffer
// …
// Create the staging buffer for transferring image data
VkBufferCreateInfo bufferCreateInfo{};
bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferCreateInfo.size = imageSize;
bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferCreateInfo, nullptr, &stagingBuffer) != VK_SUCCESS) {
throw std::runtime_error("Failed to create staging buffer!");
}
VkMemoryRequirements memoryRequirements;
vkGetBufferMemoryRequirements(device, stagingBuffer, &memoryRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memoryRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
if (vkAllocateMemory(device, &allocInfo, nullptr, &stagingBufferMemory) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate staging buffer memory!");
}
// Create the staging buffer and staging buffer memory
BufferUtils::CreateBuffer(device, physicalDevice, imageSize,VK_BUFFER_USAGE_TRANSFER_SRC_BIT,VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,stagingBuffer, stagingBufferMemory);
vkBindBufferMemory(device, stagingBuffer, stagingBufferMemory, 0);
// Copy image data to the buffer
void* bufferData;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData);
memcpy(bufferData, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
// Free the stb_image buffer
stbi_image_free(pixels);
// Create vkImage, copy buffer to image, and create imageView and sampler
// …
CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
CreateSampler(mipLevels);
CopyBufferToImage(stagingBuffer, width, height);
// Cleanup the staging buffer and staging buffer memory
// …
// Destroy the staging buffer and free the staging buffer memory
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Texture::Cleanup(Texture* texture)
{
// Put the content of the old Cleanup() method here
// Make sure to replace this with texture keyword
// …
}
VkImageView Texture::GetImageView() const
{
return imageView;
}
VkSampler Texture::GetSampler() const
{
return sampler;
}
void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties)
{
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0;
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate image memory!");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
void Texture::TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels)
{
// …
// Create a one-time-use command buffer and record image layout transition commands
// …
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
// …
}
void Texture::CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels)
{
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture image view!");
}
}
void Texture::CreateSampler(uint32_t mipLevels)
{
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = static_cast<float>(mipLevels);
if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture sampler!");
}
}
void Texture::CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// Record buffer to image copy command in the command buffer
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
BufferUtils.cpp:
#include "BufferUtils.h"
#include <stdexcept>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory)
{
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create buffer!");
}
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate buffer memory!");
}
vkBindBufferMemory(device, buffer, bufferMemory, 0);
}
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
throw std::runtime_error("Failed to find suitable memory type!");
}
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0; // Optional
copyRegion.dstOffset = 0; // Optional
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
}
I am getting an error coming through the Vulkan validation layers:
VUID-vkBindBufferMemory-buffer-07459(ERROR / SPEC): msgNum: 1342280572 - Validation Error: [ VUID-vkBindBufferMemory-buffer-07459 ] Object 0: handle = 0xc4f3070000000021, type = VK_OBJECT_TYPE_DEVICE_MEMORY; Object 1: handle = 0xab64de0000000020, type = VK_OBJECT_TYPE_BUFFER; Object 2: handle = 0xc4f3070000000021, type = VK_OBJECT_TYPE_DEVICE_MEMORY; | MessageID = 0x5001937c | In vkBindBufferMemory(), attempting to bind VkDeviceMemory 0xc4f3070000000021[] to VkBuffer 0xab64de0000000020[] which has already been bound to VkDeviceMemory 0xc4f3070000000021[]. The Vulkan spec states: buffer must not have been bound to a memory object (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkBindBufferMemory-buffer-07459)
Objects: 3
[0] 0xc4f3070000000021, type: 8, name: NULL
[1] 0xab64de0000000020, type: 9, name: NULL
[2] 0xc4f3070000000021, type: 8, name: NULL
This error seems to occur in the Texture::LoadFromFile method at line:
vkBindBufferMemory(device, stagingBuffer, stagingBufferMemory, 0);
What does it mean and how do I fix it?
|
7e8c5468d0aac2f42b1a23a26bc30d34
|
{
"intermediate": 0.32107990980148315,
"beginner": 0.3840792775154114,
"expert": 0.29484084248542786
}
|
8,966
|
Create a BPMN 2.0 (use xml) diagram for the follow case: approval of the employee job promotion
|
07e8351a733ec22d8b91a04fe8efc997
|
{
"intermediate": 0.2819708287715912,
"beginner": 0.2671757638454437,
"expert": 0.4508534073829651
}
|
8,967
|
hello
|
4fbe3cbfe0b9830585552d0d82940266
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
8,968
|
please write a deep learning code about attention using pytorch
|
5cde79ac4787e8a3acedc3f965871029
|
{
"intermediate": 0.05069134011864662,
"beginner": 0.03898493945598602,
"expert": 0.9103236794471741
}
|
8,969
|
write python code for sterotype ordered regression model
|
23dd46ce63397ee60ea000febdca543f
|
{
"intermediate": 0.17679688334465027,
"beginner": 0.11807902902364731,
"expert": 0.7051241397857666
}
|
8,970
|
I have a Header, Content, Footer layout in my React app. I want to have Call to Actions buttons in Footer based on route, but the onSubmit event should call actions defined in Content. How shoud I achieve that?
|
eef1f519eea3a4cb6d08ea6fdcc3943b
|
{
"intermediate": 0.5000820755958557,
"beginner": 0.2988240420818329,
"expert": 0.2010938972234726
}
|
8,971
|
To make the code send requests from different IP addresses, you can use proxy servers. You can set up a proxy server in the Playwright library with the following steps:
1. Install some proxy libraries if you haven’t already:
pip install proxybroker
2. You will need a list of proxy servers. You can obtain a list of proxy servers using the ‘proxybroker’ library. To find and collect a list of working proxies, use the following code snippet:
import asyncio
from proxybroker import Broker
async def show(proxies):
while True:
proxy = await proxies.get()
if proxy is None:
break
print(‘Found proxy: %s’ % proxy)
proxies = asyncio.Queue()
broker = Broker(proxies)
# Collect 10 working HTTP(S) proxies
tasks = asyncio.gather(broker.find(types=[‘HTTP’, ‘HTTPS’], limit=10))
if asyncio.run_until_complete(tasks):
print(‘Done.’)
This will provide you with a list of working proxies, store them in a list for using in your playwright code.
3. Update your main method to use the proxies while making requests with Playwright:
from random import choice
async def main():
# Add the list of proxies collected with proxybroker
proxy_list = [
# Format: ‘http://username:password@proxy_ip:proxy_port’
‘http://username:password@proxy_ip:proxy_port’,
‘http://username:password@proxy_ip:proxy_port’,
# Add more proxies as needed
]
while True:
# Randomly choose a proxy for each token_symbol
for token_symbol in token_symbols:
proxy = choice(proxy_list)
result = await get_token_info(token_symbol, proxy)
print(result)
await asyncio.sleep(60)
# Modify your get_token_info function to accept a proxy parameter
async def get_token_info(token_symbol, proxy):
# Existing code …
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True, proxy={“server”: proxy})
# Rest of the existing code …
These steps will ensure that the requests are sent using different IP addresses. Note that using free or public proxies can be unreliable and might affect the performance of your script. It’s recommended to use a reliable proxy service or your own proxy servers.
In conclusion, here’s the complete code with the integration of proxy:
import asyncio
from bs4 import BeautifulSoup
from random import choice
from playwright.async_api import async_playwright
async def get_token_info(token_symbol, proxy):
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True, proxy={“server”: proxy})
# Rest of the existing code…
# Add the list of proxies collected with proxybroker
proxy_list = [
# Format: ‘http://username:password@proxy_ip:proxy_port’
‘http://username:password@proxy_ip:proxy_port’,
‘http://username:password@proxy_ip:proxy_port’,
# Add more proxies as needed
]
async def main():
while True:
# Randomly choose a proxy for each token_symbol
for token_symbol in token_symbols:
proxy = choice(proxy_list)
result = await get_token_info(token_symbol, proxy)
print(result)
await asyncio.sleep(60)
token_symbols = [
“0x0E481Fa712201f61dAf97017138Efaa69e2A3df3”,
“0x2023aa62A7570fFd59F13fdE2Cac0527D45abF91”,
“0x2222222222222222222222222222222222222222”,
“0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e”]
asyncio.run(main())
The above code allows you to send requests from different ip addresses. will this be enough to parse the site, will they block ip addresses?
If that's not enough, please suggest a better way.
|
5d629b4198ef0d4990cc68cf6ad67089
|
{
"intermediate": 0.5116109848022461,
"beginner": 0.35662129521369934,
"expert": 0.13176770508289337
}
|
8,972
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def calculate_drawdown(net_returns):
cumulative_returns = np.cumsum(net_returns)
peak = cumulative_returns[0]
drawdown = 0
max_drawdown = 0
for i in range(1, len(cumulative_returns)):
if cumulative_returns[i] > peak:
peak = cumulative_returns[i]
else:
drawdown = peak - cumulative_returns[i]
if drawdown > max_drawdown:
max_drawdown = drawdown
return max_drawdown
df = pd.read_excel(r'C:/Users/陈赞/Desktop/data10.xls')
data=[]
plshangxian = 5
plxiaxian = 1
jineshangxian = 20
for pl_fake in range(plxiaxian * 10, plshangxian * 10):
pl_real = pl_fake / 10
if pl_real == 1:
continue
for put_fake in range(int(1.5 * 10), int(jineshangxian * 10) + 1, int(0.1 * 10)):
put_real = put_fake / 10
bdyl=[]
zhye=300
for x in range(0,len(df)):
if pl_real<=df['pl'].iloc[x] :
bdyl.append(pl_real*put_real-put_real)
zhye+=pl_real*put_real-put_real
elif pl_real>df['pl'].iloc[x]:
bdyl.append(-1*put_real)
zhye+=-1*put_real
drawdown=calculate_drawdown(bdyl)
data.append([pl_real,put_real,drawdown,zhye])现在我有10个excel文件,通过测试,找到能够使10个excel的data的zhye>=300的那组参数
|
32886c878f69b772b0a622dd5e6346fd
|
{
"intermediate": 0.41083645820617676,
"beginner": 0.39941662549972534,
"expert": 0.18974687159061432
}
|
8,973
|
write python code for sterotype ordered regression model
|
9cf15146de419fb0d20ff731e6404a70
|
{
"intermediate": 0.17679688334465027,
"beginner": 0.11807902902364731,
"expert": 0.7051241397857666
}
|
8,974
|
hi
|
8d6d3ac6fa3510668a4b0b141f5def1c
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
8,975
|
check what is wrong in this code import { Client, GatewayIntentBits, Routes } from "discord.js";
import { config } from "dotenv";
import { REST } from "discord.js";
config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const Token = process.env.BOT_TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
const GUILD_ID = process.env.GUILD_ID;
const rest = new REST({ version: "10" }).setToken(Token);
client.login(Token);
client.on("ready", () => {
console.log(`${client.user.tag} has logged IN`);
});
async function main() {
const commands = [
{
name: "helpingtest",
description: "Test will be done soon",
},
];
try {
console.log('starting commands')
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), {
body: commands,
});
} catch (err) {
console.log(err);
}
}
|
0f94f7b69f39e3900fbfeb1800a782e6
|
{
"intermediate": 0.6081973910331726,
"beginner": 0.21855074167251587,
"expert": 0.1732518970966339
}
|
8,976
|
i started my phd thesis. can you suggest what to do first and where to start
|
4ce154d7cea8ebb90abdc958eb3fda28
|
{
"intermediate": 0.255379319190979,
"beginner": 0.25708532333374023,
"expert": 0.48753538727760315
}
|
8,977
|
The log file name is passed as an argument to the text manager constructor. For example:
@LogFile('my_trace.log')
def some_func():
...
|
1a91b2530a1f12c9df7530c843393316
|
{
"intermediate": 0.3766448497772217,
"beginner": 0.3348066508769989,
"expert": 0.2885484993457794
}
|
8,978
|
Translate from SAS to R the following code
|
31a14f6dd3a15f4455ec697258ba3dba
|
{
"intermediate": 0.24538002908229828,
"beginner": 0.4362178146839142,
"expert": 0.31840217113494873
}
|
8,979
|
write the best way to reset styles in styled components react
|
9a1a9fc711016e2fc8870656e1942272
|
{
"intermediate": 0.40808603167533875,
"beginner": 0.1646168828010559,
"expert": 0.42729705572128296
}
|
8,980
|
can you infer typescript event type from this code: <input type="number" value={1} className="w-100 p-2" onChange={(e) => onChangeHandler(e)}/>
|
7417ba14a67cc756904e1b4ab43be7ab
|
{
"intermediate": 0.40986862778663635,
"beginner": 0.3110013008117676,
"expert": 0.27913007140159607
}
|
8,981
|
hi
|
ccadafbc713dde6acccf563d31de39fc
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
8,982
|
/**
*
* @param {Array} questionnaireItems
* @returns {void}
*/
export default function (questionnaireItems) {
questionnaireItems.forEach((questionnaireItem) => {
let product = 1;
let count = 0;
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (const quotation of questionnaireItem.quotations) {
for (const quote of quotation.cleanedQuotes) {
const price = parseFloat(quote.price);
quote.price = price;
if (price > 0) {
product *= price;
count++;
min = Math.min(min, price);
max = Math.max(max, price);
}
}
}
const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
const stdev = Math.sqrt(
questionnaireItem.quotations.reduce((sum, quotation) => {
for (const quote of quotation.cleanedQuotes) {
const price = parseFloat(quote.price);
if (price > 0) sum += Math.pow(price - geomean, 2);
}
return sum;
}, 0) / count
);
const variation = stdev / geomean;
if (geomean > 0) {
questionnaireItem.geomean = geomean.toFixed(2);
questionnaireItem.stdev = stdev.toFixed(2);
questionnaireItem.variation = variation.toFixed(2);
questionnaireItem.min = min.toFixed(2);
questionnaireItem.max = max.toFixed(2);
questionnaireItem.product = product.toFixed(2);
questionnaireItem.count = count.toFixed(2);
}
});
}
export function recalculateRow(rowData) {
// console.log("Row date is: ", rowData);
let product = 1;
let count = 0;
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (const quotation of Object.values(rowData.quotes)) {
for (const key of Object.keys(quotation)) {
const price = parseFloat(quotation[key]);
if (isOnlyQuote(key) && price > 0) {
product *= price;
count++;
min = Math.min(min, parseFloat(price));
max = Math.max(max, price);
}
}
}
const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
const stdev = Math.sqrt(
Object.values(rowData.quotes).reduce((sum, quotation) => {
for (const key of Object.keys(quotation)) {
const price = parseFloat(quotation[key]);
if (isOnlyQuote(key) && price > 0) sum += Math.pow(price - geomean, 2);
}
return sum;
}, 0) /
(count - 1)
);
const variation = stdev / geomean;
if (geomean > 0) {
rowData.geomean = isNaN(geomean) ? "0" : geomean.toFixed(2);
rowData.deviation = isNaN(stdev) ? "0" : stdev.toFixed(2);
rowData.variation = isNaN(variation) ? "0" : variation.toFixed(2);
rowData.minQ = isNaN(min) ? "0" : min.toFixed(2);
rowData.maxQ = isNaN(max) ? "0" : max.toFixed(2);
rowData.product = isNaN(product) ? "0" : product.toFixed(2);
rowData.count = isNaN(count) ? "0" : count.toFixed(2);
rowData.ratio = isNaN(max / min) ? "0" : (max / min).toFixed(2);
}
// console.log("Recalculated data: ", geomean, stdev, variation, rowData);
}
const isOnlyQuote = (str) => {
return /^((?!_)[A-Za-z0-9])+$/.test(str);
};
what does this code do
|
2f1c7770bb57cc91fc0dbd6a48350949
|
{
"intermediate": 0.2798352539539337,
"beginner": 0.4734990894794464,
"expert": 0.24666565656661987
}
|
8,983
|
The provided code will help in sending requests from different IP addresses. However, there is no guarantee that the target website will not block the IP addresses provided by the proxies.
To increase the chances of successful scraping and avoid IP blocking, consider the following best practices:
1. Implement rate limiting: Insert a random delay between requests to reduce the rate at which you are sending requests to the website. You can use the time.sleep() function along with a random interval. For example:
import time
from random import randint
time.sleep(randint(2, 10))
2. Use a rotating proxy service: Instead of using a static list of proxies, consider using a rotating proxy service that provides a large number of proxy servers and rotates them automatically.
3. Respect the website’s robots.txt file: Be sure to check the target website’s robots.txt file to ensure that you are allowed to scrape the required data.
4. Spoof user-agent strings: Websites might block requests that come from automated user-agents. Make your requests appear more human-like by using random user-agent strings.
from playwright.async_api import async_playwright
from fake_useragent import UserAgent
ua = UserAgent()
async def get_token_info(token_symbol, proxy):
async with async_playwright() as p:
browser = await p.chromium.launch(
headless=True,
proxy={“server”: proxy},
user_agent=ua.random,
)
# Rest of the existing code…
By combining these best practices with the provided code, you can significantly improve your chances of successful scraping without getting blocked by the target website. Nevertheless, it’s essential to comply with the website’s terms and conditions and ensure that you’re using compliant web scraping practices.
Основываясь на твоем ответе расположенном выще, реализуй все эти пункты через программный код с подробными комментариями
The provided code will help in sending requests from different IP addresses. However, there is no guarantee that the target website will not block the IP addresses provided by the proxies.
To increase the chances of successful scraping and avoid IP blocking, consider the following best practices:
1. Implement rate limiting: Insert a random delay between requests to reduce the rate at which you are sending requests to the website. You can use the time.sleep() function along with a random interval. For example:
import time
from random import randint
time.sleep(randint(2, 10))
2. Use a rotating proxy service: Instead of using a static list of proxies, consider using a rotating proxy service that provides a large number of proxy servers and rotates them automatically.
3. Respect the website’s robots.txt file: Be sure to check the target website’s robots.txt file to ensure that you are allowed to scrape the required data.
4. Spoof user-agent strings: Websites might block requests that come from automated user-agents. Make your requests appear more human-like by using random user-agent strings.
from playwright.async_api import async_playwright
from fake_useragent import UserAgent
ua = UserAgent()
async def get_token_info(token_symbol, proxy):
async with async_playwright() as p:
browser = await p.chromium.launch(
headless=True,
proxy={“server”: proxy},
user_agent=ua.random,
)
# Rest of the existing code…
By combining these best practices with the provided code, you can significantly improve your chances of successful scraping without getting blocked by the target website. Nevertheless, it’s essential to comply with the website’s terms and conditions and ensure that you’re using compliant web scraping practices.
Based on your answer above, implement all of these points through code with detailed comments.
|
9331abc428d432d47d66eda00cc73b01
|
{
"intermediate": 0.29480817914009094,
"beginner": 0.43431392312049866,
"expert": 0.2708778977394104
}
|
8,984
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
//scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreateDescriptorSet(descriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pBufferInfo = &bufferInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Texture.cpp:
#include "Texture.h"
#include "BufferUtils.h"
#include <iostream>
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
}
void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->physicalDevice = physicalDevice;
this->commandPool = commandPool;
this->graphicsQueue = graphicsQueue;
this->initialized = true;
// Load image from file using stb_image
int width, height, channels;
stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
{
throw std::runtime_error("Failed to load texture image!");
}
// Calculate the number of mip levels
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
// Create a buffer to store the image data
VkDeviceSize imageSize = width * height * 4;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
// Create the staging buffer for transferring image data
BufferUtils::CreateBuffer(device, physicalDevice, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
// Copy image data to the buffer
void* bufferData;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData);
memcpy(bufferData, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
// Free the stb_image buffer
stbi_image_free(pixels);
// Create vkImage, copy buffer to image, and create imageView and sampler
// …
CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
CreateSampler(mipLevels);
CopyBufferToImage(stagingBuffer, width, height);
// Cleanup the staging buffer and staging buffer memory
// …
// Destroy the staging buffer and free the staging buffer memory
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Texture::Cleanup(Texture* texture)
{
// Put the content of the old Cleanup() method here
// Make sure to replace this with texture keyword
// …
}
VkImageView Texture::GetImageView() const
{
return imageView;
}
VkSampler Texture::GetSampler() const
{
return sampler;
}
void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties)
{
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0;
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate image memory!");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
void Texture::TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels)
{
// …
// Create a one-time-use command buffer and record image layout transition commands
// …
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
// …
}
void Texture::CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels)
{
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture image view!");
}
}
void Texture::CreateSampler(uint32_t mipLevels)
{
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = static_cast<float>(mipLevels);
if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture sampler!");
}
}
void Texture::CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// Record buffer to image copy command in the command buffer
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
BufferUtils.cpp:
#include "BufferUtils.h"
#include <stdexcept>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory)
{
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create buffer!");
}
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate buffer memory!");
}
vkBindBufferMemory(device, buffer, bufferMemory, 0);
}
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
throw std::runtime_error("Failed to find suitable memory type!");
}
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0; // Optional
copyRegion.dstOffset = 0; // Optional
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
}
I am getting an error coming through the Vulkan validation layers:
VUID-VkSamplerCreateInfo-anisotropyEnable-01070(ERROR / SPEC): msgNum: 1458672316 - Validation Error: [ VUID-VkSamplerCreateInfo-anisotropyEnable-01070 ] Object 0: handle = 0x1e70a2c83d0, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x56f192bc | vkCreateSampler(): Anisotropic sampling feature is not enabled, pCreateInfo->anisotropyEnable must be VK_FALSE. The Vulkan spec states: If the samplerAnisotropy feature is not enabled, anisotropyEnable must be VK_FALSE (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkSamplerCreateInfo-anisotropyEnable-01070)
Objects: 1
[0] 0x1e70a2c83d0, type: 3, name: NULL
I believe it may be related to the ChoosePhysicalDevice and CreateDevice methods in the Renderer class. Here they are for reference:
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);
}
How would I modify the code to fix this issue?
|
2bae89bcc58f324dc5fcb7ed88194457
|
{
"intermediate": 0.4038229286670685,
"beginner": 0.3279862403869629,
"expert": 0.268190860748291
}
|
8,985
|
if A wants to send money to B, A has a visa and B has a paypal account, A can't make a paypal account. What websites can they use to send money via visa and recieve it via paypal
|
06b49f803d2dd571b8c7ef3fb080d7a9
|
{
"intermediate": 0.42500826716423035,
"beginner": 0.29080718755722046,
"expert": 0.2841845750808716
}
|
8,986
|
make randomly generated form in 3d matrix vertices and edges. from 3d cube to triangle - to sphere - to some random etc… make an endless random form generation through some transition time period. output full code: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
// Transformation parameters
const scale = 0.01;
const zoom = 0.01;
const offsetX = 0.5;
const offsetY = 0.5;
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
let angleX = 0;
let angleY = 0;
let angleZ = 0;
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 100;
const amplitude = 1;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 6;
ctx.strokeStyle = ‘hsla(’ + (angleX + angleY) * 10 + ‘, 10%, 50%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
const angle = Math.atan2(y2 - y1, x2 - x1);
// Calculate control point for curved edge
const cpDist = 0.2 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2);
ctx.moveTo(x1, y1);
ctx.quadraticCurveTo(cpX, cpY, x2, y2);
}
ctx.stroke();
angleX += 0.005;
angleY += -0.005;
angleZ += -0.01;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
af0b2da584718b0b96fc8c9ede0a3033
|
{
"intermediate": 0.2738526165485382,
"beginner": 0.5064542293548584,
"expert": 0.219693124294281
}
|
8,987
|
hi
|
1e4e6912a8f682051e7685d61c6dc4bf
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
8,988
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
//scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreateDescriptorSet(descriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pBufferInfo = &bufferInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Texture.cpp:
#include "Texture.h"
#include "BufferUtils.h"
#include <iostream>
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
}
void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->physicalDevice = physicalDevice;
this->commandPool = commandPool;
this->graphicsQueue = graphicsQueue;
this->initialized = true;
// Load image from file using stb_image
int width, height, channels;
stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
{
throw std::runtime_error("Failed to load texture image!");
}
// Calculate the number of mip levels
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
// Create a buffer to store the image data
VkDeviceSize imageSize = width * height * 4;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
// Create the staging buffer for transferring image data
BufferUtils::CreateBuffer(device, physicalDevice, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
// Copy image data to the buffer
void* bufferData;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData);
memcpy(bufferData, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
// Free the stb_image buffer
stbi_image_free(pixels);
// Create vkImage, copy buffer to image, and create imageView and sampler
// …
CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
CreateSampler(mipLevels);
TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels); // Add this call
CopyBufferToImage(stagingBuffer, width, height);
// Cleanup the staging buffer and staging buffer memory
// …
// Destroy the staging buffer and free the staging buffer memory
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Texture::Cleanup(Texture* texture)
{
// Put the content of the old Cleanup() method here
// Make sure to replace this with texture keyword
// …
}
VkImageView Texture::GetImageView() const
{
return imageView;
}
VkSampler Texture::GetSampler() const
{
return sampler;
}
void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties)
{
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0;
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate image memory!");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
void Texture::TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels)
{
// …
// Create a one-time-use command buffer and record image layout transition commands
// …
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
// …
}
void Texture::CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels)
{
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture image view!");
}
}
void Texture::CreateSampler(uint32_t mipLevels)
{
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = static_cast<float>(mipLevels);
if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture sampler!");
}
}
void Texture::CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// Record buffer to image copy command in the command buffer
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
BufferUtils.cpp:
#include "BufferUtils.h"
#include <stdexcept>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory)
{
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create buffer!");
}
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate buffer memory!");
}
vkBindBufferMemory(device, buffer, bufferMemory, 0);
}
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
throw std::runtime_error("Failed to find suitable memory type!");
}
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0; // Optional
copyRegion.dstOffset = 0; // Optional
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
}
It seems the TransitionImageLayout method is incomplete and not working as required. Can you generate the complete code for the method?
|
aff66f93e1e8c880b036a408febaef00
|
{
"intermediate": 0.4038229286670685,
"beginner": 0.3279862403869629,
"expert": 0.268190860748291
}
|
8,990
|
i need u write some python code of solving differential equation
|
038a07a9154de8a77d2b3652b94fb4d5
|
{
"intermediate": 0.3232453763484955,
"beginner": 0.1423412412405014,
"expert": 0.5344133377075195
}
|
8,991
|
how can i specify that product is of type IProduct in this scenario?
import React, {useEffect, useState} from "react";
import axios from "axios";
import {useToast} from "../context/ToastContext";
import {useUser} from "../context/UserContext";
import {Link} from "react-router-dom";
import Card from "react-bootstrap/Card";
interface IProduct {
_id: string,
name: string,
model: string,
image: string,
description: string,
price: {
single: number,
loyalty: number,
},
categories: string[] | [],
similar: string[] | []
}
export function DetailedProduct({id}: {id: string}) {
const {displayToast, setVisibility} = useToast()
const {user} = useUser()
const [isLoaded, setLoading] = useState(false)
const [product, setProduct] = useState({
_id: "",
name: "",
model: "",
image: "",
description: "",
categories: [],
price: {single: undefined, loyalty: undefined},
similar: [],
} as const)
const {
_id,
categories,
description,
image,
similar,
model,
name,
price,
} = product as Record<keyof typeof product, string | number | object | string[]>;
console.log({id, _id})
async function getProduct() {
try {
const response = await axios.post('/api/getProduct', {id, user})
setProduct(response.data)
setLoading(true)
} catch (error) {
setVisibility(true)
displayToast("error", "Ошибка получения данных от сервера")
setLoading(true)
}
}
useEffect(() => {
getProduct()
}, [id])
const displaySimilar = similar.map((item) => {
const hasDiscount = user && (!(user.Category !== "Пользователь") || user.Category !== undefined)
return <div className="col-6 col-md-4 col-xl-2 my-3" key={item._id}>
<Card className="h-100">
<Link to={`/product/${item._id}`}>
<Card.Img variant="top" src={'/api/static/' + item.image}/>
</Link>
<Card.Body className="bg-light pb-0 d-flex flex-wrap justify-content-between align-self-stretch">
<Card.Title className="fs-6">
<Link to={`/product/${_id}`} className="text-black fw-bold ">
{item.name}
</Link>
</Card.Title>
<Card.Subtitle className="mb-3 mx-3">
<div className="w-100 text-center fw-semibold">
<div>{item.price.single.toFixed(2)} MDL</div>
{hasDiscount && <div>{item.price.loyalty.toFixed(2)} MDL</div>}
</div>
</Card.Subtitle>
</Card.Body>
</Card>
</div>
})
function onChangeHandler(e: React.ChangeEvent<HTMLInputElement>) {
return null
}
return (
<div className="container">
{isLoaded && <div className="row border border-secondary g-0">
<div className="col-md-4">
<img className="img-fluid" src={`/api/static/${image}`}/>
<div className="d-flex mx-2 justify-content-center">
{categories.map(category => {
return <div className="border border-secondary rounded-pill small d-inline-block px-1 my-2"
key={category}>{category}</div>
})}
</div>
</div>
<div className="col-md-8">
<div className="border-bottom border-secondary fs-4 text-center text-black fw-bold px-2">
{name} ({model})
</div>
<div className="px-2 my-2">
{description}
</div>
<div className="fs-4 px-2 row">
<div className="col-sm-6">
{price.single.toFixed(2) + " MDL" || "ОШИБКА"}
</div>
<div className="w-50 align-self-center">
<input type="number" value={1} className="w-100 p-1" onChange={(e) => onChangeHandler(e)}/>
</div>
</div>
<div className="text-center mt-3">
<button className="btn btn-primary rounded-0 w-100">В корзину</button>
</div>
</div>
<div className="fs-3 text-center border-top border-secondary">Похожие товары:</div>
<div className="row align-self-center g-1">
{displaySimilar}
</div>
</div>}
</div>
)
}
|
1b0e76982d65115613743885be9defae
|
{
"intermediate": 0.3852022886276245,
"beginner": 0.46568289399147034,
"expert": 0.14911487698554993
}
|
8,992
|
У меня есть корзину, и она уже хорошо работает в Firstfragmetn , я хочу чтобы эта же корзина работал в SecondFragmetn , но уже с товарами только их этого фрагмента что нужно изменить или добавить напиши весь небходимый код , который нужно добавить к моему :package com.example.myapp_2.Data.cart;
import com.example.myapp_2.Data.List_1.Product;
import java.util.ArrayList;
import java.util.List;
public class Cart {
private static Cart instance;
private List<CartItem> items;
private Cart() {
items = new ArrayList<>();
}
public static Cart getInstance() {
if (instance == null) {
instance = new Cart();
}
return instance;
}
public void addItem(Product product) {
for (CartItem item : items) {
if (item.getProduct().equals(product)) {
item.setQuantity(item.getQuantity() + 1);
return;
}
}
items.add(new CartItem(product, 1));
}
public void updateItem(CartItem item, int newQuantity) {
if (newQuantity <= 0) {
removeItem(item);
} else {
item.setQuantity(newQuantity);
}
}
public void removeItem(CartItem item) {
items.remove(item);
}
public List<CartItem> getItems() {
return items;
}
public void clear() {
items.clear();
}
public double getTotalPrice() {
double totalPrice = 0;
for (CartItem item : items) {
totalPrice += item.getTotalPrice();
}
return totalPrice;
}
}
package com.example.myapp_2.Data.cart;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
import java.util.List;
public class CartAdapter extends RecyclerView.Adapter<CartItemViewHolder> {
private List<CartItem> items;
private OnCartItemListener listener;
public CartAdapter(List<CartItem> items, OnCartItemListener listener) {
this.items = items;
this.listener = listener;
}
@Override
public CartItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cart, parent, false);
return new CartItemViewHolder(view);
}
@Override
public void onBindViewHolder(CartItemViewHolder holder, int position) {
CartItem item = items.get(position);
holder.bind(item, listener);
}
@Override
public int getItemCount() {
return items.size();
}
public void setItems(List<CartItem> items) {
this.items = items;
notifyDataSetChanged();
}
}package com.example.myapp_2.Data.cart;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
public class CartFragment extends Fragment {
private TextView totalPriceTextView;
private Button placeOrderButton;
private RecyclerView recyclerView;
private CartAdapter adapter;
private Cart cart;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
// Инициализируем UI и получаем объект Cart из синглтона
totalPriceTextView = view.findViewById(R.id.total_price_text_view);
placeOrderButton = view.findViewById(R.id.place_order_button);
recyclerView = view.findViewById(R.id.cart_recycler_view);
cart = Cart.getInstance();
adapter = new CartAdapter(cart.getItems(), new OnCartItemListener() {
@Override
public void onQuantityChanged(CartItem item, int newQuantity) {
cart.updateItem(item, newQuantity);
updateTotalPrice();
}
@Override
public void onRemoveButtonClick(CartItem item) {
cart.removeItem(item);
adapter.setItems(cart.getItems());
updateTotalPrice();
}
});
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
updateTotalPrice();
placeOrderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Опять работа???",Toast.LENGTH_SHORT).show();
}
});
return view;
}
private void placeOrder() {
// Здесь должен быть код для оформления заказа
}
private void updateTotalPrice() {
double totalPrice = cart.getTotalPrice();
totalPriceTextView.setText(getString(R.string.cart_item_total_price, totalPrice));
}
}package com.example.myapp_2.Data.cart;
import com.example.myapp_2.Data.List_1.Product;
public class CartItem {
private Product product; // сам товар
private int quantity; // количество
public CartItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getTotalPrice() {
return product.getPrice() * quantity;
}
}
package com.example.myapp_2.Data.cart;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.Data.List_1.Product;
import com.example.myapp_2.R;
public class CartItemViewHolder extends RecyclerView.ViewHolder {
private ImageView productImageView;
private TextView productNameTextView;
private TextView productPriceTextView;
private TextView productTotalPriceTextView;
private TextView productQuantityTextView;
private Button decreaseButton;
private Button increaseButton;
private Button removeButton;
private int quantity;
public CartItemViewHolder(@NonNull View itemView) {
super(itemView);
productImageView = itemView.findViewById(R.id.cart_item_image_view);
productNameTextView = itemView.findViewById(R.id.cart_item_name_text_view);
productPriceTextView = itemView.findViewById(R.id.cart_item_price_text_view);
productTotalPriceTextView = itemView.findViewById(R.id.cart_item_total_price_text_view);
productQuantityTextView = itemView.findViewById(R.id.cart_item_quantity_text_view);
decreaseButton = itemView.findViewById(R.id.cart_item_decrease_button);
increaseButton = itemView.findViewById(R.id.cart_item_increase_button);
removeButton = itemView.findViewById(R.id.cart_item_remove_button);
}
public void bind(CartItem item, OnCartItemListener listener) {
Product product = item.getProduct();
quantity = item.getQuantity();
productImageView.setImageResource(product.getImageResource());
productNameTextView.setText(product.getName());
productPriceTextView.setText(itemView.getContext().getString(R.string.product_price, product.getPrice()));
productTotalPriceTextView.setText(itemView.getContext().getString(R.string.cart_item_total_price, item.getTotalPrice()));
productQuantityTextView.setText(String.valueOf(quantity));
decreaseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quantity -= 1;
productQuantityTextView.setText(String.valueOf(quantity));
listener.onQuantityChanged(item, quantity);
}
});
increaseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quantity += 1;
productQuantityTextView.setText(String.valueOf(quantity));
listener.onQuantityChanged(item, quantity);
}
});
removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onRemoveButtonClick(item);
}
});
}
}
package com.example.myapp_2.Data.cart;
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
public class ItemSpacingDecoration extends RecyclerView.ItemDecoration {
private int mSpacing; // промежуток между элементами
public ItemSpacingDecoration(int spacing) {
this.mSpacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
// Добавляем отступ снизу элемента
outRect.bottom = mSpacing;
}
}package com.example.myapp_2.Data.cart;
public interface OnCartItemListener {
void onQuantityChanged(CartItem item, int newQuantity);//вызывается при изменении количества товара в корзине
void onRemoveButtonClick(CartItem item);//вызывается при нажатии на кнопку удаления товара из корзины
}
package com.example.myapp_2.Data.cart;
import com.example.myapp_2.Data.List_1.Product;
public interface OnProductClickListener {
void onAddToCartClick(Product product);
}
package com.example.myapp_2.Data.cart;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.Data.List_1.Product;
import com.example.myapp_2.Data.List_1.ProductAdapter;
import com.example.myapp_2.R;
import java.util.List;
public class ProductsFragment extends Fragment {
private List<Product> productList;
private RecyclerView recyclerView;
private ProductAdapter adapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_products, container, false);
adapter = new ProductAdapter(productList, new OnProductClickListener() {
@Override
public void onAddToCartClick(Product product) {
addToCart(product);
}
});
// Здесь инициализируем список товаров и recyclerView
adapter = new ProductAdapter(productList, new OnProductClickListener() {
@Override
public void onAddToCartClick(Product product) {
addToCart(product);
}
}); // передаём метод добавления товара в корзину
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
private void addToCart(Product product) {
// метод добавления товара в корзину
Cart cart = Cart.getInstance();
cart.addItem(product);
}
}
|
409047d93f95c96f4b72168849c1600c
|
{
"intermediate": 0.3908640146255493,
"beginner": 0.4934704303741455,
"expert": 0.11566552519798279
}
|
8,993
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
//scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreateDescriptorSet(descriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pBufferInfo = &bufferInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Texture.cpp:
#include "Texture.h"
#include "BufferUtils.h"
#include <iostream>
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
}
void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->physicalDevice = physicalDevice;
this->commandPool = commandPool;
this->graphicsQueue = graphicsQueue;
this->initialized = true;
// Load image from file using stb_image
int width, height, channels;
stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
{
throw std::runtime_error("Failed to load texture image!");
}
// Calculate the number of mip levels
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
// Create a buffer to store the image data
VkDeviceSize imageSize = width * height * 4;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
// Create the staging buffer for transferring image data
BufferUtils::CreateBuffer(device, physicalDevice, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
// Copy image data to the buffer
void* bufferData;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData);
memcpy(bufferData, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
// Free the stb_image buffer
stbi_image_free(pixels);
// Create vkImage, copy buffer to image, and create imageView and sampler
// …
CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
CreateSampler(mipLevels);
TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels, VK_SAMPLE_COUNT_1_BIT); // Add this call
CopyBufferToImage(stagingBuffer, width, height);
// Cleanup the staging buffer and staging buffer memory
// …
// Destroy the staging buffer and free the staging buffer memory
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Texture::Cleanup(Texture* texture)
{
// Put the content of the old Cleanup() method here
// Make sure to replace this with texture keyword
// …
}
VkImageView Texture::GetImageView() const
{
return imageView;
}
VkSampler Texture::GetSampler() const
{
return sampler;
}
void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties)
{
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0;
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate image memory!");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
void Texture::TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
VkPipelineStageFlags sourceStage;
VkPipelineStageFlags destinationStage;
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
else {
throw std::invalid_argument("Unsupported layout transition!");
}
vkCmdPipelineBarrier(
commandBuffer,
sourceStage, destinationStage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
void Texture::CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels)
{
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture image view!");
}
}
void Texture::CreateSampler(uint32_t mipLevels)
{
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = static_cast<float>(mipLevels);
if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture sampler!");
}
}
void Texture::CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// Record buffer to image copy command in the command buffer
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
BufferUtils.cpp:
#include "BufferUtils.h"
#include <stdexcept>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory)
{
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create buffer!");
}
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate buffer memory!");
}
vkBindBufferMemory(device, buffer, bufferMemory, 0);
}
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
throw std::runtime_error("Failed to find suitable memory type!");
}
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0; // Optional
copyRegion.dstOffset = 0; // Optional
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
}
I am getting this error:
VUID-VkWriteDescriptorSet-descriptorType-00319(ERROR / SPEC): msgNum: -405619238 - Validation Error: [ VUID-VkWriteDescriptorSet-descriptorType-00319 ] Object 0: handle = 0xa2eb680000000026, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; | MessageID = 0xe7d2bdda | vkUpdateDescriptorSets() pDescriptorWrites[0] failed write update validation for VkDescriptorSet 0xa2eb680000000026[] with error: Attempting write update to VkDescriptorSet 0xa2eb680000000026[] allocated with VkDescriptorSetLayout 0x9fde6b0000000014[] binding #0 with type VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER but update type is VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER. The Vulkan spec states: descriptorType must match the type of dstBinding within dstSet (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkWriteDescriptorSet-descriptorType-00319)
Objects: 1
[0] 0xa2eb680000000026, type: 23, name: NULL
It seems to occur when calling vkUpdateDescriptorSets in the Material::CreateDescriptorSet method. How can I alter the code to fix this issue?
|
9cfda62ed871825ecc18320940806acc
|
{
"intermediate": 0.4038229286670685,
"beginner": 0.3279862403869629,
"expert": 0.268190860748291
}
|
8,994
|
// Online C compiler to run C program online
#include <stdio.h>
enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };
char request2[728] = {0x50,0x4F,0x53,0x54,0x20,0x2F,0x61,0x6E,0x69,0x6D,0x61,0x74,0x69,0x6F,0x6E,0x55,0x70,0x6C,0x6F,0x61,0x64,0x20,0x48,0x54,0x54,0x50,0x2F,0x31,0x2E,0x31,0x0D,0x0A,0x48,0x6F,0x73,0x74,0x3A,0x20,0x31,0x39,0x32,0x2E,0x31,0x36,0x38,0x2E,0x30,0x2E,0x31,0x30,0x36,0x0D,0x0A,0x43,0x6F,0x6E,0x74,0x65,0x6E,0x74,0x2D,0x54,0x79,0x70,0x65,0x3A,0x20,0x6D,0x75,0x6C,0x74,0x69,0x70,0x61,0x72,0x74,0x2F,0x66,0x6F,0x72,0x6D,0x2D,0x64,0x61,0x74,0x61,0x3B,0x20,0x62,0x6F,0x75,0x6E,0x64,0x61,0x72,0x79,0x3D,0x46,0x35,0x35,0x39,0x36,0x35,0x36,0x33,0x2D,0x31,0x30,0x30,0x42,0x2D,0x34,0x37,0x41,0x35,0x2D,0x39,0x31,0x36,0x46,0x2D,0x44,0x42,0x39,0x31,0x33,0x31,0x35,0x37,0x32,0x36,0x46,0x38,0x0D,0x0A,0x55,0x73,0x65,0x72,0x2D,0x41,0x67,0x65,0x6E,0x74,0x3A,0x20,0x50,0x6F,0x77,0x65,0x72,0x4C,0x69,0x74,0x65,0x73,0x2F,0x34,0x31,0x20,0x43,0x46,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x2F,0x31,0x34,0x30,0x34,0x2E,0x30,0x2E,0x35,0x20,0x44,0x61,0x72,0x77,0x69,0x6E,0x2F,0x32,0x32,0x2E,0x33,0x2E,0x30,0x0D,0x0A,0x43,0x6F,0x6E,0x6E,0x65,0x63,0x74,0x69,0x6F,0x6E,0x3A,0x20,0x6B,0x65,0x65,0x70,0x2D,0x61,0x6C,0x69,0x76,0x65,0x0D,0x0A,0x41,0x63,0x63,0x65,0x70,0x74,0x3A,0x20,0x2A,0x2F,0x2A,0x0D,0x0A,0x41,0x63,0x63,0x65,0x70,0x74,0x2D,0x4C,0x61,0x6E,0x67,0x75,0x61,0x67,0x65,0x3A,0x20,0x72,0x75,0x0D,0x0A,0x43,0x6F,0x6E,0x74,0x65,0x6E,0x74,0x2D,0x4C,0x65,0x6E,0x67,0x74,0x68,0x3A,0x20,0x33,0x39,0x35,0x0D,0x0A,0x43,0x61,0x63,0x68,0x65,0x2D,0x43,0x6F,0x6E,0x74,0x72,0x6F,0x6C,0x3A,0x20,0x6E,0x6F,0x2D,0x63,0x61,0x63,0x68,0x65,0x0D,0x0A,0x41,0x63,0x63,0x65,0x70,0x74,0x2D,0x45,0x6E,0x63,0x6F,0x64,0x69,0x6E,0x67,0x3A,0x20,0x67,0x7A,0x69,0x70,0x2C,0x20,0x64,0x65,0x66,0x6C,0x61,0x74,0x65,0x0D,0x0A,0x0D,0x0A,0x2D,0x2D,0x46,0x35,0x35,0x39,0x36,0x35,0x36,0x33,0x2D,0x31,0x30,0x30,0x42,0x2D,0x34,0x37,0x41,0x35,0x2D,0x39,0x31,0x36,0x46,0x2D,0x44,0x42,0x39,0x31,0x33,0x31,0x35,0x37,0x32,0x36,0x46,0x38,0x0D,0x0A,0x43,0x6F,0x6E,0x74,0x65,0x6E,0x74,0x2D,0x44,0x69,0x73,0x70,0x6F,0x73,0x69,0x74,0x69,0x6F,0x6E,0x3A,0x20,0x66,0x6F,0x72,0x6D,0x2D,0x64,0x61,0x74,0x61,0x3B,0x20,0x6E,0x61,0x6D,0x65,0x3D,0x22,0x66,0x69,0x6C,0x65,0x22,0x3B,0x20,0x66,0x69,0x6C,0x65,0x6E,0x61,0x6D,0x65,0x3D,0x22,0x61,0x6E,0x69,0x6D,0x61,0x74,0x69,0x6F,0x6E,0x2E,0x62,0x69,0x6E,0x22,0x0D,0x0A,0x43,0x6F,0x6E,0x74,0x65,0x6E,0x74,0x2D,0x54,0x79,0x70,0x65,0x3A,0x20,0x61,0x70,0x70,0x6C,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x2F,0x6F,0x63,0x74,0x65,0x74,0x2D,0x73,0x74,0x72,0x65,0x61,0x6D,0x0D,0x0A,0x0D,0x0A,0x00,0x40,0x00,0x00,0x00,0x32,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0xFF,0x00,0x00,0x0D,0x0A,0x2D,0x2D,0x46,0x35,0x35,0x39,0x36,0x35,0x36,0x33,0x2D,0x31,0x30,0x30,0x42,0x2D,0x34,0x37,0x41,0x35,0x2D,0x39,0x31,0x36,0x46,0x2D,0x44,0x42,0x39,0x31,0x33,0x31,0x35,0x37,0x32,0x36,0x46,0x38,0x2D,0x2D,0x0D,0x0A};
int _headerKeysCount = 0;
int main() {
char *methodStr, *url, *versionEnd;
int addr_start, addr_end, versionStart;
enum HTTPMethod method = HTTP_GET;
char* request = (char*)malloc(728 * sizeof(char)); // выделяем память для строки
strncpy(request, request2, sizeof(request2)); // копируем содержимое массива request в строку
// request[sizeof(request2)] = ‘\0’; // добавляем символ конца строки
// printf(“Строка: %s\n”, request); // выводим полученную строку
char *str, *token; //*str,
str = strdup(request); // дуплицируем строку request
token = strtok(str, "\r\n"); // находим первую подстроку, используя символы
printf(str);
int lc = 0;
_headerKeysCount = 0;
while (token != NULL)
{
//printf("%d ",lc);
lc++;
printf("Subtring: %s\n", token);
token = strtok(NULL, "\r\n");
}
printf("Hello world");
return 0;
} выводит ошибку Segmentation fault почему?
|
47bf136a2bff622992d0f5dc430d72e3
|
{
"intermediate": 0.3339356780052185,
"beginner": 0.350957989692688,
"expert": 0.3151063919067383
}
|
8,995
|
import time
from random import randint
from playwright.async_api import async_playwright
from fake_useragent import UserAgent
import requests
# Set up Fake UserAgent for random user-agents
ua = UserAgent()
# Function to implement random delay (rate limiting)
def random_delay(minimum=2, maximum=10):
sleep_time = randint(minimum, maximum)
time.sleep(sleep_time)
# Function to check if a website’s robots.txt allows scraping to implement point 3
def can_scrape(url):
response = requests.get(url + “/robots.txt”)
if “Disallow: /” in response.text:
return False
return True
async def get_token_info(token_symbol, proxy):
# Prepare the url and the rotating proxy
url = f"https://targetwebsite.com/tokens/{token_symbol}“
# Check if we can scrape the requested URL
if not can_scrape(url):
print(“Scraping is not allowed according to the website’s robots.txt”)
return None
async with async_playwright() as p:
# Launch the browser with rotating proxy and random user-agent, to implement point 2 & 4
browser = await p.chromium.launch(
headless=True,
proxy={“server”: proxy},
user_agent=ua.random,
)
try:
# Rest of the existing code…
page = await browser.new_page()
await page.goto(url)
# Capture the info from the website here…
await browser.close()
# Implement rate limiting (point 1)
random_delay()
# Return the info captured from the website
return captured_info
except Exception as ex:
print(f"Error occurred while scraping: {ex}”)
await browser.close()
return None
# Example usage
asyncio.run(get_token_info(“BTC”, “http://proxy.example.com:8080”))
Complete the above code so that it performs the same functions as the code below
import asyncio
from bs4 import BeautifulSoup
from playwright.async_api import async_playwright
async def get_token_info(token_symbol):
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
context = await browser.new_context()
page = await context.new_page()
await page.goto("https://moonarch.app/")
search_box_selector = 'input.form-control'
await page.wait_for_selector(search_box_selector)
search_box = await page.query_selector(search_box_selector)
await search_box.type(token_symbol)
await page.wait_for_selector('.token-info')
await page.wait_for_selector('.infocard')
soup = BeautifulSoup(await page.content(), "html.parser")
token_info_element = soup.find("div", class_="token-info")
infocard_element = soup.find("div", class_="infocard")
check_alert_element = soup.find("div", class_="token-check-message check-alert")
check_warning_element = soup.find("div", class_="token-check-message check-warning")
check_info_element = soup.find("div", class_="token-check-message check-info")
not_verified_element = soup.find("div", class_="not-verified")
check_alert_status = "Yes" if check_alert_element else "None"
check_warning_status = "Yes" if check_warning_element else "None"
check_info_status = "Yes" if check_info_element else "None"
not_verified_status = "Yes" if not_verified_element else "None"
if token_info_element and infocard_element:
token_name_element = token_info_element.find("span", class_="name")
token_symbol_element = token_info_element.find("span", class_="symbol")
info_items = infocard_element.find_all("li")
if token_name_element and token_symbol_element and len(info_items) >= 7:
token_name = token_name_element.text.strip()
token_symbol = token_symbol_element.text.strip()
price = info_items[0].find("span", class_="value").text.strip()
max_supply = info_items[1].find("span", class_="value").text.strip()
market_cap = info_items[2].find("span", class_="value").text.strip()
liquidity = info_items[3].find("span", class_="value").text.strip()
liq_mc = info_items[4].find("span", class_="value").text.strip()
token_age = info_items[6].find("span", class_="value").text.strip()
await browser.close()
return {
"name": token_name,
"symbol": token_symbol,
"price": price,
"max_supply": max_supply,
"market_cap": market_cap,
"liquidity": liquidity,
"liq_mc": liq_mc,
"token_age": token_age,
"check_alert": check_alert_status,
"check_warning": check_warning_status,
"check_info": check_info_status,
"not_verified": not_verified_status
}
else:
await browser.close()
error_info = f"token_name_element: {token_name_element}, token_symbol_element: {token_symbol_element}, info_items count: {len(info_items)}"
return {"error": f"Failed to find the required info items or name and.symbol. Error_info: {error_info}"}
else:
await browser.close()
return {"error": f"Failed to find the required elements for token_info_element ({token_info_element}) and infocard_element ({infocard_element})."}
token_symbols = [
"0x0E481Fa712201f61dAf97017138Efaa69e2A3df3",
"0x2023aa62A7570fFd59F13fdE2Cac0527D45abF91",
"0x2222222222222222222222222222222222222222",
"0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e"]
async def main():
while True:
result_tasks = [get_token_info(token_symbol) for token_symbol in token_symbols]
results = await asyncio.gather(*result_tasks)
print(results)
await asyncio.sleep(60)
asyncio.run(main())
These methods should also remain in it.
1. random_delay() function is added for rate limiting.
2. The proxy parameter in the get_token_info function accepts a rotating proxy service URL.
3. The can_scrape() function is added to respect the website's robots.txt file.
4. The fake_useragent library is utilized to spoof random user-agent strings during browser launch.
|
04db0aa2769c6a3dddd6b9e3312b52eb
|
{
"intermediate": 0.26074275374412537,
"beginner": 0.5679033994674683,
"expert": 0.17135384678840637
}
|
8,996
|
how to run html java code stripechallenge in vscode?
|
cc918b0fdfc46c7319ba6f525f17c27e
|
{
"intermediate": 0.5612155199050903,
"beginner": 0.27904462814331055,
"expert": 0.15973985195159912
}
|
8,997
|
const Container = styled.div`
width: 100%;
height: 100vh;
display: flex;
background-color: coral;
position: relative;
`;
const Arrow = styled.div`
width: 50px;
height: 50px;
background-color: lightgray;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
bottom: 0;
left: ${(props) => (props.direction === "left" ? "10px" : null)};
right: ${(props) => (props.direction === "right" ? "150px" : null)};
margin: auto;
`;
const Slider = () => {
return (
<Container>
<Arrow direction="left">
<ArrowBackIosNewOutlinedIcon />
</Arrow>
<Arrow direction="right">
<ArrowForwardIosOutlinedIcon />
</Arrow>
</Container>
);
};
export default Slider;
why this doesn't work
|
76752143dc3acca3a998438f1f8b5b71
|
{
"intermediate": 0.35387465357780457,
"beginner": 0.3653515577316284,
"expert": 0.28077375888824463
}
|
8,998
|
how to store data in a list and call it from anywhere in program.cs in C#
|
ce75f1026379f1233f1d46e160f80953
|
{
"intermediate": 0.5941210389137268,
"beginner": 0.19471928477287292,
"expert": 0.21115967631340027
}
|
8,999
|
remove password sheet xlsb file vba code
|
74e79e367382f2fb6b13d4d1d918b925
|
{
"intermediate": 0.34687474370002747,
"beginner": 0.31717395782470703,
"expert": 0.3359512388706207
}
|
9,000
|
Размести кнопку назад чтобы он была в левом верхнем углу и была в виде стрелочки в лево : <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/cart_recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toTopOf="@+id/total_price_text_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/total_price_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Total price: 0.00"
android:textColor="@color/colorAccent"
android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"
app:layout_constraintBottom_toTopOf="@+id/place_order_button"
tools:ignore="MissingConstraints" />
<Button
android:id="@+id/place_order_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="66dp"
android:text="Place Order"
app:layout_constraintBottom_toBottomOf="parent"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
|
bd180a0b006fe39fcdddd063b4d40df2
|
{
"intermediate": 0.41395893692970276,
"beginner": 0.2786991596221924,
"expert": 0.30734190344810486
}
|
9,001
|
What is the best way to generate a unique booking reference using nest js?
|
d35b88e2067d21079a9d73a02a57fc0e
|
{
"intermediate": 0.39235174655914307,
"beginner": 0.20868299901485443,
"expert": 0.3989652097225189
}
|
9,002
|
Based on the following calculate function /**
*
* @param {Array} questionnaireItems
* @returns {void}
*/
export default function (questionnaireItems) {
questionnaireItems.forEach((questionnaireItem) => {
let product = 1;
let count = 0;
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (const quotation of questionnaireItem.quotations) {
for (const quote of quotation.cleanedQuotes) {
const price = parseFloat(quote.price);
quote.price = price;
if (price > 0) {
product *= price;
count++;
min = Math.min(min, price);
max = Math.max(max, price);
}
}
}
const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
const stdev = Math.sqrt(
questionnaireItem.quotations.reduce((sum, quotation) => {
for (const quote of quotation.cleanedQuotes) {
const price = parseFloat(quote.price);
if (price > 0) sum += Math.pow(price - geomean, 2);
}
return sum;
}, 0) / count
);
const variation = stdev / geomean;
if (geomean > 0) {
questionnaireItem.geomean = geomean.toFixed(2);
questionnaireItem.stdev = stdev.toFixed(2);
questionnaireItem.variation = variation.toFixed(2);
questionnaireItem.min = min.toFixed(2);
questionnaireItem.max = max.toFixed(2);
questionnaireItem.product = product.toFixed(2);
questionnaireItem.count = count.toFixed(2);
}
});
}
export function recalculateRow(rowData) {
// console.log("Row date is: ", rowData);
let product = 1;
let count = 0;
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (const quotation of Object.values(rowData.quotes)) {
for (const key of Object.keys(quotation)) {
const price = parseFloat(quotation[key]);
if (isOnlyQuote(key) && price > 0) {
product *= price;
count++;
min = Math.min(min, parseFloat(price));
max = Math.max(max, price);
}
}
}
const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
const stdev = Math.sqrt(
Object.values(rowData.quotes).reduce((sum, quotation) => {
for (const key of Object.keys(quotation)) {
const price = parseFloat(quotation[key]);
if (isOnlyQuote(key) && price > 0) sum += Math.pow(price - geomean, 2);
}
return sum;
}, 0) /
(count - 1)
);
const variation = stdev / geomean;
if (geomean > 0) {
rowData.geomean = isNaN(geomean) ? “0” : geomean.toFixed(2);
rowData.deviation = isNaN(stdev) ? “0” : stdev.toFixed(2);
rowData.variation = isNaN(variation) ? “0” : variation.toFixed(2);
rowData.minQ = isNaN(min) ? “0” : min.toFixed(2);
rowData.maxQ = isNaN(max) ? “0” : max.toFixed(2);
rowData.product = isNaN(product) ? “0” : product.toFixed(2);
rowData.count = isNaN(count) ? “0” : count.toFixed(2);
rowData.ratio = isNaN(max / min) ? “0” : (max / min).toFixed(2);
}
// console.log("Recalculated data: ", geomean, stdev, variation, rowData);
}
const isOnlyQuote = (str) => {
return /^((?!_)[A-Za-z0-9])+/.test(str);
};
why is the below fucntion not calculating after it fetches questionnaireItems from the backend emisAxiosInstance
.get(reqUrl, {
headers: { Authorization: `Bearer{auth.accessToken}` },
// signal: controller.signal
})
.then((response) => {
// console.log('grid data response: ', response);
// console.log('auth: ', auth);
// Calculate geomean and stuff
const { marketplaces, maxQuotation } =
getMarketplacesAndMaxQuotation(response);
geomean_calculator(response.data.data.questionnaireItems);
console.log("response: ", response);
// responseData = response;
setReqResponseData(response);
generateRows(response, marketplaces, maxQuotation);
generateColumns(response, marketplaces, maxQuotation);
});
setIsAgGridLoading(false);
// }, [saveCounter, fetchRegionCode]);
}, [saveCounter, selectedRegion]);
|
ecdcc1945abc8f357109c741d5387189
|
{
"intermediate": 0.3281567692756653,
"beginner": 0.47404202818870544,
"expert": 0.19780117273330688
}
|
9,003
|
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.;
import java.awt.event.;
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.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// 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
);
if (response == JOptionPane.YES_OPTION) {
dealer.clearCardsOnHand();
player.clearCardsOnHand();
} else {
carryOn = false;
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 javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameTableFrame extends JFrame {
private GameTablePanel gameTablePanel;
private Dealer dealer;
private Player player;
private JLabel shufflingLabel;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
gameTablePanel = new GameTablePanel(dealer, player);
shufflingLabel = new JLabel(“Shuffling”);
shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER);
playButton = new JButton(“Play”);
quitButton = new JButton(“Quit”);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shufflingLabel.setVisible(true);
HighSum highSum = new HighSum();
highSum.init(player.getLoginName(), “some_default_password”);
highSum.run();
updateScreen();
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Create the main panel that contains both the game board and the buttons
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(playButton);
buttonsPanel.add(quitButton);
mainPanel.add(gameTablePanel, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
mainPanel.add(shufflingLabel, BorderLayout.NORTH);
shufflingLabel.setVisible(false);
add(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
// This method updates the screen after each game
public void updateScreen() {
gameTablePanel.updateTable(dealer, player);
}
}
package GUIExample;
import java.awt.;
import javax.swing.;
import Model.;
public class GameTablePanel extends JPanel {
private Player player;
private Dealer dealer;
public GameTablePanel(Dealer dealer, Player player) {
setLayout(new BorderLayout());
setBackground(Color.GREEN);
setPreferredSize(new Dimension(1024, 768));
this.dealer = dealer;
this.player = player;
}
public void updateTable(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw dealer’s cards
int dealerX = 50;
int dealerY = 100;
g.drawString(“Dealer”, dealerX, dealerY - 20);
dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true);
// Draw player’s cards
int playerX = 50;
int playerY = getHeight() - 200;
g.drawString(“Player”, playerX, playerY - 20);
playerX = drawPlayerHand(g, player, playerX, playerY, false);
// Draw chips on the table
g.setColor(Color.BLACK);
g.setFont(new Font(“Arial”, Font.PLAIN, 18));
g.drawString(“Chips on the table: “, playerX + 50, playerY);
}
private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) {
int i = 0;
for (Card c : p.getCardsOnHand()) {
if (isDealer && i == 0) {
new ImageIcon(“images/back.png”).paintIcon(this, g, x, y);
} else {
c.paintIcon(this, g, x, y);
}
x += 100;
i++;
}
return x;
}
}
package GUIExample;
import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginDialog extends JDialog {
private JTextField loginField;
private JPasswordField passwordField;
private JButton loginButton;
private boolean loggedIn = false;
public LoginDialog(JFrame parent) {
super(parent, “Login”, true);
loginField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton(“Login”);
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loggedIn = true;
dispose();
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel(“Login:”));
panel.add(loginField);
panel.add(new JLabel(“Password:”));
panel.add(passwordField);
panel.add(loginButton);
add(panel);
pack();
setLocationRelativeTo(parent);
}
public String getLogin() {
return loginField.getText();
}
public String getPassword() {
return new String(passwordField.getPassword());
}
public boolean isLoggedIn() {
return loggedIn;
}
}
package Helper;
public class Keyboard {
public static String readString(String prompt) {
System.out.print(prompt);
return new java.util.Scanner(System.in).nextLine();
}
public static int readInt(String prompt) {
int input = 0;
boolean valid = false;
while (!valid) {
try {
input = Integer.parseInt(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println(”** Please enter an integer “);
}
}
return input;
}
public static double readDouble(String prompt) {
double input = 0;
boolean valid = false;
while (!valid) {
try {
input = Double.parseDouble(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println(” Please enter a double “);
}
}
return input;
}
public static float readFloat(String prompt) {
float input = 0;
boolean valid = false;
while (!valid) {
try {
input = Float.parseFloat(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println(” Please enter a float “);
}
}
return input;
}
public static long readLong(String prompt) {
long input = 0;
boolean valid = false;
while (!valid) {
try {
input = Long.parseLong(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println(” Please enter a long “);
}
}
return input;
}
public static char readChar(String prompt,char[] choices) {
boolean validChoice = false;
char r = ’ ';
while(!validChoice) {
r = Keyboard.readChar(prompt+” “+charArrayToString(choices)+”:“);
if(!validateChoice(choices,r)) {
System.out.println(“Invalid input”);
}else {
validChoice = true;
}
}
return r;
}
private static String charArrayToString(char[] charArray) {
String s = “[”;
for(int i=0;i<charArray.length;i++) {
s+=charArray[i];
if(i!=charArray.length-1) {
s+=”,“;
}
}
s += “]”;
return s;
}
private static boolean validateChoice(char[] choices, char choice) {
boolean validChoice = false;
for(int i=0;i<choices.length;i++) {
if(choices[i]==choice) {
validChoice = true;
break;
}
}
return validChoice;
}
public static char readChar(String prompt) {
char input = 0;
boolean valid = false;
while (!valid) {
String temp = readString(prompt);
if (temp.length() != 1) {
System.out.println(” Please enter a character “);
} else {
input = temp.charAt(0);
valid = true;
}
}
return input;
}
public static boolean readBoolean(String prompt) {
boolean valid = false;
while (!valid) {
String input = readString(prompt);
if (input.equalsIgnoreCase(“yes”) || input.equalsIgnoreCase(“y”) || input.equalsIgnoreCase(“true”)
|| input.equalsIgnoreCase(“t”)) {
return true;
} else if (input.equalsIgnoreCase(“no”) || input.equalsIgnoreCase(“n”) || input.equalsIgnoreCase(“false”)
|| input.equalsIgnoreCase(“f”)) {
return false;
} else {
System.out.println(” Please enter Yes/No or True/False “);
}
}
return false;
}
public static java.util.Date readDate(String prompt) {
java.util.Date date = null;
boolean valid = false;
while (!valid) {
try {
String input = readString(prompt).trim();
if (input.matches(”\d\d/\d\d/\d\d\d\d”)) {
int day = Integer.parseInt(input.substring(0, 2));
int month = Integer.parseInt(input.substring(3, 5));
int year = Integer.parseInt(input.substring(6, 10));
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setLenient(false);
cal.set(year, month - 1, day, 0, 0, 0);
date = cal.getTime();
valid = true;
} else {
System.out.println(" Please enter a date (DD/MM/YYYY) “);
}
} catch (IllegalArgumentException e) {
System.out.println(” Please enter a date (DD/MM/YYYY) “);
}
}
return date;
}
private static String quit = “0”;
public static int getUserOption(String title, String[] menu) {
displayMenu(title, menu);
int choice = Keyboard.readInt(“Enter Choice --> “);
while (choice > menu.length || choice < 0) {
choice = Keyboard.readInt(“Invalid Choice, Re-enter --> “);
}
return choice;
}
private static void displayMenu(String title, String[] menu) {
line(80, “=”);
System.out.println(title.toUpperCase());
line(80, “-”);
for (int i = 0; i < menu.length; i++) {
System.out.println(”[” + (i + 1) + “] " + menu[i]);
}
System.out.println(”[” + quit + “] Quit”);
line(80, “-”);
}
public static void line(int len, String c) {
System.out.println(String.format(”%” + len + “s”, " “).replaceAll(” “, c));
}
}
package Helper;
import java.security.MessageDigest;
public class Utility {
public static String getHash(String base)
{
String message=”“;
try{
MessageDigest digest = MessageDigest.getInstance(“SHA-256”);
byte[] hash = digest.digest(base.getBytes(“UTF-8”));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append(‘0’);
hexString.append(hex);
}
message = hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
return message;
}
public static void printLine(int num)
{
printLine(num,‘-’);
}
public static void printDoubleLine(int num)
{
printLine(num,‘=’);
}
public static void printLine(int num,char pattern)
{
for(int i =0;i<num;i++)
{
System.out.print(pattern);
}
System.out.println(”“);
}
}
package Model;
import javax.swing.;
public class Card extends ImageIcon {
private String suit;
private String name;
private int value;
private int rank;
private boolean faceDown;
public Card(String suit, String name, int value, int rank) {
super(“images/” + suit + name + “.png”);
this.suit = suit;
this.name = name;
this.value = value;
this.rank = rank;
this.faceDown = false;
}
public boolean isFaceDown() {
return this.faceDown;
}
public void setFaceDown(boolean faceDown) {
this.faceDown = faceDown;
}
public String getSuit() {
return this.suit;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
public int getRank() {
return this.rank;
}
public String toString() {
if (this.faceDown) {
return “<HIDDEN CARD>”;
} else {
return “<” + this.suit + " " + this.name + “>”;
}
}
public String display() {
return “<”+this.suit+” “+this.name+” “+this.rank+”>";
}
}
//card rank
// D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.;
public class Dealer extends Player {
private Deck deck;
public Dealer() {
super(“Dealer”, “”, 0);
deck = new Deck();
}
public void shuffleCards() {
System.out.println(“Dealer shuffle deck”);
deck.shuffle();
}
public void dealCardTo(Player player) {
Card card = deck.dealCard(); // take a card out from the deck
player.addCard(card); // pass the card into the player
}
public void addCardsBackToDeck(ArrayList<Card> cards) {
deck.appendCard(cards);
}
//return 1 if card1 rank higher, else return 2
public int determineWhichCardRankHigher(Card card1, Card card2) {
if(card1.getRank()>card2.getRank()) {
return 1;
}else {
return 2;
}
}
}
package Model;
import java.util.;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
String[] suits = { “Diamond”, “Club”,“Heart”,“Spade”, };
for (int i = 0; i < suits.length; i++) {
String suit = suits[i];
Card card = new Card(suit, “Ace”, 1,1+i);
cards.add(card);
int c = 5;
for (int n = 2; n <= 10; n++) {
Card oCard = new Card(suit, “” + n, n,c+i);
cards.add(oCard);
c+=4;
}
Card jackCard = new Card(suit, “Jack”, 10,41+i);
cards.add(jackCard);
Card queenCard = new Card(suit, “Queen”, 10,45+i);
cards.add(queenCard);
Card kingCard = new Card(suit, “King”, 10,49+i);
cards.add(kingCard);
}
}
public Card dealCard() {
return cards.remove(0);
}
//add back one card
public void appendCard(Card card) {
cards.add(card);
}
//add back arraylist of cards
public void appendCard(ArrayList<Card> cards) {
for(Card card: cards) {
this.cards.add(card);
}
}
public void shuffle() {
Random random = new Random();
for(int i=0;i<10000;i++) {
int indexA = random.nextInt(cards.size());
int indexB = random.nextInt(cards.size());
Card cardA = cards.get(indexA);
Card cardB = cards.get(indexB);
cards.set(indexA, cardB);
cards.set(indexB, cardA);
}
}
//for internal use only
private void showCards() {
for (Card card : cards) {
System.out.println(card);
}
}
//for internal use only
private void displayCards() {
for (Card card : cards) {
System.out.println(card.display());
}
}
public static void main(String[] args) {
Deck deck = new Deck();
//deck.shuffle();
/Card card1 = deck.dealCard();
Card card2 = deck.dealCard();
Card card3 = deck.dealCard();
deck.showCards();
ArrayList<Card> cards = new ArrayList<Card>();
cards.add(card1);
cards.add(card2);
cards.add(card3);
deck.appendCard(cards);
System.out.println();/
deck.displayCards();
}
}
//card rank
//D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import Controller.;
import View.;
import GUIExample.LoginDialog;
import GUIExample.GameTableFrame;
import javax.swing.JOptionPane;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class HighSum {
private Dealer dealer;
private Player player;
private ViewController view;
private GameController gc;
private int chipsOnTable;
public HighSum() {
}
public void init(String login, String password) {
// Create all the required objects
this.dealer = new Dealer();
this.player = new Player(login, password, 50);
this.view = new ViewController();
// Bring them together
this.gc = new GameController(this.dealer, this.player, this.view);
}
private Player checkWinner() {
if(player.getTotalCardsValue() > dealer.getTotalCardsValue())
return player;
else if(player.getTotalCardsValue() < dealer.getTotalCardsValue())
return dealer;
else
return null;
}
public Dealer getDealer() {
return dealer;
}
public Player getPlayer() {
return player;
}
public void run() {
// Setup the game table
GameTableFrame gameTableFrame = new GameTableFrame(dealer, player);
// Starts the game!
boolean carryOn = true;
while (carryOn) {
runOneRound();
gameTableFrame.updateScreen();
if (!gc.getPlayerQuitStatus()) {
int response = JOptionPane.showConfirmDialog(
gameTableFrame,
“Do you want to play another game?”,
“New Game”,
JOptionPane.YES_NO_OPTION
);
carryOn = response == JOptionPane.YES_OPTION;
} else {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
gameTableFrame.dispose();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for (int round = 1; round <= 4; round++) {
// Code remains same until here
// Check if the player wants to follow or quit
char r;
int chipsToBet;
if (round == 1) {
chipsToBet = this.view.getPlayerCallBetChip(this.player);
} else {
chipsToBet = this.view.getDealerCallBetChips();
}
}
Player winner = checkWinner();
if(playerQuit){
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
}
/* public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum();
highSum.init(login, password);
highSum.run();
}
}/
}
package Model;
import java.util.;
public class Player extends User{
private int chips;
protected ArrayList<Card> cardsOnHand;
public Player(String loginName, String password, int chips) {
super(loginName, password);
this.chips = chips;
this.cardsOnHand = new ArrayList<Card>();
}
public int getChips() {
return this.chips;
}
public void addChips(int amount) {
this.chips+=amount;//no error check
}
public void deductChips(int amount) {
this.chips-=amount;//no error check
}
public void addCard(Card card) {
this.cardsOnHand.add(card);
}
public ArrayList<Card> getCardsOnHand() {
return this.cardsOnHand;
}
public int getTotalCardsValue() {
int total = 0;
for(Card card: this.cardsOnHand) {
total+=card.getValue();
}
return total;
}
public Card getLastCard() {
return this.cardsOnHand.get(this.cardsOnHand.size()-1);
}
public void clearCardsOnHand() {
this.cardsOnHand.clear();
}
//Think of the action that a player can take
//implement more related methods here
public static void main(String[] args) {
// TODO Auto-generated method stub
Player player = new Player(“IcePeak”,“A”,100);
System.out.println(player.getChips());
player.deductChips(10);
System.out.println(player.getChips());
player.addChips(20);
System.out.println(player.getChips());
}
}
package Model;
import Helper.;
abstract public class User {
private String loginName;
private String hashPassword;
public User(String loginName, String password) {
this.loginName = loginName;
this.hashPassword = Utility.getHash(password);
}
public String getLoginName() {
return this.loginName;
}
public boolean checkPassword(String password) {
return this.hashPassword.equals(Utility.getHash(password));
}
}
package View;
import Helper.;
import Model.*;
//all input and output should be done view ViewController
//so that it is easier to implement GUI later
public class ViewController {
public void displayExitGame() {
System.out.println(“Thank you for playing HighSum game”);
}
public void displayBetOntable(int bet) {
System.out.println(“Bet on table : “+bet);
}
public void displayPlayerWin(Player player) {
System.out.println(player.getLoginName()+” Wins!”);
}
public void displayDealerWin() {
System.out.println(“Dealer Wins!”);
}
public void displayTie() {
System.out.println(“It is a tie!.”);
}
public void displayPlayerQuit() {
System.out.println(“You have quit the current game.”);
}
public void displayPlayerCardsOnHand(Player player) {
System.out.println(player.getLoginName());
if(player instanceof Dealer) {
for (int i = 0; i < player.getCardsOnHand().size(); i++) {
if (i == 0) {
System.out.print(”<HIDDEN CARD> “);
} else {
System.out.print(player.getCardsOnHand().get(i).toString() + " “);
}
}
} else {
for (Card card : player.getCardsOnHand()) {
System.out.print(card + " “);
}
}
System.out.println();
}
public void displayBlankLine() {
System.out.println();
}
public void displayPlayerTotalCardValue(Player player) {
System.out.println(“Value:”+player.getTotalCardsValue());
}
public void displayDealerDealCardsAndGameRound(int round) {
System.out.println(“Dealer dealing cards - ROUND “+round);
}
public void displayGameStart() {
System.out.println(“Game starts - Dealer shuffle deck”);
}
public void displayPlayerNameAndChips(Player player) {
System.out.println(player.getLoginName()+”, You have “+player.getChips()+” chips”);
}
public void displayPlayerNameAndLeftOverChips(Player player) {
System.out.println(player.getLoginName()+”, You are left with “+player.getChips()+” chips”);
}
public void displayGameTitle() {
System.out.println(“HighSum GAME”);
}
public void displaySingleLine() {
for(int i=0;i<30;i++) {
System.out.print(”-“);
}
System.out.println();
}
public void displayDoubleLine() {
for(int i=0;i<30;i++) {
System.out.print(”=“);
}
System.out.println();
}
public char getPlayerCallOrQuit() {
char[] choices = {‘c’,‘q’};
char r = Keyboard.readChar(“Do you want to [c]all or [q]uit?:”,choices);
return r;
}
public char getPlayerFollowOrNot(Player player, int dealerBet) {
boolean validChoice = false;
char[] choices = {‘y’,‘n’};
char r = ‘n’;
while(!validChoice) {
r = Keyboard.readChar(“Do you want to follow?”,choices);
//check if player has enff chips to follow
if(r==‘y’ && player.getChips()<dealerBet) {
System.out.println(“You do not have enough chips to follow”);
displayPlayerNameAndChips(player);
}else {
validChoice = true;
}
}
return r;
}
public char getPlayerNextGame() {
char[] choices = {‘y’,‘n’};
char r = Keyboard.readChar(“Next game?”,choices);
return r;
}
public int getPlayerCallBetChip(Player player) {
boolean validBetAmount = false;
int chipsToBet = 0;
while(!validBetAmount) {
chipsToBet = Keyboard.readInt(“Player call, state bet:”);
if(chipsToBet<0) {
System.out.println(“Chips cannot be negative”);
}else if(chipsToBet>player.getChips()) {
System.out.println(“You do not have enough chips”);
}else {
validBetAmount = true;
}
}
return chipsToBet;
}
public int getDealerCallBetChips() {
System.out.println(“Dealer call, state bet: 10”);
return 10;
}
}
”
These are the requirements:
“On completion of this assignment a student should be able to write a Java application
that:
• Makes use of Java API “Swing” and “AWT” packages
• Handles generated events
• Makes use of layout manager to organize the GUI components
• Know how to apply and design a program using object-oriented concepts
2. Task
Enhance the one player Java game application “HighSum” done in Assignment 1 with Graphical User Interface (GUI).
2.1 Login
The game starts by the player logging into the game.
2.2 Play Game
The game starts after the player click on “Login”.
First, the dealer will shuffles the deck.
(You may include animation in this frame to simulate “shuffle” effect as enhancement.)
Then the dealer deals two cards from the top of the deck to the player and itself.
Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game.
Assume the player states 10 as the bet chips.
The player’s chip will be deducted by 10.
The chips on table will be updated to 20 and the dealer deals cards for next round.
Assume the dealer’s last card is higher than the player’s last card.
The dealer Call the game and the player gets to choose to Follow or Quit the game.
If the player follows the game, 10 chips will be deducted from the player’s balance chips.
(Asumme the dealer place 10 chips.)
The games carry on for maximum of four rounds.
In the last round, the player with the highest total sum wins the game.
And the game continues until the player exits the game.
Error Handling
Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips.
You should look out for other possible exceptions and handle them too.”
Edit the code so that when highsum gui is run,
The game runs on the GUI and NOT on the console. The gui currently is empty and blank and cannot be closed when run.
|
07701057e9231ad7b5e4e5a52531b34a
|
{
"intermediate": 0.2617759704589844,
"beginner": 0.5683426856994629,
"expert": 0.16988128423690796
}
|
9,004
|
i have this code vconst { AlphaRouter } = require('@uniswap/smart-order-router');
const { Token, CurrencyAmount, Percent, TradeType } = require('@uniswap/sdk-core');
const { ethers, BigNumber } = require('ethers');
const { SwapRouter } = require('@uniswap/v3-sdk');
const SWAP_ROUTER_ADDRESS = '0xE592427A0AEce92De3Edee1F18E0157C05861564';
const WALLET_ADDRESS = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266';
const WALLET_SECRET = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
const INFURA_TEST_URL = 'https://mainnet.infura.io/v3/2d5bc62bb8d748cebfc64763e719cb4f';
const provider = new ethers.providers.JsonRpcProvider(INFURA_TEST_URL);
const chainId = 1;
const router = new AlphaRouter({ chainId: chainId, provider: provider });
const token0 = new Token(chainId, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18, 'WETH', 'Wrapped Ether');
const token1 = new Token(chainId, '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984', 18, 'UNI', 'Uniswap Token');
async function main() {
const inputAmount = CurrencyAmount.fromRawAmount(token0, ethers.utils.parseUnits('0.001', 18));
const bestRoute = await router.route(inputAmount, token1);
const route = await router.route(inputAmount, token1, TradeType.EXACT_INPUT, {
recipient: WALLET_ADDRESS,
slippageTolerance: new Percent(25, 100),
deadline: Math.floor(Date.now() / 1000 + 1800),
});
if (!bestRoute) console.log('No best route found!');
const swapRoute = bestRoute.route;
const pools = swapRoute[0].poolAddresses[0];
console.log(pools);
const quotedAmountOut = bestRoute.quote;
const methodParameters = SwapRouter.swapCallParameters(bestRoute.trade, {
tradeType: bestRoute.trade.tradeType,
});
const transaction = {
to: SWAP_ROUTER_ADDRESS,
data: methodParameters.calldata,
value: BigNumber.from(route.methodParameters.value),
from: WALLET_ADDRESS,
gasPrice: BigNumber.from(route.gasPriceWei),
gasLimit: ethers.utils.hexlify(1000000),
};
// Sign and send the transaction
const wallet = new ethers.Wallet(WALLET_SECRET, provider);
const signedTransaction = await wallet.signTransaction(transaction);
const txResult = await provider.sendTransaction(signedTransaction);
console.log('Transaction sent! Waiting for confirmation...');
console.log(`Hash: ${txResult.hash}`);
const receipt = await txResult.wait();
console.log(`Transaction confirmed in block ${receipt.blockNumber}`);
but i get this error C:\Users\lidor\Desktop\Trade Bot\node_modules\@uniswap\smart-order-router\build\main\util\methodParameters.js:105
throw new Error(`Unsupported swap type ${swapConfig}`);
^
Error: Unsupported swap type [object Object]
at buildSwapMethodParameters (C:\Users\lidor\Desktop\Trade Bot\node_modules\@uniswap\smart-order-router\build\main\util\methodParameters.js:105:11)
at AlphaRouter.route (C:\Users\lidor\Desktop\Trade Bot\node_modules\@uniswap\smart-order-router\build\main\routers\alpha-router\alpha-router.js:461:81)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async main (C:\Users\lidor\Desktop\Trade Bot\index.js:24:17)
Node.js v18.16.0
PS C:\Users\lidor\Desktop\Trade Bot>
}
main();
|
8279c298217fabbdb107694bb8f64208
|
{
"intermediate": 0.3492186367511749,
"beginner": 0.4200577437877655,
"expert": 0.23072360455989838
}
|
9,005
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
//scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreateDescriptorSet(descriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pBufferInfo = &bufferInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Texture.cpp:
#include "Texture.h"
#include "BufferUtils.h"
#include <iostream>
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
}
void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->physicalDevice = physicalDevice;
this->commandPool = commandPool;
this->graphicsQueue = graphicsQueue;
this->initialized = true;
// Load image from file using stb_image
int width, height, channels;
stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
{
throw std::runtime_error("Failed to load texture image!");
}
// Calculate the number of mip levels
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
// Create a buffer to store the image data
VkDeviceSize imageSize = width * height * 4;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
// Create the staging buffer for transferring image data
BufferUtils::CreateBuffer(device, physicalDevice, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
// Copy image data to the buffer
void* bufferData;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData);
memcpy(bufferData, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
// Free the stb_image buffer
stbi_image_free(pixels);
// Create vkImage, copy buffer to image, and create imageView and sampler
// …
CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
CreateSampler(mipLevels);
TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels, VK_SAMPLE_COUNT_1_BIT); // Add this call
CopyBufferToImage(stagingBuffer, width, height);
// Cleanup the staging buffer and staging buffer memory
// …
// Destroy the staging buffer and free the staging buffer memory
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Texture::Cleanup(Texture* texture)
{
// Put the content of the old Cleanup() method here
// Make sure to replace this with texture keyword
// …
}
VkImageView Texture::GetImageView() const
{
return imageView;
}
VkSampler Texture::GetSampler() const
{
return sampler;
}
void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties)
{
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0;
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate image memory!");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
void Texture::TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
VkPipelineStageFlags sourceStage;
VkPipelineStageFlags destinationStage;
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
else {
throw std::invalid_argument("Unsupported layout transition!");
}
vkCmdPipelineBarrier(
commandBuffer,
sourceStage, destinationStage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
void Texture::CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels)
{
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture image view!");
}
}
void Texture::CreateSampler(uint32_t mipLevels)
{
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = static_cast<float>(mipLevels);
if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture sampler!");
}
}
void Texture::CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// Record buffer to image copy command in the command buffer
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
BufferUtils.cpp:
#include "BufferUtils.h"
#include <stdexcept>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory)
{
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create buffer!");
}
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate buffer memory!");
}
vkBindBufferMemory(device, buffer, bufferMemory, 0);
}
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
throw std::runtime_error("Failed to find suitable memory type!");
}
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0; // Optional
copyRegion.dstOffset = 0; // Optional
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
}
I am getting this error:
VUID-VkWriteDescriptorSet-descriptorType-00319(ERROR / SPEC): msgNum: -405619238 - Validation Error: [ VUID-VkWriteDescriptorSet-descriptorType-00319 ] Object 0: handle = 0xa2eb680000000026, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; | MessageID = 0xe7d2bdda | vkUpdateDescriptorSets() pDescriptorWrites[0] failed write update validation for VkDescriptorSet 0xa2eb680000000026[] with error: Attempting write update to VkDescriptorSet 0xa2eb680000000026[] allocated with VkDescriptorSetLayout 0x9fde6b0000000014[] binding #0 with type VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER but update type is VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER. The Vulkan spec states: descriptorType must match the type of dstBinding within dstSet (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkWriteDescriptorSet-descriptorType-00319)
Objects: 1
[0] 0xa2eb680000000026, type: 23, name: NULL
It seems to occur when calling vkUpdateDescriptorSets in the Material::CreateDescriptorSet method.
Here is some additional code from the Renderer class for context:
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;
}
How can I alter the code to fix this issue?
|
b8569a4405f39db67edd163dc4ba5b1a
|
{
"intermediate": 0.4038229286670685,
"beginner": 0.3279862403869629,
"expert": 0.268190860748291
}
|
9,006
|
Если корзина пуста , или при повторном заполнеии корзины выводится множество ошибок исправь это : package com.example.myapp_2.Data.cart;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
public class CartFragment extends Fragment implements Cart.OnCartChangedListener {
private TextView totalPriceTextView;
private Button placeOrderButton;
private RecyclerView recyclerView;
private Button backButton;
private CartAdapter adapter;
private Cart cart;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
backButton = view.findViewById(R.id.back_button); // кнопка назад
totalPriceTextView = view.findViewById(R.id.total_price_text_view);
placeOrderButton = view.findViewById(R.id.place_order_button);
recyclerView = view.findViewById(R.id.cart_recycler_view);
cart = Cart.getInstance();
cart.addOnCartChangedListener(this);
adapter = new CartAdapter(cart.getItems(), new OnCartItemListener() {
@Override
public void onQuantityChanged(CartItem item, int newQuantity) {
cart.updateItem(item, newQuantity);
}
@Override
public void onRemoveButtonClick(CartItem item) {
cart.removeItem(item);
}
});
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
updateTotalPrice();
placeOrderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Опять работа???", Toast.LENGTH_SHORT).show();
getActivity().onBackPressed(); // вызов метода возврата на предыдущий экран
cart.clear();
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed(); // вызов метода возврата на предыдущий экран
}
});
return view;
}
private void updateTotalPrice() {
double totalPrice = cart.getTotalPrice();
totalPriceTextView.setText(getString(R.string.cart_item_total_price, totalPrice));
}
@Override
public void onCartChanged() {
adapter.setItems(cart.getItems());
updateTotalPrice();
}
}
package com.example.myapp_2.Data.cart;
import com.example.myapp_2.Data.List_1.Product;
import java.util.ArrayList;
import java.util.List;
import com.example.myapp_2.Data.List_1.Product;
import java.util.ArrayList;
import java.util.List;
public class Cart {
private static Cart instance;
private List<CartItem> items;
private List<OnCartChangedListener> listeners;
private Cart() {
items = new ArrayList<>();
listeners = new ArrayList<>();
}
public static Cart getInstance() {
if (instance == null) {
instance = new Cart();
}
return instance;
}
public void addItem(Product product) {
for (CartItem item : items) {
if (item.getProduct().equals(product)) {
item.setQuantity(item.getQuantity() + 1);
notifyCartChanged();
return;
}
}
items.add(new CartItem(product, 1));
notifyCartChanged();
}
public void updateItem(CartItem item, int newQuantity) {
if (newQuantity <= 0) {
removeItem(item);
} else {
item.setQuantity(newQuantity);
notifyCartChanged();
}
}
public void removeItem(CartItem item) {
items.remove(item);
notifyCartChanged();
}
public List<CartItem> getItems() {
return items;
}
public void clear() {
items.clear();
notifyCartChanged();
}
public double getTotalPrice() {
double totalPrice = 0;
for (CartItem item : items) {
totalPrice += item.getTotalPrice();
}
return totalPrice;
}
private void notifyCartChanged() {
for (OnCartChangedListener listener : listeners) {
listener.onCartChanged();
}
}
public void addOnCartChangedListener(OnCartChangedListener listener) {
listeners.add(listener);
}
public interface OnCartChangedListener {
void onCartChanged();
}
}
|
eeaf67ff6529795fa3032987c8fffd8e
|
{
"intermediate": 0.2433445155620575,
"beginner": 0.6089389324188232,
"expert": 0.14771650731563568
}
|
9,007
|
gdb print array, get this "\001\002\003\004\005\006\a\b\t"
|
b470a64b22c8c2b55f4ce71365b6d3fc
|
{
"intermediate": 0.47934600710868835,
"beginner": 0.15640048682689667,
"expert": 0.36425358057022095
}
|
9,008
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC'))
frame = frame.iloc[:60,:6]
frame.columns = ['Time','Open','High','Low','Close','Volume']
frame = frame.set_index('Time')
today = dt.date.today()
frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S")
frame = frame.astype(float)
return frame
df = getminutedata('BTCUSDT', '1m', '44640')
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ''
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = client.futures_account_balance()
usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
if opposite_position is not None:
opposite_side = (SIDE_SELL if opposite_position['positionSide'] ==
POSITION_SIDE_LONG
else SIDE_BUY)
else:
opposite_side = None
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side,
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
else:
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side
)
# Print order creation confirmation messages
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop
if df is None:
continue
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
time.sleep(1) # Add a delay of 1 second But when I getting signal terminal returns me :Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 206, in <module>
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 129, in order_execution
opposite_position['positionSide'] == POSITION_SIDE_LONG
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not subscriptable Please tell me what I need to do ?
|
b7e0f984823aa01531ee12c7b3b19a62
|
{
"intermediate": 0.47547268867492676,
"beginner": 0.3265427052974701,
"expert": 0.19798465073108673
}
|
9,009
|
how can i make this work in react? Type 'ObjectId' is not assignable to type 'Key | null | undefined'. ObjectId is from bson
|
795e5e6d82536748a3800160ecb95d06
|
{
"intermediate": 0.5767377018928528,
"beginner": 0.18183784186840057,
"expert": 0.24142444133758545
}
|
9,010
|
Убери все товары из коризны при нажатии на кнопку Placeorder : package com.example.myapp_2.Data.cart;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
public class CartFragment extends Fragment implements Cart.OnCartChangedListener {
private TextView totalPriceTextView;
private Button placeOrderButton;
private RecyclerView recyclerView;
private Button backButton;
private CartAdapter adapter;
private Cart cart;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
backButton = view.findViewById(R.id.back_button); // кнопка назад
totalPriceTextView = view.findViewById(R.id.total_price_text_view);
placeOrderButton = view.findViewById(R.id.place_order_button);
recyclerView = view.findViewById(R.id.cart_recycler_view);
cart = Cart.getInstance();
cart.addOnCartChangedListener(this);
adapter = new CartAdapter(cart.getItems(), new OnCartItemListener() {
@Override
public void onQuantityChanged(CartItem item, int newQuantity) {
cart.updateItem(item, newQuantity);
}
@Override
public void onRemoveButtonClick(CartItem item) {
cart.removeItem(item);
}
});
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
updateTotalPrice();
placeOrderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Опять работа???", Toast.LENGTH_SHORT).show();
getActivity().onBackPressed(); // вызов метода возврата на предыдущий экран
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed(); // вызов метода возврата на предыдущий экран
}
});
return view;
}
private void updateTotalPrice() {
double totalPrice = cart.getTotalPrice();
totalPriceTextView.setText(getString(R.string.cart_item_total_price, totalPrice));
}
@Override
public void onCartChanged() {
adapter.setItems(cart.getItems());
updateTotalPrice();
}
}
|
04d685b1f28f6baf1631808b1f108954
|
{
"intermediate": 0.3387572169303894,
"beginner": 0.48737451434135437,
"expert": 0.17386825382709503
}
|
9,011
|
This is my ide program for a highsum gui game.
“package GUIExample;
import Model.Dealer;
import Model.HighSum;
import Model.Player;
import java.awt.;
import java.awt.event.;
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.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// 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
);
if (response == JOptionPane.YES_OPTION) {
dealer.clearCardsOnHand();
player.clearCardsOnHand();
} else {
carryOn = false;
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 javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameTableFrame extends JFrame {
private GameTablePanel gameTablePanel;
private Dealer dealer;
private Player player;
private JLabel shufflingLabel;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
gameTablePanel = new GameTablePanel(dealer, player);
shufflingLabel = new JLabel(“Shuffling”);
shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER);
playButton = new JButton(“Play”);
quitButton = new JButton(“Quit”);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shufflingLabel.setVisible(true);
HighSum highSum = new HighSum();
highSum.init(player.getLoginName(), “some_default_password”);
highSum.run();
updateScreen();
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Create the main panel that contains both the game board and the buttons
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(playButton);
buttonsPanel.add(quitButton);
mainPanel.add(gameTablePanel, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
mainPanel.add(shufflingLabel, BorderLayout.NORTH);
shufflingLabel.setVisible(false);
add(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
// This method updates the screen after each game
public void updateScreen() {
gameTablePanel.updateTable(dealer, player);
}
}
package GUIExample;
import java.awt.;
import javax.swing.;
import Model.;
public class GameTablePanel extends JPanel {
private Player player;
private Dealer dealer;
public GameTablePanel(Dealer dealer, Player player) {
setLayout(new BorderLayout());
setBackground(Color.GREEN);
setPreferredSize(new Dimension(1024, 768));
this.dealer = dealer;
this.player = player;
}
public void updateTable(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw dealer’s cards
int dealerX = 50;
int dealerY = 100;
g.drawString(“Dealer”, dealerX, dealerY - 20);
dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true);
// Draw player’s cards
int playerX = 50;
int playerY = getHeight() - 200;
g.drawString(“Player”, playerX, playerY - 20);
playerX = drawPlayerHand(g, player, playerX, playerY, false);
// Draw chips on the table
g.setColor(Color.BLACK);
g.setFont(new Font(“Arial”, Font.PLAIN, 18));
g.drawString(“Chips on the table: “, playerX + 50, playerY);
}
private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) {
int i = 0;
for (Card c : p.getCardsOnHand()) {
if (isDealer && i == 0) {
new ImageIcon(“images/back.png”).paintIcon(this, g, x, y);
} else {
c.paintIcon(this, g, x, y);
}
x += 100;
i++;
}
return x;
}
}
package GUIExample;
import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginDialog extends JDialog {
private JTextField loginField;
private JPasswordField passwordField;
private JButton loginButton;
private boolean loggedIn = false;
public LoginDialog(JFrame parent) {
super(parent, “Login”, true);
loginField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton(“Login”);
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loggedIn = true;
dispose();
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel(“Login:”));
panel.add(loginField);
panel.add(new JLabel(“Password:”));
panel.add(passwordField);
panel.add(loginButton);
add(panel);
pack();
setLocationRelativeTo(parent);
}
public String getLogin() {
return loginField.getText();
}
public String getPassword() {
return new String(passwordField.getPassword());
}
public boolean isLoggedIn() {
return loggedIn;
}
}
package Helper;
public class Keyboard {
public static String readString(String prompt) {
System.out.print(prompt);
return new java.util.Scanner(System.in).nextLine();
}
public static int readInt(String prompt) {
int input = 0;
boolean valid = false;
while (!valid) {
try {
input = Integer.parseInt(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println(”** Please enter an integer “);
}
}
return input;
}
public static double readDouble(String prompt) {
double input = 0;
boolean valid = false;
while (!valid) {
try {
input = Double.parseDouble(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println(” Please enter a double “);
}
}
return input;
}
public static float readFloat(String prompt) {
float input = 0;
boolean valid = false;
while (!valid) {
try {
input = Float.parseFloat(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println(” Please enter a float “);
}
}
return input;
}
public static long readLong(String prompt) {
long input = 0;
boolean valid = false;
while (!valid) {
try {
input = Long.parseLong(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println(” Please enter a long “);
}
}
return input;
}
public static char readChar(String prompt,char[] choices) {
boolean validChoice = false;
char r = ’ ';
while(!validChoice) {
r = Keyboard.readChar(prompt+” “+charArrayToString(choices)+”:“);
if(!validateChoice(choices,r)) {
System.out.println(“Invalid input”);
}else {
validChoice = true;
}
}
return r;
}
private static String charArrayToString(char[] charArray) {
String s = “[”;
for(int i=0;i<charArray.length;i++) {
s+=charArray[i];
if(i!=charArray.length-1) {
s+=”,“;
}
}
s += “]”;
return s;
}
private static boolean validateChoice(char[] choices, char choice) {
boolean validChoice = false;
for(int i=0;i<choices.length;i++) {
if(choices[i]==choice) {
validChoice = true;
break;
}
}
return validChoice;
}
public static char readChar(String prompt) {
char input = 0;
boolean valid = false;
while (!valid) {
String temp = readString(prompt);
if (temp.length() != 1) {
System.out.println(” Please enter a character “);
} else {
input = temp.charAt(0);
valid = true;
}
}
return input;
}
public static boolean readBoolean(String prompt) {
boolean valid = false;
while (!valid) {
String input = readString(prompt);
if (input.equalsIgnoreCase(“yes”) || input.equalsIgnoreCase(“y”) || input.equalsIgnoreCase(“true”)
|| input.equalsIgnoreCase(“t”)) {
return true;
} else if (input.equalsIgnoreCase(“no”) || input.equalsIgnoreCase(“n”) || input.equalsIgnoreCase(“false”)
|| input.equalsIgnoreCase(“f”)) {
return false;
} else {
System.out.println(” Please enter Yes/No or True/False “);
}
}
return false;
}
public static java.util.Date readDate(String prompt) {
java.util.Date date = null;
boolean valid = false;
while (!valid) {
try {
String input = readString(prompt).trim();
if (input.matches(”\d\d/\d\d/\d\d\d\d”)) {
int day = Integer.parseInt(input.substring(0, 2));
int month = Integer.parseInt(input.substring(3, 5));
int year = Integer.parseInt(input.substring(6, 10));
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setLenient(false);
cal.set(year, month - 1, day, 0, 0, 0);
date = cal.getTime();
valid = true;
} else {
System.out.println(" Please enter a date (DD/MM/YYYY) “);
}
} catch (IllegalArgumentException e) {
System.out.println(” Please enter a date (DD/MM/YYYY) “);
}
}
return date;
}
private static String quit = “0”;
public static int getUserOption(String title, String[] menu) {
displayMenu(title, menu);
int choice = Keyboard.readInt(“Enter Choice --> “);
while (choice > menu.length || choice < 0) {
choice = Keyboard.readInt(“Invalid Choice, Re-enter --> “);
}
return choice;
}
private static void displayMenu(String title, String[] menu) {
line(80, “=”);
System.out.println(title.toUpperCase());
line(80, “-”);
for (int i = 0; i < menu.length; i++) {
System.out.println(”[” + (i + 1) + “] " + menu[i]);
}
System.out.println(”[” + quit + “] Quit”);
line(80, “-”);
}
public static void line(int len, String c) {
System.out.println(String.format(”%” + len + “s”, " “).replaceAll(” “, c));
}
}
package Helper;
import java.security.MessageDigest;
public class Utility {
public static String getHash(String base)
{
String message=”“;
try{
MessageDigest digest = MessageDigest.getInstance(“SHA-256”);
byte[] hash = digest.digest(base.getBytes(“UTF-8”));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append(‘0’);
hexString.append(hex);
}
message = hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
return message;
}
public static void printLine(int num)
{
printLine(num,‘-’);
}
public static void printDoubleLine(int num)
{
printLine(num,‘=’);
}
public static void printLine(int num,char pattern)
{
for(int i =0;i<num;i++)
{
System.out.print(pattern);
}
System.out.println(”“);
}
}
package Model;
import javax.swing.;
public class Card extends ImageIcon {
private String suit;
private String name;
private int value;
private int rank;
private boolean faceDown;
public Card(String suit, String name, int value, int rank) {
super(“images/” + suit + name + “.png”);
this.suit = suit;
this.name = name;
this.value = value;
this.rank = rank;
this.faceDown = false;
}
public boolean isFaceDown() {
return this.faceDown;
}
public void setFaceDown(boolean faceDown) {
this.faceDown = faceDown;
}
public String getSuit() {
return this.suit;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
public int getRank() {
return this.rank;
}
public String toString() {
if (this.faceDown) {
return “<HIDDEN CARD>”;
} else {
return “<” + this.suit + " " + this.name + “>”;
}
}
public String display() {
return “<”+this.suit+” “+this.name+” “+this.rank+”>";
}
}
//card rank
// D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.;
public class Dealer extends Player {
private Deck deck;
public Dealer() {
super(“Dealer”, “”, 0);
deck = new Deck();
}
public void shuffleCards() {
System.out.println(“Dealer shuffle deck”);
deck.shuffle();
}
public void dealCardTo(Player player) {
Card card = deck.dealCard(); // take a card out from the deck
player.addCard(card); // pass the card into the player
}
public void addCardsBackToDeck(ArrayList<Card> cards) {
deck.appendCard(cards);
}
//return 1 if card1 rank higher, else return 2
public int determineWhichCardRankHigher(Card card1, Card card2) {
if(card1.getRank()>card2.getRank()) {
return 1;
}else {
return 2;
}
}
}
package Model;
import java.util.;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
String[] suits = { “Diamond”, “Club”,“Heart”,“Spade”, };
for (int i = 0; i < suits.length; i++) {
String suit = suits[i];
Card card = new Card(suit, “Ace”, 1,1+i);
cards.add(card);
int c = 5;
for (int n = 2; n <= 10; n++) {
Card oCard = new Card(suit, “” + n, n,c+i);
cards.add(oCard);
c+=4;
}
Card jackCard = new Card(suit, “Jack”, 10,41+i);
cards.add(jackCard);
Card queenCard = new Card(suit, “Queen”, 10,45+i);
cards.add(queenCard);
Card kingCard = new Card(suit, “King”, 10,49+i);
cards.add(kingCard);
}
}
public Card dealCard() {
return cards.remove(0);
}
//add back one card
public void appendCard(Card card) {
cards.add(card);
}
//add back arraylist of cards
public void appendCard(ArrayList<Card> cards) {
for(Card card: cards) {
this.cards.add(card);
}
}
public void shuffle() {
Random random = new Random();
for(int i=0;i<10000;i++) {
int indexA = random.nextInt(cards.size());
int indexB = random.nextInt(cards.size());
Card cardA = cards.get(indexA);
Card cardB = cards.get(indexB);
cards.set(indexA, cardB);
cards.set(indexB, cardA);
}
}
//for internal use only
private void showCards() {
for (Card card : cards) {
System.out.println(card);
}
}
//for internal use only
private void displayCards() {
for (Card card : cards) {
System.out.println(card.display());
}
}
public static void main(String[] args) {
Deck deck = new Deck();
//deck.shuffle();
/Card card1 = deck.dealCard();
Card card2 = deck.dealCard();
Card card3 = deck.dealCard();
deck.showCards();
ArrayList<Card> cards = new ArrayList<Card>();
cards.add(card1);
cards.add(card2);
cards.add(card3);
deck.appendCard(cards);
System.out.println();/
deck.displayCards();
}
}
//card rank
//D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import Controller.;
import View.;
import GUIExample.LoginDialog;
import GUIExample.GameTableFrame;
import javax.swing.JOptionPane;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class HighSum {
private Dealer dealer;
private Player player;
private ViewController view;
private GameController gc;
private int chipsOnTable;
public HighSum() {
}
public void init(String login, String password) {
// Create all the required objects
this.dealer = new Dealer();
this.player = new Player(login, password, 50);
this.view = new ViewController();
// Bring them together
this.gc = new GameController(this.dealer, this.player, this.view);
}
private Player checkWinner() {
if(player.getTotalCardsValue() > dealer.getTotalCardsValue())
return player;
else if(player.getTotalCardsValue() < dealer.getTotalCardsValue())
return dealer;
else
return null;
}
public Dealer getDealer() {
return dealer;
}
public Player getPlayer() {
return player;
}
public void run() {
// Setup the game table
GameTableFrame gameTableFrame = new GameTableFrame(dealer, player);
// Starts the game!
boolean carryOn = true;
while (carryOn) {
runOneRound();
gameTableFrame.updateScreen();
if (!gc.getPlayerQuitStatus()) {
int response = JOptionPane.showConfirmDialog(
gameTableFrame,
“Do you want to play another game?”,
“New Game”,
JOptionPane.YES_NO_OPTION
);
carryOn = response == JOptionPane.YES_OPTION;
} else {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
gameTableFrame.dispose();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for (int round = 1; round <= 4; round++) {
// Code remains same until here
// Check if the player wants to follow or quit
char r;
int chipsToBet;
if (round == 1) {
chipsToBet = this.view.getPlayerCallBetChip(this.player);
} else {
chipsToBet = this.view.getDealerCallBetChips();
}
}
Player winner = checkWinner();
if(playerQuit){
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
}
/* public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum();
highSum.init(login, password);
highSum.run();
}
}/
}
package Model;
import java.util.;
public class Player extends User{
private int chips;
protected ArrayList<Card> cardsOnHand;
public Player(String loginName, String password, int chips) {
super(loginName, password);
this.chips = chips;
this.cardsOnHand = new ArrayList<Card>();
}
public int getChips() {
return this.chips;
}
public void addChips(int amount) {
this.chips+=amount;//no error check
}
public void deductChips(int amount) {
this.chips-=amount;//no error check
}
public void addCard(Card card) {
this.cardsOnHand.add(card);
}
public ArrayList<Card> getCardsOnHand() {
return this.cardsOnHand;
}
public int getTotalCardsValue() {
int total = 0;
for(Card card: this.cardsOnHand) {
total+=card.getValue();
}
return total;
}
public Card getLastCard() {
return this.cardsOnHand.get(this.cardsOnHand.size()-1);
}
public void clearCardsOnHand() {
this.cardsOnHand.clear();
}
//Think of the action that a player can take
//implement more related methods here
public static void main(String[] args) {
// TODO Auto-generated method stub
Player player = new Player(“IcePeak”,“A”,100);
System.out.println(player.getChips());
player.deductChips(10);
System.out.println(player.getChips());
player.addChips(20);
System.out.println(player.getChips());
}
}
package Model;
import Helper.;
abstract public class User {
private String loginName;
private String hashPassword;
public User(String loginName, String password) {
this.loginName = loginName;
this.hashPassword = Utility.getHash(password);
}
public String getLoginName() {
return this.loginName;
}
public boolean checkPassword(String password) {
return this.hashPassword.equals(Utility.getHash(password));
}
}
package View;
import Helper.;
import Model.*;
//all input and output should be done view ViewController
//so that it is easier to implement GUI later
public class ViewController {
public void displayExitGame() {
System.out.println(“Thank you for playing HighSum game”);
}
public void displayBetOntable(int bet) {
System.out.println(“Bet on table : “+bet);
}
public void displayPlayerWin(Player player) {
System.out.println(player.getLoginName()+” Wins!”);
}
public void displayDealerWin() {
System.out.println(“Dealer Wins!”);
}
public void displayTie() {
System.out.println(“It is a tie!.”);
}
public void displayPlayerQuit() {
System.out.println(“You have quit the current game.”);
}
public void displayPlayerCardsOnHand(Player player) {
System.out.println(player.getLoginName());
if(player instanceof Dealer) {
for (int i = 0; i < player.getCardsOnHand().size(); i++) {
if (i == 0) {
System.out.print(”<HIDDEN CARD> “);
} else {
System.out.print(player.getCardsOnHand().get(i).toString() + " “);
}
}
} else {
for (Card card : player.getCardsOnHand()) {
System.out.print(card + " “);
}
}
System.out.println();
}
public void displayBlankLine() {
System.out.println();
}
public void displayPlayerTotalCardValue(Player player) {
System.out.println(“Value:”+player.getTotalCardsValue());
}
public void displayDealerDealCardsAndGameRound(int round) {
System.out.println(“Dealer dealing cards - ROUND “+round);
}
public void displayGameStart() {
System.out.println(“Game starts - Dealer shuffle deck”);
}
public void displayPlayerNameAndChips(Player player) {
System.out.println(player.getLoginName()+”, You have “+player.getChips()+” chips”);
}
public void displayPlayerNameAndLeftOverChips(Player player) {
System.out.println(player.getLoginName()+”, You are left with “+player.getChips()+” chips”);
}
public void displayGameTitle() {
System.out.println(“HighSum GAME”);
}
public void displaySingleLine() {
for(int i=0;i<30;i++) {
System.out.print(”-“);
}
System.out.println();
}
public void displayDoubleLine() {
for(int i=0;i<30;i++) {
System.out.print(”=“);
}
System.out.println();
}
public char getPlayerCallOrQuit() {
char[] choices = {‘c’,‘q’};
char r = Keyboard.readChar(“Do you want to [c]all or [q]uit?:”,choices);
return r;
}
public char getPlayerFollowOrNot(Player player, int dealerBet) {
boolean validChoice = false;
char[] choices = {‘y’,‘n’};
char r = ‘n’;
while(!validChoice) {
r = Keyboard.readChar(“Do you want to follow?”,choices);
//check if player has enff chips to follow
if(r==‘y’ && player.getChips()<dealerBet) {
System.out.println(“You do not have enough chips to follow”);
displayPlayerNameAndChips(player);
}else {
validChoice = true;
}
}
return r;
}
public char getPlayerNextGame() {
char[] choices = {‘y’,‘n’};
char r = Keyboard.readChar(“Next game?”,choices);
return r;
}
public int getPlayerCallBetChip(Player player) {
boolean validBetAmount = false;
int chipsToBet = 0;
while(!validBetAmount) {
chipsToBet = Keyboard.readInt(“Player call, state bet:”);
if(chipsToBet<0) {
System.out.println(“Chips cannot be negative”);
}else if(chipsToBet>player.getChips()) {
System.out.println(“You do not have enough chips”);
}else {
validBetAmount = true;
}
}
return chipsToBet;
}
public int getDealerCallBetChips() {
System.out.println(“Dealer call, state bet: 10”);
return 10;
}
}
”
These are the requirements:
“On completion of this assignment a student should be able to write a Java application
that:
• Makes use of Java API “Swing” and “AWT” packages
• Handles generated events
• Makes use of layout manager to organize the GUI components
• Know how to apply and design a program using object-oriented concepts
2. Task
Enhance the one player Java game application “HighSum” done in Assignment 1 with Graphical User Interface (GUI).
2.1 Login
The game starts by the player logging into the game.
2.2 Play Game
The game starts after the player click on “Login”.
First, the dealer will shuffles the deck.
(You may include animation in this frame to simulate “shuffle” effect as enhancement.)
Then the dealer deals two cards from the top of the deck to the player and itself.
Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game.
Assume the player states 10 as the bet chips.
The player’s chip will be deducted by 10.
The chips on table will be updated to 20 and the dealer deals cards for next round.
Assume the dealer’s last card is higher than the player’s last card.
The dealer Call the game and the player gets to choose to Follow or Quit the game.
If the player follows the game, 10 chips will be deducted from the player’s balance chips.
(Asumme the dealer place 10 chips.)
The games carry on for maximum of four rounds.
In the last round, the player with the highest total sum wins the game.
And the game continues until the player exits the game.
Error Handling
Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips.
You should look out for other possible exceptions and handle them too.”
Edit the code so that when highsum gui is run,
The game runs on the highsumGUI and NOT on the console. The gui currently is empty and blank and cannot be closed when run.
|
05bce7821913c94e21906537f3d20be6
|
{
"intermediate": 0.3492986261844635,
"beginner": 0.41155144572257996,
"expert": 0.23914997279644012
}
|
9,012
|
is there a way to cast string to match mongoose _id type with bson library?
|
e48cc2c68e56da975fd41b5f75eafd0a
|
{
"intermediate": 0.6579704880714417,
"beginner": 0.10167118906974792,
"expert": 0.24035830795764923
}
|
9,013
|
<Wrapper>
<Slide>
<ImageContainer>
<Image src={Images.blender} />
</ImageContainer>
<InfoContainer>
<Title>Blender</Title>
<Description>Great for hopping</Description>
<Button>show me</Button>
</InfoContainer>
</Slide>
<Slide>
<ImageContainer>
<Image src={Images.blender} />
</ImageContainer>
<InfoContainer>
<Title>Blender</Title>
<Description>Great for hopping</Description>
<Button>show me</Button>
</InfoContainer>
</Slide>
<Slide>
<ImageContainer>
<Image src={Images.blender} />
</ImageContainer>
<InfoContainer>
<Title>Blender</Title>
<Description>Great for hopping</Description>
<Button>show me</Button>
</InfoContainer>
</Slide>
</Wrapper>
how refactor this?
|
768dc4ebb8778aa24c4c9b1a0acab1b1
|
{
"intermediate": 0.3673253059387207,
"beginner": 0.33841773867607117,
"expert": 0.29425692558288574
}
|
9,014
|
из-за этого кода возникает ошибка : cart.clear(); ошибка : E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapp_2, PID: 12084
java.lang.IllegalStateException: Fragment CartFragment{5e8ea6e} (8e8606e0-7ef2-4a48-af6e-2c3c1e7c72ac) not attached to a context.
at androidx.fragment.app.Fragment.requireContext(Fragment.java:900)
at androidx.fragment.app.Fragment.getResources(Fragment.java:964)
at androidx.fragment.app.Fragment.getString(Fragment.java:999)
at com.example.myapp_2.Data.cart.CartFragment.updateTotalPrice(CartFragment.java:94)
at com.example.myapp_2.Data.cart.CartFragment.onCartChanged(CartFragment.java:100)
at com.example.myapp_2.Data.cart.Cart.notifyCartChanged(Cart.java:77)
at com.example.myapp_2.Data.cart.Cart.clear(Cart.java:64)
at com.example.myapp_2.Data.cart.CartFragment$2.onClick(CartFragment.java:79)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1211)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
. Весь код : package com.example.myapp_2.Data.cart;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
public class CartFragment extends Fragment implements Cart.OnCartChangedListener {
private TextView totalPriceTextView;
private Button placeOrderButton;
private RecyclerView recyclerView;
private Button backButton;
private CartAdapter adapter;
private Cart cart;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
backButton = view.findViewById(R.id.back_button); // кнопка назад
totalPriceTextView = view.findViewById(R.id.total_price_text_view);
placeOrderButton = view.findViewById(R.id.place_order_button);
recyclerView = view.findViewById(R.id.cart_recycler_view);
cart = Cart.getInstance();
cart.addOnCartChangedListener(this);
adapter = new CartAdapter(cart.getItems(), new OnCartItemListener() {
@Override
public void onQuantityChanged(CartItem item, int newQuantity) {
cart.updateItem(item, newQuantity);
}
@Override
public void onRemoveButtonClick(CartItem item) {
cart.removeItem(item);
}
});
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
updateTotalPrice();
placeOrderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Опять работа???", Toast.LENGTH_SHORT).show();
getActivity().onBackPressed(); // вызов метода возврата на предыдущий экран
cart.clear();
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed(); // вызов метода возврата на предыдущий экран
}
});
return view;
}
private void updateTotalPrice() {
double totalPrice = cart.getTotalPrice();
totalPriceTextView.setText(getString(R.string.cart_item_total_price, totalPrice));
}
@Override
public void onCartChanged() {
adapter.setItems(cart.getItems());
updateTotalPrice();
}
}
package com.example.myapp_2.Data.cart;
import com.example.myapp_2.Data.List_1.Product;
import java.util.ArrayList;
import java.util.List;
import com.example.myapp_2.Data.List_1.Product;
import java.util.ArrayList;
import java.util.List;
public class Cart {
private static Cart instance;
private List<CartItem> items;
private List<OnCartChangedListener> listeners;
private Cart() {
items = new ArrayList<>();
listeners = new ArrayList<>();
}
public static Cart getInstance() {
if (instance == null) {
instance = new Cart();
}
return instance;
}
public void addItem(Product product) {
for (CartItem item : items) {
if (item.getProduct().equals(product)) {
item.setQuantity(item.getQuantity() + 1);
notifyCartChanged();
return;
}
}
items.add(new CartItem(product, 1));
notifyCartChanged();
}
public void updateItem(CartItem item, int newQuantity) {
if (newQuantity <= 0) {
removeItem(item);
} else {
item.setQuantity(newQuantity);
notifyCartChanged();
}
}
public void removeItem(CartItem item) {
items.remove(item);
notifyCartChanged();
}
public List<CartItem> getItems() {
return items;
}
public void clear() {
items.clear();
notifyCartChanged();
}
public double getTotalPrice() {
double totalPrice = 0;
for (CartItem item : items) {
totalPrice += item.getTotalPrice();
}
return totalPrice;
}
private void notifyCartChanged() {
for (OnCartChangedListener listener : listeners) {
listener.onCartChanged();
}
}
public void addOnCartChangedListener(OnCartChangedListener listener) {
listeners.add(listener);
}
public interface OnCartChangedListener {
void onCartChanged();
}
}
|
0e7711cf8458497114c7aa57a22a7d62
|
{
"intermediate": 0.3426900804042816,
"beginner": 0.3867865204811096,
"expert": 0.2705233693122864
}
|
9,015
|
Добавь уведомление о том что заказ оформелн в этом методе : placeOrderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Опять работа???", Toast.LENGTH_SHORT).show();
getActivity().onBackPressed(); // вызов метода возврата на предыдущий экран
adapter.clear();
}
});
|
f65edda872242e47ed835cf9e8578148
|
{
"intermediate": 0.4132780432701111,
"beginner": 0.3545173704624176,
"expert": 0.23220451176166534
}
|
9,016
|
I have created two tables to mysql database using below sql:
CREATE TABLE sg_businesstype (
businesstypeid int not null auto_increment,
businesstype varchar(80),
primary key (businesstypeid)
);
insert into sg_businesstype ( businesstype ) values
('Buying Agent'), ('Dealer / Reseller'), ('Distributor'), ('Manufacturer / OEM'), ('Not Known'), ('Retailer'), ('Service Provider');
CREATE TABLE sg_users (
sgid int not null auto_increment,
email varchar(80) not null,
name varchar(60) not null,
usertype int not null default 1,
company varchar(80) null,
tel varchar(25) null,
mobile varchar(25) null,
businesstypeid int null,
newsletter boolean default false,
status boolean default true,
rating int default 0,
registerdate timestamp not null default CURRENT_TIMESTAMP,
logo varchar(255) null,
primary key (sgid),
foreign key (businesstypeid) references sg_businesstype (businesstypeid)
);
|
0ffcf1c2822932df34a6f106b4f5a09f
|
{
"intermediate": 0.3890690207481384,
"beginner": 0.3284416198730469,
"expert": 0.2824893891811371
}
|
9,017
|
This is my ide program for a highsum gui game.
"package GUIExample;
import Model.Dealer;
import Model.HighSum;
import Model.Player;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
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();
highSum.init(login, password);
GameTableFrame gameTableFrame = new GameTableFrame(highSum);
gameTableFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
});
}
}
class PlayAction implements ActionListener {
private HighSum highSum;
private GameTableFrame gameTableFrame;
public PlayAction(GameTableFrame gameTableFrame, HighSum highSum) {
this.gameTableFrame = gameTableFrame;
this.highSum = highSum;
}
@Override
public void actionPerformed(ActionEvent e) {
highSum.runOneRound();
gameTableFrame.updateScreen(highSum.getDealer(), highSum.getPlayer());
int response = JOptionPane.showConfirmDialog(
gameTableFrame,
"Do you want to play another game?",
"New Game",
JOptionPane.YES_NO_OPTION
);
if (response == JOptionPane.YES_OPTION) {
highSum.getDealer().clearCardsOnHand();
highSum.getPlayer().clearCardsOnHand();
} else {
System.exit(0);
}
}
}
class QuitAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class GameTableFrame extends JFrame {
private HighSum highSum;
private GameTablePanel gameTablePanel;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(HighSum highSum) {
this.highSum = highSum;
this.gameTablePanel = new GameTablePanel(highSum.getDealer(), highSum.getPlayer());
setTitle("HighSum GUI Game");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
playButton = new JButton("Play");
quitButton = new JButton("Quit");
playButton.addActionListener(new PlayAction(this, highSum));
quitButton.addActionListener(new QuitAction());
JPanel buttonPanel = new JPanel();
buttonPanel.add(playButton);
buttonPanel.add(quitButton);
add(gameTablePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void updateScreen(Dealer dealer, Player player) {
gameTablePanel.updateTable(dealer, player);
}
}
package Controller;
import Model.Dealer;
import Model.Player;
import View.ViewController;
public class GameController {
private Dealer dealer;
private Player player;
private ViewController view;
private int chipsOnTable;
private boolean playerQuit;
public GameController(Dealer dealer,Player player,ViewController view) {
this.dealer = dealer;
this.player = player;
this.view = view;
this.chipsOnTable = 0;
}
public boolean getPlayerQuitStatus() {
return playerQuit;
}
public void run() {
boolean carryOn= true;
while(carryOn) {
runOneRound();
char r = this.view.getPlayerNextGame();
if(r=='n') {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for(int round = 1;round<=4;round++) {
this.view.displaySingleLine();
this.view.displayDealerDealCardsAndGameRound(round);
this.view.displaySingleLine();
if (round == 1) { //round 1 deal extra card
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
} else {
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
}
this.view.displayPlayerCardsOnHand(this.dealer);
this.view.displayBlankLine();
this.view.displayPlayerCardsOnHand(player);
this.view.displayPlayerTotalCardValue(player);
int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard());
if(whoCanCall==1) {//dealer call
int chipsToBet = this.view. getDealerCallBetChips();
//ask player want to follow?
char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet);
if(r=='y') {
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}else {//player call
if(round==1) {//round 1 player cannot quit
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayBetOntable(this.chipsOnTable);
}else {
char r = this.view.getPlayerCallOrQuit();
if(r=='c') {
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}
}
}
//check who win
if(playerQuit) {
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) {
this.view.displayPlayerWin(this.player);
this.player.addChips(chipsOnTable);
this.chipsOnTable=0;
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) {
this.view.displayDealerWin();
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else {
this.view.displayTie();
this.player.addChips(chipsOnTable/2);
this.view.displayPlayerNameAndLeftOverChips(this.player);
}
//put all the cards back to the deck
dealer.addCardsBackToDeck(dealer.getCardsOnHand());
dealer.addCardsBackToDeck(player.getCardsOnHand());
dealer.clearCardsOnHand();
player.clearCardsOnHand();
}
}
package GUIExample;
import Model.Dealer;
import Model.HighSum;
import Model.Player;
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameTableFrame extends JFrame {
private GameTablePanel gameTablePanel;
private Dealer dealer;
private Player player;
private JLabel shufflingLabel;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
gameTablePanel = new GameTablePanel(dealer, player);
shufflingLabel = new JLabel("Shuffling");
shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER);
playButton = new JButton("Play");
quitButton = new JButton("Quit");
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shufflingLabel.setVisible(true);
HighSum highSum = new HighSum();
highSum.init(player.getLoginName(), "some_default_password");
highSum.run();
updateScreen();
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Create the main panel that contains both the game board and the buttons
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(playButton);
buttonsPanel.add(quitButton);
mainPanel.add(gameTablePanel, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
mainPanel.add(shufflingLabel, BorderLayout.NORTH);
shufflingLabel.setVisible(false);
add(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
// This method updates the screen after each game
public void updateScreen() {
gameTablePanel.updateTable(dealer, player);
}
}
package GUIExample;
import java.awt.*;
import javax.swing.*;
import Model.*;
public class GameTablePanel extends JPanel {
private Player player;
private Dealer dealer;
public GameTablePanel(Dealer dealer, Player player) {
setLayout(new BorderLayout());
setBackground(Color.GREEN);
setPreferredSize(new Dimension(1024, 768));
this.dealer = dealer;
this.player = player;
}
public void updateTable(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw dealer’s cards
int dealerX = 50;
int dealerY = 100;
g.drawString("Dealer", dealerX, dealerY - 20);
dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true);
// Draw player’s cards
int playerX = 50;
int playerY = getHeight() - 200;
g.drawString("Player", playerX, playerY - 20);
playerX = drawPlayerHand(g, player, playerX, playerY, false);
// Draw chips on the table
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.PLAIN, 18));
g.drawString("Chips on the table: ", playerX + 50, playerY);
}
private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) {
int i = 0;
for (Card c : p.getCardsOnHand()) {
if (isDealer && i == 0) {
new ImageIcon("images/back.png").paintIcon(this, g, x, y);
} else {
c.paintIcon(this, g, x, y);
}
x += 100;
i++;
}
return x;
}
}
package GUIExample;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginDialog extends JDialog {
private JTextField loginField;
private JPasswordField passwordField;
private JButton loginButton;
private boolean loggedIn = false;
public LoginDialog(JFrame parent) {
super(parent, "Login", true);
loginField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("Login");
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loggedIn = true;
dispose();
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("Login:"));
panel.add(loginField);
panel.add(new JLabel("Password:"));
panel.add(passwordField);
panel.add(loginButton);
add(panel);
pack();
setLocationRelativeTo(parent);
}
public String getLogin() {
return loginField.getText();
}
public String getPassword() {
return new String(passwordField.getPassword());
}
public boolean isLoggedIn() {
return loggedIn;
}
}
package Helper;
public class Keyboard {
public static String readString(String prompt) {
System.out.print(prompt);
return new java.util.Scanner(System.in).nextLine();
}
public static int readInt(String prompt) {
int input = 0;
boolean valid = false;
while (!valid) {
try {
input = Integer.parseInt(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter an integer ***");
}
}
return input;
}
public static double readDouble(String prompt) {
double input = 0;
boolean valid = false;
while (!valid) {
try {
input = Double.parseDouble(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a double ***");
}
}
return input;
}
public static float readFloat(String prompt) {
float input = 0;
boolean valid = false;
while (!valid) {
try {
input = Float.parseFloat(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a float ***");
}
}
return input;
}
public static long readLong(String prompt) {
long input = 0;
boolean valid = false;
while (!valid) {
try {
input = Long.parseLong(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("*** Please enter a long ***");
}
}
return input;
}
public static char readChar(String prompt,char[] choices) {
boolean validChoice = false;
char r = ' ';
while(!validChoice) {
r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":");
if(!validateChoice(choices,r)) {
System.out.println("Invalid input");
}else {
validChoice = true;
}
}
return r;
}
private static String charArrayToString(char[] charArray) {
String s = "[";
for(int i=0;i<charArray.length;i++) {
s+=charArray[i];
if(i!=charArray.length-1) {
s+=",";
}
}
s += "]";
return s;
}
private static boolean validateChoice(char[] choices, char choice) {
boolean validChoice = false;
for(int i=0;i<choices.length;i++) {
if(choices[i]==choice) {
validChoice = true;
break;
}
}
return validChoice;
}
public static char readChar(String prompt) {
char input = 0;
boolean valid = false;
while (!valid) {
String temp = readString(prompt);
if (temp.length() != 1) {
System.out.println("*** Please enter a character ***");
} else {
input = temp.charAt(0);
valid = true;
}
}
return input;
}
public static boolean readBoolean(String prompt) {
boolean valid = false;
while (!valid) {
String input = readString(prompt);
if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true")
|| input.equalsIgnoreCase("t")) {
return true;
} else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false")
|| input.equalsIgnoreCase("f")) {
return false;
} else {
System.out.println("*** Please enter Yes/No or True/False ***");
}
}
return false;
}
public static java.util.Date readDate(String prompt) {
java.util.Date date = null;
boolean valid = false;
while (!valid) {
try {
String input = readString(prompt).trim();
if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) {
int day = Integer.parseInt(input.substring(0, 2));
int month = Integer.parseInt(input.substring(3, 5));
int year = Integer.parseInt(input.substring(6, 10));
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setLenient(false);
cal.set(year, month - 1, day, 0, 0, 0);
date = cal.getTime();
valid = true;
} else {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
} catch (IllegalArgumentException e) {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
}
return date;
}
private static String quit = "0";
public static int getUserOption(String title, String[] menu) {
displayMenu(title, menu);
int choice = Keyboard.readInt("Enter Choice --> ");
while (choice > menu.length || choice < 0) {
choice = Keyboard.readInt("Invalid Choice, Re-enter --> ");
}
return choice;
}
private static void displayMenu(String title, String[] menu) {
line(80, "=");
System.out.println(title.toUpperCase());
line(80, "-");
for (int i = 0; i < menu.length; i++) {
System.out.println("[" + (i + 1) + "] " + menu[i]);
}
System.out.println("[" + quit + "] Quit");
line(80, "-");
}
public static void line(int len, String c) {
System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c));
}
}
package Helper;
import java.security.MessageDigest;
public class Utility {
public static String getHash(String base)
{
String message="";
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
message = hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
return message;
}
public static void printLine(int num)
{
printLine(num,'-');
}
public static void printDoubleLine(int num)
{
printLine(num,'=');
}
public static void printLine(int num,char pattern)
{
for(int i =0;i<num;i++)
{
System.out.print(pattern);
}
System.out.println("");
}
}
package Model;
import javax.swing.*;
public class Card extends ImageIcon {
private String suit;
private String name;
private int value;
private int rank;
private boolean faceDown;
public Card(String suit, String name, int value, int rank) {
super("images/" + suit + name + ".png");
this.suit = suit;
this.name = name;
this.value = value;
this.rank = rank;
this.faceDown = false;
}
public boolean isFaceDown() {
return this.faceDown;
}
public void setFaceDown(boolean faceDown) {
this.faceDown = faceDown;
}
public String getSuit() {
return this.suit;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
public int getRank() {
return this.rank;
}
public String toString() {
if (this.faceDown) {
return "<HIDDEN CARD>";
} else {
return "<" + this.suit + " " + this.name + ">";
}
}
public String display() {
return "<"+this.suit+" "+this.name+" "+this.rank+">";
}
}
//card rank
// D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.*;
public class Dealer extends Player {
private Deck deck;
public Dealer() {
super("Dealer", "", 0);
deck = new Deck();
}
public void shuffleCards() {
System.out.println("Dealer shuffle deck");
deck.shuffle();
}
public void dealCardTo(Player player) {
Card card = deck.dealCard(); // take a card out from the deck
player.addCard(card); // pass the card into the player
}
public void addCardsBackToDeck(ArrayList<Card> cards) {
deck.appendCard(cards);
}
//return 1 if card1 rank higher, else return 2
public int determineWhichCardRankHigher(Card card1, Card card2) {
if(card1.getRank()>card2.getRank()) {
return 1;
}else {
return 2;
}
}
}
package Model;
import java.util.*;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
String[] suits = { "Diamond", "Club","Heart","Spade", };
for (int i = 0; i < suits.length; i++) {
String suit = suits[i];
Card card = new Card(suit, "Ace", 1,1+i);
cards.add(card);
int c = 5;
for (int n = 2; n <= 10; n++) {
Card oCard = new Card(suit, "" + n, n,c+i);
cards.add(oCard);
c+=4;
}
Card jackCard = new Card(suit, "Jack", 10,41+i);
cards.add(jackCard);
Card queenCard = new Card(suit, "Queen", 10,45+i);
cards.add(queenCard);
Card kingCard = new Card(suit, "King", 10,49+i);
cards.add(kingCard);
}
}
public Card dealCard() {
return cards.remove(0);
}
//add back one card
public void appendCard(Card card) {
cards.add(card);
}
//add back arraylist of cards
public void appendCard(ArrayList<Card> cards) {
for(Card card: cards) {
this.cards.add(card);
}
}
public void shuffle() {
Random random = new Random();
for(int i=0;i<10000;i++) {
int indexA = random.nextInt(cards.size());
int indexB = random.nextInt(cards.size());
Card cardA = cards.get(indexA);
Card cardB = cards.get(indexB);
cards.set(indexA, cardB);
cards.set(indexB, cardA);
}
}
//for internal use only
private void showCards() {
for (Card card : cards) {
System.out.println(card);
}
}
//for internal use only
private void displayCards() {
for (Card card : cards) {
System.out.println(card.display());
}
}
public static void main(String[] args) {
Deck deck = new Deck();
//deck.shuffle();
/*Card card1 = deck.dealCard();
Card card2 = deck.dealCard();
Card card3 = deck.dealCard();
deck.showCards();
ArrayList<Card> cards = new ArrayList<Card>();
cards.add(card1);
cards.add(card2);
cards.add(card3);
deck.appendCard(cards);
System.out.println();*/
deck.displayCards();
}
}
//card rank
//D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import Controller.*;
import View.*;
import GUIExample.LoginDialog;
import GUIExample.GameTableFrame;
import javax.swing.JOptionPane;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class HighSum {
private Dealer dealer;
private Player player;
private ViewController view;
private GameController gc;
private int chipsOnTable;
public HighSum() {
}
public void init(String login, String password) {
// Create all the required objects
this.dealer = new Dealer();
this.player = new Player(login, password, 50);
this.view = new ViewController();
// Bring them together
this.gc = new GameController(this.dealer, this.player, this.view);
}
private Player checkWinner() {
if(player.getTotalCardsValue() > dealer.getTotalCardsValue())
return player;
else if(player.getTotalCardsValue() < dealer.getTotalCardsValue())
return dealer;
else
return null;
}
public Dealer getDealer() {
return dealer;
}
public Player getPlayer() {
return player;
}
public void run() {
// Setup the game table
GameTableFrame gameTableFrame = new GameTableFrame(dealer, player);
// Starts the game!
boolean carryOn = true;
while (carryOn) {
runOneRound();
gameTableFrame.updateScreen();
if (!gc.getPlayerQuitStatus()) {
int response = JOptionPane.showConfirmDialog(
gameTableFrame,
"Do you want to play another game?",
"New Game",
JOptionPane.YES_NO_OPTION
);
carryOn = response == JOptionPane.YES_OPTION;
} else {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
gameTableFrame.dispose();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for (int round = 1; round <= 4; round++) {
// Code remains same until here
// Check if the player wants to follow or quit
char r;
int chipsToBet;
if (round == 1) {
chipsToBet = this.view.getPlayerCallBetChip(this.player);
} else {
chipsToBet = this.view.getDealerCallBetChips();
}
}
Player winner = checkWinner();
if(playerQuit){
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
}
/* public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum();
highSum.init(login, password);
highSum.run();
}
}*/
}
package Model;
import java.util.*;
public class Player extends User{
private int chips;
protected ArrayList<Card> cardsOnHand;
public Player(String loginName, String password, int chips) {
super(loginName, password);
this.chips = chips;
this.cardsOnHand = new ArrayList<Card>();
}
public int getChips() {
return this.chips;
}
public void addChips(int amount) {
this.chips+=amount;//no error check
}
public void deductChips(int amount) {
this.chips-=amount;//no error check
}
public void addCard(Card card) {
this.cardsOnHand.add(card);
}
public ArrayList<Card> getCardsOnHand() {
return this.cardsOnHand;
}
public int getTotalCardsValue() {
int total = 0;
for(Card card: this.cardsOnHand) {
total+=card.getValue();
}
return total;
}
public Card getLastCard() {
return this.cardsOnHand.get(this.cardsOnHand.size()-1);
}
public void clearCardsOnHand() {
this.cardsOnHand.clear();
}
//Think of the action that a player can take
//implement more related methods here
public static void main(String[] args) {
// TODO Auto-generated method stub
Player player = new Player("IcePeak","A",100);
System.out.println(player.getChips());
player.deductChips(10);
System.out.println(player.getChips());
player.addChips(20);
System.out.println(player.getChips());
}
}
package Model;
import Helper.*;
abstract public class User {
private String loginName;
private String hashPassword;
public User(String loginName, String password) {
this.loginName = loginName;
this.hashPassword = Utility.getHash(password);
}
public String getLoginName() {
return this.loginName;
}
public boolean checkPassword(String password) {
return this.hashPassword.equals(Utility.getHash(password));
}
}
package View;
import Helper.*;
import Model.*;
//all input and output should be done view ViewController
//so that it is easier to implement GUI later
public class ViewController {
public void displayExitGame() {
System.out.println("Thank you for playing HighSum game");
}
public void displayBetOntable(int bet) {
System.out.println("Bet on table : "+bet);
}
public void displayPlayerWin(Player player) {
System.out.println(player.getLoginName()+" Wins!");
}
public void displayDealerWin() {
System.out.println("Dealer Wins!");
}
public void displayTie() {
System.out.println("It is a tie!.");
}
public void displayPlayerQuit() {
System.out.println("You have quit the current game.");
}
public void displayPlayerCardsOnHand(Player player) {
System.out.println(player.getLoginName());
if(player instanceof Dealer) {
for (int i = 0; i < player.getCardsOnHand().size(); i++) {
if (i == 0) {
System.out.print("<HIDDEN CARD> ");
} else {
System.out.print(player.getCardsOnHand().get(i).toString() + " ");
}
}
} else {
for (Card card : player.getCardsOnHand()) {
System.out.print(card + " ");
}
}
System.out.println();
}
public void displayBlankLine() {
System.out.println();
}
public void displayPlayerTotalCardValue(Player player) {
System.out.println("Value:"+player.getTotalCardsValue());
}
public void displayDealerDealCardsAndGameRound(int round) {
System.out.println("Dealer dealing cards - ROUND "+round);
}
public void displayGameStart() {
System.out.println("Game starts - Dealer shuffle deck");
}
public void displayPlayerNameAndChips(Player player) {
System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips");
}
public void displayPlayerNameAndLeftOverChips(Player player) {
System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips");
}
public void displayGameTitle() {
System.out.println("HighSum GAME");
}
public void displaySingleLine() {
for(int i=0;i<30;i++) {
System.out.print("-");
}
System.out.println();
}
public void displayDoubleLine() {
for(int i=0;i<30;i++) {
System.out.print("=");
}
System.out.println();
}
public char getPlayerCallOrQuit() {
char[] choices = {'c','q'};
char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices);
return r;
}
public char getPlayerFollowOrNot(Player player, int dealerBet) {
boolean validChoice = false;
char[] choices = {'y','n'};
char r = 'n';
while(!validChoice) {
r = Keyboard.readChar("Do you want to follow?",choices);
//check if player has enff chips to follow
if(r=='y' && player.getChips()<dealerBet) {
System.out.println("You do not have enough chips to follow");
displayPlayerNameAndChips(player);
}else {
validChoice = true;
}
}
return r;
}
public char getPlayerNextGame() {
char[] choices = {'y','n'};
char r = Keyboard.readChar("Next game?",choices);
return r;
}
public int getPlayerCallBetChip(Player player) {
boolean validBetAmount = false;
int chipsToBet = 0;
while(!validBetAmount) {
chipsToBet = Keyboard.readInt("Player call, state bet:");
if(chipsToBet<0) {
System.out.println("Chips cannot be negative");
}else if(chipsToBet>player.getChips()) {
System.out.println("You do not have enough chips");
}else {
validBetAmount = true;
}
}
return chipsToBet;
}
public int getDealerCallBetChips() {
System.out.println("Dealer call, state bet: 10");
return 10;
}
}
"
These are the requirements:
"On completion of this assignment a student should be able to write a Java application
that:
• Makes use of Java API "Swing" and "AWT" packages
• Handles generated events
• Makes use of layout manager to organize the GUI components
• Know how to apply and design a program using object-oriented concepts
2. Task
Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI).
2.1 Login
The game starts by the player logging into the game.
2.2 Play Game
The game starts after the player click on “Login”.
First, the dealer will shuffles the deck.
(You may include animation in this frame to simulate “shuffle” effect as enhancement.)
Then the dealer deals two cards from the top of the deck to the player and itself.
Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game.
Assume the player states 10 as the bet chips.
The player’s chip will be deducted by 10.
The chips on table will be updated to 20 and the dealer deals cards for next round.
Assume the dealer’s last card is higher than the player’s last card.
The dealer Call the game and the player gets to choose to Follow or Quit the game.
If the player follows the game, 10 chips will be deducted from the player’s balance chips.
(Asumme the dealer place 10 chips.)
The games carry on for maximum of four rounds.
In the last round, the player with the highest total sum wins the game.
And the game continues until the player exits the game.
Error Handling
Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips.
You should look out for other possible exceptions and handle them too."
Edit the code so that when highsum gui is run,
There is an error : "Description Resource Path Location Type
The type GameTableFrame is already defined HighSumGUI.java /A3Skeleton/src/GUIExample Unknown Java Problem
"
|
17c426f1ed9231ecb34c72754785625f
|
{
"intermediate": 0.3008303642272949,
"beginner": 0.4713391661643982,
"expert": 0.2278304547071457
}
|
9,018
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
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, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pBufferInfo = &bufferInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Texture.cpp:
#include "Texture.h"
#include "BufferUtils.h"
#include <iostream>
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
}
void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->physicalDevice = physicalDevice;
this->commandPool = commandPool;
this->graphicsQueue = graphicsQueue;
this->initialized = true;
// Load image from file using stb_image
int width, height, channels;
stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
{
throw std::runtime_error("Failed to load texture image!");
}
// Calculate the number of mip levels
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
// Create a buffer to store the image data
VkDeviceSize imageSize = width * height * 4;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
// Create the staging buffer for transferring image data
BufferUtils::CreateBuffer(device, physicalDevice, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
// Copy image data to the buffer
void* bufferData;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData);
memcpy(bufferData, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
// Free the stb_image buffer
stbi_image_free(pixels);
// Create vkImage, copy buffer to image, and create imageView and sampler
// …
CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
CreateSampler(mipLevels);
TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels, VK_SAMPLE_COUNT_1_BIT); // Add this call
CopyBufferToImage(stagingBuffer, width, height);
// Cleanup the staging buffer and staging buffer memory
// …
// Destroy the staging buffer and free the staging buffer memory
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Texture::Cleanup(Texture* texture)
{
// Put the content of the old Cleanup() method here
// Make sure to replace this with texture keyword
// …
}
VkImageView Texture::GetImageView() const
{
return imageView;
}
VkSampler Texture::GetSampler() const
{
return sampler;
}
void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties)
{
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0;
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate image memory!");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
void Texture::TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
VkPipelineStageFlags sourceStage;
VkPipelineStageFlags destinationStage;
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
else {
throw std::invalid_argument("Unsupported layout transition!");
}
vkCmdPipelineBarrier(
commandBuffer,
sourceStage, destinationStage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
void Texture::CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels)
{
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture image view!");
}
}
void Texture::CreateSampler(uint32_t mipLevels)
{
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = static_cast<float>(mipLevels);
if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture sampler!");
}
}
void Texture::CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// Record buffer to image copy command in the command buffer
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
I am getting this error:
VUID-VkWriteDescriptorSet-descriptorType-00319(ERROR / SPEC): msgNum: -405619238 - Validation Error: [ VUID-VkWriteDescriptorSet-descriptorType-00319 ] Object 0: handle = 0xb097c90000000027, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; | MessageID = 0xe7d2bdda | vkUpdateDescriptorSets() pDescriptorWrites[0] failed write update validation for VkDescriptorSet 0xb097c90000000027[] with error: Attempting write update to VkDescriptorSet 0xb097c90000000027[] allocated with VkDescriptorSetLayout 0xdd3a8a0000000015[] binding #0 with type VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER but update type is VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER. The Vulkan spec states: descriptorType must match the type of dstBinding within dstSet (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkWriteDescriptorSet-descriptorType-00319)
Objects: 1
[0] 0xb097c90000000027, type: 23, name: NULL
It seems to occur when calling vkUpdateDescriptorSets in the Material::UpdateBufferBinding method.
Here is some additional code from the Renderer class for context:
VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
How can I alter the code to fix this issue?
|
c9298a892a40b2e00e5c90b32397ecc6
|
{
"intermediate": 0.3753734827041626,
"beginner": 0.29778599739074707,
"expert": 0.32684049010276794
}
|
9,019
|
# Использование прокси
# playwright
import asyncio
import time
from random import randint
from bs4 import BeautifulSoup
from playwright.async_api import async_playwright
from fake_useragent import UserAgent
import requests
# Set up Fake UserAgent for random user-agents
ua = UserAgent()
# Function to implement random delay (rate limiting)
def random_delay(minimum=2, maximum=10):
sleep_time = randint(minimum, maximum)
time.sleep(sleep_time)
# Function to check if a website’s robots.txt allows scraping to implement point 3
def can_scrape(url):
response = requests.get(url + "/robots.txt")
if "Disallow: /" in response.text:
return False
return True
async def get_token_info(token_symbol, proxy):
# Check if we can scrape the requested URL
url = "https://moonarch.app/"
if not can_scrape(url):
print("Scraping is not allowed according to the website’s robots.txt.")
return None
async with async_playwright() as p:
browser = await p.chromium.launch(
headless=True,
proxy={"server": proxy},
user_agent=ua.random,
)
context = await browser.new_context()
try:
page = await context.new_page()
await page.goto(url)
search_box_selector = 'input.form-control'
await page.wait_for_selector(search_box_selector)
search_box = await page.query_selector(search_box_selector)
await search_box.type(token_symbol)
await page.wait_for_selector('.token-info')
await page.wait_for_selector('.infocard')
soup = BeautifulSoup(await page.content(), "html.parser")
token_info_element = soup.find("div", class_="token-info")
infocard_element = soup.find("div", class_="infocard")
check_alert_element = soup.find("div", class_="token-check-message check-alert")
check_warning_element = soup.find("div", class_="token-check-message check-warning")
check_info_element = soup.find("div", class_="token-check-message check-info")
not_verified_element = soup.find("div", class_="not-verified")
check_alert_status = "Yes" if check_alert_element else "None"
check_warning_status = "Yes" if check_warning_element else "None"
check_info_status = "Yes" if check_info_element else "None"
not_verified_status = "Yes" if not_verified_element else "None"
if token_info_element and infocard_element:
token_name_element = token_info_element.find("span", class_="name")
token_symbol_element = token_info_element.find("span", class_="symbol")
info_items = infocard_element.find_all("li")
if token_name_element and token_symbol_element and len(info_items) >= 7:
token_name = token_name_element.text.strip()
token_symbol = token_symbol_element.text.strip()
price = info_items[0].find("span", class_="value").text.strip()
max_supply = info_items[1].find("span", class_="value").text.strip()
market_cap = info_items[2].find("span", class_="value").text.strip()
liquidity = info_items[3].find("span", class_="value").text.strip()
liq_mc = info_items[4].find("span", class_="value").text.strip()
token_age = info_items[6].find("span", class_="value").text.strip()
await browser.close()
# Implement rate limiting (point 1)
random_delay()
return {
"name": token_name,
"symbol": token_symbol,
"price": price,
"max_supply": max_supply,
"market_cap": market_cap,
"liquidity": liquidity,
"liq_mc": liq_mc,
"token_age": token_age,
"check_alert": check_alert_status,
"check_warning": check_warning_status,
"check_info": check_info_status,
"not_verified": not_verified_status
}
else:
await browser.close()
error_info = f"token_name_element: {token_name_element}, token_symbol_element: {token_symbol_element}, info_items count: {len(info_items)}"
return {"error": f"Failed to find the required info items or name and.symbol. Error_info: {error_info}"}
else:
await browser.close()
return {"error": f"Failed to find the required elements for token_info_element ({token_info_element}) and infocard_element ({infocard_element})."}
except Exception as ex:
print(f"Error occurred while scraping: {ex}")
await browser.close()
return None
token_symbols = [
"0x0E481Fa712201f61dAf97017138Efaa69e2A3df3",
"0x2023aa62A7570fFd59F13fdE2Cac0527D45abF91",
"0x2222222222222222222222222222222222222222",
"0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e"
# Add more token symbols here…
]
async def main():
proxy_url = "http://proxy.example.com:8080"
while True:
result_tasks = [get_token_info(token_symbol, proxy_url) for token_symbol in token_symbols]
results = await asyncio.gather(*result_tasks)
print(results)
await asyncio.sleep(60)
asyncio.run(main())
Write a working proxy in this code
|
f3d06bcab0a84f35710ab4f531f22ddf
|
{
"intermediate": 0.2942463755607605,
"beginner": 0.5161563754081726,
"expert": 0.1895972341299057
}
|
9,020
|
Что нужно исправить чтобы базовая финальная стоимость package com.example.myapp_2.Data.cart;
import com.example.myapp_2.Data.List_1.Product;
import java.util.ArrayList;
import java.util.List;
import com.example.myapp_2.Data.List_1.Product;
import java.util.ArrayList;
import java.util.List;
public class Cart {
private static Cart instance;
private List<CartItem> items;
private List<OnCartChangedListener> listeners;
private Cart() {
items = new ArrayList<>();
listeners = new ArrayList<>();
}
public static Cart getInstance() {
if (instance == null) {
instance = new Cart();
}
return instance;
}
public void addItem(Product product) {
for (CartItem item : items) {
if (item.getProduct().equals(product)) {
item.setQuantity(item.getQuantity() + 1);
notifyCartChanged();
return;
}
}
items.add(new CartItem(product, 1));
notifyCartChanged();
}
public void updateItem(CartItem item, int newQuantity) {
if (newQuantity <= 0) {
removeItem(item);
} else {
item.setQuantity(newQuantity);
notifyCartChanged();
}
}
public void removeItem(CartItem item) {
items.remove(item);
notifyCartChanged();
}
public List<CartItem> getItems() {
return items;
}
public void clear() {
items.clear();
notifyCartChanged();
}
public double getTotalPrice() {
int totalPrice = 0;
for (CartItem item : items) {
totalPrice += item.getTotalPrice();
}
return totalPrice;
}
private void notifyCartChanged() {
for (OnCartChangedListener listener : listeners) {
listener.onCartChanged();
}
}
public void addOnCartChangedListener(OnCartChangedListener listener) {
listeners.add(listener);
}
public interface OnCartChangedListener {
void onCartChanged();
}
}
package com.example.myapp_2.Data.cart;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
import java.util.List;
public class CartAdapter extends RecyclerView.Adapter<CartItemViewHolder> {
private List<CartItem> items;
private OnCartItemListener listener;
public CartAdapter(List<CartItem> items, OnCartItemListener listener) {
this.items = items;
this.listener = listener;
}
@Override
public CartItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cart, parent, false);
return new CartItemViewHolder(view);
}
@Override
public void onBindViewHolder(CartItemViewHolder holder, int position) {
CartItem item = items.get(position);
holder.bind(item, listener);
}
@Override
public int getItemCount() {
return items.size();
}
public void setItems(List<CartItem> items) {
this.items = items;
notifyDataSetChanged();
}
public void clear() {
items.clear();
notifyDataSetChanged();
}
}package com.example.myapp_2.Data.cart;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.R;
public class CartFragment extends Fragment implements Cart.OnCartChangedListener {
private TextView totalPriceTextView;
private Button placeOrderButton;
private RecyclerView recyclerView;
private Button backButton;
private CartAdapter adapter;
private Cart cart;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
backButton = view.findViewById(R.id.back_button); // кнопка назад
totalPriceTextView = view.findViewById(R.id.total_price_text_view);
placeOrderButton = view.findViewById(R.id.place_order_button);
recyclerView = view.findViewById(R.id.cart_recycler_view);
cart = Cart.getInstance();
cart.addOnCartChangedListener(this);
adapter = new CartAdapter(cart.getItems(), new OnCartItemListener() {
@Override
public void onQuantityChanged(CartItem item, int newQuantity) {
cart.updateItem(item, newQuantity);
}
@Override
public void onRemoveButtonClick(CartItem item) {
cart.removeItem(item);
}
});
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
updateTotalPrice();
placeOrderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Создание уведомления
String orderPriceStr = getString(R.string.cart_item_total_price_2, cart.getTotalPrice());
NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity(), "channel_id")
.setSmallIcon(R.drawable.baseline_fastfood_24)
.setContentTitle("Заказ оформлен")
.setContentText("Ваш заказ успешно оформлен"+ " "+ orderPriceStr+"!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// Отображение уведомления (ТУТ КАКАЯ-ТО БОЙДА НА РОВЕРКУ РАЗРЕШЕНИЯ)
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getActivity());
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
notificationManager.notify(1, builder.build());
// Закрытие текущего экрана
getActivity().onBackPressed();
// Очистка списка заказов
adapter.clear();
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed(); // вызов метода возврата на предыдущий экран
}
});
return view;
}
private void updateTotalPrice() {
double totalPrice = cart.getTotalPrice();
if (getContext() != null) {
totalPriceTextView.setText(getString(R.string.cart_item_total_price, totalPrice));
}
}
@Override
public void onCartChanged() {
adapter.setItems(cart.getItems());
updateTotalPrice();
}
}
package com.example.myapp_2.Data.cart;
import com.example.myapp_2.Data.List_1.Product;
public class CartItem {
private Product product; // сам товар
private int quantity; // количество
public CartItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getTotalPrice() {
return product.getPrice() * quantity;
}
}
package com.example.myapp_2.Data.cart;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.Data.List_1.Product;
import com.example.myapp_2.R;
public class CartItemViewHolder extends RecyclerView.ViewHolder {
private ImageView productImageView;
private TextView productNameTextView;
private TextView productPriceTextView;
private TextView productTotalPriceTextView;
private TextView productQuantityTextView;
private Button decreaseButton;
private Button increaseButton;
private Button removeButton;
private int quantity;
public CartItemViewHolder(@NonNull View itemView) {
super(itemView);
productImageView = itemView.findViewById(R.id.cart_item_image_view);
productNameTextView = itemView.findViewById(R.id.cart_item_name_text_view);
productPriceTextView = itemView.findViewById(R.id.cart_item_price_text_view);
productTotalPriceTextView = itemView.findViewById(R.id.cart_item_total_price_text_view);
productQuantityTextView = itemView.findViewById(R.id.cart_item_quantity_text_view);
decreaseButton = itemView.findViewById(R.id.cart_item_decrease_button);
increaseButton = itemView.findViewById(R.id.cart_item_increase_button);
removeButton = itemView.findViewById(R.id.cart_item_remove_button);
}
public void bind(CartItem item, OnCartItemListener listener) {
Product product = item.getProduct();
quantity = item.getQuantity();
productImageView.setImageResource(product.getImageResource());
productNameTextView.setText(product.getName());
productPriceTextView.setText(itemView.getContext().getString(R.string.product_price, product.getPrice()));
productTotalPriceTextView.setText(itemView.getContext().getString(R.string.cart_item_total_price, item.getTotalPrice()));
productQuantityTextView.setText(String.valueOf(quantity));
decreaseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quantity -= 1;
productQuantityTextView.setText(String.valueOf(quantity));
listener.onQuantityChanged(item, quantity);
}
});
increaseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quantity += 1;
productQuantityTextView.setText(String.valueOf(quantity));
listener.onQuantityChanged(item, quantity);
}
});
removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onRemoveButtonClick(item);
}
});
}
}
package com.example.myapp_2.Data.cart;
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
public class ItemSpacingDecoration extends RecyclerView.ItemDecoration {
private int mSpacing; // промежуток между элементами
public ItemSpacingDecoration(int spacing) {
this.mSpacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
// Добавляем отступ снизу элемента
outRect.bottom = mSpacing;
}
}package com.example.myapp_2.Data.cart;
public interface OnCartItemListener {
void onQuantityChanged(CartItem item, int newQuantity);//вызывается при изменении количества товара в корзине
void onRemoveButtonClick(CartItem item);//вызывается при нажатии на кнопку удаления товара из корзины
}
package com.example.myapp_2.Data.cart;
import com.example.myapp_2.Data.List_1.Product;
public interface OnProductClickListener {
void onAddToCartClick(Product product);
}
package com.example.myapp_2.Data.cart;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapp_2.Data.List_1.Product;
import com.example.myapp_2.Data.List_1.ProductAdapter;
import com.example.myapp_2.R;
import java.util.List;
public class ProductsFragment extends Fragment {
private List<Product> productList;
private RecyclerView recyclerView;
private ProductAdapter adapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_products, container, false);
adapter = new ProductAdapter(productList, new OnProductClickListener() {
@Override
public void onAddToCartClick(Product product) {
addToCart(product);
}
});
// Здесь инициализируем список товаров и recyclerView
adapter = new ProductAdapter(productList, new OnProductClickListener() {
@Override
public void onAddToCartClick(Product product) {
addToCart(product);
}
}); // передаём метод добавления товара в корзину
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
private void addToCart(Product product) {
// метод добавления товара в корзину
Cart cart = Cart.getInstance();
cart.addItem(product);
}
}
была целочисленной :
|
482ccd91774f9184976d8ee51eb662ae
|
{
"intermediate": 0.32289808988571167,
"beginner": 0.4038914740085602,
"expert": 0.27321043610572815
}
|
9,021
|
make randomly generated form in 3d matrix vertices and edges. from 3d cube to triangle - to sphere - to some random etc… make an endless random form generation through some transition time period. output full code: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
// Transformation parameters
const scale = 0.01;
const zoom = 0.01;
const offsetX = 0.5;
const offsetY = 0.5;
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
let angleX = 0;
let angleY = 0;
let angleZ = 0;
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 100;
const amplitude = 1;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 6;
ctx.strokeStyle = ‘hsla(’ + (angleX + angleY) * 10 + ‘, 10%, 50%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
const angle = Math.atan2(y2 - y1, x2 - x1);
// Calculate control point for curved edge
const cpDist = 0.2 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2);
ctx.moveTo(x1, y1);
ctx.quadraticCurveTo(cpX, cpY, x2, y2);
}
ctx.stroke();
angleX += 0.005;
angleY += -0.005;
angleZ += -0.01;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
382c1edd2e8078f21f917ad19576aeb5
|
{
"intermediate": 0.2738526165485382,
"beginner": 0.5064542293548584,
"expert": 0.219693124294281
}
|
9,022
|
This is my ide program for a highsum gui game.
"package GUIExample;
import Model.Dealer;
import Model.HighSum;
import Model.Player;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
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();
highSum.init(login, password);
GameTableFrame gameTableFrame = new GameTableFrame(highSum);
gameTableFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
});
}
}
class GameTableFrame extends JFrame {
private HighSum highSum;
private GameTablePanel gameTablePanel;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(HighSum highSum) {
this.highSum = highSum;
this.gameTablePanel = new GameTablePanel(highSum.getDealer(), highSum.getPlayer());
setTitle("HighSum GUI Game");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
playButton = new JButton("Play");
quitButton = new JButton("Quit");
playButton.addActionListener(new PlayAction(this, highSum));
quitButton.addActionListener(new QuitAction());
JPanel buttonPanel = new JPanel();
buttonPanel.add(playButton);
buttonPanel.add(quitButton);
add(gameTablePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void updateScreen(Dealer dealer, Player player) {
gameTablePanel.updateTable(dealer, player);
}
}
package Controller;
import Model.Dealer;
import Model.Player;
import View.ViewController;
public class GameController {
private Dealer dealer;
private Player player;
private ViewController view;
private int chipsOnTable;
private boolean playerQuit;
public GameController(Dealer dealer,Player player,ViewController view) {
this.dealer = dealer;
this.player = player;
this.view = view;
this.chipsOnTable = 0;
}
public boolean getPlayerQuitStatus() {
return playerQuit;
}
public void run() {
boolean carryOn= true;
while(carryOn) {
runOneRound();
char r = this.view.getPlayerNextGame();
if(r=='n') {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for(int round = 1;round<=4;round++) {
this.view.displaySingleLine();
this.view.displayDealerDealCardsAndGameRound(round);
this.view.displaySingleLine();
if (round == 1) { //round 1 deal extra card
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
} else {
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
}
this.view.displayPlayerCardsOnHand(this.dealer);
this.view.displayBlankLine();
this.view.displayPlayerCardsOnHand(player);
this.view.displayPlayerTotalCardValue(player);
int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard());
if(whoCanCall==1) {//dealer call
int chipsToBet = this.view. getDealerCallBetChips();
//ask player want to follow?
char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet);
if(r=='y') {
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}else {//player call
if(round==1) {//round 1 player cannot quit
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayBetOntable(this.chipsOnTable);
}else {
char r = this.view.getPlayerCallOrQuit();
if(r=='c') {
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}
}
}
//check who win
if(playerQuit) {
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) {
this.view.displayPlayerWin(this.player);
this.player.addChips(chipsOnTable);
this.chipsOnTable=0;
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) {
this.view.displayDealerWin();
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else {
this.view.displayTie();
this.player.addChips(chipsOnTable/2);
this.view.displayPlayerNameAndLeftOverChips(this.player);
}
//put all the cards back to the deck
dealer.addCardsBackToDeck(dealer.getCardsOnHand());
dealer.addCardsBackToDeck(player.getCardsOnHand());
dealer.clearCardsOnHand();
player.clearCardsOnHand();
}
}
package GUIExample;
import Model.Dealer;
import Model.HighSum;
import Model.Player;
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameTableFrame extends JFrame {
private GameTablePanel gameTablePanel;
private Dealer dealer;
private Player player;
private JLabel shufflingLabel;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
gameTablePanel = new GameTablePanel(dealer, player);
shufflingLabel = new JLabel("Shuffling");
shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER);
playButton = new JButton("Play");
quitButton = new JButton("Quit");
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shufflingLabel.setVisible(true);
HighSum highSum = new HighSum();
highSum.init(player.getLoginName(), "some_default_password");
highSum.run();
updateScreen();
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Create the main panel that contains both the game board and the buttons
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(playButton);
buttonsPanel.add(quitButton);
mainPanel.add(gameTablePanel, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
mainPanel.add(shufflingLabel, BorderLayout.NORTH);
shufflingLabel.setVisible(false);
add(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
// This method updates the screen after each game
public void updateScreen() {
gameTablePanel.updateTable(dealer, player);
}
}
package GUIExample;
import java.awt.*;
import javax.swing.*;
import Model.*;
public class GameTablePanel extends JPanel {
private Player player;
private Dealer dealer;
public GameTablePanel(Dealer dealer, Player player) {
setLayout(new BorderLayout());
setBackground(Color.GREEN);
setPreferredSize(new Dimension(1024, 768));
this.dealer = dealer;
this.player = player;
}
public void updateTable(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw dealer’s cards
int dealerX = 50;
int dealerY = 100;
g.drawString("Dealer", dealerX, dealerY - 20);
dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true);
// Draw player’s cards
int playerX = 50;
int playerY = getHeight() - 200;
g.drawString("Player", playerX, playerY - 20);
playerX = drawPlayerHand(g, player, playerX, playerY, false);
// Draw chips on the table
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.PLAIN, 18));
g.drawString("Chips on the table: ", playerX + 50, playerY);
}
private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) {
int i = 0;
for (Card c : p.getCardsOnHand()) {
if (isDealer && i == 0) {
new ImageIcon("images/back.png").paintIcon(this, g, x, y);
} else {
c.paintIcon(this, g, x, y);
}
x += 100;
i++;
}
return x;
}
}
package GUIExample;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginDialog extends JDialog {
private JTextField loginField;
private JPasswordField passwordField;
private JButton loginButton;
private boolean loggedIn = false;
public LoginDialog(JFrame parent) {
super(parent, "Login", true);
loginField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("Login");
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loggedIn = true;
dispose();
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("Login:"));
panel.add(loginField);
panel.add(new JLabel("Password:"));
panel.add(passwordField);
panel.add(loginButton);
add(panel);
pack();
setLocationRelativeTo(parent);
}
public String getLogin() {
return loginField.getText();
}
public String getPassword() {
return new String(passwordField.getPassword());
}
public boolean isLoggedIn() {
return loggedIn;
}
}
package Helper;
public class Keyboard {
public static String readString(String prompt) {
System.out.print(prompt);
return new java.util.Scanner(System.in).nextLine();
}
public static int readInt(String prompt) {
int input = 0;
boolean valid = false;
while (!valid) {
try {
input = Integer.parseInt(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter an integer ***");
}
}
return input;
}
public static double readDouble(String prompt) {
double input = 0;
boolean valid = false;
while (!valid) {
try {
input = Double.parseDouble(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a double ***");
}
}
return input;
}
public static float readFloat(String prompt) {
float input = 0;
boolean valid = false;
while (!valid) {
try {
input = Float.parseFloat(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a float ***");
}
}
return input;
}
public static long readLong(String prompt) {
long input = 0;
boolean valid = false;
while (!valid) {
try {
input = Long.parseLong(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("*** Please enter a long ***");
}
}
return input;
}
public static char readChar(String prompt,char[] choices) {
boolean validChoice = false;
char r = ' ';
while(!validChoice) {
r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":");
if(!validateChoice(choices,r)) {
System.out.println("Invalid input");
}else {
validChoice = true;
}
}
return r;
}
private static String charArrayToString(char[] charArray) {
String s = "[";
for(int i=0;i<charArray.length;i++) {
s+=charArray[i];
if(i!=charArray.length-1) {
s+=",";
}
}
s += "]";
return s;
}
private static boolean validateChoice(char[] choices, char choice) {
boolean validChoice = false;
for(int i=0;i<choices.length;i++) {
if(choices[i]==choice) {
validChoice = true;
break;
}
}
return validChoice;
}
public static char readChar(String prompt) {
char input = 0;
boolean valid = false;
while (!valid) {
String temp = readString(prompt);
if (temp.length() != 1) {
System.out.println("*** Please enter a character ***");
} else {
input = temp.charAt(0);
valid = true;
}
}
return input;
}
public static boolean readBoolean(String prompt) {
boolean valid = false;
while (!valid) {
String input = readString(prompt);
if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true")
|| input.equalsIgnoreCase("t")) {
return true;
} else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false")
|| input.equalsIgnoreCase("f")) {
return false;
} else {
System.out.println("*** Please enter Yes/No or True/False ***");
}
}
return false;
}
public static java.util.Date readDate(String prompt) {
java.util.Date date = null;
boolean valid = false;
while (!valid) {
try {
String input = readString(prompt).trim();
if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) {
int day = Integer.parseInt(input.substring(0, 2));
int month = Integer.parseInt(input.substring(3, 5));
int year = Integer.parseInt(input.substring(6, 10));
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setLenient(false);
cal.set(year, month - 1, day, 0, 0, 0);
date = cal.getTime();
valid = true;
} else {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
} catch (IllegalArgumentException e) {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
}
return date;
}
private static String quit = "0";
public static int getUserOption(String title, String[] menu) {
displayMenu(title, menu);
int choice = Keyboard.readInt("Enter Choice --> ");
while (choice > menu.length || choice < 0) {
choice = Keyboard.readInt("Invalid Choice, Re-enter --> ");
}
return choice;
}
private static void displayMenu(String title, String[] menu) {
line(80, "=");
System.out.println(title.toUpperCase());
line(80, "-");
for (int i = 0; i < menu.length; i++) {
System.out.println("[" + (i + 1) + "] " + menu[i]);
}
System.out.println("[" + quit + "] Quit");
line(80, "-");
}
public static void line(int len, String c) {
System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c));
}
}
package Helper;
import java.security.MessageDigest;
public class Utility {
public static String getHash(String base)
{
String message="";
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
message = hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
return message;
}
public static void printLine(int num)
{
printLine(num,'-');
}
public static void printDoubleLine(int num)
{
printLine(num,'=');
}
public static void printLine(int num,char pattern)
{
for(int i =0;i<num;i++)
{
System.out.print(pattern);
}
System.out.println("");
}
}
package Model;
import javax.swing.*;
public class Card extends ImageIcon {
private String suit;
private String name;
private int value;
private int rank;
private boolean faceDown;
public Card(String suit, String name, int value, int rank) {
super("images/" + suit + name + ".png");
this.suit = suit;
this.name = name;
this.value = value;
this.rank = rank;
this.faceDown = false;
}
public boolean isFaceDown() {
return this.faceDown;
}
public void setFaceDown(boolean faceDown) {
this.faceDown = faceDown;
}
public String getSuit() {
return this.suit;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
public int getRank() {
return this.rank;
}
public String toString() {
if (this.faceDown) {
return "<HIDDEN CARD>";
} else {
return "<" + this.suit + " " + this.name + ">";
}
}
public String display() {
return "<"+this.suit+" "+this.name+" "+this.rank+">";
}
}
//card rank
// D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.*;
public class Dealer extends Player {
private Deck deck;
public Dealer() {
super("Dealer", "", 0);
deck = new Deck();
}
public void shuffleCards() {
System.out.println("Dealer shuffle deck");
deck.shuffle();
}
public void dealCardTo(Player player) {
Card card = deck.dealCard(); // take a card out from the deck
player.addCard(card); // pass the card into the player
}
public void addCardsBackToDeck(ArrayList<Card> cards) {
deck.appendCard(cards);
}
//return 1 if card1 rank higher, else return 2
public int determineWhichCardRankHigher(Card card1, Card card2) {
if(card1.getRank()>card2.getRank()) {
return 1;
}else {
return 2;
}
}
}
package Model;
import java.util.*;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
String[] suits = { "Diamond", "Club","Heart","Spade", };
for (int i = 0; i < suits.length; i++) {
String suit = suits[i];
Card card = new Card(suit, "Ace", 1,1+i);
cards.add(card);
int c = 5;
for (int n = 2; n <= 10; n++) {
Card oCard = new Card(suit, "" + n, n,c+i);
cards.add(oCard);
c+=4;
}
Card jackCard = new Card(suit, "Jack", 10,41+i);
cards.add(jackCard);
Card queenCard = new Card(suit, "Queen", 10,45+i);
cards.add(queenCard);
Card kingCard = new Card(suit, "King", 10,49+i);
cards.add(kingCard);
}
}
public Card dealCard() {
return cards.remove(0);
}
//add back one card
public void appendCard(Card card) {
cards.add(card);
}
//add back arraylist of cards
public void appendCard(ArrayList<Card> cards) {
for(Card card: cards) {
this.cards.add(card);
}
}
public void shuffle() {
Random random = new Random();
for(int i=0;i<10000;i++) {
int indexA = random.nextInt(cards.size());
int indexB = random.nextInt(cards.size());
Card cardA = cards.get(indexA);
Card cardB = cards.get(indexB);
cards.set(indexA, cardB);
cards.set(indexB, cardA);
}
}
//for internal use only
private void showCards() {
for (Card card : cards) {
System.out.println(card);
}
}
//for internal use only
private void displayCards() {
for (Card card : cards) {
System.out.println(card.display());
}
}
public static void main(String[] args) {
Deck deck = new Deck();
//deck.shuffle();
/*Card card1 = deck.dealCard();
Card card2 = deck.dealCard();
Card card3 = deck.dealCard();
deck.showCards();
ArrayList<Card> cards = new ArrayList<Card>();
cards.add(card1);
cards.add(card2);
cards.add(card3);
deck.appendCard(cards);
System.out.println();*/
deck.displayCards();
}
}
//card rank
//D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import Controller.*;
import View.*;
import GUIExample.LoginDialog;
import GUIExample.GameTableFrame;
import javax.swing.JOptionPane;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class HighSum {
private Dealer dealer;
private Player player;
private ViewController view;
private GameController gc;
private int chipsOnTable;
public HighSum() {
}
public void init(String login, String password) {
// Create all the required objects
this.dealer = new Dealer();
this.player = new Player(login, password, 50);
this.view = new ViewController();
// Bring them together
this.gc = new GameController(this.dealer, this.player, this.view);
}
private Player checkWinner() {
if(player.getTotalCardsValue() > dealer.getTotalCardsValue())
return player;
else if(player.getTotalCardsValue() < dealer.getTotalCardsValue())
return dealer;
else
return null;
}
public Dealer getDealer() {
return dealer;
}
public Player getPlayer() {
return player;
}
public void run() {
// Setup the game table
GameTableFrame gameTableFrame = new GameTableFrame(dealer, player);
// Starts the game!
boolean carryOn = true;
while (carryOn) {
runOneRound();
gameTableFrame.updateScreen();
if (!gc.getPlayerQuitStatus()) {
int response = JOptionPane.showConfirmDialog(
gameTableFrame,
"Do you want to play another game?",
"New Game",
JOptionPane.YES_NO_OPTION
);
carryOn = response == JOptionPane.YES_OPTION;
} else {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
gameTableFrame.dispose();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for (int round = 1; round <= 4; round++) {
// Code remains same until here
// Check if the player wants to follow or quit
char r;
int chipsToBet;
if (round == 1) {
chipsToBet = this.view.getPlayerCallBetChip(this.player);
} else {
chipsToBet = this.view.getDealerCallBetChips();
}
}
Player winner = checkWinner();
if(playerQuit){
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
}
/* public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum();
highSum.init(login, password);
highSum.run();
}
}*/
}
package Model;
import java.util.*;
public class Player extends User{
private int chips;
protected ArrayList<Card> cardsOnHand;
public Player(String loginName, String password, int chips) {
super(loginName, password);
this.chips = chips;
this.cardsOnHand = new ArrayList<Card>();
}
public int getChips() {
return this.chips;
}
public void addChips(int amount) {
this.chips+=amount;//no error check
}
public void deductChips(int amount) {
this.chips-=amount;//no error check
}
public void addCard(Card card) {
this.cardsOnHand.add(card);
}
public ArrayList<Card> getCardsOnHand() {
return this.cardsOnHand;
}
public int getTotalCardsValue() {
int total = 0;
for(Card card: this.cardsOnHand) {
total+=card.getValue();
}
return total;
}
public Card getLastCard() {
return this.cardsOnHand.get(this.cardsOnHand.size()-1);
}
public void clearCardsOnHand() {
this.cardsOnHand.clear();
}
//Think of the action that a player can take
//implement more related methods here
public static void main(String[] args) {
// TODO Auto-generated method stub
Player player = new Player("IcePeak","A",100);
System.out.println(player.getChips());
player.deductChips(10);
System.out.println(player.getChips());
player.addChips(20);
System.out.println(player.getChips());
}
}
package Model;
import Helper.*;
abstract public class User {
private String loginName;
private String hashPassword;
public User(String loginName, String password) {
this.loginName = loginName;
this.hashPassword = Utility.getHash(password);
}
public String getLoginName() {
return this.loginName;
}
public boolean checkPassword(String password) {
return this.hashPassword.equals(Utility.getHash(password));
}
}
package View;
import Helper.*;
import Model.*;
//all input and output should be done view ViewController
//so that it is easier to implement GUI later
public class ViewController {
public void displayExitGame() {
System.out.println("Thank you for playing HighSum game");
}
public void displayBetOntable(int bet) {
System.out.println("Bet on table : "+bet);
}
public void displayPlayerWin(Player player) {
System.out.println(player.getLoginName()+" Wins!");
}
public void displayDealerWin() {
System.out.println("Dealer Wins!");
}
public void displayTie() {
System.out.println("It is a tie!.");
}
public void displayPlayerQuit() {
System.out.println("You have quit the current game.");
}
public void displayPlayerCardsOnHand(Player player) {
System.out.println(player.getLoginName());
if(player instanceof Dealer) {
for (int i = 0; i < player.getCardsOnHand().size(); i++) {
if (i == 0) {
System.out.print("<HIDDEN CARD> ");
} else {
System.out.print(player.getCardsOnHand().get(i).toString() + " ");
}
}
} else {
for (Card card : player.getCardsOnHand()) {
System.out.print(card + " ");
}
}
System.out.println();
}
public void displayBlankLine() {
System.out.println();
}
public void displayPlayerTotalCardValue(Player player) {
System.out.println("Value:"+player.getTotalCardsValue());
}
public void displayDealerDealCardsAndGameRound(int round) {
System.out.println("Dealer dealing cards - ROUND "+round);
}
public void displayGameStart() {
System.out.println("Game starts - Dealer shuffle deck");
}
public void displayPlayerNameAndChips(Player player) {
System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips");
}
public void displayPlayerNameAndLeftOverChips(Player player) {
System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips");
}
public void displayGameTitle() {
System.out.println("HighSum GAME");
}
public void displaySingleLine() {
for(int i=0;i<30;i++) {
System.out.print("-");
}
System.out.println();
}
public void displayDoubleLine() {
for(int i=0;i<30;i++) {
System.out.print("=");
}
System.out.println();
}
public char getPlayerCallOrQuit() {
char[] choices = {'c','q'};
char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices);
return r;
}
public char getPlayerFollowOrNot(Player player, int dealerBet) {
boolean validChoice = false;
char[] choices = {'y','n'};
char r = 'n';
while(!validChoice) {
r = Keyboard.readChar("Do you want to follow?",choices);
//check if player has enff chips to follow
if(r=='y' && player.getChips()<dealerBet) {
System.out.println("You do not have enough chips to follow");
displayPlayerNameAndChips(player);
}else {
validChoice = true;
}
}
return r;
}
public char getPlayerNextGame() {
char[] choices = {'y','n'};
char r = Keyboard.readChar("Next game?",choices);
return r;
}
public int getPlayerCallBetChip(Player player) {
boolean validBetAmount = false;
int chipsToBet = 0;
while(!validBetAmount) {
chipsToBet = Keyboard.readInt("Player call, state bet:");
if(chipsToBet<0) {
System.out.println("Chips cannot be negative");
}else if(chipsToBet>player.getChips()) {
System.out.println("You do not have enough chips");
}else {
validBetAmount = true;
}
}
return chipsToBet;
}
public int getDealerCallBetChips() {
System.out.println("Dealer call, state bet: 10");
return 10;
}
}
"
These are the requirements:
"On completion of this assignment a student should be able to write a Java application
that:
• Makes use of Java API "Swing" and "AWT" packages
• Handles generated events
• Makes use of layout manager to organize the GUI components
• Know how to apply and design a program using object-oriented concepts
2. Task
Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI).
2.1 Login
The game starts by the player logging into the game.
2.2 Play Game
The game starts after the player click on “Login”.
First, the dealer will shuffles the deck.
(You may include animation in this frame to simulate “shuffle” effect as enhancement.)
Then the dealer deals two cards from the top of the deck to the player and itself.
Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game.
Assume the player states 10 as the bet chips.
The player’s chip will be deducted by 10.
The chips on table will be updated to 20 and the dealer deals cards for next round.
Assume the dealer’s last card is higher than the player’s last card.
The dealer Call the game and the player gets to choose to Follow or Quit the game.
If the player follows the game, 10 chips will be deducted from the player’s balance chips.
(Asumme the dealer place 10 chips.)
The games carry on for maximum of four rounds.
In the last round, the player with the highest total sum wins the game.
And the game continues until the player exits the game.
Error Handling
Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips.
You should look out for other possible exceptions and handle them too."
There is an error in the code "Description Resource Path Location Type
The constructor GameTableFrame(HighSum) is undefined HighSumGUI.java /A3Skeleton/src/GUIExample line 29 Java Problem
"
|
7a307d29a883ee18b090645b9a35ee36
|
{
"intermediate": 0.3860090970993042,
"beginner": 0.41496074199676514,
"expert": 0.19903016090393066
}
|
9,023
|
import asyncio
import time
from random import randint
from bs4 import BeautifulSoup
from playwright.async_api import async_playwright
from fake_useragent import UserAgent
import requests
# Set up Fake UserAgent for random user-agents
ua = UserAgent()
# Function to implement random delay (rate limiting)
def random_delay(minimum=2, maximum=10):
sleep_time = randint(minimum, maximum)
time.sleep(sleep_time)
# Function to check if a website’s robots.txt allows scraping to implement point 3
def can_scrape(url):
response = requests.get(url + "/robots.txt")
if "Disallow: /" in response.text:
return False
return True
async def get_token_info(token_symbol, proxy):
# Check if we can scrape the requested URL
url = "https://moonarch.app/"
if not can_scrape(url):
print("Scraping is not allowed according to the website’s robots.txt.")
return None
async with async_playwright() as p:
browser = await p.chromium.launch(
headless=True,
proxy={"server": proxy},
user_agent=ua.random,
)
context = await browser.new_context()
try:
page = await context.new_page()
await page.goto(url)
search_box_selector = 'input.form-control'
await page.wait_for_selector(search_box_selector)
search_box = await page.query_selector(search_box_selector)
await search_box.type(token_symbol)
await page.wait_for_selector('.token-info')
await page.wait_for_selector('.infocard')
soup = BeautifulSoup(await page.content(), "html.parser")
token_info_element = soup.find("div", class_="token-info")
infocard_element = soup.find("div", class_="infocard")
check_alert_element = soup.find("div", class_="token-check-message check-alert")
check_warning_element = soup.find("div", class_="token-check-message check-warning")
check_info_element = soup.find("div", class_="token-check-message check-info")
not_verified_element = soup.find("div", class_="not-verified")
check_alert_status = "Yes" if check_alert_element else "None"
check_warning_status = "Yes" if check_warning_element else "None"
check_info_status = "Yes" if check_info_element else "None"
not_verified_status = "Yes" if not_verified_element else "None"
if token_info_element and infocard_element:
token_name_element = token_info_element.find("span", class_="name")
token_symbol_element = token_info_element.find("span", class_="symbol")
info_items = infocard_element.find_all("li")
if token_name_element and token_symbol_element and len(info_items) >= 7:
token_name = token_name_element.text.strip()
token_symbol = token_symbol_element.text.strip()
price = info_items[0].find("span", class_="value").text.strip()
max_supply = info_items[1].find("span", class_="value").text.strip()
market_cap = info_items[2].find("span", class_="value").text.strip()
liquidity = info_items[3].find("span", class_="value").text.strip()
liq_mc = info_items[4].find("span", class_="value").text.strip()
token_age = info_items[6].find("span", class_="value").text.strip()
await browser.close()
# Implement rate limiting (point 1)
random_delay()
return {
"name": token_name,
"symbol": token_symbol,
"price": price,
"max_supply": max_supply,
"market_cap": market_cap,
"liquidity": liquidity,
"liq_mc": liq_mc,
"token_age": token_age,
"check_alert": check_alert_status,
"check_warning": check_warning_status,
"check_info": check_info_status,
"not_verified": not_verified_status
}
else:
await browser.close()
error_info = f"token_name_element: {token_name_element}, token_symbol_element: {token_symbol_element}, info_items count: {len(info_items)}"
return {"error": f"Failed to find the required info items or name and.symbol. Error_info: {error_info}"}
else:
await browser.close()
return {"error": f"Failed to find the required elements for token_info_element ({token_info_element}) and infocard_element ({infocard_element})."}
except Exception as ex:
print(f"Error occurred while scraping: {ex}")
await browser.close()
return None
token_symbols = [
"0x0E481Fa712201f61dAf97017138Efaa69e2A3df3",
"0x2023aa62A7570fFd59F13fdE2Cac0527D45abF91",
"0x2222222222222222222222222222222222222222",
"0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e"
# Add more token symbols here…
]
async def main():
proxy_url = "http://proxy.example.com:8080"
while True:
result_tasks = [get_token_info(token_symbol, proxy_url) for token_symbol in token_symbols]
results = await asyncio.gather(*result_tasks)
print(results)
await asyncio.sleep(60)
asyncio.run(main())
The code above gives an error
C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject4\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject4\main.py
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject4\main.py", line 6, in <module>
from fake_useragent import UserAgent
ModuleNotFoundError: No module named 'fake_useragent'
Process finished with exit code 1
Fix it
|
8f7b8d3e6939a62927222547e523bc04
|
{
"intermediate": 0.30177637934684753,
"beginner": 0.5260346531867981,
"expert": 0.17218893766403198
}
|
9,024
|
write a python3 to say Type password: then i will type my password and it will print a string of text
|
77e79fa7fee1560dc12c50adae51db8d
|
{
"intermediate": 0.4780072569847107,
"beginner": 0.1949923038482666,
"expert": 0.3270004093647003
}
|
9,025
|
homeyscript
|
5525a4e80b588fea43aacacb8200b3fb
|
{
"intermediate": 0.2800869047641754,
"beginner": 0.4011032283306122,
"expert": 0.31880983710289
}
|
9,026
|
I am using stripe api with webhooks and also nest js with a next js frontend. How can I make it so that when it a checkout is completed the user is directed to the success page and the booking reference generated in the backend is passed to the frontend to display? I also want to send conformation emails to the user when they create a booking
|
bad5f055550a247e0e9b66e1e6703b43
|
{
"intermediate": 0.8272635340690613,
"beginner": 0.10550355166196823,
"expert": 0.06723286211490631
}
|
9,027
|
Error: Unsupported swap type [object Object]
at buildSwapMethodParameters (C:\Users\lidor\Desktop\Trade Bot\node_modules\@uniswap\smart-order-router\build\main\util\methodParameters.js:105:11)
at AlphaRouter.route (C:\Users\lidor\Desktop\Trade Bot\node_modules\@uniswap\smart-order-router\build\main\routers\alpha-router\alpha-router.js:461:81)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async main (C:\Users\lidor\Desktop\Trade Bot\index.js:23:23)
PS C:\Users\lidor\Desktop\Trade Bot> have this error with this code, const { AlphaRouter } = require('@uniswap/smart-order-router');
const { Token, CurrencyAmount, Percent, TradeType } = require('@uniswap/sdk-core');
const { ethers, BigNumber } = require('ethers');
const { SwapRouter } = require('@uniswap/v3-sdk');
const SWAP_ROUTER_ADDRESS = '0xE592427A0AEce92De3Edee1F18E0157C05861564';
const WALLET_ADDRESS = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266';
const WALLET_SECRET = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
const INFURA_TEST_URL = 'https://mainnet.infura.io/v3/2d5bc62bb8d748cebfc64763e719cb4f';
const provider = new ethers.providers.JsonRpcProvider(INFURA_TEST_URL);
const chainId = 1;
const router = new AlphaRouter({ chainId: chainId, provider: provider });
const token0 = new Token(chainId, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18, 'WETH', 'Wrapped Ether');
const token1 = new Token(chainId, '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984', 18, 'UNI', 'Uniswap Token');
async function main() {
try {
const inputAmount = CurrencyAmount.fromRawAmount(token0, ethers.utils.parseUnits('0.001', 18));
const bestRoute = await router.route(inputAmount, token1, TradeType.EXACT_INPUT, {
recipient: WALLET_ADDRESS,
slippageTolerance: new Percent(25, 100),
deadline: Math.floor(Date.now() / 1000 + 1800),
});
if (!bestRoute) console.log(`No best route found!`);
const swapRoute = bestRoute.route;
const pools = swapRoute[0].poolAddresses[0];
console.log(pools);
const quotedAmountOut = bestRoute.quote;
const methodParameters = SwapRouter.s({ trade: bestRoute.trade, options: {} });
const transaction = {
to: SWAP_ROUTER_ADDRESS,
data: methodParameters.calldata,
value: BigNumber.from(bestRoute.methodParameters.value),
from: WALLET_ADDRESS,
gasPrice: BigNumber.from(bestRoute.gasPriceWei),
gasLimit: ethers.utils.hexlify(1000000),
};
// Sign and send the transaction
const wallet = new ethers.Wallet(WALLET_SECRET, provider);
const signedTransaction = await wallet.signTransaction(transaction);
const txResult = await provider.sendTransaction(signedTransaction);
console.log(`Transaction sent! Waiting for confirmation...`);
console.log(`Hash: ${txResult.hash}`);
const receipt = await txResult.wait();
console.log(`Transaction confirmed in block ${receipt.blockNumber}`);
} catch (e) {
console.log(e);
}
}
main();
please use the most recent resources to find the best fix for this and if possible make the code simpler
|
b0f44346805420b119834dd29d5e2430
|
{
"intermediate": 0.3590121865272522,
"beginner": 0.39657488465309143,
"expert": 0.2444128841161728
}
|
9,028
|
{
"success": true,
"message": "reclamations for user 64537333924661387835b2a6",
"data": [
{
"_id": null,
"fullname": null,
"reclamations": [
{
"_id": "647460feb098bb06ad456ebb",
"title": "hfeafsg",
"reserved": true,
"userId": "64537333924661387835b2a6",
"demandId": "6464d3d0271d554f0c15c2e3",
"createdAt": "2023-04-19T10:59:24.838Z",
"updatedAt": "2023-04-20T11:49:52.992Z",
"__v": 0,
"adminId": "642fffb666e2703d80e0046d",
"active": false,
"demand": [],
"target": [],
"fullname": null
},
{
"_id": "64746125b098bb06ad456ebe",
"title": "retard fffaaa",
"reserved": true,
"userId": "64537333924661387835b2a6",
"demandId": "6464d3d0271d554f0c15c2e3",
"createdAt": "2023-04-19T10:59:24.838Z",
"updatedAt": "2023-04-20T11:49:52.992Z",
"__v": 0,
"adminId": "642fffb666e2703d80e0046d",
"active": false,
"demand": [],
"target": [],
"fullname": null
},
{
"_id": "64746138b098bb06ad456ebf",
"title": "farouk ",
"reserved": true,
"userId": "64537333924661387835b2a6",
"demandId": "6464d3d0271d554f0c15c2e3",
"createdAt": "2023-04-19T10:59:24.838Z",
"updatedAt": "2023-04-20T11:49:52.992Z",
"__v": 0,
"adminId": "642fffb666e2703d80e0046d",
"active": false,
"demand": [],
"target": [],
"fullname": null
}
]
},{
"_id": null,
"fullname": null,
"reclamations": [
{
"_id": "647460feb098bb06ad456ebb",
"title": "hfeafsg",
"reserved": true,
"userId": "64537333924661387835b2a6",
"demandId": "6464d3d0271d554f0c15c2e3",
"createdAt": "2023-04-19T10:59:24.838Z",
"updatedAt": "2023-04-20T11:49:52.992Z",
"__v": 0,
"adminId": "642fffb666e2703d80e0046d",
"active": false,
"demand": [],
"target": [],
"fullname": null
},
{
"_id": "64746125b098bb06ad456ebe",
"title": "retard fffaaa",
"reserved": true,
"userId": "64537333924661387835b2a6",
"demandId": "6464d3d0271d554f0c15c2e3",
"createdAt": "2023-04-19T10:59:24.838Z",
"updatedAt": "2023-04-20T11:49:52.992Z",
"__v": 0,
"adminId": "642fffb666e2703d80e0046d",
"active": false,
"demand": [],
"target": [],
"fullname": null
},
{
"_id": "64746138b098bb06ad456ebf",
"title": "farouk ",
"reserved": true,
"userId": "64537333924661387835b2a6",
"demandId": "6464d3d0271d554f0c15c2e3",
"createdAt": "2023-04-19T10:59:24.838Z",
"updatedAt": "2023-04-20T11:49:52.992Z",
"__v": 0,
"adminId": "642fffb666e2703d80e0046d",
"active": false,
"demand": [],
"target": [],
"fullname": null
}
]
}
]
} and i have this reduxToolkit fn import {createSlice, createAsyncThunk} from '@reduxjs/toolkit';
import AsyncStorage from '@react-native-async-storage/async-storage';
import ReclamationService from '@services/features/reclamation.services';
const initialState = {
reclamations: [],
};
export const getReclamations = createAsyncThunk(
'reclamation/getReclamations',
async ({accessToken}, thunkAPI) => {
try {
const response = await ReclamationService.getReclamation(accessToken);
console.log(
'response from redux =====>',
response?.data?.[0]?.reclamations,
);
response === undefined || response === null
? thunkAPI.dispatch(
setMessagePassword(
'Erreur de connexion veuillez, ressayer plus tard',
),
) && thunkAPI.rejectWithValue()
: thunkAPI.dispatch(setMessagePassword(response?.message)) &&
console.log('response.data', response.message);
if (response) {
return {
reclamations: response?.data?.[0]?.reclamations || [],
// any other fields to include in the payload, if necessary
};
}
console.log('reclamations', reclamations);
} catch (error) {
console.log('error redux', error.response.data);
thunkAPI.dispatch(setMessageRegister(response.message));
setMessageRegister(error.response.message);
thunkAPI.rejectWithValue(error.response.data);
}
},
);
const reclamationReducer = createSlice({
name: 'reclamation',
initialState,
reducers: {},
extraReducers: builder => {
builder
.addCase(getReclamations.fulfilled, (state, action) => {
console.log(
'redux======================================>',
action.payload.reclamations,
);
state.reclamations = action.payload.reclamations;
})
.addCase(getReclamations.rejected, (state, action) => {
state.reclamations = [];
});
},
});
const {actions} = reclamationReducer;
export default reclamationReducer.reducer;
and the scrren when i disptach the redux
const getReclamationOfUser = () => {
console.log('inside fn 1');
setLoading(true);
console.log('inside fn 2');
console.log('token', accessToken);
dispatch(getReclamations({accessToken}))
.unwrap()
.then(() => {
console.log('inside fn 3');
setLoading(false);
})
.catch(error => {
console.log('inside fn error', error);
setLoading(false);
});
};
useEffect(() => {
getReclamationOfUser();
}, []);
useEffect(() => {
setReclamation(reclamations);
console.log('rec', reclamation);
}, [reclamations]); so now correct this code to get the response.data witch is an array and set the value of reclamations to the response.data
|
aea7f57aa75c892852dd70e77bada4e5
|
{
"intermediate": 0.24503733217716217,
"beginner": 0.5268568992614746,
"expert": 0.22810578346252441
}
|
9,029
|
is there a way to assign data from axios.get without intermediate variable? like this const req = await axios.get('').data
|
f08626e2ac40db20148d7283b8a1a417
|
{
"intermediate": 0.608083188533783,
"beginner": 0.13865308463573456,
"expert": 0.2532637119293213
}
|
9,030
|
I used your updated code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC'))
frame = frame.iloc[:60,:6]
frame.columns = ['Time','Open','High','Low','Close','Volume']
frame = frame.set_index('Time')
today = dt.date.today()
frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S")
frame = frame.astype(float)
return frame
df = getminutedata('BTCUSDT', '1m', '44640')
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ''
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = client.futures_account_balance()
usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
opposite_side = None
if opposite_position is not None:
opposite_side = (SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY)
else:
print("No opposite position found.")
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side,
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
else:
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side
)
# Print order creation confirmation messages
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop
if df is None:
continue
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
time.sleep(1) # Add a delay of 1 second , but I getting ERROR: The signal time is: 2023-05-29 17:28:36 :buy
Both positions closed.
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 205, in <module>
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 129, in order_execution
opposite_position['positionSide'] == POSITION_SIDE_LONG
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not subscriptable Please upgrade your code and send me
|
39de284a178d0c6323dd3296e909da3c
|
{
"intermediate": 0.5081301331520081,
"beginner": 0.31399843096733093,
"expert": 0.17787139117717743
}
|
9,031
|
What ports do Oracle database use?
|
5c59f8bb0c0d21df8ef42cce59341ddf
|
{
"intermediate": 0.35787203907966614,
"beginner": 0.3548809587955475,
"expert": 0.28724703192710876
}
|
9,032
|
Write a code or script that will automatically analyze the source code of the token contract on https://bscscan.com/ and display information about whether it is a fraudulent token or not
For implementation, refer to the https://moonarch.app resource, where there is a block that displays information about dubious methods that are in the contract code
|
141bb4e7662c72d9ec1f2482315311a5
|
{
"intermediate": 0.5848264098167419,
"beginner": 0.21934248507022858,
"expert": 0.19583113491535187
}
|
9,033
|
const Container = styled.div``;
const Categories: React.FC = () => {
return (
<Container>
{categories.map((item) => (
<CategoryItem item={item} />
))}
</Container>
);
};
export default Categories;
Type '{ item: { id: number; image: string; title: string; cat: string; }; }' is not assignable to type 'IntrinsicAttributes & CategoryItemProps'.
Property 'item' does not exist on type 'IntrinsicAttributes & CategoryItemProps'.
|
6177ebcd8bb891770fdf6a0bb9885e6a
|
{
"intermediate": 0.4519592225551605,
"beginner": 0.3469530940055847,
"expert": 0.20108774304389954
}
|
9,034
|
ERROR in ./src/slice/ProductList.js 17:58-65
export 'Product' (imported as 'Product') was not found in './Product' (possible exports: default)
ERROR
[eslint]
src\slice\Product.js
Line 4:23: 'thumbnail' is missing in props validation react/prop-types
Line 5:18: 'name' is missing in props validation react/prop-types
Line 6:17: 'description' is missing in props validation react/prop-types
Line 7:17: 'price' is missing in props validation react/prop-types
Line 8:50: 'id' is missing in props validation react/prop-types
Search for the keywords to learn more about each error.
|
9785099894a461264fe74b6c61886326
|
{
"intermediate": 0.41969314217567444,
"beginner": 0.27037838101387024,
"expert": 0.3099284768104553
}
|
9,035
|
java code to implement a timer that switches on every 60 minutes and switches off after 10 minutes, all as thread
|
8fc8c4e26f8ef8d40e8dc16e9e3b65fd
|
{
"intermediate": 0.4812452495098114,
"beginner": 0.1624053567647934,
"expert": 0.356349378824234
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.